import socket
import ssl
import core.decryptionScheme as decryptionScheme
import core.tools as tools
from cryptography.fernet import Fernet
import base64
import netifaces
import yaml

COLOR_RESET = '\033[0m'
COLOR_GREEN = '\033[32m'
COLOR_BLUE = '\033[34m'

with open('config.yaml','r') as config:
    data = yaml.safe_load(config)

AUTH_IP_ADDR = data['pkg']['ip']
AUTH_PORT = data['pkg']['port']

interfaces = netifaces.interfaces()

for interface in interfaces:
    addresses = netifaces.ifaddresses(interface)
    if netifaces.AF_INET in addresses:
        ip_addresses = [addr['addr'] for addr in addresses[netifaces.AF_INET]]
        if(ip_addresses[0][:9]=="10.10.100"):
            BOB_IP_ADDR = ip_addresses[0]

try:
    normal_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # print ("Socket successfully created")
except socket.error as err:
    print ("socket creation failed with error %s" %(err))

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations("./certificates/ca_certificate.pem")

secure_socket = ssl_context.wrap_socket(normal_socket, server_side=False, server_hostname=data['pkg']['hostname'])
# secure_socket = ssl.wrap_socket(normal_socket, server_side=False)
secure_socket.connect((AUTH_IP_ADDR, AUTH_PORT))

print(secure_socket.recv(1024).decode())
print(secure_socket.recv(1024).decode())
print(secure_socket.recv(1024).decode())
print(secure_socket.recv(1024).decode())
print(secure_socket.recv(1024).decode())

authority_MPK = int(secure_socket.recv(1024).decode())
print(authority_MPK, "AUTH MPK")

identity =  input("Identity: ")
hashed_id = tools.hashIdentity(identity, authority_MPK)

secure_socket.send(identity.encode())

print(secure_socket.recv(1024).decode())
secret_key = secure_socket.recv(1024).decode()

secure_socket.close()

#  Now bob has received its secret key and alice can send any data to it now:

try:
    bob_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print ("socket creation failed with error %s" %(err))

bob_socket.bind(('0.0.0.0', 3002))
bob_socket.listen(1)
print("Bob is now open to encrypted Communication")

while True:
    listen = input("Do you want to continue listening?(Y/N)")
    if(listen=="N"):
        bob_socket.close()
        break

    print("To connect, use the following IP : ", BOB_IP_ADDR)
    conn, addr = bob_socket.accept()
    print("You are connected to", addr)

    #  now the key exchange will happen
    print("Sender is now sending encrypted connection key")
    encrypted_str = conn.recv(10240).decode()
    print("Encrypted Communication can start, enter 'baskar()' to exit chat")
    encrypted_list = eval(encrypted_str.split("|")[1])
    connection_key = decryptionScheme.decrypt_sequence(encrypted_list, int(secret_key), hashed_id, authority_MPK)

    # connection key is retrieved and now symmtric encryption can be used
    fernetKey = base64.urlsafe_b64encode(tools.bits_to_key(connection_key))
    fernetObject = Fernet(fernetKey)

    # fernet object created for encryption and decryption
    print("------------------")
    while(True):
        rec = conn.recv(1024).decode()
        if(fernetObject.decrypt(rec).decode().lower()=="baskar()"):
            break
        print(COLOR_GREEN + "SENDER : {}".format(fernetObject.decrypt(rec).decode())+ COLOR_RESET)
        BobIn = input(COLOR_BLUE + "ME : ")
        print(COLOR_RESET, end="")
        if(BobIn.lower()=="baskar()"):
            encryptedMessage = fernetObject.encrypt(BobIn.encode())
            conn.send(encryptedMessage)
            break
        encryptedMessage = fernetObject.encrypt(BobIn.encode())
        conn.send(encryptedMessage)


import requests
import time

# api-endpoint
API_ENDPOINT = "https://challenge.crossmint.io/api/polyanets"

# candidateId
CANDIDATE_ID = "95ccae45-102c-4748-98f2-b06b2b3aa93e"

# function to make_cross
# (it also makes delete request in case there were prior polyanets in canvas)
# n defines the cross length, which is the length from center
# n = 2 would be:
# x x
#  x
# x x
def make_cross(n):
    # since it's a 11x11 canvas, max n should be 6
    if  n < 1 or n > 6 :
        print("Error: n should be between 1 and 6")
        return
    for i in range(11):
        for j in range(11):

            data = {
                "candidateId": CANDIDATE_ID,
                "row": i,
                "column": j
            }

            print(f"modyfing row: {i} column: {j}")

            # verifies it is on the cross of a 11x11 grid and makes the space acording to n
            if (i > (5 - n)) and (i < (5 + n)) and (j == i or j == (10 - i)):
                r = requests.post(url = API_ENDPOINT, data = data)
            else:
                r = requests.delete(url = API_ENDPOINT, data = data)

            print("Response: ")
            print(r.json())

            # wait one sec bewteen requests to avoid "Too many requests"
            print("waiting 1 second...")
            time.sleep(1)

make_cross(4)


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

# In[2]:

import numpy as np
import matplotlib.pyplot as plt
import array as arr
import string
import os
import pickle
from wordcloud import WordCloud
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import svm
from nltk import PorterStemmer
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()

stop_words = ["i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself",
              "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself",
              "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these",
              "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do",
              "does", "did", "doing", "a", "an", "the", "but", "and", "if", "or", "because", "as", "until", "while",
              "of", "at", "by", "for", "with", "about","against", "between", "into", "through", "during", "before",
              "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under",
              "further", "then", "once", "here", "there", "when", "where", "all", "both", "each", "few", "more",
              "other", "some", "such", "only", "own",  "so", "than", "s", "t", "can", "will", "just", "don", "now",
              "br", "39", "quot", "one", "seen", "ve", "film", "movie", "story", "one", "character", "time", "movies",
              "character","thing","people", "make"]

def clean_data(text):
  """
    processes the given string:
    - convert to lower case
    - remove punctuation
    - remove stop words
    - lemmatize
    :text: string which is the content of a comment file
    :return: processed string
  """
  lower_case = text.lower()
  wh_special_char = lower_case.translate(str.maketrans(string.punctuation,' '*len(string.punctuation)))
  cleaned_data = ""
  for word in wh_special_char.split():
    if word not in stop_words:
      cleaned_data += " " + lemmatizer.lemmatize(word)
  return cleaned_data

def print_metrics(prediction, labels):
  N = len(labels)
  count = {"P":0, "N":0, "Z":0}
  labelCount = {"P":0, "N":0, "Z":0}
  tp = {"P":0, "N":0, "Z":0}
  tn = {"P":0, "N":0, "Z":0}
  classes = ["P", "N", "Z"]
  for i in range(N):
    count[prediction[i]] += 1
    labelCount[labels[i]] += 1
    if prediction[i] == labels[i]:
      tp[prediction[i]] += 1
    for c in classes:
      if c != prediction[i] and c != labels[i]:
        tn[c] += 1
  accuracy = {"P":0, "N":0, "Z":0}
  precision = {"P":0, "N":0, "Z":0}
  recall = {"P":0, "N":0, "Z":0}
  print("\nOverall Accuracy: " + str(sum(tp.values())/N))
  for i in ["P", "N", "Z"]:
    if count[i] == 0:
      precision[i] = 1
    else:
      precision[i] = tp[i]/count[i]
    if labelCount[i] == 0:
      recall[i] = 1
    else:
      recall[i] = tp[i]/labelCount[i]
    accuracy[i] = (tp[i] + tn[i])/N
  print("\nClass Accuracies:")
  print(accuracy)
  print("\nClass Precisions:")
  print(precision)
  print("\nClass Recalls:")
  print(recall)
  print("\nMacro average accuracy: ")
  print(sum(accuracy.values()) / 3)
  print("\nMacro average precision: ")
  print(sum(precision.values()) / 3)
  print("\nMacro average recall: ")
  print(sum(recall.values()) / 3)

#def get_word_clouds(data_p, data_n, data_z):
 # word cloud images for insight into data
  # negative
#  word_cloud = WordCloud(collocation_threshold=30).generate(text = data_n)
#  plt.imshow(word_cloud, interpolation= "bilinear")
#  plt.savefig("negative_wordcloud.png")
#  # positive
#  word_cloud = WordCloud(collocation_threshold=30).generate(text = data_p)
#  plt.imshow(word_cloud, interpolation= "bilinear")
#  plt.savefig("positive_wordcloud.png")
  # neutral
#  word_cloud = WordCloud(collocation_threshold=30).generate(text = data_z)
#  plt.imshow(word_cloud, interpolation= "bilinear")
#  plt.savefig("neutral_wordcloud.png")

# word cloud for each class using bigrams
# change
#get_word_clouds(data_p, data_n, data_z)

#read the data
data = []
labels=[]
# variables to store data for word cloud
data_z = data_n = data_p = ""
FILE_PATH = "TRAIN/"
dirs = os.listdir(FILE_PATH)
dirsSorted = sorted(dirs, key=lambda filename:int(filename[:-6]))
for file in dirsSorted:
  filename=os.path.join(FILE_PATH,file)
  f = open(filename, "r", encoding="latin-1")
  text = f.read()
  text = clean_data(text)
  data.append(text)
  if file[-5] == "N":
    data_n += text
  elif file[-5] == "Z":
    data_z += text
  elif file[-5] == "P":
    data_p += text
  labels.append(file[-5])
  f.close()

#TF-IDF + SVM
vectorizer = TfidfVectorizer()
features = vectorizer.fit_transform(data)

# initiate model
clf = svm.SVC()

# train
clf.fit(features, labels)

# get the training accuracy
prediction = clf.predict(features)
print_metrics(prediction, labels)
with open("step3_model_Solis.pkl", "wb") as file:
  pickle.dump(vectorizer, file)
  pickle.dump(clf, file)

# Other methods
# We used three methods to vectorize
# 1) Count Vectorizer (binary option being True or False),  2) Tf Idf Vectorizer, 3) First two pipelined
# and three models
# 1) Naive Bayes, 2) Logistic Regression, 3) SVM
# (not all combinations)

### bag of words

# uncomment following two lines if you want to try a model with Count
#count = CountVectorizer()
#bag = count.fit_transform(data)

# use binary parameter for binary count (1 if word is in document, 0 otherwise)
# uncomment following two lines if you want to try a model with Binary Count
#count_bin = CountVectorizer(binary=True)
#bag_bin = count.fit_transform(data)

# now we can use the vectorized data (bag/bag_bin) with different models

# Naive Bayes + Count
#clf = MultinomialNB()
#clf.fit(bag.toarray(), labels)
#prediction = clf.predict(bag.toarray())
#print_metrics(prediction, labels)

# Naive Bayes + Binary Count
#clf = MultinomialNB()
#clf.fit(bag_bin.toarray(), labels)
#prediction = clf.predict(bag_bin.toarray())
#print_metrics(prediction, labels)

# SVM + Count
#clf = svm.SVC()
#clf.fit(bag.toarray(), labels)
#prediction = clf.predict(bag.toarray())
#print_metrics(prediction)

# Naive Bayes + Count + TfIdf
#transformVectorizer = TfidfTransformer()
#transformed = transformVectorizer.fit_transform(bag)
#clf = MultinomialNB()
#clf.fit(transformed, labels)
#prediction = clf.predict(transformed)
#print_metrics(prediction)

