# server.py v0.1
# Description:  A simple e2ee command line chat application. This is the server which will perform message exchanges.
# Changelog:    v0.1: Base Chat Server

import socket, threading

# Server Details
# Get the server's current IP address and ask user for the desired port to establish connection
server_ip = socket.gethostbyname(socket.gethostname())
port = int(input("Enter port number of the server: "))

# Socket Operations
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_ip, port))
server_socket.listen()

# Client Storage
client_list = []
client_name = []

# broadcast()
# Description:  Sends out the message to connected clients
# Args: message > Received message
def broadcast(message):
    for client in client_list:
        client.send(message)

# event_handler()
# Description:  Performs client connection checks and prints out its status.
# Args: client  > Server's Listener
def event_handler(client):
    while True:
        try:
            message = client.recv(4096)
            broadcast(message)
        except:
            index = client_list.index(client)
            client_list.remove(client)
            client.close()
            name = client_name[index]
            broadcast("{} left.".format(name).encode('ascii'))
            print("{} disconnected.".format(name))
            client_name.remove(name)
            break

# server_main()
# Description:  Handles system message printing/broadcasting for connectivity checks.
def server_main():
    while True:
        print("Server session initiated. ")
        print("Server IP address is " + server_ip + " with the port number of " + str(port) + ".")
        print("Checking for client connections.......")
        client, address = server_socket.accept()
        print("{} connected.".format(str(address)))
        client.send('NAME'.encode('ascii'))
        name = client.recv(4096).decode('ascii')
        client_name.append(name)
        client_list.append(client)
        print("Client Name: {}".format(name))
        broadcast("{} entered.".format(name).encode('ascii'))
        client.send('Connection Success.'.encode('ascii'))
        thread = threading.Thread(target=event_handler, args=(client,))
        thread.start()

# Run
server_main()


from tensorflow.dtensor.python import config as d_config
from tensorflow.dtensor.python import mesh_util
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute.experimental import dtensor_strategy_extended
from tensorflow.python.distribute.experimental import dtensor_util
from tensorflow.python.framework import device as tf_device

class MirroredStrategy(distribute_lib.Strategy):
  """Synchronous training across multiple replicas on one machine.

  This strategy is typically used for training on one machine with multiple
  accelerators (GPUs/TPUs).

  For example, a variable created under a `MirroredStrategy` is a distributed
  variable with layout replicated on each dimension. The variables will be
  placed on the `mesh` that is specified in the __init__.
  """

  def __init__(self, devices=None, cross_device_ops=None, *, mesh=None):
    """Synchronous training across multiple replicas on one machine.

    Args:
      devices: a list of device strings, such as ['/gpu:0', '/gpu:1']. If both
        `mesh` and `devices` are None, all the available GPU/TPU will be used.
        If no accelerators are found, CPU is used.
      cross_device_ops: optional, a descendant of `CrossDeviceOps`. The value is
        ignored at the moment, and support will be added later.
      mesh: optional DTensor mesh for the computation. Note that either `mesh`
        or `devices` should be provided, and not both. The mesh should be 1D,
        and will be used to split the input data among that dimension.
    """
    self._validate_init_args(mesh, devices)
    if not mesh:
      mesh = self._build_mesh_from_device_list(devices)

    extended = dtensor_strategy_extended.DTensorStrategyExtended(
        container_strategy=self, mesh=mesh)
    super().__init__(extended)
    self._mesh = mesh
    self._devices = devices

  @classmethod
  def _validate_init_args(cls, mesh, devices):
    if mesh and devices:
      raise ValueError('Mesh and devices can not be provided at the same time. '
                       f'received mesh = {mesh}, devices = {devices}')

    # For mirrored strategy, the mesh should be 1D, and only contains a batch
    # dimension, we will use that dimension to shard the inputs.
    if mesh and len(mesh.shape()) != 1:
      raise ValueError('The mesh for MirroredStrategy must be 1D, received: '
                       f'{len(mesh.shape())}D')

  @classmethod
  def _build_mesh_from_device_list(cls, devices):
    if devices:
      device_type = tf_device.DeviceSpec.from_string(devices[0]).device_type
      dtensor_util.initialize_accelerator_system_once(device_type)
      mesh = mesh_util.create_mesh(
          mesh_dims=[(dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, len(devices))],
          devices=devices)
    else:
      # Trying to detect if there is any GPU/TPUs attached.
      device_type = d_config.preferred_device_type()
      devices = d_config.local_devices(device_type)
      dtensor_util.initialize_accelerator_system_once(device_type)
      mesh = mesh_util.create_mesh(
          mesh_dims=[(dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, len(devices))],
          device_type=device_type)
    return mesh

  def reduce(self, reduce_op, value, axis):
    return dtensor_util.dtensor_reduce(self, reduce_op, value, axis)

  @property
  def mesh(self):
    """Returns the mesh used by the strategy."""
    return self._mesh


# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import random

from scrapy import signals
import pymysql

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter

class BossProDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    proxy_https = [
      "111.225.153.35:8089",
    ]
    user_agent_list = [
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 "
        "(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
        "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 "
        "(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 "
        "(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 "
        "(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 "
        "(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 "
        "(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
        "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 "
        "(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 "
        "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 "
        "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
    ]
    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    #用来拦截请求
    def process_request(self, request, spider):
        # UA 伪装
        request.headers['User-Agent'] = random.choice(self.user_agent_list)
        if request.url.split(":")[0] == 'https':
            request.meta['proxy'] = "https://" + random.choice(self.proxy_https)
        return None

    #拦截响应
    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        return response

    def process_exception(self, request, exception, spider):
        if request.url.split(":")[0] == 'https':
            request.meta['proxy'] = "https://" + random.choice(self.proxy_https)
        return request
    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


from parse import convert_to_graph, get_info
from rotation import randAngle, shuffleEdges, angleConvert, rotateGraph
from restore import restore
from plot import plot_graph_3d as plot

MIN_ANGLE = 0.0001745329252

if __name__ == '__main__':
    name = 'Antazoline'
    raw = get_info(name)
    graph = convert_to_graph(raw)
    graph.find_good_edges()

    vertices = graph.get_vertices()
    edges, vertex = graph.select_edges()
    edges = shuffleEdges(edges)
    angles = randAngle(len(edges))[1]
    rotated = rotateGraph(vertices, edges, angles, graph.bonds)

    res = restore(vertices, rotated, graph.bonds, vertex)
    restored = res[2]

    # Results output
    result = ''
    result += 'Vertex coordinates:\n'
    result +='{:31} {:37} {:30}\n'.format("INITIAL", "ROTATED", "RESTORED")
    for i in range(len(vertices)):
        v, n, r = vertices[i], map(lambda x: round(x, 6), rotated[i]), map(lambda x: round(x, 6), restored[i])
        result +='({:-8} {:-8} {:-8}) -> ({:-10} {:-10} {:-10}) -> ({:-10} {:-10} {:-10})\n'.format(*v, *n, *r)

    result += '\nInitial rotation angles:\n'
    result += '{:11} {:8} {:8}\n'.format("EDGE", "DEG", "RAD")
    for i in range(len(edges)):
        rad_angle, angle = angleConvert(angles[i], True, False), angleConvert(angles[i])
        result += '{:8} {:8}° {:10}rad\n'.format(str(edges[i]), angle, rad_angle)

    result += '\nRestored angles\n'
    result += '{:11} {:9} {:8}\n'.format("EDGE", "DEG", "RAD")
    for pair in zip(res[0], res[1]):
        if abs(pair[1]) < MIN_ANGLE: continue
        rad_angle, angle = angleConvert(pair[1], True, False), angleConvert(pair[1])
        result += '{:8} {:8}° {:10}rad\n'.format(str(pair[0]), angle, rad_angle)

    print(result)
    f = open("result/result.txt", "w")
    f.write(result)
    f.close()

    plot(graph, "init")
    graph.set_vertices(rotated)
    plot(graph, "rotated")
    graph.set_vertices(restored)
    plot(graph, "restored")


import tensorflow as tf

from .abstract_dataset_builder import AbstractDatasetBuilder

class BertTFRecordDatasetBuilder(AbstractDatasetBuilder):

    def __init__(self, max_sequence_length=512, max_predictions_per_seq=20, record_option=None, **kwargs):
        super().__init__(**kwargs)
        self.record_option = record_option
        self.max_sequence_length = max_sequence_length
        self.max_predictions_per_seq = max_predictions_per_seq

    def build_train_dataset(self, train_record_files, **kwargs):
        dataset = tf.data.TFRecordDataset(train_record_files, compression_type=self.record_option)
        dataset = dataset.repeat(self.train_repeat_count)
        dataset = dataset.shuffle(
            buffer_size=self.train_shuffle_buffer_size,
            seed=self.train_shuffle_seed,
            reshuffle_each_iteration=self.train_reshuffle_each_iteration)
        dataset = dataset.map(self._parse_example_fn, num_parallel_calls=self.num_parallel_calls)
        dataset = dataset.batch(
            self.train_batch_size, drop_remainder=self.train_drop_remainder
        ).prefetch(self.prefetch_size)
        dataset = dataset.map(lambda x, y, z, p, l: ((x, y, z), (p, l)))
        return dataset

    def build_valid_dataset(self, valid_record_files, **kwargs):
        if valid_record_files is None:
            return None
        dataset = tf.data.TFRecordDataset(valid_record_files, compression_type=self.record_option)
        dataset = dataset.repeat(self.valid_repeat_count)
        dataset = dataset.shuffle(
            buffer_size=self.valid_shuffle_buffer_size,
            seed=self.valid_shuffle_seed,
            reshuffle_each_iteration=self.valid_reshuffle_each_iteration
        )
        dataset = dataset.map(self._parse_example_fn, num_parallel_calls=self.num_parallel_calls)
        dataset = dataset.batch(
            self.valid_batch_size, drop_remainder=self.valid_drop_remainder
        ).prefetch(self.prefetch_size)
        dataset = dataset.map(lambda x, y, z, p, l: ((x, y, z), (p, l)))
        return dataset

    def build_predict_dataset(self, predict_record_files, **kwargs):
        dataset = tf.data.TFRecordDataset(predict_record_files, compression_type=self.record_option)
        dataset = dataset.repeat(self.predict_repeat_count)
        dataset = dataset.map(self._parse_example_fn)
        dataset = dataset.batch(
            self.predict_batch_size, drop_remainder=self.predict_drop_remainder
        ).prefetch(self.prefetch_size)
        dataset = dataset.map(lambda x, y, z, p, l: ((x, y, z), None))
        return dataset

    def _parse_example_fn(self, record):
        """Parse tfrecord to example. Change this parse process according to your record files format."""
        MAX_SEQ_LEN = self.max_sequence_length
        MAX_PREDICTIONS_PER_SEQ = self.max_predictions_per_seq
        name_to_features = {
            'original_ids': tf.io.FixedLenFeature([MAX_SEQ_LEN], tf.int64),
            'input_ids': tf.io.FixedLenFeature([MAX_SEQ_LEN], tf.int64),
            'input_mask': tf.io.FixedLenFeature([MAX_SEQ_LEN], tf.int64),
            'segment_ids': tf.io.FixedLenFeature([MAX_SEQ_LEN], tf.int64),
            'masked_lm_positions': tf.io.FixedLenFeature([MAX_PREDICTIONS_PER_SEQ], tf.int64),
            'masked_lm_ids': tf.io.FixedLenFeature([MAX_PREDICTIONS_PER_SEQ], tf.int64),
            'masked_lm_weights': tf.io.FixedLenFeature([MAX_PREDICTIONS_PER_SEQ], tf.float32),
            'next_sentence_labels': tf.io.FixedLenFeature([1], tf.int64),
        }

        example = tf.io.parse_single_example(record, name_to_features)
        # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
        # So cast all int64 to int32.
        for name in list(example.keys()):
            t = example[name]
            if t.dtype == tf.int64:
                t = tf.cast(t, tf.int32)
            example[name] = t

        # extract needed values from example to matching network's inputs and outputs
        # features = {
        #     'input_ids': example.get('input_ids', None),
        #     'input_mask': example.get('input_mask', None),
        #     'segment_ids': example.get('segment_ids', None),
        # }
        # labels = {
        #     'predictions': example['original_ids'],
        #     'relations': tf.one_hot(example['next_sentence_labels'], 2)
        # }
        input_ids = example['input_ids']
        input_mask = example['input_mask']
        segment_ids = example['segment_ids']
        predictions = example['original_ids']
        relations = example['next_sentence_labels']
        return (input_ids, input_mask, segment_ids, predictions, relations)


