from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'
db = SQLAlchemy(app)

db.create_all()

#local database that will hold items
class Item(db.Model):
    #each of these lines will be elements in our db table
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(length=30), nullable=False, unique=True)
    price = db.Column(db.Integer(), nullable=False)
    barcode = db.Column(db.String(length=12), nullable=False, unique=True)
    description = db.Column(db.String(length=1024), nullable=False, unique=True)

    def __repr__(self):
        return f'Item {self.name}'

@app.route('/')
@app.route('/home')
def home_page():
    return render_template('home.html')

@app.route('/market')
def market_page():  #market page with items

      items = [
        {'id': 1, 'name': 'Phone', 'barcode': '893212299897', 'price': 500},
        {'id': 2, 'name': 'Laptop', 'barcode': '123985473165', 'price': 900},
        {'id': 3, 'name': 'Keyboard', 'barcode': '231985128446', 'price': 150}
      ]

      return render_template('market.html', items=items)

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

     #xml
     #javascript / bootstrap


from flask import Flask, render_template
from flask import abort, request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restful import Api

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
api = Api(app)

@app.teardown_appcontext
def shutdown_session(exception=None):
    db.session.remove()

@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404

from web_hooks import OrderHook, SmartCollection

api.add_resource(OrderHook, '/wh_orders/', endpoint='wh_orders_ep')
api.add_resource(SmartCollection, '/wh_smart_cols/', endpoint='wh_smart_cols_ep')


from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet
from .models import Article, Scope, Tag

class RelationshipInlineFormset(BaseInlineFormSet):
    def clean(self):
        i = 0
        for form in self.forms:
            dictionary = form.cleaned_data
            if dictionary.get('is_main'):
                i += 1
            else:
                continue
        if i == 0:
            raise ValidationError('Выберите главную тему')
        elif i > 1:
            raise ValidationError('Главной темой может быть только одна')
        return super().clean()
    # def clean(self):
    #     count = 0
    #     # for form in self.forms:
    #     #     if 'is_main' in form.cleaned_data:
    #     #         if form.cleaned_data['is_main']:
    #     #             count += 1
    #     #     if count == 0:
    #     #         raise ValidationError('Какая-то ошибка')
    #     #     else:
    #     #         pass

    #     for self.deleted_forms in self._should_delete_form(form):
    #         continue
    #     elif self.form.cleaned_data.get(‘is_main’):
    #         count += 1
    #     if count > 1:
    #         raise ValidationError(‘Is_main should be only one tag’)
    #     elif count == 0:
    #         raise ValidationError(‘Assign is_main’)

    #     return super().clean()

class RelationshipInline(admin.TabularInline):
    model = Scope
    formset = RelationshipInlineFormset

@admin.register(Article)
class ObjectAdmin(admin.ModelAdmin):
    inlines = [RelationshipInline]

@admin.register(Tag)
class ObjectAdmin(admin.ModelAdmin):
    pass


import os
import random
from datetime import *
from dotenv import load_dotenv
from application.model.booking import *
from .db import *
import requests
load_dotenv()

class database:
    def check_order(order_number):
        db = connection()
        cursor = db.cursor()
        select_number = """
            SELECT id FROM orders WHERE id = %s
            """
        select_id = (order_number, )
        cursor.execute(select_number, select_id)
        order_existed = cursor.fetchone()
        cursor.close()
        db.close()
        return order_existed

    def insert_order(id, member_id, price, name, email, phone, payment):
        db = connection()
        cursor = db.cursor()
        insert_order = """
            INSERT INTO orders
            (id, member_id, price, name, email, phone, payment)
            VALUE (%s, %s, %s, %s, %s, %s, %s)
            """
        insert_value = (
            id, member_id, price, name, email, phone, payment)
        cursor.execute(insert_order, insert_value)
        db.commit()
        cursor.close()
        db.close()
        return True

    def insert_order_attraction(order_number, attraction_id, date, time):
        db = connection()
        cursor = db.cursor()
        insert_order = """
            INSERT INTO order_attraction
            (order_number, attraction_id, date, time)
            VALUE (%s, %s, %s, %s)
            """
        insert_value = (
            order_number, attraction_id, date, time)
        cursor.execute(insert_order, insert_value)
        db.commit()
        cursor.close()
        db.close()
        return True

    def delete_booking_by_id(member_id):
        db = connection()
        cursor = db.cursor()
        delete_booking = """
            DELETE FROM booking WHERE member_id = %s
            """
        delete_id = (member_id, )
        cursor.execute(delete_booking, delete_id)
        db.commit()
        cursor.close()
        db.close()
        return True

    def get_order_information(member_id):
        db = connection()
        cursor = db.cursor(buffered=True, dictionary=True)
        select_number = """
            SELECT orders.id, price, orders.name, email, phone, payment, attraction_id, date, time, attractions.name as attraction_name, address FROM orders
            INNER JOIN order_attraction ON orders.id = order_attraction.order_number
            INNER JOIN attractions ON order_attraction.attraction_id = attractions.id
            WHERE member_id = %s;
            """
        select_id = (member_id, )
        cursor.execute(select_number, select_id)
        order_information = cursor.fetchall()
        cursor.close()
        db.close()
        return order_information

    def get_order_information_by_number(orderNumber):
        db = connection()
        cursor = db.cursor(buffered=True, dictionary=True)
        select_number = """
            SELECT orders.id, price, orders.name, email, phone, payment, attraction_id, date, time, attractions.name as attraction_name, address FROM orders
            INNER JOIN order_attraction ON orders.id = order_attraction.order_number
            INNER JOIN attractions ON order_attraction.attraction_id = attractions.id
            WHERE orders.id = %s;
            """
        select_id = (orderNumber, )
        cursor.execute(select_number, select_id)
        order_information = cursor.fetchall()
        cursor.close()
        db.close()
        return order_information

    def image_url(attraction_id):
        db = connection()
        cursor = db.cursor(buffered=True, dictionary=True)
        select_image = """
            SELECT image_url FROM images WHERE attraction_id = %s
            """
        select_id = (attraction_id,)
        cursor.execute(select_image, select_id)
        attraction_image = cursor.fetchone()["image_url"]
        cursor.close()
        db.close()
        return attraction_image

class tap_pay:
    def check_payment(prime, amount, name, email, phone_number, trips, member_id):
        headers = {
            "content-type": "application/json",
            "x-api-key": os.getenv("PARTNER_KEY")
        }
        output_payment = {
            "prime": prime,
            "partner_key": os.getenv("PARTNER_KEY"),
            "merchant_id": "a05031113_TAISHIN",
            "details": "test",
            "amount": amount,
            "cardholder": {
                "name": name,
                "email": email,
                "phone_number": phone_number
            }
        }
        response = requests.post(
            "https://sandbox.tappaysdk.com/tpc/payment/pay-by-prime", headers=headers, json=output_payment).json()
        status_code = response["status"]
        now = datetime.now()
        time_string = now.strftime("%Y%m%d%H%M%S")
        check = False
        while check == False:
            order_number = time_string + str(random.randint(1000, 9999))
            check_order = database.check_order(order_number)
            if not check_order:
                check = True
        if status_code == 0:
            payment = True
            database.insert_order(order_number, member_id, amount,
                                  name, email, phone_number, payment)
            for trip in trips:
                database.insert_order_attraction(
                    order_number, trip["attraction"]["id"], trip["date"], trip["time"])
            database.delete_booking_by_id(member_id)
            return {
                "data": {
                    "number": order_number,
                    "payment": {
                        "status": 0,
                        "message": "付款成功"
                    }
                }
            }
        else:
            return {"error": True, "message": "付款錯誤"}

class data_output:
    def order_data(order_information):
        output = {}
        data = []
        for information in order_information:
            check = False
            order = {}
            for i in data:
                if information["id"] == i["number"]:
                    check = True
                    trip = data_output.trip(information)
                    i["trip"].append(trip)
                    break
            if not check:
                order["number"] = information["id"]
                order["price"] = information["price"]
                order["status"] = information["payment"]
                contact = {}
                contact["name"] = information["name"]
                contact["email"] = information["email"]
                contact["phone"] = information["phone"]
                order["contact"] = contact
                trip = [data_output.trip(information)]
                order["trip"] = trip
                data.append(order)
        output["data"] = data
        return output

    def order_data_by_number(order_information):
        output = {}
        trip = []
        for information in order_information:
            order = {}
            order["number"] = information["id"]
            order["price"] = information["price"]
            order["status"] = information["payment"]
            contact = {}
            contact["name"] = information["name"]
            contact["email"] = information["email"]
            contact["phone"] = information["phone"]
            order["contact"] = contact
            trip.append(data_output.trip(information))
        order["trip"] = trip
        output["data"] = order
        return output

    def trip(information):
        return {
            "attraction": {
                "id": information["attraction_id"],
                "name": information["attraction_name"],
                "address": information["address"],
                "image": database.image_url(information["attraction_id"])
            },
            "date": information["date"],
            "time": information["time"]
        }

    def amount(trips):
        price = 0
        for trip in trips:
            if trip["time"] == "morning":
                price += 2000
            elif trip["time"] == "afternoon":
                price += 2500
        return price


import xml.dom.minidom

def child_elements(node, name):
    """Iterate through direct child elements of a node that have the given tag name"""
    assert isinstance(node, xml.dom.minidom.Node), "child element was %r, not node" % type(node)
    for subnode in node.childNodes:
        if subnode.nodeType != xml.dom.minidom.Node.ELEMENT_NODE:
            continue
        assert isinstance(subnode, xml.dom.minidom.Element)
        if subnode.nodeName != name:
            continue
        yield subnode

def child_element_text(node, name, default_value=""):
    """Get the text of the direct child element(s) of a node"""
    parts = []
    found = False
    for element in child_elements(node, name):
        found = True
        for node in element.childNodes:
            if node.nodeType == element.TEXT_NODE:
                assert isinstance(node, xml.dom.minidom.Text)
                # noinspection PyUnresolvedReferences
                parts.append(node.nodeValue)
    if not found:
        return default_value
    return "".join(parts)

def element_text(element, default_value=""):
    parts = []
    found = False
    for node in element.childNodes:
        if node.nodeType == element.TEXT_NODE:
            found = True
            assert isinstance(node, xml.dom.minidom.Text)
            # noinspection PyUnresolvedReferences
            parts.append(node.nodeValue)
    if not found:
        return default_value
    return "".join(parts)

def get_path_elements(node, path):
    """:rtype: collections.Iterable[xml.dom.minidom.Element]"""
    if "/" in path:
        first, rest = path.split("/", 1)
        if first == "..":
            parent = node.parentNode
            for result in get_path_elements(parent, rest):
                yield result
        else:
            for child_node in child_elements(node, first):
                for result in get_path_elements(child_node, rest):
                    yield result
    else:
        for result in child_elements(node, path):
            yield result


from airflow import DAG
from airflow.models import Variable
from airflow.providers.docker.operators.docker import DockerOperator
from airflow.sensors.filesystem import FileSensor
from airflow.utils.dates import days_ago
from utils import DEFAULT_ARGS, VOLUMES

with DAG(
        "3_predict",
        default_args=DEFAULT_ARGS,
        schedule_interval="@daily",
        start_date=days_ago(1),
) as dag:
    date = Variable.set("TARGET_DATE", "2021-06-09")
    input_data_sensor = FileSensor(
        task_id="input_data_exists",
        poke_interval=10,
        retries=10,
        filepath="data/split/{{ ds }}/validation.csv",
    )
    model_sensor = FileSensor(
        task_id="model_exists",
        poke_interval=10,
        retries=10,
        filepath="data/artefacts/models/{{ var.value.TARGET_DATE }}/model.pkl",
    )
    scaler_sensor = FileSensor(
        task_id="scaler_exists",
        poke_interval=10,
        retries=10,
        filepath="data/artefacts/scalers/{{ var.value.TARGET_DATE }}/scaler.pkl",
    )
    predictions_sensor = FileSensor(
        task_id="predictions_exist",
        poke_interval=10,
        retries=10,
        filepath="data/predictions/{{ ds }}/predictions.csv",
    )
    predict = DockerOperator(
        image="airflow-predict",
        command="--input-data-dir /data/split/{{ ds }} "
                "--input-model-dir data/artefacts/models/{{ var.value.TARGET_DATE }} "
                "--input-scaler-dir data/artefacts/scalers/{{ var.value.TARGET_DATE }} "
                "--output-preds-dir /data/predictions/{{ ds }}",
        network_mode="bridge",
        task_id="docker-airflow-predict",
        do_xcom_push=False,
        volumes=VOLUMES
    )
    [input_data_sensor, model_sensor, scaler_sensor, predictions_sensor] >> predict