# Naive Bayes + Binary Count + TfIdf
#transformVectorizer = TfidfTransformer()
#transformed = transformVectorizer.fit_transform(bag_bin)
#clf = MultinomialNB()
#clf.fit(transformed, labels)
#prediction = clf.predict(transformed)
#print_metrics(prediction)

# Logistic Regression + TfIdf
#clf = LogisticRegression(random_state=0, solver='lbfgs')
#clf.fit(features, labels)
#prediction = clf.predict(features)
#print_metrics(prediction)

# SVM + TfIdf
#clf = svm.SVC()
#clf.fit(features, labels)
#prediction = clf.predict(features)
#print_metrics(prediction

#word2vec + SVM

#import spacy
# Load the spacy model that you have installed
#nlp = spacy.load('en_core_web_sm')

#features = []
#for i in data:
#    doc = nlp(i)
#    features.append(doc.vector)

# initiate model
#clf = svm.SVC(kernel='rbf', C=15)

# train
#clf.fit(features, labels)

# get the training accuracy
#prediction = clf.predict(features)
#print_metrics(prediction, labels)

# In[ ]:


# swea - [2005]파스칼의삼각형 (2020-09-07)
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5P0-h6Ak4DFAUq

import sys
sys.stdin = open("swea/[2005]파스칼의삼각형.txt",'r')

T = int(input())
for t in range(1, T+1):
    n = int(input())
    print("#{0}".format(t))
    mat = [[0 for _ in range(n)] for _ in range(n)]
    for i in range(n):
        for j in range(i+1):
            if i == j :
                mat[i][j] = 1
            elif j == 0 :
                mat[i][j] = 1
            else :
                mat[i][j] = mat[i-1][j-1] + mat[i-1][j]
    for i in range(n):
        for j in range(n):
            if mat[i][j] != 0:
                print(mat[i][j], end= " ")
        print()

    # 옛날에 내가 푼것
    # n = int(input())
    # tmp = []
    # tmp2 = []
    # for i in range(n):
    #     for j in range(i+1) :#012 / i 2
    #         if j == 0 or j == i :
    #             tmp2.append('1')
    #         else:
    #             tmp2.append(str(int(tmp[j]) + int(tmp[j-1])))
    #     tmp = tmp2[:]
    #     ans = ' '.join(tmp2)
    #     tmp2.clear()
    #     print(ans)


"""
445. Add Two Numbers II
https://leetcode.com/problems/add-two-numbers-ii/
"""

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        num1 = num2 = ''
        while l1 or l2:
            if l1:
                num1 += str(l1.val)
                l1 = l1.next
            if l2:
                num2 += str(l2.val)
                l2 = l2.next
        sum_str = str(int(num1) + int(num2))
        prev = None
        head = None
        for digit in sum_str:
            node = ListNode(int(digit))
            if prev:
                prev.next = node
            else:
                head = node
            prev = node
        return head


#!/usr/bin/env python

import logging
import kubernetes
import os
import random
import time
import pytz
import json
import datetime

from kubernetes.client.rest import ApiException
from http import HTTPStatus

KILL_FREQUENCY = int(os.environ.get('CHAOS_MONKEY_KILL_FREQUENCY_SECONDS', 300))
LOGGER = logging.getLogger(__name__)

logging.basicConfig(level=logging.INFO)

# No error handling, if things go wrong Kubernetes will restart for us!

kubernetes.config.load_incluster_config()
v1 = kubernetes.client.CoreV1Api()

while True:
    pods = v1.list_pod_for_all_namespaces().items
    pod = random.choice(pods)
    LOGGER.info("Terminating pod %s/%s", pod.metadata.namespace, pod.metadata.name)
    event_name = "Chaos monkey kill pod %s" % pod.metadata.name
    v1.delete_namespaced_pod(
        name=pod.metadata.name,
        namespace=pod.metadata.namespace,
        body=kubernetes.client.V1DeleteOptions(),
    )
    event_timestamp = datetime.datetime.now(pytz.utc)
    try:
        event = v1.read_namespaced_event(event_name, namespace=pod.metadata.namespace)
        event.count += 1
        event.last_timestamp = event_timestamp
        v1.replace_namespaced_event(event_name, pod.metadata.namespace, event)
    except ApiException as e:
        error_data = json.loads(e.body)
        error_code = HTTPStatus(int(error_data['code']))
        if error_code == HTTPStatus.NOT_FOUND:
            new_event = kubernetes.client.V1Event(
                count=1,
                first_timestamp=event_timestamp,
                involved_object=kubernetes.client.V1ObjectReference(
                    kind="Pod",
                    name=pod.metadata.name,
                    namespace=pod.metadata.namespace,
                    uid=pod.metadata.uid,
                ),
                last_timestamp=event_timestamp,
                message="Pod deleted by chaos monkey",
                metadata=kubernetes.client.V1ObjectMeta(
                    name=event_name,
                ),
                reason="ChaosMonkeyDelete",
                source=kubernetes.client.V1EventSource(
                    component="chaos-monkey",
                ),
                type="Warning",
            )
            v1.create_namespaced_event(namespace=pod.metadata.namespace, body=new_event)
        else:
            raise
    time.sleep(KILL_FREQUENCY)


import json
import logging
from time import sleep
from typing import Dict, List

from terragraph.ctf.tests.test_iot.test_node_software_upgrade import TestIotNSU1

LOG = logging.getLogger(__name__)

class TestNetworkIotNSU2(TestIotNSU1):
    TEST_NAME = "NetworkIOTv2-NSU-2"
    DESCRIPTION = "Upgrade network excluding specified link and node which are down using OEM's E2E controller with BitTorrent."

    def build_test_steps(self, fail_during_upgrade: bool = False) -> List[Dict]:
        """ """
        steps = []
        ignition_timeout_s = self.test_args["ignition_timeout_s"]
        upgrade_timeout_s = self.test_args["upgrade_timeout_s"]

        # read test data configs
        test_data = json.load(open(self.test_args["test_data"]))
        node_to_fail = test_data["fail_node"]
        link_to_fail = test_data["fail_link"]
        expected_offline_network = test_data["expected_offline_network"]
        skip_nodes = expected_offline_network["nodes"]
        skip_links = expected_offline_network["links"]
        if "wait_to_fail_time" in self.test_args.keys():
            wait_to_fail_time = self.test_args["wait_to_fail_time"]
        else:
            wait_to_fail_time = 0

        # upgrade controller if x86_image is given
        if self.test_args["x86_image_path"]:
            steps.append(
                {
                    "name": "Push x86 image",
                    "function": self.push_x86_image,
                    "function_args": (self.test_args["x86_image_path"],),
                    "success_msg": "x86 image was upgraded.",
                }
            )
        steps.extend(
            [
                self.get_common_test_steps()["check_software_versions"],
                self.get_common_x86_test_steps()["setup_x86_services"],
                # upload tg image to controller
                {
                    "name": "Push Puma image to x86 host",
                    "function": self.push_tg_image_to_x86,
                    "function_args": (
                        self.test_args["upload_image_path"],
                        "tg-image.bin",
                    ),
                    "success_msg": "Puma image was uploaded.",
                },
                # upload oem image to controller
                {
                    "name": "Push OEM image to x86 host",
                    "function": self.push_tg_image_to_x86,
                    "function_args": (
                        self.test_args["upload_oem_image_path"],
                        "oem-image.bin",
                    ),
                    "success_msg": "OEM image was uploaded.",
                },
                # start bitTorrent tracker service
                self.get_common_x86_test_steps()["start_x86_bt_tracker"],
                self.get_common_x86_test_steps()["start_x86_services"],
                {
                    "name": "Wait 5 seconds for controller to initialize",
                    "function": sleep,
                    "function_args": (5,),
                    "success_msg": "Finished waiting",
                },
                {
                    "name": "Verify PUMA image is seeding",
                    "function": self._verify_tg_image_seeding,
                    "function_args": (self.test_args["upload_image_path"],),
                    "success_msg": "E2E controller is seeding the Puma image.",
                },
                {
                    "name": "Check if network is ignited",
                    "function": self.try_until_timeout,
                    "function_args": (
                        self.controller_verify_topology_up,
                        (self.api_service_request, ["getTopology"]),
                        5,
                        ignition_timeout_s,
                    ),
                    "success_msg": "Network is up",
                    "error_handler": self.get_common_error_handler(),
                },
                {
                    "name": "Wait 60 seconds for last node to apply node config overrides changes",
                    "function": sleep,
                    "function_args": (60,),
                    "success_msg": "Finished waiting",
                },
                {
                    "name": "ReCheck network after node overrides take effect",
                    "function": self.try_until_timeout,
                    "function_args": (
                        self.controller_verify_topology_up,
                        (self.api_service_request, ["getTopology"]),
                        5,
                        120,
                    ),
                    "success_msg": "Network is up",
                    "error_handler": self.get_common_error_handler(),
                },
                # get tg nodes in network expected to be online for upgrading
                {
                    "name": "Get puma nodes in network expected to be online",
                    "function": self._get_puma_nodes,
                    "function_args": (skip_nodes,),
                    "success_msg": "retrieved puma nodes",
                },
                {
                    "name": f"fail tg link {link_to_fail['name']} and node {node_to_fail['name']} before upgrade",
                    "function": self.fail_link_and_node,
                    "function_args": (
                        link_to_fail,
                        node_to_fail,
                    ),
                    "concurrent": fail_during_upgrade,
                    "delay": wait_to_fail_time,
                    "success_msg": "sucesfully brought down tg link and node",
                },
                {
                    "name": "Start upgrade of online puma nodes in network",
                    "function": self._upgrade_nodes,
                    "function_args": (
                        upgrade_timeout_s,
                        self.puma_nodes,
                    ),
                    "concurrent": fail_during_upgrade,
                    "success_msg": "Upgrade request for puma nodes was sent.",
                },
                {
                    "name": "Check that all online puma nodes are upgraded",
                    "function": self.try_until_timeout,
                    "function_args": (
                        self._check_nodes_upgrade_status,
                        ([self.puma_nodes]),
                        5,
                        upgrade_timeout_s,
                    ),
                    "success_msg": "Puma nodes upgraded successfully.",
                    "error_handler": self.get_common_error_handler(),
                },
                # upgrade oem node in network after puma nodes complete upgrade
                {
                    "name": "Verify OEM image is seeding",
                    "function": self._verify_tg_image_seeding,
                    "function_args": (self.test_args["upload_oem_image_path"],),
                    "success_msg": "E2E controller is seeding the OEM image.",
                },
                {
                    "name": "Start upgrade of oem node",
                    "function": self._upgrade_nodes,
                    "function_args": (
                        upgrade_timeout_s,
                        [self.test_args["oem_node_name"]],
                    ),
                    "success_msg": "Upgrade request was sent for OEM node",
                },
                {
                    "name": "Check that OEM node is upgraded",
                    "function": self.try_until_timeout,
                    "function_args": (
                        self._check_nodes_upgrade_status,
                        ([self.test_args["oem_node_name"]]),
                        5,
                        upgrade_timeout_s,
                    ),
                    "success_msg": "OEM node is upgraded successfully",
                    "error_handler": self.get_common_error_handler(),
                },
                {
                    "name": "Check if expected nodes and links are up after upgrade",
                    "function": self.try_until_timeout,
                    "function_args": (
                        self.controller_verify_topology_up,
                        (
                            self.api_service_request,
                            ["getTopology"],
                            skip_nodes,
                            skip_links,
                        ),
                        5,
                        ignition_timeout_s,
                    ),
                    "success_msg": "Expected nodes and links are up after upgrade",
                    "error_handler": self.get_common_error_handler(),
                },
            ]
        )
        return steps

    def fail_link_and_node(self, link_to_fail: Dict, node_to_fail: Dict):
        """
        bring down link specified in link_to_fail.
        stop minion on node specified in node_to_fail
        """

        link_name = link_to_fail["name"]
        initiator_mac = link_to_fail["initiator_mac"]
        responder_mac = link_to_fail["responder_mac"]

        # disable auto ignition on link
        self.api_set_link_ignition_state(link_name, False)

        # dissoc link and wait 40s before checking link state in controller
        self.api_force_dissoc(initiator_mac, responder_mac)
        sleep(40)

        # check link is down
        self.api_check_link_state(link_name, False)

        # stop minion on node and wait 40s before checking node state in controller
        self.tg_restart_minion([node_to_fail["id"]], "stop")
        sleep(40)

        # check node is offline
        self.api_check_node_state(node_to_fail["name"], False)

    def get_test_steps(self) -> List[Dict]:

        # Get steps for software upgrade where node and link fail before upgrade begins
        steps = self.build_test_steps()
        return steps