import os
import pandas as pd

# there are two knowledge graph relationships: subClasses & (transitive-)types
# this file checks all instances with the the instances in webisALOD

folderNameWeb = '/path/to/1_WebisALOD/tuplesdb_files/' # on hard drive
folderNameInstances = '/path/to/9_FINAL/data/sanitized/subclass_ontology0.csv'

webs = os.listdir(folderNameWeb)

folderNameOut = '/path/to/9_FINAL/data/matches/subclass/' # save matches

matches = 0

instances = pd.read_csv(folderNameInstances, sep=";")

for web in webs:
    print('Start to compare with {}'.format(web))

    compare = pd.read_csv(folderNameWeb + web, sep=',', encoding='utf-8', error_bad_lines=False)

    del compare['modifications']

    # matches by merge
    match = pd.merge(instances, compare, how='inner', left_on=['subClass', 'class'], right_on=['instance', 'class'])

    len_match = len(match)

    if len_match > 0:
        # found matches
        print('Successfully found {} matches with {}'.format(len_match, web))
        matches += len_match
        outName = web.replace('.csv', '_')
        match.to_csv(folderNameOut + outName + 'subclass_ontology0.csv', sep=";")

    print('------------------------------------')

print('Found {} matches in total.'.format(matches))


import random

liczba = random.randint(1,10)
wygrana = 0

for i in range(3):
    print('Próba numer: ', i+1)
    odp = input('O jakiej liczbie myślisz: ')
    if liczba == int(odp):
        wygrana = 1
        break
    else:
        print('Nie zgadłeś')
        if int(odp) < liczba:
            print('Podana liczba jest za mała')
        else:
            print('Podana liczba jest za duża')
    print()

if wygrana ==1:
    print('Zgadłeś, miałem na myśli: ', liczba)
else:
    print('Przegrałes miałem na myśli:', liczba)


import ssl
import socket
import time,datetime
import requests
from requests.exceptions import ReadTimeout
import json
import re
from json import JSONDecodeError
from config import *
from pyquery import PyQuery as pq