# import matplotlib.pyplot as plt
# plt.scatter(2, 4, s=200)
# # 设置图表标题并给坐标轴加上标签
# plt.title("Square Numbers", fontsize=24)
# plt.xlabel("Value", fontsize=14)
# plt.ylabel("Square")
# plt.show()

# import matplotlib.pyplot as plt
# x_values = [1, 2, 3, 4, 5]
# y_values = [1, 4, 9, 16, 25]
# plt.scatter(x_values, y_values, s=200)
# plt.show()

# import matplotlib.pyplot as plt
# x_values = list(range(1, 1001))
# y_values = [x**2 for x in x_values]
# plt.scatter(x_values, y_values, s=40, edgecolors='none', c=(0, 0.8, 0))
# # 设置图表标题并给坐标轴加上标签
# plt.title("Square Numbers", fontsize=24)
# plt.xlabel("Value", fontsize=14)
# plt.ylabel("Square")
#
# plt.axis([0, 1100, 0, 1100000])
# plt.show()

# import matplotlib.pyplot as plt
# x_values = list(range(1001))
# y_values = [x**2 for x in x_values]
# plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors='none', s=40)
# # plt.show()
# plt.savefig('squares_plot.png', bbox_inches='tight')

# 练习 1
# import matplotlib.pyplot as plt
# x_values = list(range(5))
# y_values = [x**3 for x in x_values]
# plt.scatter(x_values, y_values, s=40)
# plt.title("dong", fontsize=24)
# plt.xlabel('x轴', fontsize=16)
# plt.ylabel('y轴', fontsize=16)
# plt.show()

# 练习 2
import matplotlib.pyplot as plt
x_label = list(range(5000))
y_label = [x**3 for x in x_label]
plt.scatter(x_label, y_label, c=y_label, edgecolors='none', s=40)
plt.title('dong', fontsize=24)
plt.xlabel('xxx', fontsize=16)
plt.ylabel('yyy', fontsize=16)
plt.axis([0, 1100, 0, 999900000])
plt.show()


import os
from math import floor
from scipy.io import wavfile
from scipy import signal
import numpy as np
import torch

def torch2np(*tensors):
    # Converts torch tensors to numpy
    tensors = list(tensors)
    for i in range(len(tensors)):
        if type(tensors[i]).__module__ == 'torch':
            tensors[i] = tensors[i].detach().cpu().numpy()
        if type(tensors[i]).__module__ == 'numpy':
            if len(tensors[i].shape) == 0:
                tensors[i] = tensors[i].item()

    return tuple(tensors) if len(tensors) > 1 else tensors[0]

class MovingAverages:
    # Keeps moving averages
    def __init__(self):
        self.data = {}
        self.counts = {}

    def __call__(self, data_new):
        for key in data_new.keys():
            # TODO
            data_new[key] = torch2np(data_new[key])

            if key not in self.counts.keys():
                self.counts[key] = 1
                self.data[key] = data_new[key] * 1.0
            else:
                self.counts[key] += 1
                self.data[key] = (self.data[key] * (self.counts[key] - 1) + data_new[key]) / self.counts[key]

    def get(self):
        return self.data.copy()

    def reset(self):
        for key in self.data.keys():
            self.data[key] = 0.0
            self.counts[key] = 0.0

def read_audio(path, make_stereo=True):
    sr, audio = wavfile.read(path)
    audio = audio.T
    if np.issubdtype(audio.dtype, np.int16):
        audio = audio.astype(np.float32) / 32768.0
    if len(audio.shape) == 1:    # if mono
        audio = np.expand_dims(audio, axis=0)
        if make_stereo:
            audio = np.repeat(audio, 2, axis=0)
    return audio, sr

def mse(x, ref):
    # Mean-squared error
    mse_val = ((x - ref)**2).mean()
    return mse_val

def snr(x, ref):
    # Signal-to-noise ratio
    ref_pow = (ref**2).mean().mean() + np.finfo('float32').eps
    dif_pow = ((x - ref)**2).mean().mean() + np.finfo('float32').eps
    snr_val = 10 * np.log10(ref_pow / dif_pow)
    return snr_val

def snr_torch(x, ref):
    # Signal-to-noise ratio for torch tensors
    ref_pow = (ref**2).mean(-1).mean(-1) + np.finfo('float32').eps
    dif_pow = ((x - ref)**2).mean(-1).mean(-1) + np.finfo('float32').eps
    snr_val = 10 * torch.log10(ref_pow / dif_pow)
    return snr_val.mean().item()

def weights_init_normal(m):
    # Initializes weights using normal distribution
    classname = m.__class__.__name__
    if classname.find("Linear") != -1:
        torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
    elif classname.find("Conv") != -1:
        torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
    elif classname.find("BatchNorm2d") != -1:
        torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
        torch.nn.init.constant_(m.bias.data, 0.0)

class Flatten(torch.nn.Module):
    # Flattens 2D tensors to 1D
    def forward(self, x):
        x = x.view(x.size()[0], -1)
        return x

class PixelUpscale(torch.nn.Module):
    """
    1D pixel shuffler. https://arxiv.org/pdf/1609.05158.pdf
    Upscales activations
    """
    def __init__(self, upscale_factor, odd_output=False):
        super(PixelUpscale, self).__init__()
        self.upscale_factor = upscale_factor
        self.odd_output = odd_output

    def forward(self, x):

        batch_size = x.shape[0]
        short_channel_len = x.shape[1]
        short_width = x.shape[2]

        long_channel_len = short_channel_len // self.upscale_factor
        long_width = self.upscale_factor * short_width

        x = x.contiguous().view([batch_size, self.upscale_factor, long_channel_len, short_width])
        x = x.permute(0, 2, 3, 1).contiguous()
        x = x.view(batch_size, long_channel_len, long_width)
        if self.odd_output:
            x = x[:, :, :-1]

        return x

def predict_size(input_size, kernel_size, padding=0, stride=1, dilation=1):
    # Predicts output size of convolutional layer
    return int(floor((input_size + 2 * padding - dilation * (kernel_size - 1) - 1) / stride + 1))

def makedir(path):
    os.makedirs(path, exist_ok=True)
    return path

def pad_str_zeros(x, n):
    # Pads string with zeros to have length n
    x = str(x)
    for _ in range(len(x), n):
        x = '0' + x
    return x