class TestNetworkIotNSU3(TestNetworkIotNSU2):
    TEST_NAME = "NetworkIOTv2-NSU-3"
    DESCRIPTION = "Upgrade network while specified link and node are brought down, using OEM's E2E controller with BitTorrent."

    @staticmethod
    def test_params() -> Dict[str, Dict]:
        test_params: Dict[str, Dict] = super(
            TestNetworkIotNSU3, TestNetworkIotNSU3
        ).test_params()
        test_params["wait_to_fail_time"] = {
            "desc": (
                "time to wait after upgrade is started before failing node and link in network"
            ),
            "convert": int,
            "default": 120,
        }
        return test_params

    def get_test_steps(self) -> List[Dict]:

        # Get steps for software upgrade when node and link fail during the upgrade process
        steps = self.build_test_steps(True)
        return steps


# TCP connections/Sockets
# An Internet socket or network socket is an endpoint of a bidirectional inter-process communication flow across an Internet Protocol-based computer network.
# # Ports ar application-specific or process-specific software comunnications endpoint. It allows multiple networked applications to coexist on the same server.
import socket

# Below is a veryy simple web browser using Socket

# the socket() function returns a socket object whose methods implement the various socket system calls.
# class socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
# AF_INET is the Internet address family for IPv4.
# SOCK_STREAM is the socket type for TCP, the protocol that will be used to transport messages in the network.
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect( ('data.pr4e.org', 443))

# The opposite method of bytes.decode() is str.encode(), which returns a bytes representation of the Unicode string, encoded in the requested encoding.
cmd = 'GET https://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()
mysock.send(cmd)

while True:
    # receive 512 chars at a time
    # Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified
    # by bufsize (512). See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
    data = mysock.recv(512)
    if (len(data) < 1):
        break
    # one can create a string using the decode() method of bytes. This method takes an encoding argument, such as UTF-8, and optionally an errors argument.
    print(data.decode())
mysock.close()

# Using urllib - This does all the socket work for us.

import urllib.request, urllib.parse, urllib.error

fhand = urllib.request.urlopen('https://data.pr4e.org/romeo.txt')

for line in fhand:
    print(line.decode().strip())

# Web scraping
# Be careful what sites you get data from

# Beautiful Soup - nice for doing string searches. Helps with parsing HTML.

#### Resources
# https://docs.python.org/3/library/socket.html


#!/usr/bin/env python

import rospy
import numpy as np
from std_msgs.msg import Float64MultiArray
from sensor_msgs.msg import Joy, Image
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Pose

import os.path as op

class UWTeleop(object):
    def __init__(self):
        rospy.init_node("keyboard")

        self.force_pub = rospy.Publisher('/NEXXUS_ROV/thrusters_input', Float64MultiArray, queue_size=10)
        self.rate = rospy.Rate(20)

        self.robot_pose = rospy.Subscriber("/NEXXUS_ROV/pose",Pose,self.hold_thrust_callback)
        self.joy_sub = rospy.Subscriber("/joy", Joy, self.joy_msg_callback)

        self.joy_data = Joy()
        self.vel_cmd = Float64MultiArray()
        self.past_pose = Pose()
        self.robot_pose = Pose()
        self.joy_called = 0
        self.set_pose = Pose()

    def hold_thrust_callback(self,data):
        self.robot_pose = data

        if self.joy_called == 1:
            if self.joy_data.buttons[1] == 1:
                self.set_pose = data

            if self.joy_data.buttons[1] == 0:
                x_gain = .1
                y_gain = .1
                z_gain = 0.1
                x_diff_g = 0.01
                y_diff_g = 0.01
                z_diff_g = 0.1
                x_port = (self.robot_pose.position.x - self.set_pose.position.x) * x_gain
                y_port = (self.robot_pose.position.y - self.set_pose.position.y) * y_gain
                z_port = (self.robot_pose.position.z - self.set_pose.position.z) * z_gain
                x_diff = (self.robot_pose.position.x - self.past_pose.position.x) * x_diff_g
                y_diff = (self.robot_pose.position.y - self.past_pose.position.y) * y_diff_g
                z_diff = (self.robot_pose.position.z - self.past_pose.position.z) * z_diff_g
                x_con = x_port + x_diff
                y_con = y_port + y_diff
                z_con = z_port + z_diff
                self.vel_cmd.data = [x_con,x_con,z_con,z_con,y_con]
                if self.robot_pose.position.z > 18.5:
                    self.vel_cmd.data = [x_con,x_con,-100,-100,y_con]
        self.past_pose = data

    def joy_msg_callback(self, data):
        '''
        joy_data.axes = [+left, +forward, +yaw, +up, +pitch, +roll]

        joy_data.buttons = [take_pictures, ...]
        '''

        self.joy_data = data
        self.joy_called = 1
        if self.joy_data.buttons[1]:
            x = self.joy_data.axes[1] * -10
            y = self.joy_data.axes[0] * 10
            z = self.joy_data.axes[3] * -10
            self.vel_cmd.data = [x,x,z,z,y]
            if self.robot_pose.position.z > 18.5:
                self.vel_cmd.data = [x,x,-100,-100,y]

    def start_teleop(self):
        while not rospy.is_shutdown():
            self.force_pub.publish(self.vel_cmd)
            self.rate.sleep()

if __name__ == "__main__":
    uw_teleop = UWTeleop()
    uw_teleop.start_teleop()


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 21 21:55:17 2021