class Cert_check(object):
    def __init__(self,domain):
        self.domain = domain
        self.sslchaoshi = 'https://api-tools.sslchaoshi.com/ssltools/sslVerity'
        self.myssl = 'https://myssl.com/api/v1/ssl_status?domain=' + self.domain + '&port=443&c=0'
        self.data = {
            'endDate':None,
            'expire':None
        }

    def py_check(self):
        try:
            ctx = ssl.create_default_context()
            s = ctx.wrap_socket(socket.socket(), server_hostname=self.domain)
            s.settimeout(5)
            s.connect((self.domain, 443))
            cert = s.getpeercert()
            # 有效期结束
            notAfter = time.mktime(time.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z'))
            # 当前时间
            nowDate = time.time()
            # 时间差
            self.data['expire'] = int((notAfter - nowDate) / 3600 / 24)
            # 时间格式本地化
            self.data['endDate'] = time.strftime("%Y-%m-%d", time.localtime(notAfter))
            # print(self.domain,self.data)
            return self.data
        # except socket.gaierror as e:
        #     print(self.domain,e)
        # except socket.timeout as e:
        #     print(self.domain,e)
        # except ssl.SSLError as e:
        #     print(self.domain,e)
        # except ssl.CertificateError as e:
        #     print(self.domain,e)
        except Exception:
            chacuo_result = self.getChacuoPage()
            if chacuo_result:
                return chacuo_result

            myssl_result = self.getmyssl()
            if myssl_result:
                return myssl_result

            sslchaoshi_result = self.getsslchaoshi()
            if sslchaoshi_result:
                return sslchaoshi_result
            else:
                return self.data

    # 从 https://myssl.com/ 爬取证书信息
    def getmyssl(self):
        print("myssl正在解析：%s" % self.domain)

        # 构建请求url,并发送请求
        url = 'https://myssl.com/api/v1/ssl_status?domain=' + self.domain + '&port=443&c=0'
        try:
            response = requests.get(url, timeout=20)
        except ReadTimeout:
            return False

        # 挑选出证书信息的html
        try:
            CA_info_d = json.loads(response.text)
        except JSONDecodeError:
            return False

        # 如果CA_info_doc为空,证明获取证书信息失败
        if "data" in CA_info_d:
            try:
                valid_d = CA_info_d['data']["status"]["certs"]["rsas"][0]["leaf_cert_info"]
            except IndexError:
                valid_d = CA_info_d['data']["status"]["certs"]["eccs"][0]["leaf_cert_info"]
                return False
            except KeyError:
                return False

            endValid_s = valid_d["valid_to"].split("T")[0]
            endValid_l = endValid_s.split("-")
            endValid = datetime.datetime(int(endValid_l[0]), int(endValid_l[1]), int(endValid_l[2]))
            valid = endValid - datetime.datetime.today()
            self.data['endDate'] = endValid_s
            self.data['expire'] = valid.days
            return self.data
        else:
            return False

    def getsslchaoshi(self):
        print("sslchaoshi正在解析：%s" % self.domain)

        # 设置请求url和需要POST的数据,并发送POST请求,会返回一个字典
        url = "https://api-tools.sslchaoshi.com/ssltools/sslVerity"
        data = {'hostname': self.domain, "port": 443}
        try:
            response = requests.post(url, data, timeout=20)
        except ReadTimeout:
            return False

        ssl_data = json.loads(response.text)

        # 如果有cerInfo这个key,说明获取证书信息成功,
        if "cerInfo" in ssl_data:
            # 获取证书信息成功,构建正确证书信息字典,并存入mongoDB
            to = ssl_data["cerInfo"]['activeTimeStamp']["to"]
            restTime = ssl_data["cerInfo"]['activeTimeStamp']["restTime"]
            self.data['endDate'] = time.strftime("%Y-%m-%d", time.localtime(to))
            self.data['expire'] = int(re.sub(r"天", "", restTime))

            return self.data
        else:
            return False

    # 从 http://web.chacuo.net/netsslcheck 爬去证书信息
    def getChacuoPage(self):
        print("chacuo正在解析：%s" % self.domain)

        # 拼接url
        # domain是需要检测的域名
        url = "http://web.chacuo.net/netsslcheck?type=sslcheck&data=" + self.domain

        # 发送请求
        try:
            response = requests.get(url, timeout=20)
        except ReadTimeout:
            return False
        except ConnectionError:
            return False

        # 将返回内容转换为字典,如果出现JSONDecodeError就从新调用当前函数再请求一次
        try:
            data = json.loads(response.text)
        except JSONDecodeError:
            return False

        # 如果返回的字典里的data这个key没有值,说明获取证书信息失败,
        if len(data["data"][0]) == 0:
            return False
        domainInfo_list = []
        # 解析数据,将有值的数据追加到domainInfo_list中
        doc = pq(data['data'][0])
        for i in doc("tr").items():
            info = i.text().split("\n")
            if len(info) == 2:
                domainInfo_list.append(info)

        # 将domainInfo_list转换为字典,并插入domain字段,保存到mongodb中
        detail = dict(domainInfo_list)
        self.data['endDate'] = detail['有效时间：'].split("到")[1]
        self.data['expire'] = int(re.search(r"\d+", detail['过期时间：：']).group())
        return self.data

if __name__ == '__main__':
    response = requests.post("http://"+ SERVER +":"+ PORT +"/webmoni/api/domain_all/",data={'node':NODE})
    response_dict = json.loads(response.text)

    for domain_obj in response_dict['data']:

        obj = Cert_check(domain_obj['url'])
        data = obj.py_check()
        print(domain_obj['url'],data)


inputs = [line.strip().split() for line in open("../input/day02.txt").readlines()]

# column 1: A: rock ; B: paper ; C: scissors
# column 2: X: rock ; Y: paper ; Z: scissors

shape_score = {"X": 1, "Y": 2, "Z": 3}  # rock  # paper  # scissors

# A (rock): [Y(win|paper) X(draw|rock) Z(lose|scissors)]
outcome_map = {"A": ["Y", "X", "Z"], "B": ["Z", "Y", "X"], "C": ["X", "Z", "Y"]}

# win, draw, lose
outcome_score = [6, 3, 0]

# part 2
# column 2: X: lose ; Y: dray ; Z: win
strategy_map_scores = {"X": 0, "Y": 3, "Z": 6}

score1 = 0
score2 = 0
for opponent_shape, second_column in inputs:
    outcomes = outcome_map[opponent_shape]
    score1 += shape_score[second_column] + outcome_score[outcomes.index(second_column)]

    # part 2
    strategy_score = strategy_map_scores[second_column]
    my_shape = outcomes[
        outcome_score.index(strategy_score)
    ]  # win == first, draw == second, lose == third
    score2 += shape_score[my_shape] + strategy_score

print(score1)
print(score2)


import main
import matplotlib.pyplot as plt
import numpy as np
angles = []
dtheta = 3.14 / 100
theta = 0
F = np.zeros(int(main.T / main.dt) * 2 + 2)
modules = np.zeros(int(main.T / main.dt) + 1)
for i in range(0, int(main.T / main.dt)):
    if i<main.T/main.dt/6:
        F[2 * i], F[2 * i + 1] = np.cos(0), np.sin(0)
    else:
        F[2 * i], F[2 * i + 1] = np.cos(np.pi/2), np.sin(np.pi/2)
    modules[i] = np.linalg.norm([F[2 * i], F[2 * i + 1]])
F = F * main.g * main.isp * main.fuel / main.T
X = []
Y = []
for i in range(0,200):
    X.append(main.R * np.cos(theta))
    Y.append(main.R * np.sin(theta))
    theta += dtheta
u = main.values(F)
x = u[0]
y = u[1]
m = u[4]
t = np.linspace(0, main.T, np.size(m))
#plt.plot(t, m)
plt.plot(x, y)
plt.plot(X, Y)
plt.xlim(-10 * main.R, 10 * main.R)
plt.ylim(-10 * main.R, 10 * main.R)
plt.show()
print(main.q(main.final_values(F)))


from flask import Blueprint, request, jsonify
from flask_cors import cross_origin
from database_functions.db_connection.connection import connection
from database_functions.account.token_auth_flow import refresh_token
from database_functions.groups.insertion_functions import insert_into_group_table, insert_into_pending_requests_table
from database_functions.logs.recentLogs import insert_into_recent_table
from database_functions.groups.querying_functions import get_status_for_group, get_group_title, get_group_pending_users \
    , get_group_pending_state_machine
from database_functions.groups.updation_functions import update_group_status, add_new_pending_users_group,\
    update_pending_state_machine, resolve_admin_approval
from ast import literal_eval
from time import time

addUsersGroupApi = Blueprint('addUsersGroupApi', __name__)

# API to add users to a group
@addUsersGroupApi.route('/group/addUsersGroup', methods=['POST'])
@cross_origin()
def add_users_to_group():
    try:
        user_name = request.json['user_name']
        refresh_token(connection(), user_name)
        users = request.json['users']
        users = list(set(users))  # Avoid adding same users multiple times to the groups

        group_id = request.json['group_id']
        group_title = get_group_title(connection(), group_id)

        # updating list of pending users
        pending_users = get_group_pending_users(connection(), group_id)
        new_set_users = literal_eval(pending_users)
        new_set_users = list(set(new_set_users + users))
        add_new_pending_users_group(connection(), group_id, str(new_set_users))

        response = {'success': [], 'fail': []}

        if not group_title:
            return jsonify(False)
        for user in users:
            try:  # resolving admin approvals
                group_admin = request.json['group_admin']
                resolve_admin_approval(connection(), group_admin, "add", user, group_id)
            except:
                pass

            #  if user has rejected the group, or exited, or has been removed, update the status to pending
            if get_status_for_group(connection(), group_id, user, "rejected") or \
                    get_status_for_group(connection(), group_id, user, "removed") or \
                    get_status_for_group(connection(), group_id, user, "exited") or \
                    get_status_for_group(connection(), group_id, user, "pending") or \
                    get_status_for_group(connection(), group_id, user, "awaiting"):
                if get_status_for_group(connection(), group_id, user, "rejected") and \
                        get_group_pending_state_machine(connection(), user, group_id) >= 4:
                    # user has rejected the group too many times, can't be added
                    response['fail'].append(user)
                else:  # successfully add the user to the group
                    update_group_status(connection(), group_id, user, "pending")
                    response['success'].append(user)
            #  if user entry does not exist in the group, then add a new entry
            elif not get_status_for_group(connection(), group_id, user, "accepted"):
                response['success'].append(user)
                insert_into_pending_requests_table(connection(), group_id, user, "pending", 0)
        # adding transaction to logs

        if response['success']:
            message = "You added a few users to the group " + group_title + ". The users are: "
            message_description = response['success']
            insert_into_recent_table(connection(), user_name, str(time()), "6:Added users to group " + group_title,
                                     message + str(message_description))

        return jsonify(response)
    except:
        return jsonify(False)


from sqlalchemy import and_

import db
from db.models.alienvault import Hids_Agents

from apimethods.decorators import require_db

from apimethods.utils import get_bytes_from_uuid
from apimethods.utils import get_hex_string_from_uuid
from apimethods.utils import get_uuid_string_from_bytes

from apiexceptions.sensor import APICannotResolveSensorID
from apiexceptions.asset import APICannotResolveAssetID
from apiexceptions.hids import APICannotGetHIDSAgents
from apiexceptions.hids import APIInvalidHIDSAgentID
from apiexceptions.hids import APICannotAddHIDSAgent
from apiexceptions.hids import APICannotUpdateHIDSAgent
from apiexceptions.hids import APICannotDeleteHIDSAgent
from apiexceptions.hids import APICannotDeleteHIDSAgentList
from apiexceptions.hids import APICannotGetHIDSAgentByAsset

import api_log

@require_db
def get_hids_agents_by_asset(asset_id, sensor_id=None):
    """ Get HIDS agents by asset
    Args:
        asset_id(str): Asset ID
        sensor_id(str): Sensor ID
    Returns:
        Dictionary with HIDS agents related to asset in the database

    Raises:
        APICannotGetHIDSAgentByAsset
        APICannotResolveAssetID
    """

    hids_agents = {}

    if asset_id is None:
        api_log.error("[get_hids_agents_by_asset]: Asset ID could not be empty")
        raise APICannotResolveAssetID(asset_id)

    query = "SELECT HEX(ha.sensor_id) AS sensor_id, ha.agent_id, ha.agent_name, ha.agent_ip, " \
                "ha.agent_status, HEX(ha.host_id) AS host_id " \
                "FROM hids_agents ha WHERE ha.host_id = UNHEX('{0}')".format(get_hex_string_from_uuid(asset_id))

    if sensor_id is not None:
        query = query + " AND ha.sensor_id = UNHEX('{0}')".format(get_hex_string_from_uuid(sensor_id))

    try:
        ha_list = db.session.connection(mapper=Hids_Agents).execute(query)

        for hids_agent in ha_list:
            ha_id = hids_agent.agent_id
            ha_name = hids_agent.agent_name
            ha_ip = hids_agent.agent_ip
            ha_status = hids_agent.agent_status
            ha_sensor_id = hids_agent.sensor_id
            ha_host_id = hids_agent.host_id if hids_agent.host_id is not None else ''

            ha_key = ha_sensor_id + '#' + ha_id

            hids_agents[ha_key] = {
                'id': ha_id,
                'name': ha_name,
                'ip_cidr': ha_ip,
                'status': {
                    'id': ha_status,
                    'descr': Hids_Agents.get_status_string_from_integer(ha_status)
                },
                'sensor_id': ha_sensor_id,
                'host_id': ha_host_id
            }

    except Exception as msg:
        api_log.error("[get_hids_agents_by_asset]: %s" % str(msg))
        raise APICannotGetHIDSAgentByAsset(asset_id)

    return hids_agents

@require_db
def get_linked_assets():
    """ Get assets
    Returns:
        Dictionary with linked assets

    Raises:
        APICannotGetLinkedAssets
    """

    assets_ids = {}

    query = "SELECT ha.host_id AS host_id, ha.sensor_id AS sensor_id, ha.agent_id FROM hids_agents ha WHERE ha.host_id is not NULL"

    try:
        asset_list = db.session.connection(mapper=Hids_Agents).execute(query)

        for asset in asset_list:
            ha_id = asset.agent_id
            ha_sensor_id = asset.sensor_id
            ha_host_id = asset.host_id

            ha_host_id = get_uuid_string_from_bytes(ha_host_id)

            assets_ids[ha_host_id] = {
                'ha_id': ha_id,
                'sensor_id': get_uuid_string_from_bytes(ha_sensor_id)
            }

    except Exception as msg:
        api_log.error("[get_linked_assets]: %s" % str(msg))
        raise APICannotGetLinkedAssets()

    return assets_ids

@require_db
def get_hids_agents_by_sensor(sensor_id):
    """ Get HIDS agents by sensor
    Args:
        sensor_id(str): Sensor ID
    Returns:
        Dictionary with HIDS agents of the sensor in the database

    Raises:
        APICannotResolveSensorID
        APICannotGetHIDSAgents
    """

    hids_agents = {}

    if sensor_id is None:
        api_log.error("[get_hids_agents_by_sensor]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    try:
        sensor_id_hex = get_hex_string_from_uuid(sensor_id)
        query = "SELECT HEX(ha.sensor_id) AS sensor_id, ha.agent_id, ha.agent_name, ha.agent_ip, " \
                "ha.agent_status, HEX(ha.host_id) AS host_id " \
                "FROM hids_agents ha WHERE ha.sensor_id = UNHEX('{0}')".format(sensor_id_hex)
        ha_list = db.session.connection(mapper=Hids_Agents).execute(query)

        for hids_agent in ha_list:
            ha_id = hids_agent.agent_id
            ha_name = hids_agent.agent_name
            ha_ip = hids_agent.agent_ip
            ha_status = hids_agent.agent_status
            ha_host_id = hids_agent.host_id if hids_agent.host_id is not None else ''

            hids_agents[ha_id] = {
                'id': ha_id,
                'name': ha_name,
                'ip_cidr': ha_ip,
                'status': {
                    'id': ha_status,
                    'descr': Hids_Agents.get_status_string_from_integer(ha_status)
                },
                'host_id': ha_host_id
            }

    except Exception as msg:
        api_log.error("[get_hids_agents_by_sensor]: %s" % str(msg))
        raise APICannotGetHIDSAgents(sensor_id)

    return hids_agents

@require_db
def get_hids_agent_by_sensor(sensor_id, agent_id):
    """ Get HIDS agent by sensor
    Args:
        sensor_id(str): Sensor ID
        agent_id(str): Agent ID
    Returns:
        Dictionary with the HIDS agent of the sensor in the database

    Raises:
        APICannotResolveSensorID
        APIInvalidHIDSAgentID
        APICannotGetHIDSAgents
    """

    if sensor_id is None:
        api_log.error("[get_hids_agent_by_sensor]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    if agent_id is None:
        api_log.error("[get_hids_agent_by_sensor]: Agent ID could not be empty")
        raise APIInvalidHIDSAgentID(agent_id)

    hids_agent = {}

    try:
        sensor_id_hex = get_hex_string_from_uuid(sensor_id)

        query = "SELECT HEX(ha.sensor_id) AS sensor_id, ha.agent_id, ha.agent_name, ha.agent_ip, " \
                "ha.agent_status, HEX(ha.host_id) AS host_id " \
                "FROM hids_agents ha WHERE ha.sensor_id = UNHEX('{0}') AND ha.agent_id = '{1}' " \
                "LIMIT 1".format(sensor_id_hex, agent_id)

        ha_list = db.session.connection(mapper=Hids_Agents).execute(query).fetchall()

        if ha_list:
            ha_list = ha_list[0]

            ha_id = ha_list.agent_id
            ha_name = ha_list.agent_name
            ha_ip = ha_list.agent_ip
            ha_status = ha_list.agent_status
            ha_host_id = ha_list.host_id if ha_list.host_id is not None else ''

            hids_agent = {
                'id': ha_id,
                'name': ha_name,
                'ip_cidr': ha_ip,
                'status': {
                    'id': ha_status,
                    'descr': Hids_Agents.get_status_string_from_integer(ha_status)
                },
                'host_id': ha_host_id
            }
    except Exception as msg:
        api_log.error("[get_hids_agent_by_sensor]: %s" % str(msg))
        raise APICannotGetHIDSAgents(sensor_id)

    return hids_agent

@require_db
def delete_hids_agent(agent_id, sensor_id):
    """ Delete a HIDS agent
    Args:
        agent_id(str): HIDS agent ID
        sensor_id(str): Sensor ID

    Raises:
        APICannotResolveSensorID
        APIInvalidHIDSAgentID
        APICannotDeleteHIDSAgent
    """
    if sensor_id is None:
        api_log.error("[delete_hids_agent]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    if agent_id is None:
        api_log.error("[delete_hids_agent]: Agent ID could not be empty")
        raise APIInvalidHIDSAgentID(agent_id)

    try:
        sensor_id_bin = get_bytes_from_uuid(sensor_id)
        db.session.begin()
        db.session.query(Hids_Agents).filter(and_(Hids_Agents.agent_id == agent_id,
                                                  Hids_Agents.sensor_id == sensor_id_bin)).delete()
        db.session.commit()
    except Exception as msg:
        db.session.rollback()
        api_log.error("[delete_hids_agent] %s" % str(msg))
        raise APICannotDeleteHIDSAgent(agent_id, sensor_id)

@require_db
def delete_orphan_hids_agents(agent_list, sensor_id):
    """ Delete orphan HIDS agents
    Args:
        agent_list(list): List of active HIDS agents
        sensor_id(str): Sensor ID

    Raises:
        APICannotResolveSensorID
        APICannotDeleteHIDSAgentList
    """
    if sensor_id is None:
        api_log.error("[delete_orphan_hids_agents]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    try:
        if agent_list:
            q_agent_list = "'" + "','".join(agent_list) + "'"
            sensor_id_hex = get_hex_string_from_uuid(sensor_id)
            query = "DELETE FROM hids_agents WHERE sensor_id = UNHEX('{0}') " \
                    "AND agent_id NOT IN ({1})".format(sensor_id_hex, q_agent_list)
            db.sesion.begin()
            db.session.connection(mapper=Hids_Agents).execute(query)
            db.session.commit()

    except Exception as msg:
        db.session.rollback()
        api_log.error("[delete_orphan_hids_agents]: %s" % str(msg))
        raise APICannotDeleteHIDSAgentList(agent_list, sensor_id)

@require_db
def add_hids_agent(agent_id, sensor_id, agent_name, agent_ip, agent_status, host_id=None):
    """ Add a new HIDS agent

    Raises:
        APICannotResolveSensorID
        APIInvalidHIDSAgentID
        APICannotAddHIDSAgent
    """

    if sensor_id is None:
        api_log.error("[add_hids_agent]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    if agent_id is None:
        api_log.error("[add_hids_agent]: Agent ID could not be empty")
        raise APIInvalidHIDSAgentID(agent_id)

    try:
        db.session.begin()

        sensor_id_bin = get_bytes_from_uuid(sensor_id)

        if host_id:
            hex_id_bin = get_bytes_from_uuid(host_id)
        else:
            hex_id_bin = None

        status_integer = Hids_Agents.get_status_integer_from_string(agent_status)

        hids_agent = Hids_Agents()
        hids_agent.agent_id = agent_id
        hids_agent.sensor_id = sensor_id_bin
        hids_agent.agent_name = agent_name
        hids_agent.agent_ip = agent_ip
        hids_agent.agent_status = status_integer
        hids_agent.host_id = hex_id_bin

        db.session.merge(hids_agent)
        db.session.commit()
    except Exception as msg:
        db.session.rollback()
        api_log.error("[add_hids_agent]: %s" % str(msg))
        raise APICannotAddHIDSAgent(agent_id, sensor_id)

@require_db
def update_hids_agent_status(agent_id, sensor_id, agent_status):
    """ Update status of HIDS agent

    Raises:
        APICannotResolveSensorID
        APIInvalidHIDSAgentID
        APICannotUpdateHIDSAgent
    """

    if sensor_id is None:
        api_log.error("[update_hids_agent_status]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    if agent_id is None:
        api_log.error("[update_hids_agent_status]: Agent ID could not be empty")
        raise APIInvalidHIDSAgentID(agent_id)

    try:
        sensor_id_bin = get_bytes_from_uuid(sensor_id)
        status_integer = Hids_Agents.get_status_integer_from_string(agent_status)

        db.session.begin()
        db.session.query(Hids_Agents).filter(
            and_(Hids_Agents.agent_id == agent_id,
                 Hids_Agents.sensor_id == sensor_id_bin)).update({"agent_status": status_integer})
        db.session.commit()
    except Exception as msg:
        db.session.rollback()
        api_log.error("[update_hids_agent_status]: %s" % str(msg))
        raise APICannotUpdateHIDSAgent(agent_id, sensor_id)

@require_db
def update_asset_id(sensor_id, agent_id, asset_id):
    """ Update Asset ID related to agent

    Raises:
        APICannotResolveSensorID
        APIInvalidHIDSAgentID
        APICannotUpdateHIDSAgent
        APICannotResolveAssetID
    """

    if sensor_id is None:
        api_log.error("[update_asset_id]: Sensor ID could not be empty")
        raise APICannotResolveSensorID(sensor_id)

    if agent_id is None:
        api_log.error("[update_asset_id]: Agent ID could not be empty")
        raise APIInvalidHIDSAgentID(agent_id)

    if asset_id is None:
        api_log.error("[update_asset_id]: Asset ID could not be empty")
        raise APICannotResolveAssetID(asset_id)

    try:
        sensor_id_bin = get_bytes_from_uuid(sensor_id)
        asset_id_bin = get_bytes_from_uuid(asset_id)

        db.session.begin()
        db.session.query(Hids_Agents).filter(
            and_(Hids_Agents.agent_id == agent_id,
                 Hids_Agents.sensor_id == sensor_id_bin)).update({"host_id": asset_id_bin})
        db.session.commit()
    except Exception as msg:
        db.session.rollback()
        api_log.error("[update_asset_id]: %s" % str(msg))
        raise APICannotUpdateHIDSAgent(agent_id, sensor_id)


from unittest.mock import MagicMock
from flaskr.resources.drive_list_files import GoogleDrive

def test_list_files_success(monkeypatch):
    mock_get_creds = MagicMock(return_value={"message": "Conexão realizada com sucesso!"})
    monkeypatch.setattr("flaskr.resources.drive_list_files.GoogleDrive.get_creds", mock_get_creds)

    monkeypatch.setattr("flaskr.cloud.drive.GoogleDrive.get_folder_id_by_name", lambda x, y: "folder_id")
    monkeypatch.setattr("flaskr.cloud.drive.build", MagicMock())
    monkeypatch.setattr("builtins.open", MagicMock())
    monkeypatch.setattr("json.load", MagicMock())

    gd = GoogleDrive()
    gd.credentials = True

    result = gd.list_files()

    assert "files" in result


# https://youtu.be/IEEhzQoKtQU?t=1352

import concurrent.futures

import time
start = time.perf_counter()

def do_something(seconds):
    print(f"Sleeping {seconds} second(s)...")
    time.sleep(seconds)
    return f"Done sleeping... for sec={seconds}"

with concurrent.futures.ThreadPoolExecutor() as executor:

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

    list_futures_instances = [
        executor.submit(do_something, sec) for sec in seconds_list]

    # for f in concurrent.futures.as_completed(list_futures_instances):
    #     print(f.result())

    # here we needed to wait all 5 seconds for the result to be printed
    print([f.result() for f in list_futures_instances])

finish = time.perf_counter()

print(f"Finished in {round(finish - start, 4)} second(s)")


# Move Player Left/Right
def MovePlayerX():
    global PlayerX
    if inputToggleVar:
        if not (PlayerX == 4):
            PlayerX = PlayerX + 1
    elif not (PlayerX == 0):
        PlayerX = PlayerX - 1

# Move Player Up/Down
def MovePlayerY():
    global PlayerY
    if inputToggleVar:
        if not (PlayerY == 4):
            PlayerY = PlayerY + 1
    elif not (PlayerY == 0):
        PlayerY = PlayerY - 1

# Call Move CMD

def on_button_pressed_a():
    MovePlayerX()
    sendUserData()
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_ab():
    toggleInputType()
input.on_button_pressed(Button.AB, on_button_pressed_ab)

def on_button_pressed_b():
    MovePlayerY()
    sendUserData()
input.on_button_pressed(Button.B, on_button_pressed_b)

# Toggle Direction

def toggleInputType():
    global inputToggleVar
    inputToggleVar = not inputToggleVar

# Set varyables

PlayerX = 2
PlayerY = 2
inputToggleVar = True
OtherX = 2
OtherY = 2

# Start MultiPlayer

radio.set_transmit_power(5)
radio.set_group(194)

def verifiyConection():
    radio.send_value("ping", 0)

verifiyConection()

def sendUserData():
    radio.send_value("x", PlayerX)
    radio.send_value("y", PlayerY)

def getMultiPlayerData(name, value):
    global OtherX, OtherY
    if name == "x":
        OtherX = value
    elif name == "y":
        OtherY = value
    elif name == "ping":
        sendUserData()

radio.on_received_value(getMultiPlayerData)

# Run Loop

def startProgram():
    try:
        basic.clear_screen()
        led.plot_brightness(OtherX, OtherY, (255 / 2))
        led.plot(PlayerX, PlayerY)
    except:
        basic.show_string("Error On Startup")

basic.forever(startProgram)


#!/usr/bin/env python3
'''
Filename:
obtainMAData.py

Purpose:
This file is used to obtain and clean the data of new covid cases reported by
the state of Massachusetts. It will output the data into a file that can be
easily added to the database.

How to Execute:
$ python3 obtainMAData.py --output MAoutput.csv
'''

###################
# Import Libraries
###################

import sys
import argparse
import pandas as pd

############
# Main Code
############

def main():
    ''' Business Logic '''
    # Get command line arguments
    args = get_cli()
    print(f'The arguments are:\n{args}')

    # Make sure the output is acceptable
    if args.output == 'output.csv':
        print(f'{args.output} is already being used. Please try another filename',
              file=sys.stderr)
        sys.exit()

    # At some point here I want to add a web scraping function to download the
    # file from MA directly

    # Read in the worksheet
    ma_data = pd.read_excel(args.input, engine='openpyxl',
                            sheet_name='TestingByDate (Test Date)',
                            usecols='A, C:F, L, M, R, T')
    print(f'The data is:\n {ma_data.head()}')

def get_cli():
    '''
    Parameter: None
    Returns: cli (an instance of the command line arguments)
    Purpose: This function obtains the arguments passed into the command line
    '''
    parser = argparse.ArgumentParser(description = 'Clean MA Covid Data')

    # Add arguments
    parser.add_argument('-input', '--i', dest='input', type = str,
                        help = 'Name of file to download data into',
                        required = False,
                        default ='../data/covid-19-raw-data-12-27-2021.xlsx')

    parser.add_argument('-output', '--o', dest = 'output', type = str,
                        help = 'Name of Output File', required = False,
                        default = '../data/MAoutput.csv')

    return parser.parse_args()

if __name__ == '__main__':
    main()


import ast
import collections
import textwrap

import gast

from tensorflow.python.autograph.pyct import anno
from tensorflow.python.autograph.pyct import ast_util
from tensorflow.python.autograph.pyct import loader
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.autograph.pyct import pretty_printer
from tensorflow.python.autograph.pyct import qual_names
from tensorflow.python.platform import test

class AstUtilTest(test.TestCase):

  def assertAstMatches(self, actual_node, expected_node_src):
    expected_node = gast.parse('({})'.format(expected_node_src)).body[0]
    msg = 'AST did not match expected:\n{}\nActual:\n{}'.format(
        pretty_printer.fmt(expected_node),
        pretty_printer.fmt(actual_node))
    self.assertTrue(ast_util.matches(actual_node, expected_node), msg)

  def setUp(self):
    super(AstUtilTest, self).setUp()
    self._invocation_counts = collections.defaultdict(lambda: 0)

  def test_rename_symbols_basic(self):
    node = parser.parse('a + b')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.QN('a'): qual_names.QN('renamed_a')})
    source = parser.unparse(node, include_encoding_marker=False)
    expected_node_src = 'renamed_a + b'

    self.assertIsInstance(node.value.left.id, str)
    self.assertAstMatches(node, source)
    self.assertAstMatches(node, expected_node_src)

  def test_rename_symbols_attributes(self):
    node = parser.parse('b.c = b.c.d')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.from_str('b.c'): qual_names.QN('renamed_b_c')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'renamed_b_c = renamed_b_c.d')

  def test_rename_symbols_nonlocal(self):
    node = parser.parse('nonlocal a, b, c')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.from_str('b'): qual_names.QN('renamed_b')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'nonlocal a, renamed_b, c')

  def test_rename_symbols_global(self):
    node = parser.parse('global a, b, c')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.from_str('b'): qual_names.QN('renamed_b')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'global a, renamed_b, c')

  def test_rename_symbols_annotations(self):
    node = parser.parse('a[i]')
    node = qual_names.resolve(node)
    anno.setanno(node, 'foo', 'bar')
    orig_anno = anno.getanno(node, 'foo')

    node = ast_util.rename_symbols(node,
                                   {qual_names.QN('a'): qual_names.QN('b')})

    self.assertIs(anno.getanno(node, 'foo'), orig_anno)

  def test_rename_symbols_function(self):
    node = parser.parse('def f():\n  pass')
    node = ast_util.rename_symbols(node,
                                   {qual_names.QN('f'): qual_names.QN('f1')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'def f1():\n    pass')

  def test_copy_clean(self):
    node = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 1
    """))
    setattr(node, '__foo', 'bar')
    new_node = ast_util.copy_clean(node)
    self.assertIsNot(new_node, node)
    self.assertFalse(hasattr(new_node, '__foo'))

  def test_copy_clean_preserves_annotations(self):
    node = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 1
    """))
    anno.setanno(node, 'foo', 'bar')
    anno.setanno(node, 'baz', 1)
    new_node = ast_util.copy_clean(node, preserve_annos={'foo'})
    self.assertEqual(anno.getanno(new_node, 'foo'), 'bar')
    self.assertFalse(anno.hasanno(new_node, 'baz'))

  def test_keywords_to_dict(self):
    keywords = parser.parse_expression('f(a=b, c=1, d=\'e\')').keywords
    d = ast_util.keywords_to_dict(keywords)
    # Make sure we generate a usable dict node by attaching it to a variable and
    # compiling everything.
    node = parser.parse('def f(b): pass')
    node.body.append(ast.Return(d))
    result, _, _ = loader.load_ast(node)
    self.assertDictEqual(result.f(3), {'a': 3, 'c': 1, 'd': 'e'})

  def assertMatch(self, target_str, pattern_str):
    node = parser.parse_expression(target_str)
    pattern = parser.parse_expression(pattern_str)
    self.assertTrue(ast_util.matches(node, pattern))

  def assertNoMatch(self, target_str, pattern_str):
    node = parser.parse_expression(target_str)
    pattern = parser.parse_expression(pattern_str)
    self.assertFalse(ast_util.matches(node, pattern))

  def test_matches_symbols(self):
    self.assertMatch('foo', '_')
    self.assertNoMatch('foo()', '_')
    self.assertMatch('foo + bar', 'foo + _')
    self.assertNoMatch('bar + bar', 'foo + _')
    self.assertNoMatch('foo - bar', 'foo + _')

  def test_matches_function_args(self):
    self.assertMatch('super(Foo, self).__init__(arg1, arg2)',
                     'super(_).__init__(_)')
    self.assertMatch('super().__init__()', 'super(_).__init__(_)')
    self.assertNoMatch('super(Foo, self).bar(arg1, arg2)',
                       'super(_).__init__(_)')
    self.assertMatch('super(Foo, self).__init__()', 'super(Foo, _).__init__(_)')
    self.assertNoMatch('super(Foo, self).__init__()',
                       'super(Bar, _).__init__(_)')

  def _mock_apply_fn(self, target, source):
    target = parser.unparse(target, include_encoding_marker=False)
    source = parser.unparse(source, include_encoding_marker=False)
    self._invocation_counts[(target.strip(), source.strip())] += 1

  def test_apply_to_single_assignments_dynamic_unpack(self):
    node = parser.parse('a, b, c = d')
    ast_util.apply_to_single_assignments(node.targets, node.value,
                                         self._mock_apply_fn)
    self.assertDictEqual(self._invocation_counts, {
        ('a', 'd[0]'): 1,
        ('b', 'd[1]'): 1,
        ('c', 'd[2]'): 1,
    })

  def test_apply_to_single_assignments_static_unpack(self):
    node = parser.parse('a, b, c = d, e, f')
    ast_util.apply_to_single_assignments(node.targets, node.value,
                                         self._mock_apply_fn)
    self.assertDictEqual(self._invocation_counts, {
        ('a', 'd'): 1,
        ('b', 'e'): 1,
        ('c', 'f'): 1,
    })

  def test_parallel_walk(self):
    src = """
      def f(a):
        return a + 1
    """
    node = parser.parse(textwrap.dedent(src))
    for child_a, child_b in ast_util.parallel_walk(node, node):
      self.assertEqual(child_a, child_b)

  def test_parallel_walk_string_leaves(self):
    src = """
      def f(a):
        global g
    """
    node = parser.parse(textwrap.dedent(src))
    for child_a, child_b in ast_util.parallel_walk(node, node):
      self.assertEqual(child_a, child_b)

  def test_parallel_walk_inconsistent_trees(self):
    node_1 = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 1
    """))
    node_2 = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + (a * 2)
    """))
    node_3 = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 2
    """))
    with self.assertRaises(ValueError):
      for _ in ast_util.parallel_walk(node_1, node_2):
        pass
    # There is not particular reason to reject trees that differ only in the
    # value of a constant.
    # TODO(mdan): This should probably be allowed.
    with self.assertRaises(ValueError):
      for _ in ast_util.parallel_walk(node_1, node_3):
        pass

  def assertLambdaNodes(self, matching_nodes, expected_bodies):
    self.assertEqual(len(matching_nodes), len(expected_bodies))
    for node in matching_nodes:
      self.assertIsInstance(node, gast.Lambda)
      self.assertIn(
          parser.unparse(node.body, include_encoding_marker=False).strip(),
          expected_bodies)

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


import string
from copy import copy
from random import sample

import numpy as np
import pytest

import filter_functions as ff
from filter_functions import numeric
from tests import testutil
from tests.testutil import rng

from . import qutip

plotting = pytest.importorskip('filter_functions.plotting',
                               reason='Skipping plotting tests for build without matplotlib')
if plotting is not None:
    import matplotlib.pyplot as plt
    from matplotlib import cycler

simple_pulse = testutil.rand_pulse_sequence(2, 1, 1, 1, btype='Pauli')
complicated_pulse = testutil.rand_pulse_sequence(2, 100, 3, 3)
two_qubit_pulse = testutil.rand_pulse_sequence(4, 1, 1, 6, btype='Pauli')

class PlottingTest(testutil.TestCase):

    def test_plot_pulse_train(self):
        # Call with default args
        fig, ax, leg = plotting.plot_pulse_train(simple_pulse)

        # Call with no axes but figure
        fig = plt.figure()
        fig, ax, leg = plotting.plot_pulse_train(simple_pulse, fig=fig)

        # Call with axes but no figure
        fig, ax, leg = plotting.plot_pulse_train(simple_pulse, axes=ax)

        # Call with custom args
        c_oper_identifiers = sample(
            complicated_pulse.c_oper_identifiers.tolist(), rng.integers(2, 4)
        )

        fig, ax = plt.subplots()
        fig, ax, leg = plotting.plot_pulse_train(complicated_pulse,
                                                 c_oper_identifiers,
                                                 fig=fig, axes=ax)

        # Test cycler arg
        cycle = cycler(color=['r', 'g', 'b'])
        fig, ax, leg = plotting.plot_pulse_train(simple_pulse, cycler=cycle)

        # invalid identifier
        with self.assertRaises(ValueError):
            plotting.plot_pulse_train(complicated_pulse,
                                      c_oper_identifiers=['foo'],
                                      fig=fig, axes=ax)

        # Test various keyword args for matplotlib
        plot_kw = {'linewidth': 1}
        subplot_kw = {'facecolor': 'r'}
        gridspec_kw = {'hspace': 0.2,
                       'wspace': 0.1}
        figure_kw = {'num': 1}

        fig, ax, leg = plotting.plot_pulse_train(simple_pulse, plot_kw=plot_kw,
                                                 subplot_kw=subplot_kw,
                                                 gridspec_kw=gridspec_kw,
                                                 **figure_kw)

        plt.close('all')

    def test_plot_filter_function(self):
        # Call with default args
        simple_pulse.cleanup('all')
        fig, ax, leg = plotting.plot_filter_function(simple_pulse)

        # Call with no axes but figure
        fig = plt.figure()
        fig, ax, leg = plotting.plot_filter_function(simple_pulse, fig=fig)

        # Call with axes but no figure
        fig, ax, leg = plotting.plot_filter_function(simple_pulse, axes=ax)

        # Non-default args
        n_oper_identifiers = sample(
            complicated_pulse.n_oper_identifiers.tolist(), rng.integers(2, 4)
        )

        fig, ax = plt.subplots()
        omega = ff.util.get_sample_frequencies(complicated_pulse, n_samples=50,
                                               spacing='log')
        fig, ax, leg = plotting.plot_filter_function(
            complicated_pulse, omega=omega,
            n_oper_identifiers=n_oper_identifiers,
            fig=fig, axes=ax, omega_in_units_of_tau=False
        )

        # Test cycler arg
        cycle = cycler(color=['r', 'g', 'b'])
        fig, ax, leg = plotting.plot_filter_function(simple_pulse, cycler=cycle)

        # invalid identifier
        with self.assertRaises(ValueError):
            plotting.plot_filter_function(complicated_pulse,
                                          n_oper_identifiers=['foo'],
                                          fig=fig, axes=ax)

        # Test different axis scales
        scales = ('linear', 'log')
        for xscale in scales:
            for yscale in scales:
                fig, ax, leg = plotting.plot_filter_function(simple_pulse,
                                                             xscale=xscale,
                                                             yscale=yscale)

        # Test various keyword args for matplotlib
        plot_kw = {'linewidth': 1}
        subplot_kw = {'facecolor': 'r'}
        gridspec_kw = {'hspace': 0.2,
                       'wspace': 0.1}
        figure_kw = {'num': 1}
        fig, ax, leg = plotting.plot_filter_function(simple_pulse,
                                                     plot_kw=plot_kw,
                                                     subplot_kw=subplot_kw,
                                                     gridspec_kw=gridspec_kw,
                                                     **figure_kw)

        plt.close('all')

    @pytest.mark.filterwarnings('ignore::UserWarning')  # tight_layout warning
    def test_plot_pulse_correlation_filter_function(self):
        omega = np.linspace(-1, 1, 50)
        concatenated_simple_pulse = ff.concatenate(
            (simple_pulse, simple_pulse),
            calc_pulse_correlation_FF=True,
            omega=omega
        )
        concatenated_complicated_pulse = ff.concatenate(
            (complicated_pulse, complicated_pulse),
            calc_pulse_correlation_FF=True,
            omega=omega
        )

        # Exception if not pulse correl. FF is cached
        with self.assertRaises(ff.util.CalculationError):
            plotting.plot_pulse_correlation_filter_function(simple_pulse)

        # Call with default args
        fig, ax, leg = plotting.plot_pulse_correlation_filter_function(
            concatenated_simple_pulse
        )

        # Non-default args
        n_oper_identifiers = sample(
            complicated_pulse.n_oper_identifiers.tolist(), rng.integers(2, 4)
        )

        fig, ax = plt.subplots()
        omega = np.linspace(-10, 10, 50)
        fig, ax, leg = plotting.plot_pulse_correlation_filter_function(
            concatenated_complicated_pulse, omega=omega,
            n_oper_identifiers=n_oper_identifiers, fig=fig,
            omega_in_units_of_tau=False
        )

        # Test cycler arg
        cycle = cycler(color=['r', 'g', 'b'])
        fig, ax, leg = plotting.plot_pulse_correlation_filter_function(concatenated_simple_pulse,
                                                                       cycler=cycle)

        # invalid identifiers
        with self.assertRaises(ValueError):
            plotting.plot_pulse_correlation_filter_function(
                concatenated_complicated_pulse,
                n_oper_identifiers=['foo'], fig=fig, axes=ax
            )

        # Test different axis scales
        scales = ('linear', 'log')
        for xscale in scales:
            for yscale in scales:
                fig, ax, leg = plotting.plot_pulse_correlation_filter_function(
                    concatenated_simple_pulse, xscale=xscale, yscale=yscale
                )

        # Test various keyword args for matplotlib
        plot_kw = {'linewidth': 1}
        subplot_kw = {'facecolor': 'r'}
        gridspec_kw = {'hspace': 0.2,
                       'wspace': 0.1}
        figure_kw = {'num': 1}
        fig, ax, leg = plotting.plot_pulse_correlation_filter_function(
            concatenated_simple_pulse, plot_kw=plot_kw, subplot_kw=subplot_kw,
            gridspec_kw=gridspec_kw, **figure_kw
        )

        plt.close('all')

    # Ignore deprecation warning caused by qutip
    @pytest.mark.filterwarnings('ignore::PendingDeprecationWarning')
    def test_plot_cumulant_function(self):
        omega = ff.util.get_sample_frequencies(simple_pulse)
        spectrum = 1e-4*np.sin(omega)/omega

        # Test calling with pulse, spectrum, omega
        fig, grid = plotting.plot_cumulant_function(simple_pulse, spectrum, omega,
                                                    colorscale='linear')
        fig, grid = plotting.plot_cumulant_function(simple_pulse, spectrum, omega, fig=fig)
        fig, grid = plotting.plot_cumulant_function(simple_pulse, spectrum, omega, grid=grid)

        # Test calling with precomputed transfer matrix
        K = numeric.calculate_cumulant_function(simple_pulse, spectrum, omega)
        fig, grid = plotting.plot_cumulant_function(cumulant_function=K)

        # Test calling with precomputed transfer matrix and pulse
        K = numeric.calculate_cumulant_function(simple_pulse, spectrum, omega)
        fig, grid = plotting.plot_cumulant_function(simple_pulse, cumulant_function=K)

        # Test calling with precomputed transfer matrix of ndim == 2
        K = numeric.calculate_cumulant_function(simple_pulse, spectrum, omega)
        fig, grid = plotting.plot_cumulant_function(cumulant_function=K[0])

        # Log colorscale
        fig, grid = plotting.plot_cumulant_function(cumulant_function=K, colorscale='log')

        # Non-default args
        n_oper_inds = sample(range(len(complicated_pulse.n_opers)), rng.integers(2, 4))
        n_oper_identifiers = complicated_pulse.n_oper_identifiers[n_oper_inds]

        basis_labels = []
        for i in range(4):
            basis_labels.append(string.ascii_uppercase[rng.integers(0, 26)])

        omega = ff.util.get_sample_frequencies(complicated_pulse, n_samples=50, spacing='log')
        spectrum = np.exp(-omega**2)
        K = numeric.calculate_cumulant_function(complicated_pulse, spectrum, omega)
        fig, grid = plotting.plot_cumulant_function(
            complicated_pulse, spectrum=spectrum, omega=omega,
            n_oper_identifiers=n_oper_identifiers, basis_labels=np.array(basis_labels),
            basis_labelsize=4, linthresh=1e-4, cmap=plt.cm.jet
        )
        fig, grid = plotting.plot_cumulant_function(
            cumulant_function=K[n_oper_inds], n_oper_identifiers=n_oper_identifiers,
            basis_labels=basis_labels, basis_labelsize=4, linthresh=1e-4,
            cmap=plt.cm.jet
        )

        # neither K nor all of pulse, spectrum, omega given
        with self.assertRaises(ValueError):
            plotting.plot_cumulant_function(complicated_pulse, spectrum)

        # invalid identifiers
        with self.assertRaises(ValueError):
            plotting.plot_cumulant_function(complicated_pulse, spectrum, omega,
                                            n_oper_identifiers=['foo'])

        # K and identifiers given but unequal length
        with self.assertRaises(ValueError):
            plotting.plot_cumulant_function(cumulant_function=K,
                                            n_oper_identifiers=n_oper_identifiers[0])

        # number of basis_labels not correct
        with self.assertRaises(ValueError):
            plotting.plot_cumulant_function(complicated_pulse, spectrum, omega,
                                            basis_labels=basis_labels[:2])

        # grid too small
        with self.assertRaises(ValueError):
            plotting.plot_cumulant_function(complicated_pulse, spectrum, omega,
                                            grid=grid[:1])

        # Test various keyword args for matplotlib for the two-qubit pulse
        spectrum = np.tile(spectrum, (6, 6, 1))
        grid_kw = {'axes_pad': 0.1}
        cbar_kw = {'orientation': 'horizontal'}
        imshow_kw = {'interpolation': 'bilinear'}
        figure_kw = {'num': 1}
        fig, ax = plotting.plot_cumulant_function(two_qubit_pulse, spectrum, omega,
                                                  imshow_kw=imshow_kw, grid_kw=grid_kw,
                                                  cbar_kw=cbar_kw, **figure_kw)

        plt.close('all')

    def test_plot_infidelity_convergence(self):
        n, infids = ff.infidelity(simple_pulse, lambda x: x**0, {}, test_convergence=True)
        fig, ax = plotting.plot_infidelity_convergence(n, infids)

        fig, ax = plt.subplots(1, 2)
        cfig, ax = plotting.plot_infidelity_convergence(n, infids, ax)
        self.assertIs(cfig, fig)

class LaTeXRenderingTest(testutil.TestCase):

    def test_plot_filter_function(self):
        pulse = copy(simple_pulse)
        pulse.c_oper_identifiers = np.array([f'B_{i}' for i in range(len(pulse.c_opers))])
        pulse.n_oper_identifiers = np.array([f'B_{i}' for i in range(len(pulse.n_opers))])
        with plt.rc_context(rc={'text.usetex': True}):
            _ = plotting.plot_pulse_train(pulse)
            _ = plotting.plot_filter_function(pulse)

@pytest.mark.skipif(
    qutip is None,
    reason='Skipping bloch sphere visualization tests for build without qutip')
class BlochSphereVisualizationTest(testutil.TestCase):

    def test_get_bloch_vector(self):
        states = [qutip.rand_ket(2) for _ in range(10)]
        bloch_vectors_qutip = plotting.get_bloch_vector(states)
        bloch_vectors_np = plotting.get_bloch_vector([state.full()
                                                      for state in states])

        for bv_qutip, bv_np in zip(bloch_vectors_qutip, bloch_vectors_np):
            self.assertArrayAlmostEqual(bv_qutip, bv_np)

    def test_get_states_from_prop(self):
        P = testutil.rand_unit(2, 10)
        Q = np.empty((11, 2, 2), dtype=complex)
        Q[0] = np.identity(2)
        for i in range(10):
            Q[i+1] = P[i] @ Q[i]

        psi0 = qutip.rand_ket(2)
        psi0_np = psi0.full()
        states = plotting.get_states_from_prop(Q, psi0)
        states_np = plotting.get_states_from_prop(Q, psi0_np)
        states_0 = plotting.get_states_from_prop(Q)
        self.assertArrayAlmostEqual(Q @ psi0_np, states)
        self.assertArrayAlmostEqual(Q @ psi0_np, states_np)
        self.assertArrayAlmostEqual(Q @ qutip.basis(2, 0).full(), states_0)

        with self.assertRaises(ValueError):
            plotting.get_states_from_prop(Q, rng.standard_normal((3, 1, 2)))
        with self.assertRaises(ValueError):
            plotting.get_states_from_prop(Q, rng.standard_normal((3, 4)))

    def test_plot_bloch_vector_evolution(self):
        # Call with default args
        b = plotting.plot_bloch_vector_evolution(simple_pulse)
        # Call with custom args
        b = plotting.init_bloch_sphere(background=True)
        b = plotting.plot_bloch_vector_evolution(simple_pulse,
                                                 psi0=qutip.basis(2, 1), b=b,
                                                 n_samples=50, show=False,
                                                 return_Bloch=True)

        b = plotting.plot_bloch_vector_evolution(complicated_pulse)

        # Test add_cbar kwarg
        b = plotting.plot_bloch_vector_evolution(simple_pulse, cmap='viridis', add_cbar=True)

        # Check exceptions being raised
        with self.assertRaises(ValueError):
            plotting.plot_bloch_vector_evolution(two_qubit_pulse)

        plt.close('all')

    def test_box_aspect(self):
        """Fix https://github.com/qutech/filter_functions/issues/41"""
        b = plotting.plot_bloch_vector_evolution(simple_pulse, return_Bloch=True)
        aspect = b.axes.get_box_aspect()
        self.assertAlmostEqual(aspect.std(), 0)