def conv1d_same(in_channels, out_channels, kernel_size, bias=True, dilation=1, pad_type='zero'):
    # Convolution which does not change input size
    if pad_type == 'zero':
        return torch.nn.Conv1d(in_channels, out_channels, kernel_size,
                               padding=(kernel_size - 1) // 2, bias=bias, dilation=dilation)
    elif pad_type == 'reflection':
        return torch.nn.Sequential(
            torch.nn.ReflectionPad1d((kernel_size - 1) // 2),
            torch.nn.Conv1d(in_channels, out_channels, kernel_size, bias=bias, dilation=dilation)
        )
    elif pad_type == 'replication':
        return torch.nn.Sequential(
            torch.nn.ReplicationPad1d((kernel_size - 1) // 2),
            torch.nn.Conv1d(in_channels, out_channels, kernel_size, bias=bias, dilation=dilation)
        )
    else:
        raise ValueError('Unknown padding type')

def conv2d_same(in_channels, out_channels, kernel_size, bias=True, dilation=1, pad_type='zero'):
    # Convolution which does not change input size
    if len(kernel_size) == 1:
        kernel_size = (kernel_size, kernel_size)
    pad_size = ((kernel_size[0] - 1) // 2, (kernel_size[1] - 1) // 2)

    if pad_type == 'zero':
        return torch.nn.Conv2d(in_channels, out_channels, kernel_size,
                               padding=pad_size, bias=bias, dilation=dilation)
    elif pad_type == 'reflection':
        return torch.nn.Sequential(
            torch.nn.ReflectionPad2d(pad_size),
            torch.nn.Conv2d(in_channels, out_channels, kernel_size, bias=bias, dilation=dilation)
        )
    elif pad_type == 'replication':
        return torch.nn.Sequential(
            torch.nn.ReplicationPad2d(pad_size),
            torch.nn.Conv2d(in_channels, out_channels, kernel_size, bias=bias, dilation=dilation)
        )
    else:
        raise ValueError('Unknown padding type')

def conv1d_halve(in_channels, out_channels, kernel_size, bias=True, dilation=1, pad_type='zero'):
    # Convolution which halves the input size
    if pad_type == 'zero':
        return torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=2,
                               padding=(kernel_size - 1) // 2, bias=bias, dilation=dilation)
    elif pad_type == 'reflection':
        return torch.nn.Sequential(
            torch.nn.ReflectionPad1d((kernel_size - 1) // 2),
            torch.nn.Conv1d(in_channels, out_channels, kernel_size, bias=bias, dilation=dilation, stride=2)
        )
    elif pad_type == 'replication':
        return torch.nn.Sequential(
            torch.nn.ReplicationPad1d((kernel_size - 1) // 2),
            torch.nn.Conv1d(in_channels, out_channels, kernel_size, bias=bias, dilation=dilation, stride=2)
        )
    else:
        raise ValueError('Unknown padding type')

def lowpass(sig, cutoff, filter_=('cheby1', 8), sr=44100):
    """Lowpasses input signal based on a cutoff frequency

    Arguments:
        sig {numpy 1d array} -- input signal
        cutoff {int} -- cutoff frequency

    Keyword Arguments:
        sr {int} -- sampling rate of the input signal (default: {44100})
        filter_type {str} -- type of filter, only butter and cheby1 are implemented (default: {'butter'})

    Returns:
        numpy 1d array -- lowpassed signal
    """
    nyq = sr / 2
    cutoff /= nyq

    if filter_[0] == 'butter':
        B, A = signal.butter(filter_[1], cutoff)
    elif filter_[0] == 'cheby1':
        B, A = signal.cheby1(filter_[1], 0.05, cutoff)
    elif filter_[0] == 'bessel':
        B, A = signal.bessel(filter_[1], cutoff, norm='mag')
    elif filter_[0] == 'ellip':
        B, A = signal.ellip(filter_[1], 0.05, 20, cutoff)

    sig_lp = signal.filtfilt(B, A, sig)
    return sig_lp.astype(np.float32)


"""
Flask app that run my python code
"""
from flask import Flask, render_template, request
import functionality

app = Flask(__name__)

@app.route('/')
def dashboard():
    """
    Open html file
    :return: file html in the internet server.
    """
    return render_template('index.html')

@app.route('/')
def dashboard_errors(h_file):
    """
    Open another html file if first was with an error.
    :param h_file: error.html
    :return: file html in the internet server.
    """
    return render_template(h_file)

@app.route('/create/map', methods=['GET', 'POST'])
def create():
    """
    Run python code.
    :return: result of the app.
    """
    name = request.form.get('domain')
    number_of_friends = request.form.get('amount')
    try:
        int(number_of_friends)
        return functionality.main(name, number_of_friends)
    except ValueError:
        return dashboard_errors('for_errors.html')

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


"""
Здесь находятся все возможные кнопки, которые размещены на панели меню.
"""

import color
import pygame
import time

pygame.font.init()

class Widget:

        def __init__(self, id = 0, weight = 1, color_pack = color.GREY_PACK, text = "",
            clickable = True, switch = False, radio = False, text_pos_modifier = [1, 1]):
            # weight отвечает за то, сколько места в группе (group.py) занимает эта клетка по отношению к другим
            # text_pos_modifier требуется для выведения особых ascii символов, которые съезжат при попытке вывести их
            # просто так

            self.id     = id
            self.x      = 0
            self.y      = 0
            self.width  = 0
            self.height = 0
            self.weight = weight
            self.text_pos_modifier = text_pos_modifier

            if radio: switch = False
            self.clickable = clickable  # Ее можно нажать?
            self.switch    = switch     # Это переключатель?
            self.radio     = radio      # Это радио кнопка? (это как переключатель,
                                        # но единовременно может быть активна только одна из групппы)

            self.color_pack = list(color_pack)
            self.text       = text
            self.__text     = None # Отрендеренный текст, готовый к расположению на поверхности

            self.isPressed = False
            self.time_when_pressed = 0

        def update(self):
            current_time = time.time()
            if current_time - self.time_when_pressed > 0.2 and not self.switch and not self.radio:
                self.onReleased()
                return True
            return False

        def onReleased(self):
            if self.isPressed:
                self.isPressed = False

        def click(self, pos):
            if self.clickable:
                if self.x < pos[0] < self.x + self.width:
                    if self.y < pos[1] < self.y + self.height:
                        self.onClick()
                        return True
            return False

        def onClick(self):
            old_time = self.time_when_pressed
            self.time_when_pressed = time.time()

            if self.isPressed == False and not self.switch:
                self.isPressed = True

            if self.switch and self.time_when_pressed - old_time > 0.15 and not self.radio:
                self.isPressed = not self.isPressed

        def draw(self, screen, pos, size, font, text_scale, text_y_offset):

            width  = size[0]
            height = size[1]

            x  = pos[0];     x1 = x + width
            y  = pos[1];     y1 = y + height

            self.x = x ;     self.width  = width
            self.y = y ;     self.height = height

            l_sc = 1
            a = 1

            pygame.draw.rect(screen, self.color_pack[0],   [x, y, size[0], size[1]])
            if self.isPressed:
                pygame.draw.line(screen, self.color_pack[2], [x+a-1 , y     ],   [x+a-1 , y1    ], l_sc)   # left line
                pygame.draw.line(screen, self.color_pack[2], [x+a   , y1-a+1],   [x1-a  , y1-a+1], l_sc)   # bottom line
                pygame.draw.line(screen, self.color_pack[1], [x     , y+a-1 ],   [x1-1  , y+a-1 ], l_sc)   # top line
                pygame.draw.line(screen, self.color_pack[1], [x1-a  , y     ],   [x1-a  , y1    ], l_sc)   # right line
            else:
                pygame.draw.line(screen, self.color_pack[1], [x+a-1 , y     ],   [x+a-1 , y1    ], l_sc)   # left line
                pygame.draw.line(screen, self.color_pack[1], [x+a   , y1-a+1],   [x1-a  , y1-a+1], l_sc)   # bottom line
                pygame.draw.line(screen, self.color_pack[2], [x     , y+a-1 ],   [x1-1  , y+a-1 ], l_sc)   # top line
                pygame.draw.line(screen, self.color_pack[2], [x1-a  , y     ],   [x1-a  , y1    ], l_sc)   # right line

            offset = 1 if self.isPressed else 0
            if self.text:
                x_mod = self.text_pos_modifier[0]
                y_mod = self.text_pos_modifier[1]
                text = font.render(self.text, 1, color.FONT_ORANGE) # 2-й аргумент это сглаживание 1 - есть, 0 - нет
                b = text.get_height()
                screen.blit(text, (x+size[0]/2-len(self.text)*text_scale/5*x_mod-offset, y+b/2*y_mod+offset+text_y_offset))


import random

def simulator ():
    dice_rolling = random.randint(1,6)
    print (dice_rolling)

user_1 = input("Would you like to roll the dice? (yes/no):")

while True:
    if user_1.lower() == "yes":
        simulator ()
    elif user_1.lower() == "no":
        print ("ok see you again later")
        break
    else:
        print("please answer yes or no")
    user_1 = input("Would you like to roll the dice again (yes/no)?")


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

Purpose:
Web Scraper to obtain and analyze Northeastern's covid testing strategy

How to Execute:
$ python3 NortheasternCovidTesting.py --o output.csv
'''

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

import argparse
import time
import pandas as pd
from selenium import webdriver
from os.path import exists

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

def main():
    '''Business Logic'''
    # Read in the command line arguments
    args = get_cli()

    # Code adapted from (Parker, 2020)
    urlpage = 'https://news.northeastern.edu/coronavirus/reopening/testing-dashboard/'
    driver = webdriver.Firefox()
    driver.get(urlpage) # Want to figure out how to hide this
    time.sleep(1)

    # Obtain the data from the table
    data = findRows(driver)

    # Close the driver
    driver.quit()

    # Change data into a dataframe
    df = convertToDataframe(data)

    # Find the rate of change
    df = findRateOfChange(df)

    # Save to File
    saveFile(df, args.output)
    print('\nWeb Scrape Successful!')

def findRows(driver):
    '''
    Function: findRows
    Parameters: driver (webdriver)
    Outputs: Data (list)
    Purpose: This function finds the rows in the website and saves to a dataframe
    '''
    # Click the buttons to expand the view
    _clickButton(driver)

    # Obtain the data from the table
    rows = driver.find_elements_by_xpath('//*[@id="data-table"]/div/table/tbody')[0]

    # Save to a dataframe
    row_text = rows.text.split()

    return row_text

def _clickButton(driver):
    '''
    Function: _clickButton
    Paramters: driver (webdriver)
    Outputs: None
    Purpose: This function clicks the "Show More" button to get the whole table
    Code adapted from [2]
    '''
    # Click "Accept Cookies" button
    cookie_button = driver.find_elements_by_xpath('/html/body/div[4]/div')[0]
    print(f'Cookie Button: {cookie_button}')
    cookie_button.click()

    # Sleep for a second
    time.sleep(3)

    # Click "Load More" button
    load_more_btn = driver.find_elements_by_xpath('/html/body/div[1]/main/article/div[3]/div/div[2]/div/section[3]/button')[0]
    load_more_btn.click()

def convertToDataframe(dataset):
    '''
    Function: convertToDataFrame
    Parameters: dataset (list)
    Outputs: df (dataframe)
    Purpose: This function converts the row data to a dataframe
    '''
    # Convert to a list of lists
    dataset_lol = _buildListofLists(dataset)

    # Convert to data frame
    df = pd.DataFrame(dataset_lol, columns=['Date', 'Tests Completed',
                                            'Negative Tests', 'Negative Rate',
                                            'Positive Tests', 'Positive Rate'])

    # Convert date to datetime
    df['Date'] = pd.to_datetime(df['Date'])

    # Reverse the data frame to start with oldest date
    df = df.reindex(index=df.index[::-1])
    df.reset_index(inplace=True, drop=True)

    return df

def _buildListofLists(dataset):
    '''
    Function: _buildListofLists
    Parameters: dataset (list)
    Outputs: dataset_lol (list of lists)
    Purpose: This function converts the list into a list of lists to later be
             converted into a dataframe
    '''
    # Convert to list of lists
    dataset_lol = [dataset[x : x+6] for x in range(0, len(dataset), 6)]

    return dataset_lol

def findRateOfChange(dataframe):
    '''
    Function: findRateOfChange
    Parameters: dataframe
    Output: dataframe
    Purpose: This function finds the rate of change in the positive transmission
             rate
    '''
    dataframe['NU RoC'] = 0

    # Calculate the rate of change
    for row in dataframe.index:
        if row != 0:
            # This could be made another helper function
            dataframe.loc[row, 'NU RoC'] = float(dataframe.loc[row, 'Positive Rate'][:-1]) - float(dataframe.loc[row - 1, 'Positive Rate'][:-1])

    return dataframe

def saveFile(dataframe, output_file):
    '''
    Parameters: dataframe
                output_file (str)
    Output: None
    Purpose: Checks if output file exists, if it does it appends, otherwise
             it writes a new output file
    '''

    # Check if the file exists
    if exists(output_file):
        print('appending')
        # Append rows
        _appendRows(dataframe, output_file)

    else:
        print('New file')
        dataframe.to_csv(output_file, mode = 'w')

def _appendRows(dataframe, output_file):
    '''
    Parameters: dataframe
                output_file (str)
    Output: None
    Purpose: Finds most recent date in old output file, removes anything before
             that date in dataframe, appends new data to old data frame
    '''
    # Open the output_file
    output = pd.read_csv(output_file)

    # Find most recent date
    most_recent_date = output['Date'].max()

    # Remove any rows with a date before the most recent date
    dataframe = dataframe[dataframe['Date'] > most_recent_date]

    # Append the data to the output file
    dataframe.to_csv(output_file, mode = 'a', header = False)

def get_cli():
    '''
    Parameters: None
    Output: cli (command line instance)
    Purpose: This function gets the command line arguments
    '''
    parser = argparse.ArgumentParser(description = 'Give Output File')

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

    return parser.parse_args()

if __name__ == '__main__':
    main()

##########
# Sources
##########

'''
[1] Parker, K. (2020, June 25). Data Science Skills: Web scraping javascript using
python. Retrieved September 27, 2020, from
https://towardsdatascience.com/data-science-skills-web-scraping-javascript-using-python-97a29738353f

[2] https://stackoverflow.com/questions/37341667/click-on-show-more-button-on-nytimes-com-with-selenium
'''


def isItRight(string):
    blankCnt = 0
    for s in string:
        if s == '(':
            blankCnt += 1
        elif s == ')':
            if blankCnt == 0:
                return False
            blankCnt -= 1
    return True

def stringSplit(string):
    blankCnt = 1 if string[0] == '(' else -1
    for i in range(1, len(string)):
        if blankCnt == 0:
            return string[:i], string[i:]
        if string[i] == '(':
            blankCnt += 1
        else:
            blankCnt -= 1
    return string, ''

def solution(p):
    if isItRight(p) == True:
        return p
    u, v = stringSplit(p)
    if isItRight(u) == True:
        return u + solution(v)
    else:
        v = '(' + solution(v) + ')'
        for b in u[1:-1]:
            if b == '(':
                v += ')'
            else:
                v += '('
    return v


import mmap, os, time, signal

memoria = mmap.mmap(-1, 100)

pid = os.fork()

if pid == 0:
    # hijo
    memoria.write(b"hola papa que tal\n")
    print("offset hijo: ", memoria.tell())
    time.sleep(2)
    memoria.seek(0)
    leido = memoria.readline().decode()
    print("leido en el hijo: ", leido)
    exit()

# padre
time.sleep(1)
print("offset en el padre: ", memoria.tell())
# memoria.seek(0)
leido = memoria.readline()
print("Padre leyendo: ", leido.decode())
memoria.seek(0)
memoria.write(b"hola hijo que tal\n")

os.wait()

print("antes de irme: ")
memoria.seek(0)
print(memoria.read().decode())


import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn

import os
import sys
# os.chdir('/home/hector/project/proj-pytorch/pytorch-dt/')
sys.path.insert(0, '/home/hector/project/proj-pytorch/pytorch-dt/')

from PIL import Image, ImageDraw
from torch.autograd import Variable
from models.ssd import SSD300, SSDBoxCoder

print('Loading model..')
net = SSD300(num_classes=61)

checkpoint = torch.load('/home/hector/project/proj-pytorch/pytorch-dt/example/ssd/checkpoint/ckpt.pth')
net.load_state_dict(checkpoint['net'])
net.cuda()
# net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
net.eval()
box_coder = SSDBoxCoder(net)

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])

file_path = '/media/disk4/share/DataSet/baidu_dataset/fusai/datasets/test.txt'
with open(file_path) as f:
    lines = f.readlines()

al = len(lines)
with open(file_path[:-4]+'_submit.txt', 'w') as f:
    for num, line in enumerate(lines):
        print('{}/{}'.format(num, al))

        img_org = Image.open('/media/disk4/share/DataSet/baidu_dataset/fusai/datasets/Image/'+line[:-1])
        ow = oh = 300
        img = img_org.resize((ow, oh))

        x = transform(img)
        x = Variable(x.cuda(), volatile=True)
        loc_preds, cls_preds = net(x.unsqueeze(0))

        boxes, labels, scores = box_coder.decode(
            loc_preds.cpu().data.squeeze(), F.softmax(cls_preds.squeeze(), dim=1).cpu().data, score_thresh=0.01, nms_thresh=0.45)
        print('______________')

        _, idx = scores.sort(descending=True)

        scale = torch.Tensor([img_org.size[0], img_org.size[1],
                              img_org.size[0], img_org.size[1]])

        boxes = boxes * scale / 300

        # take gt_label for baidu race
        gt_label = labels[idx[0]].item()
        for i in range(min(8, len(idx))):
            if labels[idx[i]].item() == gt_label and scores[idx[i]].item() > 0.1:
                f.write(line[:-1])
                f.write(' {}'.format(labels[idx[i]].item()+1))
                f.write(' {}'.format(scores[idx[i]].item()))
                f.write(' {}'.format(int(boxes[idx[i]][0].item())))
                f.write(' {}'.format(int(boxes[idx[i]][1].item())))
                f.write(' {}'.format(int(boxes[idx[i]][2].item())))
                f.write(' {}'.format(int(boxes[idx[i]][3].item())))
                f.write('\n')


#!/usr/bin/python3

from itertools import permutations

s = input()
n = len(s)
suits = {x for x in s}
k = len(suits)

mini = 10000000
perms = list(permutations(list(suits)))
for p in perms:
    dp = [[0] * (k + 1) if i == 0 else [10000000] * (k + 1) for i in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, k + 1):
            dp[i][j] = min(dp[i - 1][j] + (s[i - 1] != p[j- 1]), dp[i][j - 1])
    mini = min(mini, dp[n][k])

print(mini)


from . import util, errors, dispatcher

class ProjectionBase(util.ConfigurableObject):
    def parse_config(self, config):
        super(ProjectionBase, self).parse_config(config)
        res = config.pop('resolution')  # or just give 1 number for all dimensions
        self.config.limits = util.parse_pairs(config.pop('limits', None))  # Optional, set the limits of the space object in projected coordinates. Syntax is same as numpy e.g. 'limits = [:0,-1:,:], [0:,:-1,:], [:0,:-1,:], [0:,-1:,:]'
        labels = self.get_axis_labels()
        if not self.config.limits is None:
            for lim in self.config.limits:
                if len(lim) != len(labels):
                    raise errors.ConfigError('dimension mismatch between projection axes ({0}) and limits specification ({1}) in {2}'.format(labels, self.config.limits, self.__class__.__name__))
        if ',' in res:
            self.config.resolution = util.parse_tuple(res, type=float)
            if not len(labels) == len(self.config.resolution):
                raise errors.ConfigError('dimension mismatch between projection axes ({0}) and resolution specification ({1}) in {2}'.format(labels, self.config.resolution, self.__class__.__name__))
        else:
            self.config.resolution = tuple([float(res)] * len(labels))

    def project(self, *args):
        raise NotImplementedError

    def get_axis_labels(self):
        raise NotImplementedError

class Job(object):
    weight = 1.  # estimate of job difficulty (arbitrary units)

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

class InputBase(util.ConfigurableObject):
    """Generate and process Job()s.

    Note: there is no guarantee that generate_jobs() and process_jobs() will
    be called on the same instance, not even in the same process or on the
    same computer!"""

    def parse_config(self, config):
        super(InputBase, self).parse_config(config)
        self.config.target_weight = int(config.pop('target_weight', 1000))  # approximate number of images per job, only useful when running on the oar cluster

    def generate_jobs(self, command):
        """Receives command from user, yields Job() instances"""
        raise NotImplementedError

    def process_job(self, job):
        """Receives a Job() instance, yields (intensity, args_to_be_sent_to_a_Projection_instance)

        Job()s could have been pickle'd and distributed over a cluster"""
        self.metadata = util.MetaBase('job', job.__dict__)

    def get_destination_options(self, command):
        """Receives the same command as generate_jobs(), but returns
        dictionary that will be used to .format() the dispatcher:destination
        configuration value."""
        return {}

def get_dispatcher(config, main, default=None):
    return _get_backend(config, 'dispatcher', dispatcher.DispatcherBase, default=default, args=[main])

def get_input(config, default=None):
    return _get_backend(config, 'input', InputBase, default=default)

def get_projection(config, default=None):
    return _get_backend(config, 'projection', ProjectionBase, default=default)

def _get_backend(config, section, basecls, default=None, args=[], kwargs={}):
    if isinstance(config, util.ConfigSection):
        return config.class_(config, *args, **kwargs)
    type = config.pop('type', default)
    if type is None:
        raise errors.ConfigError("required option 'type' not given in section '{0}'".format(section))
    type = type.strip()

    if ':' in type:
        try:
            modname, clsname = type.split(':')
        except ValueError as e:
            raise errors.ConfigError("invalid type '{0}' in section '{1}', error {}".format(type, section, e))
        try:
            backend = __import__('backends.{0}'.format(modname), globals(), locals(), [], 1)
        except ImportError as e:
            raise errors.ConfigError("unable to import module backends.{0}: {1}".format(modname, e))
        module = getattr(backend, modname)
    elif section == 'dispatcher':
        module = dispatcher
        clsname = type
    else:
        raise errors.ConfigError("invalid type '{0}' in section '{1}'".format(type, section))
    clsname = clsname.lower()
    names = dict((name.lower(), name) for name in dir(module))
    if clsname in names:
        cls = getattr(module, names[clsname])
        if issubclass(cls, basecls):
            return cls(config, *args, **kwargs)
        else:
            raise errors.ConfigError("type '{0}' not compatible in section '{1}': expected class derived from '{2}', got '{3}'".format(type, section, basecls.__name__, cls.__name__))
    else:
        raise errors.ConfigError("invalid type '{0}' in section '{1}'".format(type, section))


import threading
import time

class Auction:
    """Auction for a station"""

    OPEN = 'open'
    CLOSED = 'closed'

    def __init__(self, base_value, station, logs, logs_file):
        self.base_value = base_value
        self.station = station
        self.end_time = time.time() + 30
        self.bids = []
        self.winning_bid = None
        self.state = Auction.OPEN
        self.logs = logs
        self.logs_file = logs_file

        # Create thread to handle auction and results
        # The thread must be run when the end_time is reached
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

        # Lock the bid list
        self.lock = threading.Lock()

    def is_over(self):
        return self.state == Auction.CLOSED

    def add_bid(self, bid):
        if not self.is_over():
            if bid.value >= self.base_value:
                with self.lock:
                    self.bids.append(bid)
                    return True
        return False

    def next_winner(self):
        if self.winning_bid:
            with self.lock:
                self.bids.remove(self.winning_bid)
                self.winning_bid = max(self.bids, key=lambda bid: bid.value)

    def run(self):
        self.write_log("Auction for station {} started.".format(self.station.id))

        # Sleep until end_time
        while time.time() < self.end_time:
            time.sleep(1)

        self.write_log("Auction for station {} ended. Choosing the winner...".format(self.station.id))

        # Choose the winner
        with self.lock:
            self.state = Auction.CLOSED
            if self.bids:
                self.winning_bid = max(self.bids, key=lambda bid: bid.value)
                self.write_log("Auction for station {} ended. Station sold from {} to {} for {}.".format(self.station.id, self.station.airline_name, self.winning_bid.bidder_jid, self.winning_bid.value))
            else:
                self.write_log("Auction for station {} ended. No bids.".format(self.station.id))

    def write_log(self,message):
        '''Escreve os logs no ficheiro especificado, ou no stdout por default'''
        if self.logs:
            self.logs_file.write(message+'\n')


#Tags - string, nums
#https://leetcode.com/problems/sum-of-digits-in-the-minimum-number/description/
#beats 88%

class Solution:
    def sumOfDigits(self, nums: List[int]) -> int:
        num = min(nums)
        sum_ = 0
        for i in str(num):
            sum_ += int(i)
        if sum_ % 2 == 1:
            return 0
        return 1


import pytest

from startupradar.transformers.util.input import DomainInputCleaner, RedirectHandling

@pytest.fixture
def api():
    # not used currently, so none is fine
    return None

def test_domain_input_cleaner(api):
    dic = DomainInputCleaner(api)
    result = dic.get(["https://karllorey.com"])
    assert result == ["karllorey.com"]

def test_domain_input_cleaner_raw_domain(api):
    dic = DomainInputCleaner(api)
    result = dic.get(["karllorey.com"])
    assert result == ["karllorey.com"]

@pytest.mark.vcr
def test_domain_input_cleaner_redirect(api):
    url = "http://pointnine.vc"

    dic = DomainInputCleaner(api, redirect_handling=RedirectHandling.FOLLOW)
    print(dic.redirect_handling)
    result = dic.get([url])
    assert result == ["pointninecap.com"]


"""
非 dp 方法， 只能通过 71%
"""
class Solution(object):
    def maxVacationDays(self, flights, days):
        """
        :type flights: List[List[int]]
        :type days: List[List[int]]
        :rtype: int
        """
        self.result = 0
        if len(flights) == 0 or len(days) == 0:
            return self.result
        self.helper(flights, days, 0, 0, 0)
        return self.result

    def helper(self, flights, days, city, cur_week, total):
        if cur_week == len(days):
            if total > self.result:
                self.result = total
            return
        for i in xrange(len(flights[city])):
            if (i == city or flights[city][i] == 1) and i < len(days) and cur_week < len(days[i]):
                self.helper(flights, days, i, cur_week + 1, total+days[i][cur_week])

"""
方法2： dp
起始状态为在最后一个week里面在每个city所能呆的最长时间
然后从后往前更新DP数组，需要考虑flights的限制
最后在第一天的DP数组里面，找出从city 0能到达的里面天数最大的即可
"""
class Solution2(object):
    def maxVacationDays(self, flights, days):
        """
        :type flights: List[List[int]]
        :type days: List[List[int]]
        :rtype: int
        """
        m = len(days)
        n = len(days[0])
        dp = [[0 for _ in xrange(n)] for _ in xrange(m)]
        for i in xrange(m):
            dp[i][n-1] = days[i][n-1]

        for week in xrange(n-2, -1, -1):
            for city in xrange(m):
                dp[city][week] = days[city][week] + self.getMaxDays(dp, city, week+1, flights)

        return self.getMaxDays(dp, 0, 0, flights)

    def getMaxDays(self, dp, city, week, flights):
        maxDays = dp[city][week]
        for i in xrange(len(flights)):
            if flights[city][i] == 1:
                maxDays = max(maxDays, dp[i][week])
        return maxDays


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

import numpy as np
import os
import soundfile
import matplotlib.pyplot as plt

__author__ = 'Paul Magron -- IRIT'
__docformat__ = 'reStructuredText'

def record_wav(sources, audio_folder_path, estim_or_oracle, algo_name, fs=16000):
    """A function that record the sources in the .wav format
    Args:
        sources: numpy.ndarray (nsamples, nsrc) - input time signals
        audio_folder_path: string - the folder where the sounds must be recorded
        estim_or_oracle: string - 'oracle' or 'estim'
        algo_name: string - the name of the algorithm used for computing the sources
        fs: int - sample rate
    """
    # Define the file names
    if algo_name == 'ref':
        file1 = os.path.join(audio_folder_path, 'sig1.wav')
        file2 = os.path.join(audio_folder_path, 'sig2.wav')
        # Record the mixture
        soundfile.write(os.path.join(audio_folder_path, 'mix.wav'), np.sum(sources, axis=1), fs)
    else:
        file1 = os.path.join(audio_folder_path, 'sig1_' + estim_or_oracle + '_' + algo_name + '.wav')
        file2 = os.path.join(audio_folder_path, 'sig2_' + estim_or_oracle + '_' + algo_name + '.wav')

    # Record wav
    soundfile.write(file1, sources[:, 0], fs)
    soundfile.write(file2, sources[:, 1], fs)

def folder_handler(parameters, indx_speaker=0):
    """Returns a dictionary with folders paths
    Args:
        parameters: dict with audio parameters:
            'sample_rate': int - the sample rate
            'win_length': int - the window length for the STFT
        indx_speaker: int - the index of the speaker pair
    Returns:
        folders: dict with fields:
            'data': the dataset path
            'speakers': the name of the folder corresponding to the chosen speaker pair
            'outputs': the folder where the outputs (audio files, metrics, models) are stored
    """
    # Get the working directory
    working_folder = os.getcwd()

    # General info about the dataset
    dataset_name = 'HINT'
    speaker_pairs = ['F1_F2', 'M1_F1', 'M1_M2']
    database_folder = working_folder + '/data/HINT'

    # Pick the speaker pair and create a subfolder
    chosen_speaker_pair = speaker_pairs[indx_speaker]
    speaker_folders = [chosen_speaker_pair[:len(chosen_speaker_pair)//2], chosen_speaker_pair[len(chosen_speaker_pair)//2+1:]]

    # Create a subfolder for the corresponding window length
    win_length_folder = str(int(parameters['win_length'] / parameters['sample_rate'] * 1000)) + 'ms'

    # Folder to store outputs (model, training log, audio files and metrics)
    outputs_folder_path = os.path.join(working_folder, 'outputs/', dataset_name, chosen_speaker_pair, win_length_folder)
    if not os.path.isdir(outputs_folder_path):
        os.makedirs(outputs_folder_path)

    folders = {'data': database_folder,
          'speakers': speaker_folders,
          'outputs': outputs_folder_path
          }

    return folders

def display_results(outputs_folder_path):
    """Display inline the mean results for the separation and plot the error/SDR for MISI over iterations
    Args:
        outputs_folder_path: string - the folder where the 'metrics.npz' file is stored
    """
    # Load npz data
    data_loader = np.load(outputs_folder_path + '/metrics.npz')
    metric_omisi = data_loader['metric_omisi']
    metric_misi = data_loader['metric_misi']
    mean_metric_misi = np.mean(metric_misi, axis=2)

    # Display the mean results
    print(np.mean(metric_omisi, axis=1))
    print(mean_metric_misi[-1, 0])

    # Plot the loss and SI-SDR over iterations for MISI
    plt.figure()
    plt.subplot(1, 2, 1)
    plt.plot(np.log10(mean_metric_misi[:, 1]))
    plt.xlabel('Iterations')
    plt.title('log(Error)')
    plt.subplot(1, 2, 2)
    plt.plot(mean_metric_misi[:, 0])
    plt.xlabel('Iterations')
    plt.title('SI-SDRi (dB)')
    plt.tight_layout()
    plt.show()

# EOF


import math
print('''Условия задачи:
 Написать функцию, которая будет переводить градусы в радианы (без использования math.radians).
 Используя эту функцию, вывести на экран значения косинусов углов в 60, 45 и 40 градусов.
def degrees2radians(degrees): # returns float
''')

def degrees2radians(degrees):

    result_radians = degrees * math.pi/180
    return float(result_radians)

result_40 = degrees2radians(40)
result_45 = degrees2radians(45)
result_60 = degrees2radians(60)
print('Results: %.2f, %.2f, %.2f,' %  (result_40, result_45, result_60))


""" Pull out the RA and Dec of all fields """

import numpy as np
import matplotlib.pyplot as plt
from math import floor

def deg_to_ra(deg):
    """ Convert deg to RA in hh:mm:ss.ss """
    hours = deg * 24 / 360
    hh = floor(hours)
    minutes = (hours-hh)*60
    mm = floor(minutes)
    seconds = (minutes-mm)*60
    return "%s:%s:%s" %(hh,mm,seconds)

def ra_to_deg(ra):
    """ Convert RA to degrees.
    Input format: XX:XX:XX.XXXX """
    hh,mm,ss = ra.split(':')
    hours = float(hh) + float(mm)/60 + float(ss)/3600
    deg = hours*360/24
    return deg

def decl_to_deg(decl):
    """ Convert declination to degrees.
    Input format: +XX.XX.XX.XXXXX """
    dd,mm,ss,frac = decl.split('.')
    deg = float(dd) + float(mm)/60 + (float(ss+'.'+frac))/3600
    return deg

def get_field_positions():
    direc = "/Users/annaho/Dropbox/Research/VLA-GW"
    inputf = open("%s/casapy-20160615-210844.log" %direc, "r")
    log = inputf.readlines()
    inputf.close()

    sizes = np.array([len(val) for val in log])

    # When I plot the sizes, I see a jump at sizes[5510] and sizes[10988].
    # I assume that everything in between is the fields...

    # OK, the field descriptions start at log[5513]
    # and there are 5474 scans, so it makes sense that the last one
    # would be at 10987

    field_data_raw = np.array([val.split(' ') for val in log[5513:10988]])
    field_data = np.array([list(filter(None, val)) for val in field_data_raw])

    # the values are
    # DATE, TIME+stuff, ID, Code, Name, RA, Dec, Epoch, SrcID, nRows

    ra = field_data[:,5]
    dec = field_data[:,6]
    ra_deg = np.array([ra_to_deg(val) for val in ra])
    dec_deg = np.array([decl_to_deg(val) for val in dec])
    # plot(ra_deg, dec_deg)

    return ra_deg, dec_deg

def plot(ra_deg, dec_deg):
    plt.scatter(ra_deg, dec_deg, s=2, c='k')
    plt.gca().invert_xaxis()
    plt.xlabel("RA (deg)", fontsize=16)
    plt.ylabel("Dec (deg)", fontsize=16)
    plt.title("11 Feb: Region 2, Epoch 1", fontsize=16)
    #plt.show()
    plt.savefig("11feb_field_map.png")

if __name__=="__main__":
    get_field_positions()


#!/usr/bin/env python3

import graphviz

from blocks import find_blocks
from classes import BasicBlock
from dead_code_removal import remove_dead_code
from graph import create_graph
from leaders import find_leaders
from parse import parse_lines
from rules import Cpu, get_rules

def create_graphviz_graph(basic_blocks: list[BasicBlock]):
    dot = graphviz.Digraph('cfg', comment='Control flow graph', graph_attr={'rankdir': 'TB'})
    dot.attr('node', shape='box')

    for basic_block in basic_blocks:
        instruction = ''
        for line in basic_block.lines:
            joined_code = ' '.join(line.code)
            instruction += f'{line.address:04x} {joined_code}\\l'

        dot.node(str(basic_block.id), instruction)

    for basic_block in basic_blocks:
        for successor in basic_block.successors:
            if basic_block.id == successor[0].id:
                dot.edge(str(basic_block.id), str(successor[0].id), dir='back')
            else:
                dot.edge(str(basic_block.id), str(successor[0].id))

    dot.render(directory='output').replace('\\', '/')

def main():
    i8080_rules = get_rules(Cpu.I8080)

    with open('test_source_code.txt') as f:
        lines = f.readlines()

    disassembled_lines = parse_lines(lines, ignore_ranges=[(0x1a93, 0x1fff)])
    find_leaders(disassembled_lines, i8080_rules)
    basic_blocks = find_blocks(disassembled_lines)
    create_graph(basic_blocks, i8080_rules)
    basic_blocks_proper = remove_dead_code(basic_blocks, i8080_rules)
    create_graphviz_graph(basic_blocks_proper)

if __name__ == "__main__":
    main()


import random

def base():
    print("Enter [1] to get a random 3 digit number")
    print("Enter [2] to exit the program")

base()
option = int(input(""))

while option != 0:
    if option == 1:
        print(random.randrange(100, 999))
    elif option == 2:
        print("Thank you for using the program. Goodbye.")
        break
    else:
        print("Invalid option, try again")

    print()
    base()
    option = int(input(""))


import sys
input = lambda: sys.stdin.readline().rstrip()

def combMod(n, r, p):
    numer = 1
    denom = 1
    for i in range(1, r+1):
        numer = numer * (n-r+i) % p
        denom = denom * i % p
    return numer * pow(denom, p-2, p) % p

def resolve():
    n, a, b = map(int, input().split())
    mod = 10**9+7
    print((pow(2, n, mod) - 1 - combMod(n, a, mod) - combMod(n, b, mod)) % mod)

if __name__ == '__main__':
    resolve()


import psutil
import struct
import crcmod
import gdal
import pyproj
import numpy as np
import cv2
import re
import json

from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import QApplication
from plyfile import PlyData, PlyElement

_ = lambda x: x
_projections = {}

def utm_zone(coordinates):  # coordinates = (longitude, latitude)
    # if 56 <= coordinates[0] < 64 and 3 <= coordinates[1] < 12:
    #     return 32
    # if 72 <= coordinates[0] < 84 and 0 <= coordinates[1] < 42:
    #     if coordinates[1] < 9:
    #         return 31
    #     elif coordinates[1] < 21:
    #         return 33
    #     elif coordinates[1] < 33:
    #         return 35
    #     return 37
    return int((coordinates[0] + 180) / 6) + 1

def letter(coordinates):
    return 'CDEFGHJKLMNPQRSTUVWXX'[int((coordinates[1] + 80) / 8)]

def project(coordinates, zone=None):  # coordinates = (longitude, latitude)
    if not zone:
        zone = utm_zone(coordinates)
    l = 'N' if coordinates[1] > 0 else 'S'
    # print(zone, l)
    if zone not in _projections:
        _projections[zone] = pyproj.Proj(proj='utm', zone=zone, ellps='WGS84')
    x, y = _projections[zone](coordinates[0], coordinates[1])
    if y < 0:
        y += 10000000
    return x, y, zone, l

def project_array(x, y, srcp='latlong', dstp='utm', zone=None):
    """
    Project a numpy (n,2) array in projection srcp to projection dstp
    Returns a numpy (n,2) array.
    """
    if not zone:
        zone = utm_zone((x[0], y[0]))
    l = 'N' if y[0] > 0 else 'S'
    p1 = pyproj.Proj(proj=srcp, datum='WGS84')
    p2 = pyproj.Proj(proj=dstp, zone=zone, ellps='WGS84')
    fx, fy = pyproj.transform(p1, p2, x, y)
    # Re-create (n,2) coordinates
    return fx, fy, zone, l

def unproject(z, l, x, y):
    if z not in _projections:
        _projections[z] = pyproj.Proj(proj='utm', zone=z, ellps='WGS84')
    if l < 'N':
        y -= 10000000
    lng, lat = _projections[z](x, y, inverse=True)
    return lng, lat

def magnet_color(magnet, min_m=None, max_m=None):
    if not min_m and not max_m:
        min_m = np.amin(magnet)
        max_m = np.amax(magnet)
    delta = max_m - min_m
    if delta:
        colors = np.array(((magnet-min_m)/delta)*255)
        colors[colors > 255] = 255
        colors[colors < 0] = 0
        colors = colors.astype('uint8')
    else:
        colors = np.repeat(0.5*255, len(magnet)).astype('uint8')
    lut = np.empty(shape=(256, 3), dtype="uint8")
    cmap = (
        (0, (0, 0, 255)),
        (0.2, (128, 128, 255)),
        (0.5, (255, 255, 255)),
        (0.8, (255, 128, 128)),
        (1.0, (255, 0, 0))
    )

    lastval, lastcol = cmap[0]
    for step, col in cmap[1:]:
        val = int(step * 256)
        for i in range(3):
            lut[lastval:val, i] = np.linspace(lastcol[i], col[i], val - lastval)

        lastcol = col
        lastval = val
    im_color = np.empty(shape=(colors.shape[0], 3), dtype="uint8")
    for i in range(3):
        im_color[:, i] = cv2.LUT(colors, lut[:, i]).reshape(-1)
    return im_color/255

def get_point_cloud(filename, progress, zone):
    gdal_dem_data = gdal.Open(filename)
    assert gdal_dem_data is not None, _('Wrong tif type.')
    assert gdal_dem_data.RasterCount == 1, _('Wrong tif type. Too many channels.')
    no_data = gdal_dem_data.GetRasterBand(1).GetNoDataValue()
    size = 4 * gdal_dem_data.RasterYSize * gdal_dem_data.RasterYSize
    step = int(np.ceil(np.sqrt(size // (512 * 1024 * 1024))))
    step = max(1, step)
    if psutil.virtual_memory().available <= 6 * (size/step**2):
        raise MemoryError
    gdal.SetCacheMax(round((psutil.virtual_memory().available - 2 * (size/step**2)) / 2))
    arr = []
    for i in range(0, gdal_dem_data.RasterYSize, step):
        arr.append(np.copy(gdal_dem_data.ReadAsArray(0, i, gdal_dem_data.RasterXSize, 1)[:, ::step]))
        progress.setValue((i / gdal_dem_data.RasterYSize) * 25)
        QApplication.processEvents()
    dem = np.vstack(tuple(arr))

    top_left_lon, pixel_w, turn, top_left_lat, turn_, pixel_h = gdal_dem_data.GetGeoTransform()
    pixel_h *= step
    pixel_w *= step
    del gdal_dem_data, arr
    assert top_left_lon != 0 and top_left_lat != 0, _("Couldn't define metadata (top left corner)!")

    progress.setValue(25)
    height, width = dem.shape
    # picture is created from top left corner
    x_space = (np.arange(0, width))*abs(pixel_w) + top_left_lon
    y_space = (np.arange(0, -height, -1))*abs(pixel_h) + top_left_lat
    xx, yy = np.meshgrid(x_space.astype(np.float32), y_space.astype(np.float32))

    assert xx.shape == yy.shape and xx.shape == dem.shape
    X, Y, Z = xx.flatten(), yy.flatten(), dem.flatten()
    del xx, yy, dem

    mask = Z != no_data
    progress.setValue(38)
    QApplication.processEvents()
    X = X[mask]
    Y = Y[mask]
    Z = Z[mask]
    min_z = np.amin(Z)
    max_z = np.amax(Z)
    delta = max_z - min_z
    colors = np.array(((Z-min_z)/delta)*255, dtype='uint8')

    lut = np.empty(shape=(256, 3), dtype="uint8")
    # cmap = (
    #     (0, (255, 213, 0)),
    #     (0.2, (255, 85, 0)),
    #     (0.5, (255, 0, 0)),
    #     (0.8, (230, 4, 0)),
    #     (1.0, (192, 3, 0))
    # )
    cmap = (
        (0, (59, 140, 64)),
        (0.25, (162, 166, 68)),
        (0.5, (214, 212, 153)),
        (0.75, (217, 154, 37)),
        (1.0, (191, 107, 33))
    )

    lastval, lastcol = cmap[0]
    for step, col in cmap[1:]:
        val = int(step * 256)
        for i in range(3):
            lut[lastval:val, i] = np.linspace(
                lastcol[i], col[i], val - lastval)

        lastcol = col
        lastval = val
    im_color = np.empty(shape=(colors.shape[0], 3), dtype="uint8")
    for i in range(3):
        im_color[:, i] = cv2.LUT(colors, lut[:, i]).reshape(-1)

    progress.setValue(84)
    QApplication.processEvents()
    X, Y, zone, letter = project_array(X, Y, zone=zone)
    progress.setValue(98)
    QApplication.processEvents()
    pcd = np.column_stack((X, Y, Z, im_color))
    #print(pcd.shape, len(X))
    #print(pcd[:, 0], pcd.T[0])
    assert len(pcd.shape) == 2 and pcd.shape[0] == len(X) and pcd.shape[1] == 6
    return pcd, zone, letter

def save_point_cloud(point_cloud, path):
    dt = [('x', '<f4'), ('y', '<f4'), ('z', '<f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]
    vertex = np.array(np.zeros(point_cloud.shape[0]), dtype=dt)
    vertex['x'] = point_cloud[:, 0]
    vertex['y'] = point_cloud[:, 1]
    vertex['z'] = point_cloud[:, 2]
    vertex['red'] = point_cloud[:, 3]
    vertex['green'] = point_cloud[:, 4]
    vertex['blue'] = point_cloud[:, 5]
    el = PlyElement.describe(vertex, 'vertex')
    PlyData([el]).write(path)

def read_point_cloud(path):
    pcd = PlyData.read(path)
    data = pcd.elements[0].data
    if 4 * 6 * 2 * data.shape[0] >= psutil.virtual_memory().available * 0.8:
        raise MemoryError
    x = np.array(data['x'])
    y = np.array(data['y'])
    z = np.array(data['z'])
    red = np.array(data['red'])
    green = np.array(data['green'])
    blue = np.array(data['blue'])
    points = np.column_stack((x, y, z, red, green, blue))
    return points

def parse_mag_file(filepath, progress):
    crc8 = crcmod.predefined.mkCrcFun('crc-8-maxim')
    file = open(filepath, 'rb').read()
    gpst_arr = np.zeros(300000, dtype=np.uint64)
    freq_arr = np.zeros(300000, dtype=np.uint32)
    sig1_arr = np.zeros(300000, dtype=np.int32)
    sig2_arr = np.zeros(300000, dtype=np.int16)
    # sens_temp_arr = np.empty(length, dtype=np.uint16)
    # lamp_temp_arr = np.empty(length, dtype=np.uint16)
    # status_arr = np.empty(length, dtype=np.uint8)
    # dc_current_arr = np.empty(length, dtype=np.uint16)
    # board_temp_arr = np.empty(length, dtype=np.int8)
    length = len(file)
    position = 0
    gpst_counter = 0
    last_timestamp = None
    low_mask = 0xFFFF

    while position + 1 < length:
        if file[position] == 0xFE and position + file[position + 1] + 4 <= length:
            data_size = file[position + 1]
            packet = file[position:position+data_size+5]
            # if packet[-1] != crc8(packet[position+1:-1]):
            #     if packet[3] == 0x28:
            #         last_timestamp = None
            #     position += 1
            #     continue
            if packet[3] == 0x27 and last_timestamp:
                data_layout = '<HHIi'
                gpst, sig2, frequency, sig1 = struct.unpack(data_layout, packet[4:-1])

                low_timestamp = last_timestamp & low_mask
                high_timestamp = last_timestamp & ~low_mask
                high_time = high_timestamp if gpst >= low_timestamp else (high_timestamp + (low_mask + 1))

                last_timestamp = high_time + gpst
                gpst = high_time + gpst

                if position >= len(gpst_arr):
                    gpst_arr.resize(len(gpst_arr) + 100000)
                    freq_arr.resize(len(gpst_arr) + 100000)
                    sig1_arr.resize(len(gpst_arr) + 100000)
                    sig2_arr.resize(len(gpst_arr) + 100000)

                gpst_arr[gpst_counter] = gpst
                freq_arr[gpst_counter] = frequency
                sig1_arr[gpst_counter] = sig1
                sig2_arr[gpst_counter] = sig2
                gpst_counter += 1
            elif packet[3] == 0x28:
                data_layout = '<QbbHHHhHh'
                last_timestamp, version, status, lamp_t, lamp_v, dc_current, chamber_t, chamber_v, main_unit_t = \
                    struct.unpack(data_layout, packet[4: 4 + 22])
            position += data_size + 5
        else:
            position += 1

            progress.setValue((position / length) * 99)
            QApplication.processEvents()

    gpst_arr = np.copy(gpst_arr[0:gpst_counter])
    freq_arr = np.copy(freq_arr[0:gpst_counter])
    sig1_arr = np.copy(sig1_arr[0:gpst_counter])
    sig2_arr = np.copy(sig2_arr[0:gpst_counter])

    return gpst_arr, freq_arr, sig1_arr, sig2_arr
        # , sens_temp_arr, lamp_temp_arr, status_arr, dc_current_arr, board_temp_arr

class CICFilter(QObject):
    signal_output = pyqtSignal(object)

    def __init__(self):
        QObject.__init__(self)
        self.first_integrator = np.uint64(0)
        self.second_integrator = np.uint64(0)
        self.d_1_1 = np.uint64(0)
        self.d_1_2 = np.uint64(0)

        self.d_2_1 = np.uint64(0)
        self.d_2_2 = np.uint64(0)

        self.first_diff = np.uint64(0)
        self.output = np.uint64(0)
        self.counter = 0
        self.decimate_idx = 1

    def filtering(self, array):
        for i in range(len(array)):
            self.first_integrator = array[i] + self.first_integrator
            self.second_integrator = self.first_integrator + self.second_integrator
            self.counter += 1
            if self.counter % self.decimate_idx == 0:
                self.first_diff = self.second_integrator - self.d_1_1
                self.d_1_1 = self.d_1_2
                self.d_1_2 = self.second_integrator

                self.output = self.first_diff - self.d_2_1
                self.d_2_1 = self.d_2_2
                self.d_2_2 = self.first_diff
                k = (2 * self.decimate_idx) ** 2
                self.signal_output.emit(self.output / k)

class IIRFilter(QObject):
    def __init__(self):
        QObject.__init__(self)

        self.filters = {}
        try:
            with open('filters.json') as json_file:
                self.filters = json.load(json_file)
        except FileNotFoundError:
            pass

        self.clear_data = [0] * 10
        self.filtered_data = [0] * 10

        self.current_filter = None

    def set_current_filter(self, filter):
        if filter in self.filters:
            self.current_filter = filter
            self.clear_data = [0] * 10
            self.filtered_data = [0] * 10

    def filtering(self, array):
        if self.current_filter is None:
            return array
        out_put = np.zeros(array.shape)

        for i in range(len(array)):
            data = array[i]
            for block in self.filters[self.current_filter]:
                numerators = block[0:3]
                denumerators = block[3:5]
                G = block[-1]
                data = self.filter_data(data, numerators, denumerators, G)
            out_put[i] = data
        return out_put

    def filter_data(self, data, numerators, denumenators, G):
        self.clear_data.insert(0, data)
        self.clear_data.pop()
        filtered = 0
        for i in range(len(numerators)):
            filtered += numerators[i] * self.clear_data[i]
        for j in range(len(denumenators)):
            filtered -= denumenators[j] * self.filtered_data[j]
        self.filtered_data.insert(0, filtered)
        self.filtered_data.pop()
        return filtered * G


import tntorch as tn
import torch
import numpy as np

class AllIndices():

    def __init__(self, t, eps=1e-9, verbose=False):

        # if isinstance(t, tt.core.vector.vector):
        #     t = tn.Tensor([torch.Tensor(c) for c in tt.vector.to_list(t)])

        ###########################################
        # Precompute all 4 types of Sobol indices #
        ###########################################

        t = t
        N = t.dim()
        tsq = t.decompress_tucker_factors()
        for n in range(N):
            tsq.cores[n] = torch.cat([torch.mean(tsq.cores[n], dim=1, keepdim=True), tsq.cores[n]], dim=1)
        tsq = tn.cross(tensors=[tsq], function=lambda x: x ** 2, eps=eps, verbose=verbose)

        st_cores = []
        for n in range(N):
            st_cores.append(torch.cat(
                [tsq.cores[n][:, :1, :], torch.mean(tsq.cores[n][:, 1:, :], dim=1, keepdim=True) - tsq.cores[n][:, :1, :]],
                dim=1))
        st = tn.Tensor(st_cores)
        var = tn.sum(st) - st[(0,) * N]
        self.st = tn.round_tt(st / var, eps=eps)
        self.st -= tn.none(N)*self.st[(0,)*N]  # Set element 0, ..., 0 to zero
        self.sst = tn.Tensor([torch.cat([c[:, :1, :] + c[:, 1:2, :], c[:, 1:2, :]], dim=1) for c in self.st.cores])
        self.cst = tn.Tensor([torch.cat([c[:, :1, :], c[:, :1, :] + c[:, 1:2, :]], dim=1) for c in self.st.cores])
        self.tst = 1-tn.Tensor([torch.cat([c[:, :1, :] + c[:, 1:2, :], c[:, :1, :]], dim=1) for c in self.st.cores])

        ##########################################
        # Precompute all directional covariances #
        ##########################################

        # # Center the model (make it have mean 0)
        # t = t.clone() - tn.mean(t)

        # # Compute the directional function: x1 + ... + xk for
        # # every subset of variables
        # cores = []
        # for n in range(N):
        #     I = t.shape[n]
        #     c = torch.eye(2)[:, None, :].repeat(1, 2 * I, 1)
        #     c[1, I:, 0] = torch.linspace(0, 1, I)
        #     cores.append(c)
        # cores[0] = cores[0][1:2, ...]
        # cores[N - 1] = cores[N - 1][..., 0:1]
        # vecs = tn.Tensor(cores)

        # # Center all directional functions (make them have mean 0)
        # cores = []
        # for n in range(N):
        #     I = t.shape[n]
        #     c1 = torch.mean(vecs.cores[n][:, :I, :], dim=1, keepdim=True).repeat(1, I, 1)
        #     c2 = torch.mean(vecs.cores[n][:, I:, :], dim=1, keepdim=True).repeat(1, I, 1)
        #     cores.append(torch.cat([c1, c2], dim=1))
        # vecs_means = tn.Tensor(cores)
        # vecs -= vecs_means

        # # Compute the variance of all directional functions
        # vecs_sq = vecs * vecs
        # cores = []
        # for n in range(N):
        #     I = t.shape[n]
        #     c1 = torch.mean(vecs_sq.cores[n][:, :I, :], dim=1, keepdim=True)
        #     c2 = torch.mean(vecs_sq.cores[n][:, I:, :], dim=1, keepdim=True)
        #     cores.append(torch.cat([c1, c2], dim=1))
        # vecs_variance = tn.Tensor(cores)
        # vecs_variance += tn.none(N)  # To avoid division by 0

        # # Compute covariances between the model and all directional functions
        # trep = tn.Tensor([c.repeat(1, 2, 1) for c in t.cores])
        # covs = tn.cross(tensors=[trep, vecs], function=lambda x, y: x * y, verbose=verbose)
        # for n in range(N):
        #     I = t.shape[n]
        #     c1 = torch.mean(covs.cores[n][:, :I, :], dim=1, keepdim=True)
        #     c2 = torch.mean(covs.cores[n][:, I:, :], dim=1, keepdim=True)
        #     covs.cores[n] = torch.cat([c1, c2], dim=1)

        # # Tensor containing all 2^N desired indices
        # dircov = tn.cross(tensors=[covs, vecs_variance], function=lambda x, y: x / torch.sqrt(y), verbose=verbose)

        # # Normalize result so that the largest index in absolute value is 1.
        # # That should be useful for color coding
        # dircov /= max(torch.abs(tn.minimum(dircov)), torch.abs(tn.maximum(dircov)))

        # self.dircov = dircov

    def _get_index(self, variables, tensor):

        if len(variables) == 0:
            return 0

        # Read out the desired index
        idx = np.zeros(tensor.dim(), dtype=np.int)
        idx[np.array(variables)] = 1
        return tensor[tuple(idx)].item()

    def variance_component(self, variables):
        return self._get_index(variables, self.st)

    def superset_index(self, variables):
        return self._get_index(variables, self.sst)

    def closed_index(self, variables):
        return self._get_index(variables, self.cst)

    def total_index(self, variables):
        return self._get_index(variables, self.tst)

    # def directional_covariance(self, variables):
    #     return self._get_index(variables, self.dircov)

if __name__ == '__main__':  # For example and testing purposes
    torch.manual_seed(0)
    I = 32
    N = 4
    R = 5
    t = tn.rand([I]*N, ranks_tt=R)
    ind = AllIndices(t)

    s = tn.symbols(N)

    print('Variance component example:')
    print(ind.variance_component([0, 1]))
    print(tn.sobol(t, mask=tn.only(s[0]&s[1])).item())
    print()

    print('Superset index example:')
    print(ind.superset_index([0, 1]))
    print(tn.sobol(t, mask=s[0]&s[1]).item())
    print()

    print('Closed index example:')
    print(ind.closed_index([0, 1]))
    print(tn.sobol(t, mask=tn.only(s[0] | s[1])).item())
    print()

    print('Variance component example:')
    print(ind.total_index([0, 1]))
    print(tn.sobol(t, mask=s[0]|s[1]).item())
    print()


from PyQt5 import QtSql
from PyQt5 import QtCore

class MMAccountTableModel(QtSql.QSqlTableModel):
    def __init__(self, parent):
        QtSql.QSqlTableModel.__init__(self, parent)
        self.setTable("account_type")
        self.setEditStrategy(QtSql.QSqlTableModel.OnRowChange)
        self.setHeaderData(0, QtCore.Qt.Horizontal, "Id")
        self.setHeaderData(1, QtCore.Qt.Horizontal, "Name")
        self.select()


"""
There is an undirected tree where each vertex is numbered from 1 to n, and each contains
a data value. The sum of a tree is the sum of all its nodes' data values. If an edge is
cut, two smaller trees are formed. The difference between two trees is the absolute
value of the difference in their sums.
Given a tree, determine which edge to cut so that the resulting trees have a minimal
difference between them, then return that difference.
Example
    data=[1,2,3,4,5,6]
    edges=[(1,2),(1,3),(2,6),(3,4),(3,5)]
    In this case, node numbers match their weights for convenience. The graph is shown
    below.
        image
    The values are calculated as follows:
        Edge    Tree 1  Tree 2  Absolute
        Cut     Sum      Sum     Difference
        1        8         13         5
        2        9         12         3
        3        6         15         9
        4        4         17        13
        5        5         16        11
    The minimum absolute difference is 3.
    Note: The given tree is always rooted at vertex 1.
Function Description
    Complete the cutTheTree function in the editor below.
    cutTheTree has the following parameter(s):
        -int data[n]: an array of integers that represent node values
        -int edges[n-1][2]: an 2 dimensional array of integer pairs where each pair
        represents nodes connected by the edge
Returns
    int: the minimum achievable absolute difference of tree sums
Input Format
    The first line contains an integer n, the number of vertices in the tree.
    The second line contains  space-separated integers, where each integer u denotes the
    node[u] data value, data[u].
    Each of then-1  subsequent lines contains two space-separated integers u and v that
    describe edge u<-v in tree t.
Constraints
    3<=n<=10^5
    1<=data[u]<=1001, where 1<=u<=n.
Sample Input
    STDIN                       Function
    -----                       --------
    6                           data[] size n = 6
    100 200 100 500 100 600     data = [100, 200, 100, 500, 100, 600]
    1 2                         edges = [[1, 2], [2, 3], [2, 5], [4, 5], [5, 6]]
    2 3
    2 5
    4 5
    5 6
Sample Output
    400
Explanation
    We can visualize the initial, uncut tree as:
        cut-the-tree.png
    There are n-1=5 edges we can cut:
        1.Edge 1<->2 results in d_(1<->2) = 1500 - 100 = 1400
        2.Edge 2<->3 results in d_(2<->3) = 1500 - 100 = 1400
        3.Edge 2<->5 results in d_(2<->5) = 1200 - 400 = 800
        4.Edge 4<->5 results in d_(4<->5) = 1100 - 500 = 600
        5.Edge 5<->6 results in d_(5<->6) = 1000 - 600 = 400
    The minimum difference is 400.
"""

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'cutTheTree' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER_ARRAY data
#  2. 2D_INTEGER_ARRAY edges
#
sys.setrecursionlimit(10**5)

def dfs(conn , node, sums, data, parent):
    if sums[node]!=0:
        return sums[node]
    nb = conn[node]
    if len(nb)==1 and node!=0:
        sums[node] = data[node]
        return data[node]
    ans = 0
    for n1 in nb:
        if n1!=parent:
            ans += dfs(conn, n1, sums, data, node)
    ans += data[node]
    sums[node] = ans
    return ans

def cutTheTree(data, edges):
    conn = [[] for i in range(n)]
    for e in edges:
        e1 = e[0]-1
        e2 = e[1]-1
        conn[e1].append(e2)
        conn[e2].append(e1)
    sums = [0 for i in range(n)]
    dfs(conn , 0, sums, data, 0)
    print(sums)
    mindiff = 999999999
    for i in range(1, n):
        ## seperate node i
        sum1 = sums[i]
        sum2 = sums[0] - sums[i]
        diff = abs(sum1 - sum2)
        mindiff = min(mindiff, diff)
    return mindiff

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    data = list(map(int, input().rstrip().split()))

    edges = []

    for _ in range(n - 1):
        edges.append(list(map(int, input().rstrip().split())))

    result = cutTheTree(data, edges)

    fptr.write(str(result) + '\n')

    fptr.close()


# WAP to swap commas and dots in a string
# Remember that strings in python are immutable.

def swap(str1):
    newStr = ''

    for ch in str1:
        if ch == ',':
            newStr += '.'
        elif ch == '.':
            newStr += ','
        else:
            newStr += ch
    return newStr

text = 'Hi, I am Akash. Nice to meet you. Hey, are you alright?'
print("Original text:\n"+text)

print("\nAfter modification:")
print(swap(text))


import functools
from itertools import groupby
import itertools
import pathlib
import subprocess
import os
from typing import Dict, List

def ld_to_dl(ld : list, keep_dim = True) -> dict:
    #list of dicts to dict of lists
    dl = {k : [dic[k] for dic in ld if k in dic] for k in functools.reduce(set.union, [set(D.keys()) for D in ld])}
    if keep_dim:
        squeeze = lambda x: x[0] if len(x) == 1 else x
        dl = {k:squeeze(v) for k, v in dl.items()}
    return dl

def dl_to_ld(dl : dict, product = False, repeat_keys = False) -> list:
    only_scalars = {k:v for k,v in dl.items() if not(isinstance(v, list))}
    only_lists = {k:v for k,v in dl.items() if (isinstance(v, list))}

    if not(only_lists):
        return [only_scalars]

    list_lens = [len(v) for v in only_lists.values()]
    if not(all_equal(list_lens)) and not(product):
        raise ValueError("List lengths are not equal")

    if product:
        ld = [{
            k : v for k, v in zip(dl.keys(), values_)
            } for values_ in itertools.product(*only_lists.values())]
    else:
        ld = [dict(zip(only_lists,t)) for t in zip(*only_lists.values())]
    if repeat_keys:
        for d in ld:
            d.update(only_scalars)
    else:
        ld[0].update(only_scalars)
    return ld

def check_int(s : str):
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()

def try_cast_to_numeric(s : str, float_only = False):
    if s == 'false' or s == 'False':
        return False
    if s == 'true' or s == 'True':
        return True
    try:
        num = float(s)
    except:
        return s
    if not float_only:
        if check_int(s):
            num = int(s)
    return num

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

def check_homogeneous_dtype(iterable, dtype = None):
    if dtype is None:
        types = map(type, iterable)
        return all_equal(types)
    else:
        return all_equal(map(lambda x: isinstance(x, dtype), iterable))

def split_calculations(filename):
    filename = pathlib.Path(filename)
    print(f"Split all calculations in {filename.name} to separate files")
    script_dir = pathlib.Path(__file__).parent
    bash_script = str(script_dir / "scripts" / "split_output.sh")
    subprocess.run(
        [bash_script+f" {filename.name}"],
        shell =True,
        stdout=subprocess.PIPE,
        cwd = filename.parent
        )

def get_number_of_calculations_in_file(filename):
    bashCommand = f"grep 'system delimiter' {str(filename)} | wc -l"
    n = int(subprocess.check_output(bashCommand, shell = True))
    return n

import numpy as np
def read_initial_guess_file(file, reshape = False):
    init_guess = open(file)

    line = init_guess.readline().strip()

    ngradients = int(init_guess.readline().strip())

    shape = int(init_guess.readline().strip()), int(init_guess.readline().strip())

    molecules = {}
    line = init_guess.readline().strip()
    while line == "molecule":
        header = [init_guess.readline().strip() for i in range(2)]
        if header != ['all', 'state']:
            raise Exception("not implemented")
        molecule = init_guess.readline().strip()
        arr_size = shape[0]*shape[1]
        arr = [init_guess.readline().strip() for i in range(arr_size)]
        if reshape:
            arr = np.array(np.reshape(arr, shape), dtype = float)
        else:
            arr = np.array(arr, dtype = float)
        molecules.update({molecule:arr})
        line = init_guess.readline().strip()

    phibulk_solvent = float(init_guess.readline().strip())

    alphabulks = {}
    while line:
        line = init_guess.readline().strip()
        if line=="alphabulk":
            molecule = init_guess.readline().strip()
            val = float(init_guess.readline().strip())
            alphabulks.update({molecule:val})
            continue
        if line == "": continue
        if line is not None:
            raise Exception("unexpected keyword")

    return_dict = {"state" : molecules, "phibulk solvent" : phibulk_solvent, "alphabulk" : alphabulks, "gradients" : (ngradients, *shape)}

    return return_dict

def write_initial_guess(filename, initial_guess_dict):
    f = open(filename, 'w')
    def writeline(x):
        f.write(str(x))
        f.write("\n")
    writeline("gradients")
    [writeline(i) for i in initial_guess_dict["gradients"]]
    for molecule, state in initial_guess_dict["state"].items():
        writeline("molecule")
        writeline("all")
        writeline("state")
        writeline(molecule)
        vals = np.ravel(initial_guess_dict["state"][molecule])
        [writeline(v) for v in vals]
    writeline("phibulk solvent")
    writeline(initial_guess_dict["phibulk solvent"])
    for molecule, bulk in initial_guess_dict["alphabulk"].items():
        writeline("alphabulk")
        writeline(molecule)
        writeline(bulk)
    f.write("\n")


from tkinter import *

class lesson1():
    def __init__(self,root):
        self.root=root
        self.root.title("Lesson1")
        self.root.geometry("1000x900+250+5")
        root.configure(bg="#e60000")

        headline = Label(root, text="INTRODUCTION AND INTIAL TEST", font=("times new roman", 20, "bold"), fg="white", bg="#990000")
        headline.place(x=250, y=10)

        information= Label(root, text="What is Touch Typing?\nTouch typing is a keyboarding technique used to help\n you type more accurately and efficiently without looking the keyboard.", font=("times new roman", 20, "bold"), fg="white",bg="#990000")
        information.place(x=60, y=80)

        information1 = Label(root,
                            text="It Begins With the Home Keys \nStop bouncing around the keyboard and find the best position for your fingers.\nThe Home Keys, also called the home row,\n are the keys A S D F and J K L.\n They're the starting point for touch typing and the home base for each finger.",
                            font=("times new roman", 20, "bold"), fg="white", bg="#990000")
        information1.place(x=30, y=200)

        information2 = Label(root,text="Position Your Left Hand..\n.Place your left hand on the keyboard, just like in the picture. \nStarting with your little finger on the A, place remaining left hand fingers \non the S, D and F keys.Let your thumb rest on the space bar.",
                            font=("times new roman", 20, "bold"), fg="white", bg="#990000")
        information2.place(x=60, y=380)

        information3 = Label(root,
text="Now, for Your Right Hand...\nPlace your right hand on the keyboard. \nStarting with the index finger, place your fingers on the J, K, L and keys.Again\n rest your thumb on the space bar.",
                             font=("times new roman", 20, "bold"), fg="white", bg="#990000")
        information3.place(x=30, y=520)

if __name__ == '__main__':
    less1=Tk()
    app=lesson1(less1)
    less1.mainloop()


from gevent.pool import Pool
from lib.connector import AssetsConnector
from requests import HTTPError
from requests.auth import _basic_auth_str
from requests.exceptions import RetryError

class Connector(AssetsConnector):
    MappingName = 'AirWatch'
    Settings = {
        'url':        {'order': 1, 'default': "https://apidev.awmdm.com"},
        'username':   {'order': 2, 'example': "username@example.com"},
        'password':   {'order': 3, 'example': "change-me"},
        'api_token':  {'order': 4, 'example': "YOUR AirWatch API TOKEN"},
        'dep_uuid':   {'order': 6, 'default': ''}
    }

    def __init__(self, section, settings):
        super(Connector, self).__init__(section, settings)
        self.url_template = "%s/api/mdm/devices/search?pagesize={0}&page={1}" % self.settings['url']
        self.network_url_template = "%s/api/mdm/devices/{device_id}/network" % self.settings['url']
        self.dep_devices = {}  # this is the storage for the device info retrieved through the DEP-specific API

        self.__load_network_data = False
        for key, value in self.field_mappings.items():
            if 'network.' in value.get('source', ''):
                self.__load_network_data = True
                self.logger.info("Network data request.")
                break

    def get_headers(self):
        return {
            'Authorization': _basic_auth_str(self.settings['username'], self.settings['password']),
            'Accept': 'application/json',
            'aw-tenant-code': self.settings['api_token']
        }

    def device_page_url_generator(self, options):
        """
        This is generator of urls for device pages
        :return:
        """
        page = options.get('start_page', 0)
        rows = options.get('rows_per_page', 250)
        while True:
            yield self.url_template.format(rows, page)
            page += 1

    def get_device_page_info(self, page_url):
        """
        This is method used to return page information
        :param page_url: url for the airwatch `page`
        :return:
        """
        response = self.get(page_url)

        if response.status_code == 204:
            # Sometimes it is just an empty response!
            self.logger.warning("Got a 204 (Empty Response) from AirWatch! No devices found to process.")
            return []

        response = response.json()
        return response['Devices']

    def device_page_generator(self, options):
        """
        Page info generator
        :param options:
        :return:
        """

        pool_size = self.settings['__workers__']

        connection_pool = Pool(size=pool_size)

        for page in connection_pool.imap(self.get_device_page_info, self.device_page_url_generator(options), maxsize=pool_size):
            if not page:
                break
            yield page

    def retrieve_device_info(self, devices):
        """
        Extract device info

        :param devices: list of devices to process
        :return:
        """
        def set_network_info(device):
            device['network'] = self._load_network_information(device.get('Id', {}).get('Value', ''))
            return device

        def set_dep_info(device):
            serial_number = device.get('SerialNumber')
            if serial_number:
                dep_info_about_device = self.dep_devices.get(serial_number)
                if dep_info_about_device:
                    device['dep'] = dep_info_about_device
            return device

        # extend the info about devices using info from the separate API
        if self.dep_devices:
            devices = list(map(set_dep_info, devices))

        if self.__load_network_data:
            pool_size = self.settings['__workers__']
            connection_pool = Pool(size=pool_size)
            processed_devices = connection_pool.map(set_network_info, devices)
        else:
            processed_devices = devices

        return processed_devices

    def _load_records(self, options):

        if self.settings.get('dep_uuid'):
            # if the dep_uuid is given, we have to retrieve the different subset of devices from the separate API
            # it is not clear from the docs if the API supports pagination, looks like not
            # also this API is supported only by the AirWatch starting from 9.2(?)
            dep_api_url = '%s/api/mdm/dep/groups/%s/devices' % (self.settings['url'], self.settings['dep_uuid'])
            self.dep_devices = {_['deviceSerialNumber']: _ for _ in self.get(dep_api_url).json()}

        pool_size = self.settings['__workers__']

        connection_pool = Pool(size=pool_size)

        for device_info in connection_pool.imap(self.retrieve_device_info, self.device_page_generator(options), maxsize=pool_size):
            if not device_info:
                break
            yield device_info

    def _load_network_information(self, device_id):
        try:
            if not device_id:
                return {}

            url = self.network_url_template.format(device_id=device_id)
            response = self.get(url).json()
            return response
        except (HTTPError, RetryError):
            self.logger.exception("Error trying to load network details for device: %s", device_id)
            return {}


# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 23:37:12 2023

@author: USER
"""

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread('lena.jpg')
print(img.shape)

#%%
#gray = np.ones((128,128,3), dtype=np.uint8)
cv.imshow("Color",img)

b,g,r = cv.split(img)
#print(b.shape)
#cv.imshow("Green",g)
#cv.imshow("Red",r)
#cv.imshow("Blue",b)
r[:]=0
b[:]=0
merged = cv.merge((b,g,r))
#cv.imshow("Merged",merged )

#%%
image_bordered = cv.copyMakeBorder(src=img, top=25, bottom=25, left=25, right=25,borderType= cv.BORDER_CONSTANT)#BORDER_WRAP, cv.BORDER_REFLECT
print(image_bordered.shape)
cv.imshow("Bordered",image_bordered )

#%%
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow("GRAY", gray)

#%%
im = plt.imread("Lena.jpg")
gray = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
plt.title("GRAY IMG")
plt.imshow(gray,"gray", vmin=0, vmax=255)
plt.show()

cv.waitKey(0)
cv.destroyAllWindows()


# Question 16

# Level 2

# Question: Use a list comprehension to square each odd number in a list. The
# list is input by a sequence of comma-separated numbers. Suppose the following
# input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should
# be: 1,3,5,7,9

# Hints: In case of input data being supplied to the question, it should be
# assumed to be a console input.

string_list = input("Write a sequence of comma-separated numbers: ").split(',')

numbers_list = [odd for odd in string_list if int(odd) % 2 != 0]

print(','.join(numbers_list))


import cv2
import numpy as np
import os.path
from sys import argv

if len(argv) < 2:
    print("Usage: {} img_file [img_file ...]".format(argv[0]))
    exit()

# process images
for fn in argv[1:]:
    img = cv2.imread(fn)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 50, 120)
    minLineLength = 20
    maxLineGap = 5
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 10, minLineLength, maxLineGap)
    for line in lines:
        for x1, y1, x2, y2 in line:
            print(x1, y1, x2, y2)
            cv2.line(img, (x1,y1), (x2,y2), (0, 255, 0), 8)
    fn1 = os.path.split(fn)
    fn2 = os.path.join(fn1[0], "e_" + fn1[1])
    fn3 = os.path.join(fn1[0], "l_" + fn1[1])
    cv2.imwrite(fn2, edges)
    cv2.imwrite(fn3, img)

    cv2.imshow('img', img)
    cv2.waitKey(0)
    cv2.imshow('edges', edges)
    cv2.waitKey(0)


from django.urls import path

from . import views

app_name = "institute"
urlpatterns = [
    path('institutes', views.AllInstituteView.as_view(), name='institutes'),
    path('ajax/load-state/', views.load_state, name='ajax_load_state'),
    path('ajax/load-city/', views.load_cities, name='ajax_load_city'),
    path('institute_detail/<int:pk>', views.InstituteDetailView.as_view(), name='institute_detail'),
    path('edit_institute_view/<int:pk>/', views.InstituteEditView.as_view(), name='edit_institute_view'),
    path('delete_institute/',  views.InstituteDeleteView.as_view(), name='crud_ajax_delete'),
    path('add_institute/', views.AddInstituteView.as_view(), name="add_institute"),
    path('edit_institute/', views.EditInstituteView.as_view(), name="edit_institute"),
    path('edit_institute_image/', views.InstituteImageEdit.as_view(), name="edit_institute_image"),

]