@author: MengZY
"""

import numpy as np

measure = np.load('X_final.npy')
label = np.load('label.npy')

from sklearn.model_selection import KFold
kf = KFold(n_splits = 5, shuffle = True)

from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import roc_auc_score, classification_report
import time

for train_index, test_index in kf.split(measure):

    X_train, X_test = measure[train_index], measure[test_index]
    y_train, y_test = label[train_index], label[test_index]
    start = time.time()
    clf = MultinomialNB().fit(X_train, y_train)
    end = time.time()
    print('GauNB time: ', end-start)
    print('GauNB report: ', classification_report(y_test,clf.predict(X_test)))
    print('GauNB auc: ', roc_auc_score(y_test, clf.predict_proba(X_test)[:,1]))


import requests
from bs4 import BeautifulSoup

pageNum = 1

base_url = 'https://hiculturearts.pastperfectonline.com'

url = '{}/search?page={}&utf8=%E2%9C%93&search_criteria=*&searchButton=Search'.format(base_url, pageNum)

r = requests.get(url)

while 'No results found' not in r.text:
    soup = BeautifulSoup(r.text, 'html.parser')

    results = soup.findAll("div", {"class": "indvImage"})
    for result in results:
        for a in result.find_all('a', href=True):
            print(base_url + a['href'])
    pageNum += 1
    url = '{}/search?page={}&utf8=%E2%9C%93&search_criteria=*&searchButton=Search'.format(base_url, pageNum)
    r = requests.get(url)


input = open('input.txt', 'r').read().strip().split(',')
ex = open('example.txt', 'r').read().strip().split(',')

def solve(strdata):
    data = []
    for i in range(len(strdata)):
        data.append(int(strdata[i]))

    fuels1 = []
    for i in range(len(data)):
        fuels1.append(0)
        for crab in data:
            fuels1[i] += abs(i - crab)

    fuels2 = []
    for i in range(len(data)):
        fuels2.append(0)
        for crab in data:
            distance = abs(i - crab)
            fuels2[i] += int(distance * (distance + 1) / 2)

    return min(fuels1), min(fuels2)

print(solve(ex))


from abc import ABCMeta, abstractmethod

import numpy as np
from scipy import integrate

class BaseDiscretizer(ABCMeta):
    """
    Base class for the discretizer classes in pgmpy. The discretizer
    classes are used to discretize a continuous random variable
    distribution into discrete probability masses.

    Parameters
    ----------
    factor: A ContinuousNode or a ContinuousFactor object
        the continuous node or factor representing the distribution
        to be discretized.

    low, high: float
        the range over which the function will be discretized.

    cardinality: int
        the number of states required in the discretized output.

    Examples
    --------
    >>> from scipy.stats import norm
    >>> from pgmpy.factors.continuous import ContinuousNode
    >>> normal = ContinuousNode(norm(0, 1).pdf)
    >>> from pgmpy.discretize import BaseDiscretizer
    >>> class ChildDiscretizer(BaseDiscretizer):
    ...     def get_discrete_values(self):
    ...         pass
    >>> discretizer = ChildDiscretizer(normal, -3, 3, 10)
    >>> discretizer.factor
    <pgmpy.factors.continuous.ContinuousNode.ContinuousNode object at 0x04C98190>
    >>> discretizer.cardinality
    10
    >>> discretizer.get_labels()
    ['x=-3.0', 'x=-2.4', 'x=-1.8', 'x=-1.2', 'x=-0.6', 'x=0.0', 'x=0.6', 'x=1.2', 'x=1.8', 'x=2.4']

    """

    def __init__(self, factor, low, high, cardinality):
        self.factor = factor
        self.low = low
        self.high = high
        self.cardinality = cardinality

    @abstractmethod
    def get_discrete_values(self):
        """
        This method implements the algorithm to discretize the given
        continuous distribution.

        It must be implemented by all the subclasses of BaseDiscretizer.

        Returns
        -------
        A list of discrete values or a DiscreteFactor object.
        """
        pass

    def get_labels(self):
        """
        Returns a list of strings representing the values about
        which the discretization method calculates the probability
        masses.

        Default value is the points -
        [low, low+step, low+2*step, ......... , high-step]
        unless the method is overridden by a subclass.

        Examples
        --------
        >>> from pgmpy.factors import ContinuousNode
        >>> from pgmpy.discretize import BaseDiscretizer
        >>> class ChildDiscretizer(BaseDiscretizer):
        ...     def get_discrete_values(self):
        ...         pass
        >>> from scipy.stats import norm
        >>> node = ContinuousNode(norm(0).pdf)
        >>> child = ChildDiscretizer(node, -5, 5, 20)
        >>> chld.get_labels()
        ['x=-5.0', 'x=-4.5', 'x=-4.0', 'x=-3.5', 'x=-3.0', 'x=-2.5',
         'x=-2.0', 'x=-1.5', 'x=-1.0', 'x=-0.5', 'x=0.0', 'x=0.5', 'x=1.0',
         'x=1.5', 'x=2.0', 'x=2.5', 'x=3.0', 'x=3.5', 'x=4.0', 'x=4.5']

        """
        step = (self.high - self.low) / self.cardinality
        labels = [
            f"x={str(i)}" for i in np.round(np.arange(self.low, self.high, step), 3)
        ]
        return labels

class RoundingDiscretizer(BaseDiscretizer):
    """
    This class uses the rounding method for discretizing the
    given continuous distribution.

    For the rounding method,

    The probability mass is,
    cdf(x+step/2)-cdf(x), for x = low

    cdf(x+step/2)-cdf(x-step/2), for low < x <= high

    where, cdf is the cumulative density function of the distribution
    and step = (high-low)/cardinality.

    Examples
    --------
    >>> import numpy as np
    >>> from pgmpy.factors.continuous import ContinuousNode
    >>> from pgmpy.factors.continuous import RoundingDiscretizer
    >>> std_normal_pdf = lambda x : np.exp(-x*x/2) / (np.sqrt(2*np.pi))
    >>> std_normal = ContinuousNode(std_normal_pdf)
    >>> std_normal.discretize(RoundingDiscretizer, low=-3, high=3,
    ...                       cardinality=12)
    [0.001629865203424451, 0.009244709419989363, 0.027834684208773178,
     0.065590616803038182, 0.120977578710013, 0.17466632194020804,
     0.19741265136584729, 0.17466632194020937, 0.12097757871001302,
     0.065590616803036905, 0.027834684208772664, 0.0092447094199902269]
    """

    def get_discrete_values(self):
        step = (self.high - self.low) / self.cardinality

        # for x=[low]
        discrete_values = [
            self.factor.cdf(self.low + step / 2) - self.factor.cdf(self.low)
        ]

        # for x=[low+step, low+2*step, ........., high-step]
        points = np.linspace(self.low + step, self.high - step, self.cardinality - 1)
        discrete_values.extend(
            [
                self.factor.cdf(i + step / 2) - self.factor.cdf(i - step / 2)
                for i in points
            ]
        )

        return discrete_values

class UnbiasedDiscretizer(BaseDiscretizer):
    """
    This class uses the unbiased method for discretizing the
    given continuous distribution.

    The unbiased method for discretization is the matching of the
    first moment method. It involves calculating the first order
    limited moment of the distribution which is done by the _lim_moment
    method.

    For this method,

    The probability mass is,
    (E(x) - E(x + step))/step + 1 - cdf(x), for x = low

    (2 * E(x) - E(x - step) - E(x + step))/step, for low < x < high

    (E(x) - E(x - step))/step - 1 + cdf(x), for x = high

    where, E(x) is the first limiting moment of the distribution
    about the point x, cdf is the cumulative density function
    and step = (high-low)/cardinality.

    References
    ----------
    Klugman, S. A., Panjer, H. H. and Willmot, G. E.,
    Loss Models, From Data to Decisions, Fourth Edition,
    Wiley, section 9.6.5.2 (Method of local moment matching) and
    exercise 9.41.

    Examples
    --------
    >>> import numpy as np
    >>> from pgmpy.factors import ContinuousNode
    >>> from pgmpy.factors.continuous import UnbiasedDiscretizer
    # exponential distribution with rate = 2
    >>> exp_pdf = lambda x: 2*np.exp(-2*x) if x>=0 else 0
    >>> exp_node = ContinuousNode(exp_pdf)
    >>> exp_node.discretize(UnbiasedDiscretizer, low=0, high=5, cardinality=10)
    [0.39627368905806137, 0.4049838434034298, 0.13331784003148325,
     0.043887287876647259, 0.014447413395300212, 0.0047559685431339703,
     0.0015656350182896128, 0.00051540201980112557, 0.00016965346326140994,
     3.7867260839208328e-05]

    """

    def get_discrete_values(self):
        lev = self._lim_moment
        step = (self.high - self.low) / (self.cardinality - 1)

        # for x=[low]
        discrete_values = [
            (lev(self.low) - lev(self.low + step)) / step
            + 1
            - self.factor.cdf(self.low)
        ]

        # for x=[low+step, low+2*step, ........., high-step]
        points = np.linspace(self.low + step, self.high - step, self.cardinality - 2)
        discrete_values.extend(
            [(2 * lev(i) - lev(i - step) - lev(i + step)) / step for i in points]
        )

        # for x=[high]
        discrete_values.append(
            (lev(self.high) - lev(self.high - step)) / step
            - 1
            + self.factor.cdf(self.high)
        )

        return discrete_values

    def _lim_moment(self, u, order=1):
        """
        This method calculates the kth order limiting moment of
        the distribution. It is given by -

        E(u) = Integral (-inf to u) [ (x^k)*pdf(x) dx ] + (u^k)(1-cdf(u))

        where, pdf is the probability density function and cdf is the
        cumulative density function of the distribution.

        Reference
        ---------
        Klugman, S. A., Panjer, H. H. and Willmot, G. E.,
        Loss Models, From Data to Decisions, Fourth Edition,
        Wiley, definition 3.5 and equation 3.8.

        Parameters
        ----------
        u: float
            The point at which the moment is to be calculated.

        order: int
            The order of the moment, default is first order.
        """

        def fun(x):
            return np.power(x, order) * self.factor.pdf(x)

        return integrate.quad(fun, -np.inf, u)[0] + np.power(u, order) * (
            1 - self.factor.cdf(u)
        )

    def get_labels(self):
        labels = list(
            f"x={str(i)}"
            for i in np.round(np.linspace(self.low, self.high, self.cardinality), 3)
        )
        return labels


import os
import time
import random
import json

import youtube_dl

def channel(key):
    channel_list = []
    with open('{}.json'.format(key), 'r') as f:
        data = json.load(f)
        channel_list.append(data)
    return channel_list

def download(url, folder, title):

    video_info = youtube_dl.YoutubeDL().extract_info(url, download=False)
    formats = video_info.get('formats')
    format_list = []
    for i in formats:
        a = i.get('format').split(' - ')[0]
        format_list.append(a)

    ydl_opts = {
        'outtmpl': '/root/{}/{}'.format(folder, title)
    }

    # 检测480p分辨率，如果没有就用默认的。
    if '135' in format_list:
        ydl_opts['format'] = '135+m4a'
    else:
        ydl_opts['format'] = 'mp4+m4a'

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        result = ydl.extract_info(url, download=True)

if __name__ == '__main__':

    a = 'vlog 动画 日本医疗'

    for key in a.split(' '):
        channel_list = channel(key)

        for i in channel_list:

            keyword = i['keyword']
            down_nums = i['down_nums']
            details_list = i['details']

            # 创建目录
            file_path = os.path.exists('/root/{}'.format(keyword))
            if not file_path:
                os.mkdir('/root/{}'.format(keyword))
                print('{}'.format(keyword)+'目录创建成功')

            else:
                print('{}'.format(keyword)+'目录已存在')

            # 下载失败记录
            failure_list = []

            # 开始下载
            for video in details_list:
                title_set = video['title_set']
                title_set_mp4 = title_set + '.mp4'
                href = video['href']

                mp4_list = []
                for root,dirs,files in os.walk('/root/{}'.format(keyword)):

                    for mp4 in files:
                        if '.mp4' in mp4:
                            mp4_list.append(mp4)

                # 已经下过的视屏，包含失败的
                down_video_list = mp4_list + failure_list

                if len(mp4_list)<down_nums:
                    if title_set_mp4 not in down_video_list:
                        try:
                            download(href, keyword, title_set)
                            print(details_list.index(video)+1)
                        except:
                            # 保存表
                            failure_list.append(title_set_mp4)
                            print('{}下载失败'.format(details_list.index(video)+1))

                            time.sleep(random.randint(1, 3))  # 限制爬取时间


import pandas as pd
from collections import defaultdict
import warnings
import visualize
import neat
import multiprocessing
import os
import matplotlib.pyplot as plt

import numpy as np

from sklearn.datasets import load_digits

os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

digits = load_digits()

X = digits.images.reshape(
    digits.images.shape[0], digits.images.shape[1] * digits.images.shape[2])
y = digits.target

def softmax(x, axis=1):
    # 计算每行的最大值
    row_max = x.max(axis=axis)

    # 每行元素都需要减去对应的最大值，否则求exp(x)会溢出，导致inf情况
    row_max = row_max.reshape(-1, 1)
    x = x - row_max

    # 计算e的指数次幂
    x_exp = np.exp(x)
    x_sum = np.sum(x_exp, axis=axis, keepdims=True)
    s = x_exp / x_sum
    return s

def eval_genomes(genomes, config):
    for genome_id, genome in genomes:
        net = neat.nn.FeedForwardNetwork.create(genome, config)

        outputs = []
        for xi in x_inputs:
            output = net.activate(xi)
            outputs.append(output)

        px_outputs = softmax(np.array(outputs).reshape(
            samplesize, number_of_classification), axis=1)
        # the index of maximum in each line
        pred_outputs = np.argmax(px_outputs, axis=1)
        # replace index to real number, from higher number to lower number!!
        for i in range(number_of_classification):
            index = number_of_classification - i - 1
            pred_outputs[pred_outputs == index] = numbers[index]

        real_outputs = np.array(x_outputs).reshape(samplesize,)

        acc = np.sum(pred_outputs == real_outputs)/samplesize

        genome.fitness = acc

numbers = [*range(10)]  # number 2 > number 1
number_of_classification = len(numbers)
number_of_sampling = 100

list_y = y.tolist()
digits_indexes = []
for digit in numbers:
    li = [i for i in range(len(list_y)) if list_y[i] == digit]
    digits_indexes.extend(li[:number_of_sampling])

samplesize = X[digits_indexes].shape[0]
x_inputs = [tuple(c) for c in X[digits_indexes].tolist()]
x_outputs = [tuple(c)
             for c in y[digits_indexes].reshape(samplesize, 1).tolist()]

def run(config_file):
    # Load configuration.
    config = neat.Config(
        neat.DefaultGenome,
        neat.DefaultReproduction,
        neat.DefaultSpeciesSet,
        neat.DefaultStagnation,
        config_file,
    )

    # Create the population, which is the top-level object for a NEAT run.
    p = neat.Population(config)

    # add a stdout reporter to show progress in the terminal
    reporter = neat.StdOutReporter(False)
    p.add_reporter(reporter)
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    #checkpointer = neat.Checkpointer(100)
    # p.add_reporter(checkpointer)
    # Run for up to 300 generations.
    winner = p.run(eval_genomes, 1000)

    return [stats, winner]

samplesize = len(x_outputs)

local_dir = os.getcwd()
config_path = os.path.join(
    local_dir, "config-feedforward-mnist"+str(number_of_classification))
[stats, winner] = run(config_path)

config = neat.Config(
    neat.DefaultGenome,
    neat.DefaultReproduction,
    neat.DefaultSpeciesSet,
    neat.DefaultStagnation,
    config_path,
)
winner_net = neat.nn.FeedForwardNetwork.create(winner, config)

visualize.draw_net(config, winner, prune_unused=False)
visualize.plot_stats(stats, ylog=False, view=False)
visualize.plot_species(stats, view=False)


import numpy as np
import asyncio
import datetime as dt

from ..utils.spear3_api import within_spear3, _get_lifetime
from ..utils.spear3_lt_opt import _set_origin, x_to_pv

async def _get_objective(x, connection):
    assert len(x) == 13, 'Input dimension must be equal to 13'

    # set quadrupole PV values
    df = _set_origin(x.reshape(1, -1), connection)
    await asyncio.sleep(2)

    # calculate objective
    lifetime = await _get_lifetime(connection)
    obj = np.array([-lifetime])

    return obj

@within_spear3
async def get_objective(x, connection):
    return await _get_objective(x, connection)

def evaluator_generator(connection):
    async def evaluate(X, hook):
        assert type(X) == np.ndarray, 'Input X must be a numpy array'

        PV = x_to_pv(X)

        Y = np.zeros((PV.shape[0], 1))
        for i, pv in enumerate(PV):
            obj = await get_objective(pv, connection)
            finished_time = dt.datetime.now().strftime("%m-%d-%Y_%H-%M-%S")
            Y[i] = obj
            if hook:
                hook(pv, obj, finished_time)

        return Y

    return evaluate


import sys
import importlib

class LasyModule:
    def __init__(self, modulename):
        self.modulename = modulename
        self.module = None

    def __getattr__(self, attr):
        if self.module is None:
            try:
                self.module = importlib.import_module(self.modulename)
            except ImportError:
                print(f"LazyModule: {self.modulename} is missing.", file=sys.stderr)
                raise

        return self.module.__getattribute__(attr)

xarray = LasyModule('xarray')
diskcache = LasyModule('diskcache')


#recursion error handling
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

def dfs(x):
    global ans
    visit[x] = True
    cycle.append(x)
    num = selections[x]

    if visit[num]:
        if num in cycle:
            ans += cycle[cycle.index(num):]
        return
    else:
        dfs(num)

T = int(input())

for _ in range(T):
    n = int(input())
    selections = [0] + list(map(int, input().split()))
    visit = [False] * (n+1)
    ans = []

    for i in range(1, n+1):
        if not visit[i]:
            cycle = []
            dfs(i)

    print(n - len(ans))


import gamelib
import png
import diseño
import TP_3
from pila import Pila

ANCHO_GRILLA=400
ALTO_GRILLA=500

def paint_nuevo(ancho, alto):
    '''inicializa el deshacer del programa con una imagen vacía de ancho x alto'''
    paint=[]
    for i in range(alto):
        fila=[]
        for j in range(ancho):
            fila.append("#FFFFFF")
        paint.append(fila)
    return paint

def copiar_paint(paint):
    paint_copia=paint_nuevo(len(paint[0]),len(paint))
    for i in range(len(paint)):
        for j in range(len(paint[0])):
            paint_copia[i][j]=paint[i][j]
    return paint_copia

def png_aux(paint):
    contador=6
    colores={
        "#FFFFFF":0,
        "#000000":1,
        "#0000FF":2,
        "#FFFF00":3,
        "#FF0000":4,
        "#00FF00":5
    }
    paleta = [
    (255, 255, 255),
    (0, 0, 0),
    (0, 0, 255),
    (255, 255, 0),
    (255,0,0),
    (0,255,0)
    ]
    paint_aux=paint_nuevo(len(paint[0]),len(paint))
    for i in range(len(paint)):
        for j in range(len(paint[0])):
            if paint[i][j] in colores:
                paint_aux[i][j]=colores[paint[i][j]]
            else:
                colores[paint[i][j]]=contador
                contador+=1
                r,g,b=int(paint[i][j][1:3],16),int(paint[i][j][3:5],16),int(paint[i][j][5:7],16)
                paleta.append((r,g,b))
                paint_aux[i][j]=colores[paint[i][j]]
    return paint_aux,paleta

def guardar_png(paint):
    ruta=gamelib.input("¿Como quiere guardar la imagen?")
    paint_aux,paleta=png_aux(paint)
    png.escribir(f"{ruta}.png",paleta,paint_aux)

def guardar_ppm(paint):
    alto=len(paint)
    ancho=len(paint[0])
    while True:
        ruta = gamelib.input("Ingrese ruta")
        if ruta is None or ".ppm" not in ruta:
            gamelib.say("El archivo no es un PPM")
        else:
            break
    try:
        with open(ruta,"w")as arch:
            arch.write("P3"+"\n")
            arch.write(f'{alto} {ancho}'+"\n")
            arch.write("255"+"\n")
            for i in range(alto):
                for j in range(ancho):
                    arch.write(f'{int(paint[i][j][1:3],16)} {int(paint[i][j][3:5],16)} {int(paint[i][j][5:7],16)}'+"\n")
    except FileNotFoundError:
        gamelib.say("No existe el archivo")
    except TypeError:
        pass

def cargar_ppm(paint,deshacer,rehacer):
    while True:
        ruta = gamelib.input("Ingrese ruta")
        if not ruta is None and ".ppm" not in ruta :
            gamelib.say("El archivo no es un PPM")
            continue
        else:
            break
    try:
        with open(ruta, "r") as arch:
            next(arch)
            alto, ancho = arch.readline().split(" ")
            alto = int(alto)
            ancho = int(ancho)
            paint=paint_nuevo(ancho,alto)
            next(arch)
            for i in range(alto):
                for j in range(ancho):
                    colores = arch.readline().split()
                    r, g, b = f'{int(colores[0]):02x}',f'{int(colores[1]):02x}',f'{int(colores[2]):02x}'
                    paint[i][j]=f'#{r+g+b}'
    except FileNotFoundError:
        gamelib.say("No existe el archivo")
    except TypeError:
        pass
    while not rehacer.esta_vacia():
        rehacer.desapilar()
    while not deshacer.esta_vacia():
        deshacer.desapilar()
    #Elimine la apilacion en esta funcion
    return paint

def botones(paint,ev,deshacer,rehacer):
    if 450<=ev.y<=470 and 30<=ev.x<=120:
        gamelib.draw_rectangle(29,449,121,471,fill="black")
        diseño.boton_PNG()
        guardar_png(paint)
    elif 450<=ev.y<=470 and 150<=ev.x<=240:
        gamelib.draw_rectangle(149,449,241,471,fill="black")
        diseño.boton_gppm()
        guardar_ppm(paint)
    elif 450<=ev.y<=470 and 270<=ev.x<=360:
        gamelib.draw_rectangle(269,449,361,471,fill="black")
        diseño.boton_cppm()
        paint=cargar_ppm(paint,deshacer,rehacer)
    elif 410<=ev.y<=430 and 240<=ev.x<=260: #Nueva funcion
        #Agregue un mensaje para cuando el usuario apreta sobre el balde
        gamelib.say("Para utilizar el balde, utilice la rueda del raton")
    return paint

def verificar_color():
    hexadecimal="abcdefABCDEF0123456789"
    while True:
        color=gamelib.input("Ingrese color:")
        if color==None or len(color)!=6 or any(car not in hexadecimal for car in color):
            gamelib.say("Color incorrecto")
            continue
        else:
            break
    return color

def copiar_color(paint,fila,columna):
    return paint[fila][columna][1:]

def main():
    gamelib.title("AlgoPaint")
    gamelib.resize(ANCHO_GRILLA,ALTO_GRILLA)
    paint=paint_nuevo(4,4)
    color="ffffff"
    tecla="n"
    deshacer=Pila()
    rehacer=Pila()
    #Aca habia una apilacion que elimine
    while gamelib.loop(fps=15):
        diseño.paint_mostrar(paint)
        diseño.color_seleccionado(tecla,color)
        diseño.cuadros_colores(color)
        for ev in gamelib.get_events():
            if ev.type == gamelib.EventType.KeyPress:
                tecla=ev.key
                if tecla=="e":
                    color=verificar_color()
                    tecla=color
                elif tecla=="c":
                    tecla=color
                elif tecla=="z":
                    if not deshacer.esta_vacia():
                        paint=TP_3.deshacer_paint(deshacer,rehacer)
                #Agrego la tecla "n", para que el usuario pueda volver a pintar por lo menos con el color negro
                    tecla="n"
                elif tecla=="x":
                #Evite usar la tecla "y" para hacer rehacer. Era la misma que para el color amarillo
                    if not rehacer.esta_vacia():
                        paint=TP_3.rehacer_paint(rehacer,deshacer)
                    tecla="n"
            if ev.type == gamelib.EventType.ButtonPress:
                fila = ev.y // (400//len(paint))
                columna = ev.x // (400//len(paint[0]))
                if 0 <= fila < len(paint) and 0 <= columna < len(paint[0]) and ev.y<=400:
                    if ev.mouse_button==1:
                        #Vacio pila de rehacer y cambio el orden en donde apilo
                        while not rehacer.esta_vacia():
                            rehacer.desapilar()
                        paint_copia=copiar_paint(paint)
                        deshacer.apilar(paint_copia)
                        diseño.pintar(tecla,paint,fila,columna,color)
                    if ev.mouse_button==2: #El balde ahora es un evento de tipo 2 (rueda del mouse)
                        #Vacio pila de rehacer y cambio el orden en donde apilo
                        while not rehacer.esta_vacia():
                            rehacer.desapilar()
                        paint_copia=copiar_paint(paint)
                        deshacer.apilar(paint_copia)
                        TP_3.balde(tecla,paint,fila,columna)
                    if ev.mouse_button==3:
                        color=copiar_color(paint,fila,columna)
                        tecla=color
                paint=botones(paint,ev,deshacer,rehacer)

gamelib.init(main)


from lib.AuroraExtension import AuroraExtension
import time
import datetime
import numpy as np
import pandas as pd
import cv2

class Aurora_Rainbow(AuroraExtension):
    def __init__(self, NeoPixels, HDMI):
        super().__init__(NeoPixels, HDMI)
        self.Author = "Andrew MacPherson (@AndrewMohawk)"
        self.Description = "This extension displays a rainbow pattern on the LEDs, a lot of this code is from https://learn.adafruit.com/circuitpython-essentials/circuitpython-neopixel"
        self.Name = "Aurora Rainbow Display ( LED Only )"
        self.count = 0
        self.current_frame = False
        self.noHDMI = True

    def takeScreenShot(self, filepath):
        # We have no screenshot since... well its just LEDs
        return True

    def wheel(self, pos):
        # Input a value 0 to 255 to get a color value.
        # The colours are a transition r - g - b - back to r.
        if pos < 0 or pos > 255:
            return (0, 0, 0)
        if pos < 85:
            return (255 - pos * 3, pos * 3, 0)
        if pos < 170:
            pos -= 85
            return (0, 255 - pos * 3, pos * 3)
        pos -= 170
        return (pos * 3, 0, 255 - pos * 3)

    def rainbow_cycle(self, j):
        for i in range(self.pixelsCount):
            rc_index = (i * 256 // self.pixelsCount) + j
            self.pixels[i] = self.wheel(rc_index & 255)
        self.getFrame(False)  # hack to have 'FPS'
        self.pixels.show()

    def visualise(self):

        # visualise!
        self.count += 1
        self.rainbow_cycle(self.count)
        if self.count == 255:
            self.count = 0

        time.sleep(0.01)


from wagtail.core.models import Page

def is_donation_page(page_id):
    from .models import CampaignPage, LandingPage   # Avoid circular import
    try:
        page = Page.objects.live().get(pk=page_id).specific
    except Page.DoesNotExist:
        return False

    return page.__class__ in [CampaignPage, LandingPage]

def queue_ga_event(request, event_data):
    if 'ga_events' in request.session:
        request.session['ga_events'].append(event_data)
        request.session.modified = True
    else:
        request.session['ga_events'] = [event_data]

def queue_datalayer_event(request, event_data):
    request.session['datalayer_event'] = event_data
    request.session.modified = True


import openai as openai

from SmartFriend.helpers import MAKE_SUMMARY, OPENING_TEXT, BONUS_CONDITION, FALLBACK_TEXT

def fallback_for_ai(response, conversation):
    if "ai" in response.lower():
        conversation.append(
            {
                "role": "system",
                "content": FALLBACK_TEXT,
            }
        )

        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=conversation,
        )

        return response.choices[0].message.content

    return response

def get_response(conversation):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=conversation,
    )

    response = fallback_for_ai(
        response.choices[0].message.content,
        conversation
    )

    return response

def start_conversation(summary):
    conversation = [
        {
            'role': 'system',
            'content': BONUS_CONDITION + " " + summary,
        },
        {
            'role': 'system',
            'content': OPENING_TEXT,
        },
    ]

    return conversation

def post_summary(conversation):
    if conversation:
        result = {
            'role': 'system',
            'content': MAKE_SUMMARY
        }

        return result

    return ""


# coding: utf-8
import pprint
import re  # noqa: F401

import six
from enum import Enum
from schema.aws.kms.awsapicallviacloudtrail.AWSAPICallViaCloudTrailItem import AWSAPICallViaCloudTrailItem  # noqa: F401,E501
from schema.aws.kms.awsapicallviacloudtrail.Object import Object  # noqa: F401,E501
from schema.aws.kms.awsapicallviacloudtrail.RequestParameters import RequestParameters  # noqa: F401,E501
from schema.aws.kms.awsapicallviacloudtrail.UserIdentity import UserIdentity  # noqa: F401,E501

class AWSAPICallViaCloudTrail(object):

    _types = {
        'requestParameters': 'RequestParameters',
        'userIdentity': 'UserIdentity',
        'eventID': 'str',
        'awsRegion': 'str',
        'eventVersion': 'str',
        'responseElements': 'Object',
        'sourceIPAddress': 'str',
        'eventSource': 'str',
        'resources': 'list[AWSAPICallViaCloudTrailItem]',
        'userAgent': 'str',
        'readOnly': 'bool',
        'eventType': 'str',
        'requestID': 'str',
        'eventTime': 'datetime',
        'eventName': 'str'
    }

    _attribute_map = {
        'requestParameters': 'requestParameters',
        'userIdentity': 'userIdentity',
        'eventID': 'eventID',
        'awsRegion': 'awsRegion',
        'eventVersion': 'eventVersion',
        'responseElements': 'responseElements',
        'sourceIPAddress': 'sourceIPAddress',
        'eventSource': 'eventSource',
        'resources': 'resources',
        'userAgent': 'userAgent',
        'readOnly': 'readOnly',
        'eventType': 'eventType',
        'requestID': 'requestID',
        'eventTime': 'eventTime',
        'eventName': 'eventName'
    }

    def __init__(self, requestParameters=None, userIdentity=None, eventID=None, awsRegion=None, eventVersion=None, responseElements=None, sourceIPAddress=None, eventSource=None, resources=None, userAgent=None, readOnly=None, eventType=None, requestID=None, eventTime=None, eventName=None):  # noqa: E501
        self._requestParameters = None
        self._userIdentity = None
        self._eventID = None
        self._awsRegion = None
        self._eventVersion = None
        self._responseElements = None
        self._sourceIPAddress = None
        self._eventSource = None
        self._resources = None
        self._userAgent = None
        self._readOnly = None
        self._eventType = None
        self._requestID = None
        self._eventTime = None
        self._eventName = None
        self.discriminator = None
        self.requestParameters = requestParameters
        self.userIdentity = userIdentity
        self.eventID = eventID
        self.awsRegion = awsRegion
        self.eventVersion = eventVersion
        self.responseElements = responseElements
        self.sourceIPAddress = sourceIPAddress
        self.eventSource = eventSource
        self.resources = resources
        self.userAgent = userAgent
        self.readOnly = readOnly
        self.eventType = eventType
        self.requestID = requestID
        self.eventTime = eventTime
        self.eventName = eventName

    @property
    def requestParameters(self):

        return self._requestParameters

    @requestParameters.setter
    def requestParameters(self, requestParameters):

        self._requestParameters = requestParameters

    @property
    def userIdentity(self):

        return self._userIdentity

    @userIdentity.setter
    def userIdentity(self, userIdentity):

        self._userIdentity = userIdentity

    @property
    def eventID(self):

        return self._eventID

    @eventID.setter
    def eventID(self, eventID):

        self._eventID = eventID

    @property
    def awsRegion(self):

        return self._awsRegion

    @awsRegion.setter
    def awsRegion(self, awsRegion):

        self._awsRegion = awsRegion

    @property
    def eventVersion(self):

        return self._eventVersion

    @eventVersion.setter
    def eventVersion(self, eventVersion):

        self._eventVersion = eventVersion

    @property
    def responseElements(self):

        return self._responseElements

    @responseElements.setter
    def responseElements(self, responseElements):

        self._responseElements = responseElements

    @property
    def sourceIPAddress(self):

        return self._sourceIPAddress

    @sourceIPAddress.setter
    def sourceIPAddress(self, sourceIPAddress):

        self._sourceIPAddress = sourceIPAddress

    @property
    def eventSource(self):

        return self._eventSource

    @eventSource.setter
    def eventSource(self, eventSource):

        self._eventSource = eventSource

    @property
    def resources(self):

        return self._resources

    @resources.setter
    def resources(self, resources):

        self._resources = resources

    @property
    def userAgent(self):

        return self._userAgent

    @userAgent.setter
    def userAgent(self, userAgent):

        self._userAgent = userAgent

    @property
    def readOnly(self):

        return self._readOnly

    @readOnly.setter
    def readOnly(self, readOnly):

        self._readOnly = readOnly

    @property
    def eventType(self):

        return self._eventType

    @eventType.setter
    def eventType(self, eventType):

        self._eventType = eventType

    @property
    def requestID(self):

        return self._requestID

    @requestID.setter
    def requestID(self, requestID):

        self._requestID = requestID

    @property
    def eventTime(self):

        return self._eventTime

    @eventTime.setter
    def eventTime(self, eventTime):

        self._eventTime = eventTime

    @property
    def eventName(self):

        return self._eventName

    @eventName.setter
    def eventName(self, eventName):

        self._eventName = eventName

    def to_dict(self):
        result = {}

        for attr, _ in six.iteritems(self._types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(AWSAPICallViaCloudTrail, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        return self.to_str()

    def __eq__(self, other):
        if not isinstance(other, AWSAPICallViaCloudTrail):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other


import pandas as pd
import numpy as np
import time
import tqdm

# 时间处理
def process_time(train):
    print('时间处理...')
    st_times = list(train['time_stamp'].values)
    if np.nan in st_times:
        st_times.remove(np.nan)
    st_times = list(map(lambda x: time.strptime(x.split('.')[0], '%Y-%m-%d %H:%M'), st_times))
    time_min = []
    time_day = []
    #工作日是1，周末是0
    for timet in st_times:
        if timet.tm_wday==0 or timet.tm_wday==6:
            time_day.append(0)
        else:
            time_day.append(1)
        time_min.append(timet.tm_hour * 60 + timet.tm_min)
    train.loc[:, 'minutes'] = time_min
    train.loc[:, 'wday'] = time_day

    return train

def process_wifi(train):
    print('处理wifi...')
    wifi_infos=list(train['wifi_infos'].values)
    if np.nan in wifi_infos:
        wifi_infos.remove(np.nan)
    wifi_dis=[]
    for w in wifi_infos:
        w2=w.split(';')
        wifi_dis_detail={}
        for wifi_detail in w2:
            w3=wifi_detail.split('|')
            wifi_dis_detail[w3[0]]=float(w3[1])
        wifi_dis.append(wifi_dis_detail)
    train.loc[:,'wifi_dis']=wifi_dis

    return train

def set_wifi(x,dict_counts_shop,dict_avgdis_shop):
    if x[0] in dict_avgdis_shop:
        x['wifi_counts_shop']=str(dict_counts_shop[x[0]])
        x['wifi_avgdis_shop']=str(dict_avgdis_shop[x[0]])
    else:
        x['wifi_counts_shop']='{}'
        x['wifi_counts_shop']='{}'
    return x

# shop wifi地址统计 去除次数等于1的
def wifi_count(shop_info,df_train):
    dict_counts_shop={}
    dict_avgdis_shop={}
    limit=-90
    s_in_train=df_train['shop_id'].values
    wifi_in_train=df_train['wifi_infos'].values
    for i,s in enumerate(s_in_train):
        # if i>50000:
        #     break
        print(i)
        if s not in dict_counts_shop:
            dict_counts_shop[s]={}
            dict_avgdis_shop[s]={}
        w=wifi_in_train[i].split(';')
        wifi_ssid=[]
        wifi_dis=[]
        for ss in w:
            infos=ss.split('|')
            wifi_ssid.append(infos[0])
            wifi_dis.append(int(infos[1]))
        wifi_ssid=np.array(wifi_ssid)
        wifi_dis=np.array(wifi_dis)
        add_index=np.where(wifi_dis>limit)[0]
        wifi_ssid=wifi_ssid[add_index]
        wifi_dis=wifi_dis[add_index]
        for j,wi in enumerate(wifi_ssid):
            if wi not in dict_counts_shop[s]:
                dict_counts_shop[s][wi]=1
                dict_avgdis_shop[s][wi]=wifi_dis[j]
            else:
                dict_counts_shop[s][wi]+=1
                dict_avgdis_shop[s][wi]+= wifi_dis[j]

    # dict_avgdis_shop_backup={}
    # for k1 in dict_avgdis_shop:
    #     if k1 not in dict_avgdis_shop_backup:
    #         dict_avgdis_shop_backup[k1]={}
    #     for k2 in dict_avgdis_shop[k1]:
    #         dict_avgdis_shop_backup[k1][k2]=dict_avgdis_shop[k1][k2]
    for k1 in dict_avgdis_shop.keys():
        for k2 in dict_avgdis_shop[k1].keys():
            dict_avgdis_shop[k1][k2] /= dict_counts_shop[k1][k2]
    shop_info.loc[:,'wifi_counts_shop']=0
    shop_info.loc[:, 'wifi_avgdis_shop'] = 0
    shop_info=shop_info.apply(lambda x:set_wifi(x,dict_counts_shop,dict_avgdis_shop),axis=1)

    return shop_info

train_path='训练数据-ccf_first_round_user_shop_behavior.csv'
test_path='AB榜测试集-evaluation_public.csv'
shop_path='训练数据-ccf_first_round_shop_info.csv'
#时间处理
df_train=pd.read_csv(train_path)
# df_train=process_time(df_train)
# df_train=process_wifi(df_train)
# df_train.to_csv('train_data.csv',index=False)
#
# df_test=pd.read_csv(test_path)
# df_test=process_time(df_test)
# df_test=process_wifi(df_test)
# df_test.to_csv('test_data.csv',index=False)

#shop wifi统计
shop_info=pd.read_csv(shop_path)
shop_info=wifi_count(shop_info,df_train[(df_train['time_stamp'] < '2017-08-28 00:00:00')])
shop_info.to_csv('shop_info.csv',index=False)


import random
import time

SUIT_UNICODE = {
    "spades": chr(0x2664),
    "hearts": chr(0x2665),
    "diamonds": chr(0x2666),
    "clubs": chr(0x2667)
}

CARD_VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

class Card:
    def __init__(self, value, suit):
        self._suit = SUIT_UNICODE[suit]
        self._value = value
        self.is_hole = False;

    def __repr__(self):
        if self.is_hole:
            return "** "
        else:
            return self._value + self._suit + " "

class Deck():
    def __init__(self):
        self._cards = []
        for suit in SUIT_UNICODE:
            for value in CARD_VALUES:
                self._cards.append(Card(value, suit))
        self.shuffle()

        self.discarded_cards = []

    def shuffle(self):
        random.shuffle(self._cards)

    def deal_card(self):
        if not self._cards:
            self._cards = self.discarded_cards.copy()
            self.discarded_cards.clear()
            self.shuffle()
        return self._cards.pop()

    def __repr__(self):
        return str(self._cards)

class Hand():
    def __init__(self):
        self._cards = []
        self.hole_cards = []

    def add(self, card, is_hole=False):
        card.is_hole = is_hole
        self._cards.append(card)
        if is_hole:
            self.hole_cards.append(card)

    def __repr__(self):
        output = ""
        for card in self._cards:
            output += str(card) + " "
        return output

    def get_blackjack_val(self):
        tot = 0;
        for card in self._cards:
            royals = ['J', 'Q', 'K']
            if card._value in royals:
                tot += 10
            elif card._value != 'A':
                tot += int(card._value)
            else: # HANDLE ACE, CAN BE 1 OR 11
                if tot + 11 > 21:
                    tot += 1
                else:
                    tot += 11
        return tot

    def is_under(self):
        return self.get_blackjack_val() <= 21

    def reveal_hole_cards(self):
        for card in self.hole_cards:
            card.is_hole = False

    def discard(self, card, deck):
        card.is_hole = False
        self._cards.remove(card)
        deck.discarded_cards.append(card)

    def fold(self, deck):
        self.reveal_hole_cards()
        deck.discarded_cards.extend(self._cards.copy())
        self._cards.clear()

class Player:
    def __init__(self, buy_in):
        self.chips = buy_in
        self.bet = 0
        self.hand = Hand()

    def place_bet(self):
        while True:
            response = input("Place your bet: ")
            if response.isdigit():
                response = int(response)
                if response > self.chips:
                    print("You can't bet that much")
                else:
                    self.bet = response
                    return self.bet
            else:
                print("Enter a number")

class BlackjackGame:
    def __init__(self, buy_in):
        print("$" + str(buy_in) + " buy-in")
        self.dealer_hand = Hand()
        self.deck = Deck()
        self.buy_in = buy_in
        self.player = Player(self.buy_in)

    def start_round(self):
        if not self.player.chips:
            print("You have mortgaged you're house and now have $500")
            self.player.chips = 500

        self.player.place_bet()

        self._deal_cards()

        player_bust = self._prompt_player()

        if player_bust:
            print("Bust!")
            self.player.chips -= self.player.bet
            return self.end_game()

        dealer_bust = self._deal_with_dealer()

        if dealer_bust:
            print("Dealer busts. You win!")
            self.player.chips += self.player.bet
            return self.end_game()

        player_score = self.player.hand.get_blackjack_val()
        dealer_score = self.dealer_hand.get_blackjack_val()
        print("Player: " + str(player_score) + " Dealer: " + str(dealer_score))
        time.sleep(1)
        if player_score > dealer_score:
            print("You Win!")
            self.player.chips += self.player.bet
        elif player_score == dealer_score:
            print("Push")
        else:
            print("you lose")
            self.player.chips -= self.player.bet

        return self.end_game()

    def _deal_cards(self):
        self.player.hand.add(self.deck.deal_card())
        self.dealer_hand.add(self.deck.deal_card())
        self.player.hand.add(self.deck.deal_card())
        self.dealer_hand.add(self.deck.deal_card(), True)

        print("Player: " + str(self.player.hand))
        print("Dealer: " + str(self.dealer_hand))

    def _prompt_player(self):
        while self.player.hand.is_under():
            response = input("Hit or Stand? ").lower()

            if response == "hit" or response == "h":
                self.player.hand.add(self.deck.deal_card())
            elif response == "stand" or response == "s":
                return False
            else:
                print("Enter 'h' or 's'")
                continue

            print("Player: " + str(self.player.hand))
            time.sleep(1)

        return True

    def _deal_with_dealer(self):
        self.dealer_hand.reveal_hole_cards()
        print("Dealer: " + str(self.dealer_hand))
        time.sleep(1)

        while self.dealer_hand.get_blackjack_val() < 17:
            self.dealer_hand.add(self.deck.deal_card())
            print("Dealer: " + str(self.dealer_hand))
            time.sleep(1)

        return not self.dealer_hand.is_under()

    def end_game(self):
        self._turn_in_cards()
        return self._ask_play_again()

    def _turn_in_cards(self):
        self.player.hand.fold(self.deck)
        self.dealer_hand.fold(self.deck)

    def _ask_play_again(self):
        print("You have $" + str(self.player.chips))
        while True:
            play_again = input("Play again? ").lower()
            if play_again == "yes" or play_again == "y":
                return True
            elif play_again == "no" or play_again == "n":
                return False
            else:
                print("Enter 'y' or 'n'")


#!/home/mihaly/hadoop/anaconda3/bin/python
from random import randint
import time
def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 4096):
    res='{0:d}'.format(randint(1,1000))
    my_st = res+'\n'
    try:
        conn.send(my_st.encode("utf8"))
        return 0
    except:
        return -1

def start_server():

    import socket
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # this is for easy starting/killing the app
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print('Socket created')
    soc.bind(("localhost", 9000))
    print('Socket bind complete')
    #Start listening on socket
    soc.listen(10)
    print('Socket now listening')
    while True:
        conn, addr = soc.accept()
        ip, port = str(addr[0]), str(addr[1])
        print('Accepting connection from ' + ip + ':' + port)
        time.sleep(1)
        while True: #conn.__getstate__:
            if client_thread(conn, ip, port) != 0:
                break
            time.sleep(randint(0,1)*0.01)
            print(".", end='')
    soc.close()

start_server()


from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from tqdm import tqdm
from typing import List

import imageio
import os
import pandas as pd
import requests

PATH_FILE = os.path.dirname(os.path.abspath(__file__))
ARIAL_PATH = os.path.join(PATH_FILE, "arial.ttf")

def get_detections(oid: str) -> [dict, None]:
    url = f"https://api.alerce.online/ztf/v1/objects/{oid}/lightcurve"
    querystring = {"survey_id": "ztf"}
    payload = ""
    response = requests.request("GET", url, data=payload, params=querystring)
    if response.status_code == 200:
        data = response.json()
        detections = data["detections"]
        return detections
    return None

def get_stamp(oid: str, candid: str, source="science"):
    url = "https://avro.alerce.online/get_stamp"
    querystring = {"oid": oid, "candid": candid, "type": source, "format": "png"}
    payload = ""
    response = requests.request("GET", url, data=payload, params=querystring)
    if response.status_code == 200:
        img = Image.open(BytesIO(response.content))
        return img
    return None

def make_gif(oid: str, path: str = "./") -> List:
    detections = get_detections(oid)
    detections = pd.DataFrame(detections)
    detections.sort_values(by="mjd", inplace=True, ascending=True)
    t_0 = detections["mjd"].values[0]
    stamps = []

    progress_bar = tqdm(detections.iterrows(), total=len(detections))
    for i, d in progress_bar:
        progress_bar.set_description(f"Retrieving {oid}: {d['candid']}")
        stamp = get_stamp(oid, d["candid"])
        if stamp is not None:
            draw = ImageDraw.Draw(stamp)
            font = ImageFont.truetype(ARIAL_PATH, 20)
            mjd = d["mjd"]
            delta = mjd - t_0
            mjd = f"{mjd:0.5f} Δ{delta:0.3f}"
            draw.text((10, 10), mjd, (255, 255, 255), font=font)
            stamps.append(stamp)
    output_path = os.path.join(path, f"{oid}.gif")
    imageio.mimsave(output_path, stamps, duration=0.5)
    return stamps


################################################################################
# Author: Atharva Gunda
# Date: 11/22/2020
# This program prints the word frequency, common words, and uncommon words of two given text files.
################################################################################

from string import punctuation

def main():
    file1 = readFile('xian_1.txt')
    file2 = readFile('xian_2.txt')
    lib1 = toLibrary(file1)
    lib2 = toLibrary(file2)
    writeOutput(lib1, 'xian_1_word_frequency.txt')
    writeOutput(lib2, 'xian_2_word_frequency.txt')
    commonWords(lib1, lib2, 'common_words.txt')
    uncommonWords(lib1, lib2, 'eitherbutnotboth.txt')

def readFile(txt):
    fid = open(txt, 'r')
    lines = fid.readlines()
    lines = [sorted(i.split()) for i in lines]
    fid.close()

    return lines

def toLibrary(list):
    temp = []
    for i in range(len(list)):
        for j in range(len(list[i])):
            list[i][j] = list[i][j].lower().strip(punctuation)
            temp.append(list[i][j])
    temp = sorted(set(temp))
    counts = [0] * len(temp)
    for i in range(len(temp)):
        c = 0
        for j in range(len(list)):
            for k in range(len(list[j])):
                if(list[j][k] == temp[i]):
                    c += 1
        counts[i] = c

    return dict(zip(temp, counts))

def writeOutput(lib, txt):
    fid = open(txt, 'w')
    keys = lib.keys()
    for key in keys:
        fid.write(f'{key}: {lib.get(key)}\n')
    fid.close()

def commonWords(words1, words2, txt):
    fid = open(txt, 'w')
    common = sorted(set(words1.keys()) & set(words2.keys()))
    for word in common:
        fid.write(word + "\n")
    fid.close()

def uncommonWords(words1, words2, txt):
    fid = open(txt, 'w')
    common = sorted(set(words1.keys()) ^ set(words2.keys()))
    for word in common:
        fid.write(word + "\n")
    fid.close()

main()


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

from flask import request

from ApplicationExample import create_app

app = create_app()

@app.before_request
def before_request_api():
    """
    PC端app拦截器
    :return:
    """
    print('app app app app')
    path = request.path
    print(path)
    return


"""
Source: https://docs.python.org/2/library/sqlite3.html
This is an example implementation of a database.
In this program, a database will be initialized and filled with data.
Then, the data will be printed to the console.