from string import ascii_uppercase
a=list(ascii_uppercase)
m=input('Digite a mensagem: ')
m=m.upper()
mc=""
for l in m:
 i=ord(l)-65
 if l in a:
    mc+=a[(i+3)%26]
 else:
    l
print(f'Mensagem criptografada: {mc}')


import sys
input = sys.stdin.readline

def check(fake_coin: str, symbol: str, commands: list):
    sign = ('=', '>', '<') if symbol == '+' else ('=', '<', '>')

    for command in commands:
        test = 0
        if fake_coin in command[:4]:
            test = 1
        elif fake_coin in command[5:]:
            test = 2
        if command[4] != sign[test]:
            return False
    return True

commands = []
for _ in range(3):
    temp = input().split()
    if not temp:
        temp = input().split()
    commands.append(temp)

answer = []
for i in map(str, range(1, 13)):
    for symbol in ('+', '-'):
        if check(i, symbol, commands):
            answer.append(i + symbol)

if not answer:
    print('impossible')
elif len(answer) > 1:
    print('indefinite')
else:
    print(*answer)


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

"""
Trains and tests a loudness-threshold classifier for every given .pkl file.

For usage information, call without any parameters.

Author: Jan Schlüter
"""

from __future__ import print_function

import sys
import os
from argparse import ArgumentParser

import numpy as np
import scipy.optimize

def opts_parser():
    descr = ("Trains and tests a loudness-threshold classifier for every given "
             ".pkl file.")
    parser = ArgumentParser(description=descr)
    parser.add_argument('targets',
            type=str,
            help='a pickle file with ground truth targets')
    parser.add_argument('inputs', nargs='+',
            type=str,
            help='a pickle file with loudnesses (summarized magnitudes)')
    parser.add_argument('--plot',
            action='store_true',
            help='If given, saves a histogram plot next to each input file.')
    parser.add_argument('--plot-data',
            action='store_true',
            help='If given along with --plot, saves the histogram values next '
                 'to each plot.')
    parser.add_argument('--smooth-width', metavar='WIDTH',
            type=int, default=0,
            help='Optionally apply temporal median smoothing over WIDTH frames '
                 '(default: (default)s)')
    return parser

def error(thr, inputs, targets):
    return 1. - np.mean((inputs >= thr) == targets)

def main():
    # parse command line
    parser = opts_parser()
    options = parser.parse_args()
    targetfile = options.targets
    inputfiles = options.inputs

    # load targets
    targetdata = np.load(targetfile)
    targets = targetdata['labels']
    splits = targetdata['splits']
    targets_train = np.concatenate(targets[splits['train']])

    # print baseline
    for t in 0, 1:
        print("baseline (all %d)" % t)
        for part in 'train', 'valid', 'test':
            print("%s err: %.4g" %
                  (part,
                   np.abs(t - np.mean(np.concatenate(targets[splits[part]])))))

    # iterate over the inputs
    for inputfile in inputfiles:
        print(inputfile)
        inp = np.load(inputfile)['sums']
        if options.smooth_width:
            from scipy.ndimage.filters import median_filter
            inp = [median_filter(p, options.smooth_width, mode='nearest')
                   for p in inp]
        inp_train = np.concatenate(inp[splits['train']])
        thr = .5 * (inp_train.min() + inp_train.max())
        thr = scipy.optimize.fmin(error, thr, args=(inp_train, targets_train),
                                  disp=False)[0]
        print("threshold: %f" % thr)
        for part in 'train', 'valid', 'test':
            print("%s err: %.4g" %
                  (part, error(thr, np.concatenate(inp[splits[part]]),
                               np.concatenate(targets[splits[part]]))))

        if options.plot:
            import matplotlib.pyplot as plt
            if not 'log' in inputfile:
                low = inp_train.max() / 10**(50. / 20)  # cutoff at -50 dB FS
            else:
                k = int(len(inp_train) * .02)  # cutoff at 2-percentile
                low = np.partition(inp_train, k)[k]
            np.maximum(low, inp_train, inp_train)  # apply cutoff
            if not 'log' in inputfile:
                inp_train = 20 * np.log10(inp_train)
                low = inp_train.min()
                thr = 20 * np.log10(thr)
            high = inp_train.max()
            plt.figure()
            posvals, bins, _ = plt.hist(inp_train[targets_train], 50,
                                        range=(low, high), alpha=.8)
            negvals, _, _ = plt.hist(inp_train[~targets_train], bins, alpha=.8)
            plt.axvline(thr, linestyle=':', color='r')
            plt.savefig(inputfile[:-3] + 'png')
            if options.plot_data:
                np.savez(inputfile[:-3] + 'hist.npz', bins=bins, thr=thr,
                         posvals=posvals, negvals=negvals)