Any changes to the database structure need to be committed into a new
database file. The old file will not accept changes to the structure of
data.
"""

import sqlite3

conn = sqlite3.connect("data_files/ex_database.db")
c = conn.cursor()

try:
    # Create table
    c.execute('''CREATE TABLE listings
              (sku INTEGER, title TEXT, price REAL)''')
except sqlite3.OperationalError:
    print("Skipping Creation of database file: Already Created.")

# # Never do this -- insecure!
# some_title = 'New Blue Shoes'
# c.execute("SELECT * FROM listings WHERE title = '%s'" % some_title)

# Do this instead
# t = ('RHAT',)
# c.execute('SELECT * FROM stocks WHERE symbol=?', t)
# print(c.fetchone())

# Larger example that inserts many records at a time
list_of_listings = [(1, 'Like-New Medium Blue Socks', 10.99),
                    (2, 'Used Small Lime Green Gloves', 11.99),
                    (3, 'New Medium Navy Blue Gloves', 12.99),
                    (4, 'Like-New Extra Large Brown Hat', 13.99),
                    ]

c.executemany('INSERT INTO listings VALUES (?,?,?)', list_of_listings)
conn.commit()  # Commit changes to database file.

for row in c.execute('SELECT * FROM listings ORDER BY price'):
    print(row)

conn.close()  # Close the connection to the database.


#Faça um programa que lê as duas notas parciais obtidas por um aluno numa disciplina ao longo de um semestre, e calcule a sua média. A atribuição de conceitos obedece à tabela abaixo:
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a Segunda nota: '))
media = (nota1 + nota2) / 2

if media >= 9.0:
    c = 'A'
elif media >= 7.5 and media < 9.0:
    c = 'B'
elif media >= 6.0 and media < 7.5:
    c = 'C'
elif media >= 4.0 and media < 6.0:
    c = 'D'
elif media >= 0 and media < 4.0:
    c = 'E'
if c in ("A","B","C"):
    resultado = "Aprovado!"
elif c in ("D", "E"):
    resultado = "Reprovado"

print('As notas P1: {} e P2 {}, são {} e voce foi {}'.format(nota1, nota2, c, resultado))


# pylint: skip-file
"""remove upload dir id from db

Revision ID: 83c0cf708bbd
Revises: 2c76c101e8eb
Create Date: 2020-05-18 16:34:10.195705

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '83c0cf708bbd'
down_revision = '2c76c101e8eb'
branch_labels = None
depends_on = None

def upgrade():
    op.drop_column('submission', 'upload_dir_id')

def downgrade():
    op.add_column('submission',
        sa.Column('upload_dir_id', sa.Integer)
    )


# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 16:19:55 2018

@author: nathaniel
@class: BMI650
@HW: NA
@title: Midterm review
"""

"""
Topics
- Code Documentation
    # docstrings
    # doc testing
    # PEP styles
- Data types
    - Numerical, Sequence types, Dictionaries
        #Numerical: int, float, imaginary
        #Sequence types: tuple (immutable) ,list (mutable) [] , string (immutable) str(), '', numpy array
        #Dictionaries: Set of keys mapped to value object ... {}
    - Mutable vs. Immutable
        # objects that can be modified after initialization are mutable
        # mutable objects are passed by reference
        # immutable objects are passed by copy
        # immuatable data types: <int>, <float>, <str> <tuple> - others?
        # mutable data types: <list>, <dict>, <set> - others?
"""
_set = set()
_dict = {} # or dict()
_list = [] # or list()
_tuple = (1,2,3)

_set.add(1)
_set.remove(1)

_dict['new key'] = 420
_dict['new key'] # 420

_list.append('first')
_list.append('mid')
_list.append('end')
end = _list.pop() # comes off the end (end)
first = _list.pop(0)

"""
- Python operators
    - Operator precedence
        # ??? mathamatical operators or logical operators ?
    - String formatting
        # r'string' -> gives raw output ???
        # h'string' -> hexadecimal ???
        # 'here is a string, here is a string formater, %s' %'some string'
        # 'another str, but with int: %d' %5
        # 'last one, with float! %f' %4.34
        # 'just kidding, a double with truncated float: %s %.1f' % ('added string',3.333333333)