if __name__=="__main__":
    main()


import sys

from UI.main import run_ui

CONFIG_FILE = 'user.config'
BASE_URL = "http://34.142.141.69/" #'http://127.0.0.1:8000/'
#BASE_URL = "http://34.66.216.13"
RTMP_URL = "rtmp://34.142.141.69/live/"

if __name__ == "__main__":

    app, config = run_ui(CONFIG_FILE, BASE_URL, RTMP_URL)
    app.exec_()
    print('HIIIII')
    sys.exit()


# -*- coding: utf-8 -*-
"""
A path in a binary tree is a sequence of nodes where each
pair of adjacent nodes in the sequence has an edge
connecting them. A node can only appear in the sequence
at most once. Note that the path does not need to pass
through the root.

The path sum of a path is the sum of the node's values in
the path.

Given the root of a binary tree, return the maximum path
sum of any non-empty path.

Example 1:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path
sum of 2 + 1 + 3 = 6.
Example 2:

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path
sum of 15 + 20 + 7 = 42.

Constraints:

The number of nodes in the tree is in the range
[1, 3 * 104].
-1000 <= Node.val <= 1000

"""

import unittest

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        #placing the root val into a list helps make it easier to modify from the recursive function
        res = [root.val]

        #basecase
        def dfs(root):
            if not root:
                    return 0
            leftMax= dfs(root.left)
            rightMax = dfs(root.right)
            # set to 0 in the case of negatives:
            leftMax = max(leftMax, 0)
            rightMax = max(rightMax, 0)
            # compute max path sum with a split:
            res[0] = max(res[0],root.val + leftMax + rightMax)
            return root.val + max(leftMax, rightMax)

        dfs(root)
        return res[0]