- Control structures
    - if/else
        # ...
    - while and for loops
         # ...
- List comprehension
    # wrapped in brackets: [<operation> for <handle> in <iterable> if <logic>]
    # there is also dictionary comprehension
- File I/O
    # with open(path, 'w/r/a') as f:
- Functions / generators (know the difference)
    # function is executed completely before returning, generators maintain a state and *yield* a value every time they are called.
    # PRACTICE WITH THIS A BIT
"""
def myGen():
    a = list( range(10) )

    while (len(a) > 0):
        yield a.pop(0)

    yield -1

g = myGen()
for a in g:
    print(a)

"""
- Modules
    # import xxx
    # making your own module, make sure to add the: if __name__ == '__main__' : so as not to execute when imported.
- Regular Expressions
    # import re
    - Groups
        # you can group your findings by components - PRACTICE THIS
        # (...)
    - Sets
        # list functions
    - Meta-characters (^, *, +, etc.)
        # These should be memorized.
            # . : anything
            # * : any number of repitions?
            # ^
"""
print('---------------------')
import re
my_str_ = "+-0.01 % of people want ATTTCGGGCG to be in there bodyyyy IN MY BODDYYY"
a = re.finditer('(?P<plus_minus>(?P<first>[+-]?)(?P<second>[+-]?))[0-9]*.[0-9]', my_str_)

for found in a:
    print(found.group('plus_minus'))
    print(found.group('first'))
    print(found.group('second'))

"""
- OOP / Classes and methods
    - Features of the OOP paradigm
        # a class has attributes and functions, can extend and inherit from other objects
        - Inheritance, polymophism, encapsulation (mangling)