class TestMethods(unittest.TestCase):

    def test_isMatch_ex1(self):
        inputs = 3
        output = "III"
        mySolution = Solution()
        self.assertEqual(mySolution.intToRoman(inputs), output)

    def test_isMatch_ex2(self):
        inputs = 58
        output = "LVIII"
        mySolution = Solution()
        self.assertEqual(mySolution.intToRoman(inputs), output)

    def test_isMatch_ex3(self):
        inputs = 1994
        output = "MCMXCIV"
        mySolution = Solution()
        self.assertEqual(mySolution.intToRoman(inputs), output)

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


# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1438909689.735831
_enable_loop = True
_template_filename = '/Users/mq20155490/Desktop/CEL/abstrackr_test/abstrackr/templates/reviews/show_review.mako'
_template_uri = '/reviews/show_review.mako'
_source_encoding = 'utf-8'
from webhelpers.html import escape
_exports = ['title']

def _mako_get_namespace(context, name):
    try:
        return context.namespaces[(__name__, name)]
    except KeyError:
        _mako_generate_namespaces(context)
        return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
    pass
def _mako_inherit(template, context):
    _mako_generate_namespaces(context)
    return runtime._inherit_from(context, u'../site.mako', _template_uri)
def render_body(context,**pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs)
        url = context.get('url', UNDEFINED)
        c = context.get('c', UNDEFINED)
        float = context.get('float', UNDEFINED)
        len = context.get('len', UNDEFINED)
        __M_writer = context.writer()
        __M_writer(u'\n')
        __M_writer(u'\n')
        __M_writer(u'\n\n\n\n
')
        __M_writer(escape(c.review.name))
        __M_writer(u'
\n\t
\n    review labels\n    review terms\n
\n
\n
Project description
 \n')
        __M_writer(escape(c.review.description))
        __M_writer(u'\n

\n
Progress
\n\n')
        if float(c.num_labels)/float(c.num_citations) >= .1:
            __M_writer(u'\t
\n')
        __M_writer(u'\nThere are ')
        __M_writer(escape(c.num_citations))
        __M_writer(u' citations in this review, so far ')
        __M_writer(escape(c.num_labels))
        __M_writer(u' have been labeled.\n

\n\n
Participants
\nThis review is lead by\n
\n
\n')
        for leader in c.project_leaders:
            __M_writer(u'
\n                ')
            __M_writer(escape(leader.fullname))
            __M_writer(u'\n
\n')
        __M_writer(u'
\n
\n
\n')
        if len(c.participating_reviewers) > 1:
            __M_writer(u'    The following people are reviewers on the project: \n')
            for user in c.participating_reviewers[:-1]:
                __M_writer(u'        ')
                __M_writer(escape(user.fullname))
                __M_writer(u',\n')
            __M_writer(u'    and ')
            __M_writer(escape(c.participating_reviewers[-1].fullname))
            __M_writer(u'.\n')
        else:
            __M_writer(u'    This project is a lonely undertaking by ')
            __M_writer(escape(c.participating_reviewers[0].fullname))
            __M_writer(u'.\n')
        __M_writer(u'

\nNumber of citations screened by reviewers:\n\n\n\n
\n')
        return ''
    finally:
        context.caller_stack._pop_frame()

def render_title(context):
    __M_caller = context.caller_stack._push_frame()
    try:
        c = context.get('c', UNDEFINED)
        __M_writer = context.writer()
        __M_writer(escape(c.review.name))
        return ''
    finally:
        context.caller_stack._pop_frame()

"""
__M_BEGIN_METADATA
{"source_encoding": "utf-8", "line_map": {"27": 0, "36": 1, "37": 2, "38": 3, "39": 7, "40": 7, "41": 10, "42": 10, "43": 12, "44": 12, "45": 16, "46": 16, "47": 20, "48": 21, "49": 21, "50": 21, "51": 23, "52": 24, "53": 24, "54": 24, "55": 24, "56": 31, "57": 32, "58": 33, "59": 33, "60": 36, "61": 39, "62": 40, "63": 41, "64": 42, "65": 42, "66": 42, "67": 44, "68": 44, "69": 44, "70": 45, "71": 46, "72": 46, "73": 46, "74": 48, "75": 51, "76": 51, "82": 3, "87": 3, "93": 87}, "uri": "/reviews/show_review.mako", "filename": "/Users/mq20155490/Desktop/CEL/abstrackr_test/abstrackr/templates/reviews/show_review.mako"}
__M_END_METADATA
"""


from matplotlib.figure import Figure
from matplotlib.pyplot import imread
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from numpy import ndarray
from PyQt5.QtCore import QThread, pyqtSignal

class ImgFigure(FigureCanvas):
    def __init__(self, dpi=100):
        self.fig = Figure(dpi=dpi)
        super(ImgFigure, self).__init__(self.fig)
        self.axes = self.fig.add_subplot(111)
        self.axes.get_yaxis().set_visible(False)
        self.axes.get_xaxis().set_visible(False)

class WorkThread(QThread):

    finishSignal = pyqtSignal(ndarray, ndarray)

    def __init__(self, imgPath, progressBar, alpha, gamma):
        super(WorkThread, self).__init__()

        from LIME import LIME
        img = imread(imgPath)
        self.lime = LIME(img, alpha, gamma)
        self.lime.setMaximumSignal.connect(progressBar.setMaximum)
        self.lime.setValueSignal.connect(progressBar.setValue)

    def run(self):
        T = self.lime.optimizeIllumMap()
        R = self.lime.enhance()
        self.finishSignal.emit(T, R)


import json

from django.http import JsonResponse
from django.views import View

from owners.models import Owner, Dog

class OwnersView(View):
# """
# 목적: Client가 보내주는 owner정보(name, age, email) 등록 요청에 맞게 owner테이블 in database 에 저장

# Input:
#     {
# 'name'  = '홍길동'
# 'age'   = 20
# 'email' = asd@gmail.com
#     }

# Logic:
#     1. owner 모델을 사용해서 owner 테이블에 데이터 입력
#     2. Owner.objects.create(...)

# Output:
#     {
# "message": "SUCCESS"
#     }, status = 201

# """
    def post(self, request):
        data = json.loads(request.body)

        Owner.objects.create(
            name  = data['name'],
            age   = data['age'],
            email = data['email']
        )
        return JsonResponse({"message" : "SUCCESS"}, status = 201)

# """
# 목적: owners의 정보를 client 요청하는 바와 맞게 database에서 호출하고, 가공해서 응답(반환)

# Logic:
# 1. 응답해야할 방식에 맞춰주기 위해서 빈 리스트 생성 / results = []

# 2. 모든 owner의 정보 추출 / owners = Owner.Objects.all()

#     3. for loop으로 강아지 리스트(name , age 포함되도록)가 함께 응답될 수 있도록 짜야함

# Output:
#     {
# "results" = result
# },         status = 200

# """

# list comprehension
# dict comprehension

    def get(self, request):

        # 신버전 ver3
        results = [
            {
                    'name' : owner.name,
                    'age'  : owner.age,
                    'email': owner.email,
                    'dogs' : [{
                        'name': dog.name,
                        'age' : dog.age,
                    } for dog in owner.dog_set.all()]
            } for owner in Owner.objects.all()
        ]
        return JsonResponse({'results' : results}, status = 200)

        # 구버전 ver 2
        results = []
        owners  = Owner.objects.all()

        for owner in owners:
            results.append(
                {
                    'name' : owner.name,
                    'age'  : owner.age,
                    'email': owner.email,
                    'dogs' : [{
                        'name': dog.name,
                        'age' : dog.age,
                    } for dog in owner.dog_set.all()]
                }
            )

        # 구버전 ver 1
        for owner in owners:
            dogs = list(Dog.objects.filter(owner=owner.id).values('name', 'age'))
            results.append(
                {
                    'name' : owner.name,
                    'age'  : owner.age,
                    'email': owner.email,
                    'dogs' : dogs,
                }
            )

class DogsView(View):

# """
# 목적: Client가 보내주는 dog정보(name, age, owner_id) 등록 요청에 맞게 dog테이블 in database 에 저장

# Input:
#     {
# 'name'  = '라온'
# 'age'   = 1
# 'owner' = '홍길동'
#     }

# Logic:
#     1. dog 모델을 사용해서 dog 테이블에 데이터 입력
#     2. Dog.objects.create()

# Output:
#     {
# "message": "SUCCESS"
#     }, status = 201

# """

    def post(self, request):
        data = json.loads(request.body)

        owner = Owner.objects.get(name=data['owner'])

        Dog.objects.create(
            name     = data['name'],
            age      = data['age'],
            owner_id = owner.id
        )
        return JsonResponse({"message" : "SUCCESS"}, status = 201)

# """
# 목적: dogs의 정보를 client 요청하는 바와 맞게 database에서 호출하고, 가공해서 응답(반환)

# Logic:
# 1. 응답해야할 방식에 맞춰주기 위해서 빈 리스트 생성 / results = []

# 2. 모든 dog의 정보 추출 / dogs = Dog.Objects.all()

# Output:
#     {
# "results" = result
# },         status = 200

# """

    def get(self, request):
        results = []
        dogs    = Dog.objects.all()

        for dog in dogs:
            results.append(
                {
                    'name' : dog.name,
                    'age'  : dog.age,
                    'owner': dog.owner.name
                }
            )
        return JsonResponse({"results" : results}, status=200)


from django.shortcuts import render
from stove.models import State
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt

import json
# Create your views here.

@csrf_exempt
def index(request):
    return render(request, 'index.html')

def getState(request):
    result =  State.get_state()
    #print("from result", result["temp"])

    if (result['temp'] > 30 and result['proximity1'] > 15):
        display_msg= "Stove seems to be ON and nothing is cooking!"
    elif (result['temp'] > 30 and result['proximity1'] < 15):
        display_msg = "Food on stove. Must be burning!"
    else:
        display_msg = "Everything is OK"

    context = {
    'temp' : result['temp'],
    'proximity1' : result['proximity1'],
    'proximity2' : result['proximity2'],
    'display_msg' : display_msg,
        }

    #request.session['temp'] = result.temp
    #request.session['proximity1'] = result.proximity1
    #request.session['proximity2'] = result.proximity2
    return render(request,'dashboard.html', context=context)
    #return JsonResponse(State.get_state())

def mobileApp(request):
    return JsonResponse(State.get_state())

def saveState(request, temp, p1, p2):
    # temp = float(request.POST.get('temp'))
    # p1 = float(request.POST.get('p1'))
    # p2 = float(request.POST.get('p2'))
    created = State.saveState(float(temp), float(p1), float(p2))
    return JsonResponse({"success": created})

Web Server and Client/smart_stove/stove/views.py


from collections import defaultdict

import matplotlib.pyplot as plt
import numpy as np

from hrv.classical import time_domain
from hrv.rri import RRi

__all__ = ["time_varying"]

class TimeVarying:
    def __init__(self, rri, results, rri_segments, seg_size, overlap):
        self.rri = rri
        self.results = results
        self.transponsed = self._transform_results(results)
        self.rri_segments = rri_segments
        self.seg_size = seg_size
        self.overlap = overlap

    def _transform_results(self, results):
        return {key: [item[key] for item in results] for key in results[0].keys()}

    def ylabel_mapper(self, index):
        mapper = {
            "rmssd": "RMSSD (ms)",
            "sdnn": "SDNN (ms²)",
            "sdsd": "SDSD (ms²)",
            "nn50": "nn50 (count)",
            "pnn50": "pnn50 (%)",
            "mrri": "mean RRi (ms)",
            "mhr": "mean HR (bpm)",
        }
        return mapper.get(index)

    def build_xaxis(self):
        return [np.median(r.time) for r in self.rri_segments]

    def __getattr__(self, index):
        try:
            return self.transponsed[index]
        except KeyError:
            raise ValueError(f"index `{index}` does not exist.")

    def plot(self, ax=None, index="rmssd", *args, **kwargs):
        fig = None
        if ax is None:
            fig, ax = plt.subplots(1, 1)

        ax.plot(self.build_xaxis(), self.__getattr__(index), *args, **kwargs)
        ax.set(xlabel="Time Interval (s)", ylabel=self.ylabel_mapper(index))
        plt.show(block=False)

        return fig, ax

    def plot_together(self, ax=None, index="rmssd", *args, **kwargs):
        fig, ax = self.rri.plot(alpha=0.7, color="grey")
        ax1 = ax.twinx()
        self.plot(ax=ax1, index=index, *args, **kwargs)

        return fig, ax

    def __str__(self):
        return f"Time Varying {self.seg_size}:{self.overlap} - #{len(self.results)}"

def time_varying(rri, seg_size, overlap, keep_last=False):
    if not isinstance(rri, RRi):
        rri = RRi(rri)

    segments = rri.time_split(seg_size=seg_size, overlap=overlap, keep_last=keep_last)
    results = []
    for segment in segments:
        results.append(time_domain(segment))

    return TimeVarying(rri, results, segments, seg_size=seg_size, overlap=overlap)


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

__author__ = 'Robert Zeng'
__updated__ = '18.08.2018'  # day.month.year

import logging

"""
All objects imported here are exposed as the public API of GoogleScraper
"""

logging.getLogger(__name__)


# def get_username():
#     user_name = "bhandariayush_"
#     return user_name
#
#
# def get_api(user_name):
#     return "https://www.instagram.com/{0}/?__a=1".format(user_name)
import requests

from insta_profile import InstaProfile
#diff
list_username = [
    "minionish_1994",
    "nvnainaverma",
    "komaldegwekar",
    "aasif.jamadar",
    "anuj.salsa",
    "shashwat_mishra3",
    "kunal_sahani14",
    "mike.2331",
    "charvi_chouhan",
    "diyadutta",
    "hitesh.auji",
    "azizadegwekar",
    "kimberlyd98",
    "figment_of_the_universe",
    "poorvakarnik",
    "shwetaskul",
    "houseofdarbouka_",
    "abhidnya_pawar",
    "nirajpardeshi",
    "pranavpardeshi",
    "samhita_adc",
    "adc.madhurima",
    "adc.akram",
    "sahsahil",
    "sagarrathore123",
    "_harshali_1415",
    "bhagya_st",
    "x_ru_sh_ab_x",
    "rushi_rich1",
    "mr_r_a_j_p_u_t_2019",
    "deepikatikoo",
    "21_tej_12",
    "pramoddancerdp",
    "_suiya_",
    "sweta_fernandes_",
    "pouravi_patwardhan",
    "radhikamehta_",
    "dishamulik1",
    "juileed",
    "kasturikarandikar",
    "rising_star_aniket",
    "ianuprita",
    "ipoojapawar",
    "chica_tootsie",
    "apurval95",
    "tannushreerakshit",
    "unnikriishnan",
    "either_hungry_or_sleepy",
    "prernakhoda",
    "nishkamble",
    "shubhshitole123",
    "zin_prince_",
    "surve_sayali",
    "tahitisenguptadutta",
    "harshit.rungta",
    "leena_patle",
    "shreyachauhan1526",
    "suraj_dancemachine",
    "choreographer_satish",
    "namit_chhajed",
    "pune_dance_fitness",
    "akshaygrms",
    "abhi_isiwaqt",
    "goag7",
    "gokhale.archana",
    "rahul_theswagcrew",
    "moze_sushant",
    "dancingdevilpawan",
    "dancingdevil_komal",
    "rasikas_art_studio_official",
    "ritikajoybox",
    "navtaalgarba2622",
    "radhikapatil140890",
    "mehul.khimavat",
    "_m_u_g_d_h_a",
    "manasikanetkar",
    "nitikeshgaikwadbpcindia",
    "suraj_beatpopper_01",
    "shubh191",
    "priyanka_sonya",
    "sushil_keskar__24",
    "hiren_swcpune",
    "pareshadmane",
    "ajinkyasinghbansi_",
    "tttejaaallll",
    "swarali_umesh1111",
    "dancewithtrupti",
    "dance_addictor",
    "lady_praj",
    "prakashsatya19",
    "pranjal_17_kothari",
    "shelarpravin87",
    "sajan.rajpurohit.58",
    "murumkarrahul",
    "poojapb_artistree",
    "karpepurva551",
    "priyapashankar",
    "rishikaysh_desae",
    "anjalikukreja",
    "rahulindulkar",
    "punam4dance",
    "sushmita_thedancingsoul",
    "kartikiiii__ ",
    "dikshalankeshwar",
    "asha_ponikiewska",
    "iamvishaltelang",
    "arunbhardwaj_official",
    "bajaj.tanvi",
    "ms.sayli",
    "akshay_bhosle1",
    "priyankasonya",
    "theamritayadav",
    "sandeep_shivashankar",
    "zinnishi7557",
    "kalyani.choudhari",
    "poojalokhande5",
    "nikitaraja2014",
    "suresh_dahale",
    "punam_majee",
    "shubham_lokhande000",
    "shashikumar_shetty_999",
    "i.am.satyakisaha",
    "surabhiparikh",
    "rutuja.rode",
    "vipuldevrani",
    "himali__walkoli",

    "nimitkotian",
    "aki_nikhs",
    "ajit_insideme",
    "ravivarma.iam",

    "suraj_9721",
    "virengiri_",
    "elvisrgdc",
    "sameepdhakne_np",

]

def get_json(user_name):
    api = "https://www.instagram.com/{0}/?__a=1".format(user_name)
    try:
        r = requests.get(api)
    except requests.exceptions.ConnectionError:
        print("connection error")
        return
    if r.status_code != 200:
        return
    j = r.json()
    return j

# json_bhandari = get_json("bhandariayush_")
# if json_bhandari:
#     bhandari = InstaProfile(json_bhandari)
#
# print(bhandari.user_name, bhandari.followers)

def get_followers(json):
    value = json["graphql"]
    value1 = value["user"]
    value2 = value1["edge_followed_by"]
    value3 = value2["count"]
    return value3

dict = {}
list2 = []
for i in list_username:
    if get_json(i) is None:
        dict[i] = 0
    else:
        dict[i] = get_followers(get_json(i))
print(len(list_username),"without sorting")
list1 = sorted(dict.items(), key=lambda x: x[1], reverse=True)
for i in list1:
    list2.append(i[0])
print(len(list2), "after sorting")
print(list2)


import json

def input_number():
    """用户输入喜欢的数字"""
    try:
        number = int(input('Please in put your favorite number: '))
    except ValueError:
        print('Please input the number')
    else:
        filename = 'number_1.json'
        with open(filename, 'w') as file_object:
            json.dump(number,file_object)
        return number

def print_number():
    """打印用户喜欢的数字"""
    try:
        filename = 'number_1.json'
        with open(filename) as file_object:
            number = json.load(file_object)
    except FileNotFoundError:
        number = input_number()
        print('Your favorite is ' + str(number) + '!')
    else:
        print("I know your favorite number! It's " + str(number) + '!')

print_number()


from kivy.app import App
# from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
import logging
from random import randint

# Настройка уровня логирования
logging.basicConfig(level=logging.WARNING)

# Примеры логирования
# logging.debug     Это сообщение отладки
# logging.info      Это информационное сообщение
# logging.warning   Это предупреждение
# logging.error     Это сообщение об ошибке
# logging.critical  Это критическая ошибка

Window.size = (1300, 800) # Размер окна
Window.clearcolor = (177/255, 157/255, 207/255) # Цвет

class Diva(App): # Название класса = название приложения

    def __init__(self):
        super().__init__()
        self.label = Label(text='Моя программа\nDiva Привет!')

    def btn_pressed(self, *args):
        self.label.color = (randint(0, 255)/255, randint(0, 255)/255, randint(0, 255)/255, )

    def build(self):
        box = BoxLayout()
        btn = Button(text='Нажми на меня')
        btn.bind(on_press=self.btn_pressed)
        box.add_widget(self.label)
        box.add_widget(btn)

        return box

if __name__ == "__main__":
    Diva().run()


#Pregunta: ¿Cómo se pueden intercambiar los valores de dos variables?

#Echa un vistazo al fragmento:

variable1 = 1
variable2 = 2

variable1, variable2 = variable2, variable1

#Ahora puedes intercambiar fácilmente los elementos de la lista para revertir su orden:

miLista = [10, 1, 8, 3, 5] #EL centro queda estático

miLista [0], miLista [4] = miLista [4], miLista [0]
miLista [1], miLista [3] = miLista [3], miLista [1]

print(miLista)

#¿Seguirá siendo aceptable con una lista que contenga 100 elementos? No, no lo hará.
#¿Puedes usar el bucle for para hacer lo mismo automáticamente, independientemente de la longitud de la lista? Sí, sí puedes.

miLista = [10, 1, 8, 3, 5]
longitud = len(miLista)

for i in range (longitud // 2): #Esto intercambia cualquier tamaño de lista
    miLista[i], miLista[longitud-i-1] = miLista[longitud-i-1], miLista[i]

print(miLista)
#Hemos asignado la variable longitud a la longitud de la lista actual (esto hace que nuestro código sea un poco más claro y más corto).
#Hemos lanzado el ciclo for para que se ejecute a través de su cuerpo longitud // 2 veces
#(esto funciona bien para listas con longitudes pares e impares,
#porque cuando la lista contiene un número impar de elementos, el del medio permanece intacto).
#Hemos intercambiado el elemento i (desde el principio de la lista) por el que tiene un índice igual a (longitud-i-1)
#(desde el final de la lista); en nuestro ejemplo, for i igual a 0 la (longitud-i-1) da 4; for i igual a 3, da 3: esto es exactamente lo
#que necesitábamos.