- Exceptions
    # assert logical "exception note"
    # try, except
    #
    class myException(Exception):
    '''This does not get printed, just doc string'''
        def __init__(self, vals_passed):

            '''this only needs to be definied if your passing variables to use in __str__'''

        def __str__(self):
            return 'this message'

    raise myException

- XML/HTML # yukkkkk <--------------------------------------------------------
    - Elementree
        # et.ElementTree()
        # reading... # review this
    - lxml
    - Basic Xpath syntax
"""


#!/usr/bin/env python

from flask import Flask, request, redirect, url_for, render_template
import rpyc

UPLOAD_FOLDER = '../uploads/'
ALLOWED_EXTENSIONS = set(['py', 'sh'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/',methods=['GET', 'POST'])
def node_page():
    if request.method == 'POST':
        return 'posted'

    c = rpyc.connect('localhost',18861)
    info = c.root.exposed_get_node_info()
    load = c.root.exposed_get_load()
    return render_template('index.html', info=info, load=load)

"""
@app.route('/node_info/')
@app.route('/submit_job/')
@app.route('/network_load/')
@app.route('/projects/')

def projects():
    return render_template('projects.html')

@app.route('/about')
def about():
    return 'render_template('about.html')
"""

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


'''
Very simple script to monitor the LiDAR temperature and status.
Can also toggle the LiDAR state to Run/Idle

Was a quick hack job... No guarantees are made about how well it all works

By Jasper Harvey - 17/10/2022
'''

import requests
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QPushButton, QVBoxLayout, QHBoxLayout, QLabel, QWidget, QApplication, QComboBox
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QFont

OFFLINE_DEBUG = False # For development when I dont have access to the LiDAR

class MainWindow(QMainWindow):

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

        self.api_url = "http://192.168.9.10:8007/"

        # Link api call and scan name
        # Typical way to call the API is playtable=playtable-[name].txt
        self.scanOptions = (
            ("128 Point", self.api_url + "playtable/set?playtable=playtable-128_point.txt"),
            ("1000 Point", self.api_url + "playtable/set?playtable=playtable-1000_point.txt"),
            ("128 Point Uniform", self.api_url + "playtable/set?playtable=playtable-128_Uniform.txt"),
            ("96 Point Uniform", self.api_url + "playtable/set?playtable=playtable-96_Uniform.txt"),
        )

        self.toggleButton = QPushButton("Run/Idle")
        self.toggleButton.setFont(QFont("Arial", 20))
        self.toggleButton.pressed.connect(self.toggleMode)

        self.modeBox = QComboBox()
        for item in self.scanOptions:
            self.modeBox.addItem(item[0])

        self.modeOk = QPushButton("Change Mode")
        self.modeOk.clicked.connect(self.changeScanMode)
        self.currentModeLabel = QLabel("Current Mode: \n96 Point")
        self.currentModeLabel.setFont(QFont("Arial", 14))
        modeLabel = QLabel("Set scan mode:")
        modeLabel.setFont(QFont("Arial", 14))

        self.mode = QLabel()
        self.mode.setFont(QFont("Arial", 20))
        self.tx_temp = QLabel()
        self.tx_temp.setFont(QFont("Arial", 20))
        self.rx_temp = QLabel()
        self.rx_temp.setFont(QFont("Arial", 20))
        self.processor_temp = QLabel()
        self.processor_temp.setFont(QFont("Arial", 20))

        Vlayout = QVBoxLayout()
        Vlayout.setSpacing(15)
        Vlayout.addWidget(self.toggleButton, alignment=Qt.AlignTop)
        Vlayout.addWidget(self.mode)
        Vlayout.addWidget(self.tx_temp)
        Vlayout.addWidget(self.rx_temp)
        Vlayout.addWidget(self.processor_temp)

        leftPanel = QWidget()
        leftPanel.setLayout(Vlayout)

        Vlayout = QVBoxLayout()
        Vlayout.addWidget(modeLabel, alignment=Qt.AlignTop)
        Vlayout.addWidget(self.modeBox, alignment=Qt.AlignTop)
        Vlayout.addWidget(self.modeOk)
        Vlayout.addWidget(self.currentModeLabel)
        Vlayout.setSpacing(15)
        Vlayout.addStretch(1)
        rightPanel = QWidget()
        rightPanel.setLayout(Vlayout)

        Hlayout = QHBoxLayout()
        Hlayout.addWidget(leftPanel)
        Hlayout.addWidget(rightPanel)

        w = QWidget()
        w.setLayout(Hlayout)

        self.setCentralWidget(w)
        self.show()

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.update_stats)
        self.timer.start()

    def update_stats(self):
        temps = self.get_temperature()
        mode = self.get_mode()

        tx_temp = temps["stat_tx_temp"]
        rx_temp = temps["stat_rx_temp"]
        proc_temp = temps["stat_proc_temp"]

        self.tx_temp.setText("TX Temp: " + str(tx_temp/100) + " C")
        self.rx_temp.setText("RX Temp: " + str(rx_temp/100) + " C")
        self.processor_temp.setText("Processor Temp: " + str(proc_temp/100) + " C")

        if proc_temp/100 > 70:
            self.processor_temp.setStyleSheet("background-color: red")
        if proc_temp/100 < 70:
            self.processor_temp.setStyleSheet("background-color: green")

        if mode["Error"] == 0:
            self.mode.setText("Mode: " + mode["Mode"])
        else:
            self.mode.setText("Mode: error" + mode["Error"])

        if mode["Mode"] == "Idle":
            self.mode.setStyleSheet("background-color: green")
        if mode["Mode"] == "Running":
            self.mode.setStyleSheet("background-color: red")

    def get_temperature(self):
        if OFFLINE_DEBUG:
            return {"stat_tx_temp": 2033,
                    "stat_rx_temp": 2213,
                    "stat_proc_temp" : 5535}

        reply = requests.get(self.api_url + "DeviceStatus/Get?stat_tx_temp&stat_rx_temp&stat_proc_temp")
        return reply.json()

    def get_mode(self):
        if OFFLINE_DEBUG:
            return {"Mode" : "Idle",
                    "Error" : 0}

        reply = requests.get(self.api_url + "Mode/Get")
        return reply.json()

    def toggleMode(self):
        current_mode = requests.get(self.api_url + "Mode/Get")

        if current_mode.json()["Mode"] == "Idle":
            change_mode = requests.get(self.api_url + "Mode/Set/Run")

        if current_mode.json()["Mode"] == "Running":
            change_mode = requests.get(self.api_url + "Mode/Set/Idle")

        # print(current_mode.json)

    def changeScanMode(self):
        currentIdx = self.modeBox.currentIndex()
        print(self.scanOptions[currentIdx])
        if OFFLINE_DEBUG:
            return

        try:
            option = self.scanOptions[currentIdx]
            change_mode = requests.post(option[1]).json()
            print(change_mode)

            for items in self.scanOptions:
                if change_mode["result"] in items[1]:
                    self.currentModeLabel.setText("Current Mode: \n" + items[0])

        except IndexError:
            print("Not implemented yet.")
            return

########### Main #############
if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    app.exec_()