from datetime import datetime

def getBasicInfo():
    choice = input("""\t1. Add new income
    2. Add new expense
    3. Check current balance (income - expenses)
    4. Check specific month's balance
    5. Check specific month's income data
    6. Check specific month's expenses data
    7. Check total income by category
    8. Check total expenses by category
    9. Exit the program
    Choose an option (int): """)
    return choice

def addNewIncome():
    is_correct = True
    info = "New income was not added due to:"
    arr = []
    month_id = None
    amount = None

    name = str(input("Enter income name [str]: "))
    try:
        amount = int(input("Enter income amount [int]: "))
    except ValueError:
        info += "\nIncorrect datatype for amount."
        is_correct = False
    category = str(input("Enter income category [str]: "))
    datetime_str = str(input("Enter date & time of income (YYYY-MM-DD HH:MM:SS) or leave blank to add current date % "
                             "time [str]: "))
    if datetime_str == "":
        datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if checkIfDateTimeIsValid(datetime_str):
        month_id = int(datetime_str[5:7])
    else:
        info += "\nIncorrect pattern for datetime field."
        is_correct = False

    arr.append(name)
    arr.append(amount)
    arr.append(category)
    arr.append(datetime_str)
    arr.append(month_id)
    arr.append(is_correct)
    arr.append(info)
    return arr

def addNewExpense():
    arr = addNewIncome()
    note = str(input("Enter note (optional) [str]: "))
    arr.insert(5, note)

    return arr

def getMonth(month):
    months = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6,
              "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}

    if isinstance(month, int):
        for name, month_id in months.items():
            if month_id == month:
                return name

    elif isinstance(month, str):
        month_id = months.get(month)
        return month_id

def checkForMonth(month):
    month_id = None

    if len(month) > 2:
        if getMonth(month.capitalize()) is not None:
            month_id = getMonth(month.capitalize())
        else:
            print("Incorrect month name input.")
    elif 2 >= len(month) > 0 and 1 <= int(month) <= 12:
        month_id = month
    else:
        print("Month with this ID does not exist.")

    return month_id

def checkIfDateTimeIsValid(datetime_str):
    try:
        datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        return True
    except ValueError:
        return False


n = int(input())
player = []
for _ in range(n):
    c,k = map(int,input().split())
    player.append((c,k))

player.sort(reverse=True)

largest = 0
cnt = 0
for x,y in player:
    if y > largest:
        largest = y
        cnt+=1

print(cnt)


from selenium import webdriver
from selenium.webdriver.common.by import By
options = webdriver.FirefoxOptions()
options.add_argument('--headless')
import time

class jay:

    driver = webdriver.Firefox()

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

    def by_anchor_tag(self,anchor_tag_link):
        try:
            driver = webdriver.Firefox(firefox_options=options)
            self.driver.get(self.url)
            anchor_tag_link = self.driver.find_element(by = By.LINK_TEXT , value = anchor_tag_link)
            time.sleep(7)
            anchor_tag_link.click()

        except:
            print("anchor tag not found !")

url_1 = "https://www.w3schools.com"

s = jay(url_1)

s.by_anchor_tag("HTML Reference")


import sys
nombres = sys.stdin.readline().split()
nombre1 = int(nombres[0])
nombre2 = int(nombres[1])
nombre3 = int(nombres[2])
for i in range(1,nombre3+1):
    if i % nombre1 == 0:
        if i % nombre2 == 0:
            print("FizzBuzz")
        else:
            print("Fizz")
    else:
        if i % nombre2 == 0:
            print("Buzz")
        else:
            print(i)


import logging
import os.path
import random
import time

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, \
    ElementNotInteractableException
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from util.mode import Mode
from util.util import Util

class Better:

    def __init__(self, config):
        self.is_bet = config.bet
        self.bet_tournament = config.bet_tournament
        self.bet_streak = config.bet_streak
        self.bet_ignore = config.bet_ignore
        self.simple_ui = config.simple_ui
        self.amount = config.amount
        self.amount_direct = config.amount_direct
        self.amount_close = config.amount_close
        self.min_balance = config.min_balance
        self.min_balance_streak = config.min_balance_streak
        self.max_streak = config.max_streak
        self.max_balance = config.max_balance
        self.close_range = config.close_range
        self.least_matches = config.least_matches

        self.driver = None
        self.init()

    def init(self):
        if not self.is_bet:
            return
        self.init_driver()
        self.log_in()
        if self.simple_ui:
            self.remove_unused()

    def init_driver(self):
        if os.path.exists('chromedriver.exe'):
            self.driver = webdriver.Chrome(executable_path='chromedriver.exe')
        else:
            self.driver = webdriver.Chrome()

    def log_in(self):
        self.driver.get('https://www.saltybet.com/authenticate?signin=1')
        wait = WebDriverWait(self.driver, 300)
        wait.until(expected_conditions.url_to_be('https://www.saltybet.com/'))
        wait.until(self.is_loaded)

    def remove_unused(self):
        self.driver.execute_script('document.getElementById("video-embed").remove()')
        self.driver.execute_script('document.getElementById("chat-frame-stream").remove()')
        self.driver.execute_script('document.getElementById("sbettorswrapper").remove()')

    def is_loaded(self, driver):
        return driver.execute_script('return document.readyState') == 'complete'

    def bet(self, player_stats):
        try:
            self.try_bet(player_stats)
        except (NoSuchElementException, StaleElementReferenceException, ElementNotInteractableException):
            logging.warning('Error occurred while trying to bet!')

    def try_bet(self, player_stats):
        logging.info(f'Current balance: {self.get_balance()}')

        if not self.is_bet:
            logging.info('Betting is disabled.')
            return

        if player_stats.mode == Mode.EXHIBITION:
            logging.info('Exhibition betting is disabled.')
            return

        if not self.bet_tournament and (player_stats.mode == Mode.TOURNAMENT or
                                        player_stats.mode == Mode.MATCHMAKING and player_stats.left <= 1):
            logging.info('Tournament betting is disabled.')
            return

        if self.is_ignored(player_stats):
            logging.info('Character is ignored.')
            return

        if not self.has_least_matches(player_stats):
            logging.info('Least matches criteria not met.')
            return

        if self.bet_streak:
            self.bet_streak_mode(player_stats)
        else:
            self.bet_normal_mode(player_stats)

    def bet_streak_mode(self, player_stats):
        streak = self.get_streak()
        if self.max_streak > 0 and streak >= self.max_streak:
            return

        balance = self.get_balance()
        if balance == 0:
            return

        streak_balance = balance - self.min_balance_streak
        amount = self.get_normal_amount(player_stats)

        if streak < 0:
            if streak_balance <= 0:
                self.bet_amount_player(player_stats=player_stats, amount=1, probable=True)
            else:
                self.bet_amount_player(player_stats=player_stats, amount=streak_balance, probable=False)
        elif streak > 0:
            if streak_balance <= 0:
                self.bet_amount_player(player_stats=player_stats, amount=1, probable=True)
            elif streak_balance != streak:
                self.bet_amount_player(player_stats=player_stats, amount=streak_balance, probable=False)
            elif amount > 0:
                self.bet_amount_player(player_stats=player_stats, amount=1, probable=True)

    def bet_normal_mode(self, player_stats):
        amount = self.get_normal_amount(player_stats)
        self.bet_amount_player(player_stats=player_stats, amount=amount, probable=True)

    def bet_amount_player(self, player_stats, amount: int, probable: bool):
        if amount <= 0:
            return

        time.sleep(random.randint(5, 8))

        self.bet_amount(amount)

        if self.is_probability_range(player_stats, player_stats.p1):
            if probable:
                self.bet_player_p1(player_stats, amount)
            else:
                self.bet_player_p2(player_stats, amount)
        elif self.is_probability_range(player_stats, player_stats.p2):
            if probable:
                self.bet_player_p2(player_stats, amount)
            else:
                self.bet_player_p1(player_stats, amount)

    def is_ignored(self, player_stats):
        in_ignore = player_stats.p1.name in self.bet_ignore or player_stats.p2.name in self.bet_ignore
        return in_ignore and player_stats.mode != Mode.TOURNAMENT

    def has_least_matches(self, player_stats):
        if player_stats.is_direct_explicitly():
            return player_stats.p1_direct.total >= self.least_matches
        return player_stats.p1.total_games >= self.least_matches and player_stats.p2.total_games >= self.least_matches

    def is_probability_range(self, player_stats, player):
        skill_probability = player_stats.get_bet_probability_player(player)
        if player_stats.mode == Mode.TOURNAMENT:
            return skill_probability is not None and skill_probability >= 0.5

        p1_wl_ratio = player_stats.get_wl_ratio_player(player_stats.p1)
        p2_wl_ratio = player_stats.get_wl_ratio_player(player_stats.p2)
        if p1_wl_ratio is None or p2_wl_ratio is None:
            return False

        if player == player_stats.p1:
            return p1_wl_ratio > p2_wl_ratio
        else:
            return p1_wl_ratio < p2_wl_ratio

    def bet_player_p1(self, player_stats, amount):
        self.bet_player('player1', player_stats, amount)

    def bet_player_p2(self, player_stats, amount):
        self.bet_player('player2', player_stats, amount)

    def bet_player(self, player_id, player_stats, amount):
        player = player_stats.p1 if player_id == 'player1' else player_stats.p2
        player_input = self.driver.find_element(value=player_id)
        player_input.click()
        logging.info(f'Betting: {player.name} ({Util.get_amount(amount)} | {Util.get_amount(self.get_balance())})')

    def bet_amount(self, amount):
        wager_input = self.driver.find_element(value='wager')
        wager_input.send_keys(str(amount))

    def get_normal_amount(self, player_stats):
        if player_stats.is_direct_explicitly():
            return self.get_amount(player_stats, self.amount_direct)

        p1_wl_ratio = player_stats.get_wl_ratio_player(player_stats.p1)
        p2_wl_ratio = player_stats.get_wl_ratio_player(player_stats.p2)
        if p1_wl_ratio is None or p2_wl_ratio is None:
            logging.info('Probability is undecided.')
            return 0

        diff = self.close_range / 200
        if p1_wl_ratio >= 0.5 + diff and p2_wl_ratio <= 0.5 - diff or \
                p2_wl_ratio >= 0.5 + diff and p1_wl_ratio <= 0.5 - diff:
            logging.info('Far probability.')
            return self.get_amount(player_stats, self.amount)
        else:
            logging.info('Close probability.')
            return self.get_amount(player_stats, self.amount_close)

    def get_amount(self, player_stats, amount):
        mode = player_stats.mode
        if mode == Mode.MATCHMAKING or mode == Mode.TOURNAMENT:
            balance = self.get_balance()
            if mode == Mode.MATCHMAKING:
                if 0 < self.max_balance <= balance:
                    logging.info('Max balance reached.')
                    return 0
                max_amount = balance - self.min_balance
                if max_amount < 0:
                    logging.info('Min balance reached.')
                    return 0
                amount = min(amount, max_amount)
                return min(balance, amount)
            if mode == Mode.TOURNAMENT:
                return balance
        return 0

    def get_balance(self):
        balance_text = self.driver.find_element(value='balance').text
        balance_text = balance_text.replace(',', '')
        return int(balance_text) if balance_text else 0

    def get_streak(self):
        streak_text = self.driver.find_element(value='betStreak').text
        return int(streak_text) if streak_text else 0


from torch.utils.data import DataLoader
from datasets.coco_dataset import COCO_Dataset
import datasets.transforms_ as T
from torch.utils.data.distributed import DistributedSampler

def build_dataloader(opts):

    transform_test = T.Compose([
        T.Resize([800, 800]),
        T.ToTensor(),
    ])

    test_set = COCO_Dataset(data_root=opts.data_root,
                            split='val',
                            download=True,
                            transform=transform_test,
                            boxes_coord=opts.boxes_coord,
                            visualization=False)

    test_loader = DataLoader(test_set,
                             batch_size=opts.batch_size,
                             collate_fn=test_set.collate_fn,
                             shuffle=False,
                             num_workers=opts.num_workers,
                             pin_memory=True)

    if opts.distributed:
        test_loader = DataLoader(test_set,
                                 batch_size=int(opts.batch_size / opts.world_size),
                                 collate_fn=test_set.collate_fn,
                                 shuffle=False,
                                 num_workers=int(opts.num_workers / opts.world_size),
                                 pin_memory=True,
                                 sampler=DistributedSampler(dataset=test_set, shuffle=False),
                                 drop_last=False)

    opts.num_classes = 91
    return test_loader


from django.urls import path, include
# Импортируем созданное нами представление
from .views import PostList,PostDetail,PostCreate,PostUpdate,PostDelete,subscribe_me,PostCount, upgrade_me, notsubscribe_me, TTT
from django.views.decorators.cache import cache_page

urlpatterns = [
    path('', cache_page(60)(PostList.as_view()), name='post_list'),
    path('<int:pk>', PostDetail.as_view(), name='post_detail'),
    path('news/create/', PostCreate.as_view(), name='news_create'),
    path('news/<int:pk>/edit/', PostUpdate.as_view(), name='news_edit'),
    path('news/<int:pk>/delete/', PostDelete.as_view(), name='news_delete'),
    path('articles/create/', PostCreate.as_view(), name='post_create'),
    path('articles/<int:pk>/edit/', PostUpdate.as_view(), name='post_edit'),
    path('articles/<int:pk>/delete/', PostDelete.as_view(), name='post_delete'),
    path('subscribe/', subscribe_me, name='subscribe'),
    path('notsubscribe/', notsubscribe_me, name='notsubscribe'),
    path('post_count/', PostCount.as_view(), name='post_count'),
    path('upgrade/', upgrade_me, name='upgrade'),
    path('hello', TTT.as_view(), name='index_ttt'),
    path('i18n/', include('django.conf.urls.i18n'))
    ]


#!/usr/bin/env python3

import pygame as pg
import colors as col
import solar_vis as vis
import solar_model as physics
import solar_input as file_io

def main():
    pg.init()

    screen = pg.display.set_mode((vis.window_width, vis.window_height))
    GUI_manager = vis.InterfaceManager(screen)
    model = physics.Model([])

    clock = pg.time.Clock()
    quit_flag = False

    while not quit_flag:
        time_delta = clock.tick(60) / 1000.0
        if GUI_manager.is_running:
            model.update(time_delta * GUI_manager.get_speed())

        screen.fill(col.black)
        GUI_manager.update(time_delta, model.time)
        for event in pg.event.get():
            GUI_manager.process_event(event)
            if event.type == pg.QUIT:
                quit_flag = True
            elif event.type == vis.LOADEVENT:
                model = physics.Model(file_io.load_from_file(event.file))
            elif event.type == vis.SAVEEVENT:
                file_io.save_to_file(model.objects, event.file)

        vis.draw_objects(model.objects, model.scale_factor, screen)
        pg.display.update()

if __name__ == "__main__":
    main()


# IMPORTS #
import os
import requests
from bs4 import BeautifulSoup as bs

# SET VARIABLES #
url = "https://unsplash.com/search/photos/puppet"
page = requests.get(url)
soup = bs(page.text, 'html.parser')
image_tags = soup.find_all('img')
i = 0

# CREATE DIRECTORY TO STORE IMAGES #

if not os.path.exists('puppet'):
    os.makedirs('puppet')

# CHANGE TO CREATED DIRECTORY
os.chdir('puppet')

# DOWNLOAD 50 IMAGES INTO FOLDER #
for image in image_tags:
    try:
        url = image['src']
        source = requests.get(url)
        if source.status_code == 200 and i < 50:
            with open('puppet_' +str(i) + '.jpg', 'wb') as f:
                f.write(requests.get(url).content)
                f.close()
                i += 1
    except:
        pass


import numpy as np

def max_pooling(A,k):
    n, p = A.shape
    B = A.reshape(n//k,k,p//k,k)
    C = B.transpose((0, 2, 1, 3))
    D = C.max(axis=(2,3))
    return D

def average_pooling(A,k):
    n, p = A.shape
    B = A.reshape(n//k,k,p//k,k)
    C = B.transpose((0, 2, 1, 3))
    D = C.mean(axis=(2,3))
    return D

# Un exemple

A = np.arange(24)     # liste d'entier
np.random.shuffle(A)  # mélange aléatoire
A = A.reshape((4,6))  # matrice

print("\n===== Exemple =====")
print("Matrice de départ :\n",A)
print("Taille de la matrice de départ", A.shape)

B = max_pooling(A,2)
print("Matrice après max-pooling :\n", B)
print("Taille de la matrice d'arrivée", B.shape)

C = average_pooling(A,2)
print("Matrice après pooling en moyenne :\n", C)
print("Taille de la matrice d'arrivée", C.shape)

################################
################################

# Exemple pas à pas pour comprendre comment
# fonctionne les fonctions ci-dessus

def exemple():
    N = 6  # taille de la matrice initiale
    k = 3  # taille du pooling

    # matrice résultatnte sera de taille N//k

    A = np.arange(N**2).reshape((N,N))

    n, p = A.shape
    B = A.reshape(n//k,k,p//k,k)
    C = B.transpose((0, 2, 1, 3))
    D = C.max(axis=(2,3))

    print("===== Exemple pas à pas =====")
    print("Matrice de départ :\n", A)
    print("Taille de la matrice de départ", A.shape)

    print('Première sous matrice : \n', C[0,0])
    print('Max de cette sous matrice', C[0,0].max())
    print('Matrice des max : \n', C.max(axis=(2,3)))
    print('Matrice des moyennes :\n', C.mean(axis=(2,3)))

    return

exemple()


# Задача 6
# Вы пользуетесь общественным транспортом? Вероятно, вы расплачивались за проезд и получали билет с номером.
# Счастливым билетом называют такой билет с шестизначным номером, где сумма первых трех цифр равна сумме последних трех.
# Пример:
# 385916 -> yes
# 123456 -> no

a = input("Введите номер билета: ")
while len(a) != 6:
    print("Это не тот билет, введите номер билета из 6 цифр:")
    a = input()
if int(a[0]) + int(a[1]) + int(a[2]) == int(a[3]) + int(a[4]) + int(a[5]):
    print("Билет счастливый!")
else:
    print("Билет не счастливый")


""" Discord bot """

#! /usr/bin/env python3

import discord
from discord.ext import commands
from typing import Dict, List, Any

from compute.middle_layer import check_backend
from utils.env import TOKEN, CHANNEL, GUILD, CMD_PREFIX

CUSTOM_COGS = ["cogs.players_cmds", "cogs.elevated_cmds"]

NEED_REGISTER_FUNCS = {"submit-by-map-name", "submit", "unregister", "rename", "mysubs", "cancelsub"}

# BOT FUNCTIONS START HERE
BOT = commands.Bot(command_prefix=CMD_PREFIX)

@BOT.check
def check_channel(ctx):
    if str(ctx.channel) in CHANNEL and str(ctx.guild) in GUILD:
        return True
    else:
        raise commands.errors.CheckFailure("channelerr")

@BOT.event
async def on_ready():
    print(f"{BOT.user.name} has connected to Discord and ready to get cmds")

@BOT.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.NoPrivateMessage):
        await ctx.send("Sorry, this command is not available in DMs.")
        return
    if isinstance(error, commands.errors.CheckFailure):
        if str(error) == "channelerr":
            print(
                f"[CHANNELERR] {ctx.author} asked for {ctx.message.content} on chan {ctx.channel} of {ctx.guild} at {ctx.message.created_at}"
            )
            return
        try:
            # Check if player is registered
            err_str = str(error)
            command_failed = err_str.split('command')[1].split('failed')[0].strip()
            print(str(error))
            print(err_str)
            print(command_failed)
            if command_failed in NEED_REGISTER_FUNCS:
                await ctx.send('Player not registered. Please use `!register "YOUR_INGAME_NAME"` (yeah, with **quotes** ^^) to register.\n \
    Exple : `!register "OMDN | Gneuh [knee-uh]"`')
                return
        except IndexError:
            await ctx.send("Sorry, you do not have the correct role for this command.")
            return
    if isinstance(error, commands.errors.CommandOnCooldown):
        await ctx.send(
            "Sorry, we have to limit this command to 1 use every 60 seconds..."
        )
        return
    else:
        print(error)
        return

def start_bot() -> None:
    # Ensure that backend is coherent and up&running before anything
    if not check_backend():
        print("Hmm, backend is having issues. Is mongodb up? Stopping here")
        return

    for cust_cog in CUSTOM_COGS:
        BOT.load_extension(cust_cog)

    BOT.run(TOKEN, bot=True, reconnect=True)

if __name__ == "__main__":
    start_bot()


from collections import Counter

import pytest

from startupradar.transformers.basic import (
    DomainNameTransformer,
    CommonStringTransformer,
    CounterTransformer,
)
from startupradar.transformers.util.exceptions import InvalidDomainError

DOMAINS_INVALID = [
    "127.0.0.1",
    "localhost",
    "api.startupradar.co",
    "www.startupradar.co",
]

def test_domain_name_transformer_lengths():
    t = DomainNameTransformer()
    df = t.transform(["karllorey.com", "startupradar.co"])
    assert df["length"].values.tolist() == [9, 12]

@pytest.mark.parametrize("invalid_domain", DOMAINS_INVALID)
def test_domain_name_transformer_raises(invalid_domain):
    t = DomainNameTransformer()
    with pytest.raises(InvalidDomainError):
        t.transform([invalid_domain])

def test_domain_name_transformer_feature_names_out():
    t = DomainNameTransformer()
    df = t.transform(["karllorey.com", "startupradar.co"])
    assert df.columns.tolist() == t.get_feature_names_out()

def test_common_string_transformer():
    t = CommonStringTransformer(max_df=1.0, min_df=0.5, ngram_range=(3, 5))
    domains = ["kit.edu", "hs-ka.de", "rwth-aachen.de", "rwth-campus.com"]
    df_out = t.fit_transform(domains)
    common_substrings = [
        ".de",
        "rwt",
        "rwth",
        "rwth-",
        "th-",
        "wth",
        "wth-",
    ]
    assert df_out.columns.values.tolist() == common_substrings

def test_counter_transformer():
    class CharacterCount(CounterTransformer):
        def create_counter(self, x):
            # count characters
            return Counter(list(x))

    out = CharacterCount().fit_transform(["aaa", "bbb", "abc"])

    assert set(out.columns) == set("abc")
    assert out["a"].values.tolist() == [3, 0, 1]
    assert out["b"].values.tolist() == [0, 3, 1]
    assert out["c"].values.tolist() == [0, 0, 1]


from datetime import datetime

from flask import Blueprint, render_template, request, g, redirect, url_for, flash
from blueprints.forms import QuestionForm, AnswerForm
from exts import db
from decorators import login_required, admin_login_required
from models import QuestionModel, AnswerModel, UserModel

# /auth
bp = Blueprint('admin_question', __name__, url_prefix='/admin_question')

# http://127.0.0.1:5000
@bp.route('/')
@admin_login_required
def index():
    page = request.args.get('page', 1, type=int)
    per_page = 5  # Set the number of questions per page
    offset = (page - 1) * per_page
    questions = QuestionModel.query.limit(per_page).offset(offset).all()
    total_questions= QuestionModel.query.count()
    pages = total_questions // per_page + (total_questions % per_page > 0)
    return render_template('admin/question/admin_question.html', questions=questions,
                           total_questions=total_questions, per_page=per_page,
                           pages=pages, page=page
                           )

@bp.route('/add_question', methods=['GET', 'POST'])
@admin_login_required
def add_question():
    print(request.form)
    if request.method == 'POST':
        form = QuestionForm(request.form)
        new_question = QuestionModel(
            title=form.title.data,
            content=form.content.data,
            author_id = '111'
        )
        print(new_question.title)
        db.session.add(new_question)
        db.session.commit()
        flash('New question was added successfully!', 'success')
        return redirect(url_for('admin_question.index'))
    return render_template('admin/question/add_question.html')

class DeleteQuestionForm:
    pass

@bp.route('/delete_question/<int:question_id>', methods=['GET', 'POST'])
@admin_login_required
def delete_question(question_id):
    question = QuestionModel.query.get_or_404(question_id)
    form = DeleteQuestionForm()
    if request.method == 'POST':
        answers = AnswerModel.query.filter_by(question_id=question.id)

        for answer in answers:
            db.session.delete(answer)
        db.session.delete(question)
        db.session.commit()
        return redirect(url_for('admin_question.index'))
    return render_template('admin/question/delete_question.html',
                           question=question, form=form)

@bp.route('/edit_question/<int:question_id>', methods=['GET', 'POST'])
@admin_login_required
def edit_question(question_id):
    question = QuestionModel.query.get_or_404(question_id)
    form = QuestionForm(obj=question)
    if request.method=='POST':
        form.populate_obj(question)
        db.session.commit()
        flash('Question updated successfully!', 'success')
        return redirect(url_for('admin_question.index'))
    return render_template('admin/question/edit_question.html', form=form)


#!/usr/bin/env python3

import logging
import os
import sys

import netaddr
import requests
import yaml

logger = logging.getLogger("dhcp-hook")
if not logger.handlers:
    formatter = logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
    # stdout logging
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

def get_apidata(configfile="/etc/cnaas-nms/apiclient.yml"):
    with open(configfile, "r") as apiclient_file:
        return yaml.safe_load(apiclient_file)

def get_jwt_token():
    try:
        token = os.environ["JWT_AUTH_TOKEN"]
    except Exception:
        raise ValueError("Could not find JWT token")
    return token

def canonical_mac(mac):
    """Return a standardized format of MAC-addresses for CNaaS to
    store in databases etc."""
    na_mac = netaddr.EUI(mac)
    na_mac.dialect = netaddr.mac_bare
    return str(na_mac)

def main() -> int:
    if len(sys.argv) < 3:
        return 1

    if sys.argv[1] == "commit":
        try:
            ztp_mac = canonical_mac(sys.argv[2])
            dhcp_ip = sys.argv[3]
            platform = sys.argv[4]
        except Exception as e:
            print(str(e))
            return 2

        apidata = get_apidata()
        base_url = apidata["cnaas_nms"]["base_url"]
        verify_tls = apidata["cnaas_nms"]["verify_tls"]
        params = {"filter[ztp_mac]": ztp_mac}
        token = get_jwt_token()

        if token is None:
            return 9

        r = requests.get(
            f"{base_url}/api/v1.0/devices",
            params=params,
            verify=verify_tls,
            headers={"Authorization": "Bearer " + token},
        )
        if r.status_code != 200:
            logger.error("Could not query device API: {} (status {})".format(r.text, r.status_code))
            return 10
        try:
            r_data = r.json()
            if "status" not in r_data or "data" not in r_data:
                raise ValueError("No status key in json data")
        except Exception:  # noqa: S110
            logger.error("Invalid JSON response from devices API: {}".format(r.text))
            return 11
        if r_data["status"] != "success":
            logger.error("Could not query device API: {} (status {})".format(r.text, r_data["status"]))
            return 12
        devices = r_data["data"]["devices"]
        if devices:
            dev_dict: dict = devices[0]
            dev_id: int = int(dev_dict["id"])
            if dev_dict["state"] == "DHCP_BOOT":
                data = {"ztp_mac": ztp_mac, "dhcp_ip": dhcp_ip}
                r = requests.post(
                    f"{base_url}/api/v1.0/device_discover",
                    json=data,
                    verify=verify_tls,
                    headers={"Authorization": "Bearer " + token},
                )
                if r.status_code != 200:
                    logger.error("Error when scheduling job to discover device: {} ({})".format(r.text, r.status_code))
                    return 20
                try:
                    r_data = r.json()
                    if "status" not in r_data or "job_id" not in r_data:
                        raise ValueError("No status key in json data")
                except Exception:  # noqa: S110
                    logger.error("Invalid JSON response from device_discover API: {}".format(r.text))
                    return 21

                logger.info(
                    "Device in state DHCP_BOOT acquired new lease, "
                    + "scheduling job id {} to discover device".format(r_data["job_id"])
                )
            elif dev_dict["state"] == "DISCOVERED":
                if dev_dict["dhcp_ip"] != dhcp_ip:
                    data = {"dhcp_ip": dhcp_ip}
                    r = requests.put(
                        f"{base_url}/api/v1.0/device/{dev_id}",
                        json=data,
                        verify=verify_tls,
                        headers={"Authorization": "Bearer " + token},
                    )
                    logger.info(
                        "Updating DHCP IP for device with ZTP MAC {} to: {} (status {})".format(
                            ztp_mac, dhcp_ip, r.status_code
                        )
                    )
            else:
                logger.error(
                    "Device with ztp_mac {} in state {} unexpectedly booted via DHCP ({})".format(
                        ztp_mac, dev_dict["state"], dhcp_ip
                    )
                )

        else:
            # Add new device
            logger.info("New device booted via DHCP to state DHCP_BOOT: {}".format(ztp_mac))
            data = {
                "ztp_mac": ztp_mac,
                "dhcp_ip": dhcp_ip,
                "hostname": f"mac-{ztp_mac}",
                "platform": platform,
                "state": "DHCP_BOOT",
                "device_type": "UNKNOWN",
            }
            r = requests.post(
                f"{base_url}/api/v1.0/device",
                json=data,
                verify=verify_tls,
                headers={"Authorization": "Bearer " + token},
            )
            if r.status_code != 200:
                logger.error("Error when adding new device: {} ({})".format(r.text, r.status_code))
                return 30
            try:
                r_data = r.json()
                if "status" not in r_data or "data" not in r_data:
                    raise ValueError("No status key in json data")
            except Exception:  # noqa: S110
                logger.error("Invalid JSON response from POST to device API: {}".format(r.text))
                return 31
            logger.info(
                "Added new device with hostname {} as id {} in device database".format(
                    r_data["data"]["added_device"]["hostname"], r_data["data"]["added_device"]["id"]
                )
            )

if __name__ == "__main__":
    sys.exit(main())


class Solution(object):
    def mergeStones(self, stones, K):
        """
        :type stones: List[int]
        :type K: int
        :rtype: int
        """
        N = len(stones)
        prefix = [0 for i in range(N + 1)]
        for i in range(N):
            prefix[i + 1] += (prefix[i] + stones[i])

        inf = float("inf")

        import functools

        @functools.lru_cache(None)
        def dp(i, j, m):
            if (j - i + 1 - m) % (K - 1) != 0:
                return inf
            if i == j:
                return inf if m != 1 else 0
            if m == 1:
                return dp(i, j, K) + prefix[j + 1] - prefix[i]

            return min(dp(i, mid, 1) + dp(mid + 1, j, m - 1) for mid in range(i, j))

        res = dp(0, N - 1, 1)
        return res if res != inf else -1

python/Dynamic Programming/Minimum Cost to Merge Stones/Minimum Cost to Merge Stones.py


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('project', '0016_auto_20141101_2222'),
    ]

    operations = [
        migrations.AddField(
            model_name='project',
            name='internal_rate_return',
            field=models.DecimalField(default=0.0, help_text=b'The internal rate of return for this project.', verbose_name=b'Internal Rate of Return', max_digits=6, decimal_places=3),
            preserve_default=True,
        ),
    ]


'''
Let's see how clunky it is to define and run ltspice simulations from python.
Will be possible to express much more complicated operations than in the spice language

As far as I know, we must communicate with ltspice via file io

Just need to translate python into spice language.
More often we will input existing netlists and modify them.
I'm taking a ~functional programming approach for fun, but could imagine an object oriented way that could be ok, too.

There is a library by Nuno Brum called PyLTSpice, which I tested and it seems to work.
https://github.com/nunobrum/PyLTSpice
Problem is he wrote his own data container classes which are clunky and I don't want to use them.
I want to use built-in data classes, like dict and list
which can be converted into well established and maintained containers like pandas series and dataframes for further analysis.

There's also this, which I haven't tested
https://github.com/DongHoonPark/ltspice_pytool
'''
#TODO: Spice can't tolerate spaces in equations, which makes them really hard to read.
# It took me an hour to realize this, anything following a space is just ignored
# We could easily allow spaces here and then always delete them before writing to disk
#TODO: Spice is case insensitive -- change everything to account for that
#TODO: Spice has lots of different syntax for the same thing.  e.g. .param name value  .PARAM name=value ..
#      write a better parser

import subprocess
import os
import re
import numpy as np
from collections.abc import Iterable
from datetime import datetime
import time
import fnmatch
from numbers import Number
from functools import reduce, partial
import warnings
import hashlib

# ltspice uses whatever encoding it feels like using, needs to be detected
# I think it takes cues from what kind of characters you use in the GUI
import chardet

# Make sure this points to your spice executable, and that it is the XVII version
spicepath = r"C:\Program Files\LTC\LTspiceXVII\XVIIx64.exe"

# Here is where all the simulation files (netlists and results) will be dumped
# It can get quite large if you don't delete the files afterward
simfolder = r"ltspice_sims"
simfolder = os.path.abspath(simfolder)

if not os.path.isdir(simfolder):
    os.makedirs(simfolder)

net_hashes = dict()

# Sample netlist -- list of strings
netlist = '''
* Example netlist
V1 in 0 PULSE(0 5 1m 1n 1n 10m)
R1 in N001 {R}
L1 N001 N002 {L}
C1 N002 0 {C}
.PARAM C=1e-6
.PARAM L=1e-3
.PARAM R=1
.tran 0 10m 0
.backanno
.end
'''.strip().split('\n')

def read_and_decode(filepath):
    ''' Use this to read a file if you don't know what the encoding is '''
    with open(filepath, 'rb') as f:
        data = f.read()
    encoding = chardet.detect(data)['encoding']
    return data.decode(encoding)

### File IO
def netlist_fromfile(filepath):
    ''' Read ltspice .net file.  Return a list of strings'''
    netlist = read_and_decode(filepath).split('\n')
    return [nl.strip() for nl in netlist if nl]

def read_log(filepath):
    ''' Read ltspice .log file and parse out some information.  Return a dict'''
    filepath = replace_ext(filepath, 'log')
    print(f'Reading {filepath}')
    lines = read_and_decode(filepath)
    logitems = re.findall('(.[^\s]*)[=,:] (.*)', lines)
    if not logitems:
        # quick fix, don't know why, but sometimes we have utf-16 encoding and sometimes not
        # chardet can't seem to detect this
        with open(filepath, 'r', encoding='utf-16-le') as f:
            lines = f.read()
        logitems = re.findall('(.[^\s]*)[=,:] (.*)', lines)
    def convert_vals(val):
        val = val.strip()
        if val.isdigit():
            val = np.int32(val)
        return val
    # might have more than one of each type (e.g. multiple WARNINGs)
    # store them as lists of strings if there are multiple and regret it later
    logdict = {}
    for k,v in logitems:
        key = k.strip()
        if key in logdict:
            if not isinstance(logdict[key], list):
                logdict[key] = [logdict[key]]
            logdict[key].append(convert_vals(v))
        else:
            logdict[key] = convert_vals(v)
    if 'Total elapsed time' in logdict:
        logdict['sim_time'] = np.float32(logdict['Total elapsed time'].split(' ')[0])
        del logdict['Total elapsed time']
    return logdict

def read_net(filepath):
    ''' Read ltspice .net file and parse out some information.  Return a dict'''
    netinfo = {}
    filepath = replace_ext(filepath, 'net')
    print(f'Reading {filepath}')
    netlist = netlist_fromfile(filepath)
    netparams = get_params(netlist)
    #netfuncs = re.findall('.FUNC (.*)=(.*)', netlist)
    #netfuncs = {k:v for k,v in netfuncs}
    netinfo['netlist'] = netlist
    netinfo.update(netparams)
    return netinfo

def read_raw(filepath):
    '''
    Read ltspice output .raw file.
    return dict of parameters and arrays contained in the file
    for ltspice XVII version
    Does not load parameter runs because I think those should just be done in python
    '''
    filepath = os.path.abspath(filepath)
    filepath = replace_ext(filepath, 'raw')

    # Read information from the .raw file
    print(f'Reading {filepath}')
    with open(filepath, 'rb') as raw_file:
        colnames = []
        units = []
        raw_params = {'filepath': filepath}

        def readline():
            line = raw_file.readline()
            # Read the newline...
            raw_file.read(1)
            return line.decode(encoding='utf_16_le', errors='ignore')

        # Read the header
        line = readline()
        while not line.startswith('Variables:'):
            tag, value_str = line.split(':', 1)
            value_str = value_str.strip()
            if value_str.isdigit():
                value_str = int(value_str)
            raw_params[tag] = value_str
            line = readline()

        # Read the column names
        line = readline()
        while not line.startswith('Binary'):
            _, name, unit = line.strip().split('\t')
            colnames.append(name)
            units.append(unit)
            line = readline()

        # Read the numerical data
        # Time values are 8 bytes, rest are 4 bytes.
        # (raw_file_size - 930) / numpoints / ((numvars-1)*4 + 8) = 1
        numpoints = raw_params['No. Points']
        numvars = raw_params['No. Variables']
        dtype = np.dtype({'names':colnames,
                          'formats':[np.float64] + [np.float32]*(numvars - 1)})
        # d is a dreaded numpy structured array
        d = np.fromfile(raw_file, dtype)
        ddict = {k:d[k] for k in colnames}
        # I have no idea why this is necessary
        if 'time' in ddict:
            ddict['time'] = np.abs(ddict['time'])
        for k,v in ddict.items():
            if v.size == 1:
                # numpy 0d arrays are stupid
                ddict[k] = v.item()
    # Put data and metadata together in one dict
    outdict = {**raw_params, **ddict}

    return outdict

def read_spice(filepath, namemap=None):
    ''' Read all the information contained in all the spice files with the same name (.raw, .net, .log)'''
    filepath = os.path.abspath(filepath)

    rawdata = read_raw(filepath)
    logdata = read_log(filepath)
    netdata = read_net(filepath)

    # Pick and choose the data you want to output
    dataout = {**rawdata, **netdata}
    dataout['sim_time'] = logdata.get('sim_time')
    dataout['solver'] = logdata.get('solver')
    dataout['method'] = logdata.get('method')
    dataout['WARNING'] = logdata.get('WARNING')

    # Map to other names if you want
    if namemap is not None:
        for oldk, newk in namemap.items():
            if oldk in dataout:
                dataout[newk] = dataout[oldk]
                del dataout[oldk]

    return dataout

def replace_ext(path, newext):
    return os.path.splitext(path)[0] + '.' + newext.strip('.')

def timestamp():
    ''' Timestamp string with ms accuracy '''
    return datetime.now().strftime('%Y-%m-%d_%H%M%S_%f')[:-3]

def valid_filename(s):
    s = str(s).strip().replace(' ', '_')
    return re.sub(r'(?u)[^-\w.]', '', s)

def write_wav(times, voltages, filename):
    import struct

    def lin_interp(x0, x1, y0, y1, x):
        x0 = float(x0)
        x1 = float(x1)
        y0 = float(y0)
        y1 = float(y1)
        x = float(x)
        return y0 + (x - x0) * (y1 - y0) / (x1 - x0)

    with wave.open(filename, 'w') as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(44100)
        w.setnframes(0)
        w.setcomptype('NONE')
        w.writeframes(np.sin(np.linspace(0, 8000*2*pi, 100000)))
        m = max(max(voltages), -min(voltages))
        vrange = m

        values = bytes([])
        t = 0.0
        step = 1.0 / SAMPLING_RATE

        for i in range(len(voltages)-1):
            while times[i] <= t * step < times[i+1]:
                sample = lin_interp(times[i], times[i+1],
                    voltages[i], voltages[i+1], t*step) / vrange
                sample = 1 if sample >1 else sample
                sample = -1 if sample <-1 else sample
                d = struct.pack('<h',int(32767 * sample))
                values += d
                t += 1

        w.writeframes(values)

def hash(netlist):
    return hashlib.md5(bytes('\n'.join(netlist), 'utf-8')).hexdigest()

def from_cache(netlist, namemap=None):
    ''' Check whether the same netlist has already been run, and if yes, return the results written to disk'''
    # Update cache
    existing_fns = fnmatch.filter(os.listdir(simfolder), '*.net')
    for fn in existing_fns:
        if fn not in net_hashes.values():
            existing_net = netlist_fromfile(os.path.join(simfolder, fn))
            #net_hashes[fn] = hash(existing_net)
            # only add to cache if there is corresponding output data
            raw_exists = os.path.isfile(os.path.join(simfolder, fn[:-3] + 'raw'))
            log_exists = os.path.isfile(os.path.join(simfolder, fn[:-3] + 'log'))
            if raw_exists & log_exists:
                net_hashes[hash(existing_net)] = fn
    # Check if hash already in the cache
    h = hash(netlist)
    if h in net_hashes:
        print('Reading previous matching sim from disk')
        return read_spice(os.path.join(simfolder, net_hashes[h]), namemap=namemap)

    return False

# TODO somehow stop spice from stealing focus even though no window is visible
# TODO cache some inputs and outputs, so that you don't keep running the same simulations
# at least cache the file locations
#from functools import lru_cache
#@lru_cache(maxsize=32)
def runspice(netlist, namemap=None, timeout=None, check_cache=True):
    ''' Run a netlist with ltspice and return all the output data '''
    # TODO: Sometimes when spice has an error, python just hangs forever.  Need a timeout or something.
    # TODO: is there any benefit to spawning many ltspice processes at once, instead of sequentially?
    if type(netlist) is str:
        netlist = netlist.split('\n')
    if check_cache:
        old_result = from_cache(netlist, namemap=namemap)
        if old_result: return old_result
    t0 = time.time()
    # Write netlist to disk
    title = valid_filename(get_title(netlist))
    netlistfp = os.path.join(simfolder, timestamp() + f'_{title}.net')
    netlistfp = os.path.abspath(netlistfp)
    print(f'Writing {netlistfp}')
    with open(netlistfp, 'w') as f:
        f.write('\n'.join(netlist))
    print(f'Executing {netlistfp}')
    # Tell spice to execute it
    # If error/timeout, maybe we want to keep running things, don't raise the error just return empty data
    try:
        subprocess.check_output([spicepath, '-b', '-Run', netlistfp], timeout=timeout)
    except subprocess.CalledProcessError as err:
        print(err)
        print(read_log(replace_ext(netlistfp, 'log')))
        return {}
    except subprocess.TimeoutExpired as err:
        print(err)
        return {}

    #subprocess.check_output([spicepath, '-b', '-ascii', '-Run', netlistfp])
    # Read result
    rawfp = os.path.splitext(netlistfp)[0] + '.raw'
    d = read_spice(rawfp, namemap=namemap)
    t1 = time.time()
    # Sim time including file io
    d['sim_time_total'] = t1 - t0
    return d

def recentfile(filter='', n=0, folder=simfolder):
    ''' Return the nth most recent filepath'''
    filter = f'*{filter}*'
    dirlist = os.listdir(folder)
    matches = fnmatch.filter(dirlist, filter)
    matchingfps = [os.path.join(folder, m) for m in matches]
    # might be able to just assume they are in sorted order because of the file names...
    recent = np.argsort([os.path.getmtime(f) for f in matchingfps])
    return os.path.join(folder, matches[recent[-1-n]])

### Netlist parsing
def get_params(netlist):
    params = re.findall('.PARAM (.*)=(.*)', '\n'.join(netlist))
    params = {k:v for k,v in params}
    # Try to convert params to number
    for k,v in params.items():
        try:
            params[k] = np.float32(v)
        except ValueError:
            pass
    return params

def get_title(netlist):
    ''' My understanding is that the first line must always be the title '''
    if netlist[0].startswith('*'):
        title = netlist[0][1:].strip()
    else:
        title = netlist[0]
    return title

### Functions for operating on netlist
def netinsert(netlist, newline):
    '''
    Replace a line in the netlist if it corresponds to an existing command,
    or else add it as a new line in a reasonable position
    Does not check if you are putting in a command that makes sense or will run!
    Return the netlist with the inserted line
    '''
    # Spice language is not very uniform so it's not completely trivial how to decide
    # When to replace a line or when to add a new line.

    netlist = netlist.copy()

    # Find the part of the string that identifies what the command does
    cmd, *rest = newline.split(' ', 1)
    if cmd.lower() in ('.param', '.func', '.ic'):
        # Compare also with the thing before the = sign
        cmd_id = newline[:newline.find('=') + 1]
    else:
        cmd_id = cmd

    # How similar is each line to the identifying string?
    # I will put the new line after the one most similar to it
    # There's probably a better approach.
    def similarity(netlist, line):
        '''
        Return the number of characters that are the same as 'line' for each line of netlist
        '''
        # This is not the most efficient thing ever but who cares
        def compare(str1, str2):
            if str1.lower().startswith(str2.lower()):
                return len(str2)
            else:
                return [c1.lower() == c2.lower() for c1,c2 in zip(str1, str2)].index(False)
        return [compare(l, line) for l in netlist]

    simi = similarity(netlist, cmd_id)
    maxsim = max(simi)
    if maxsim == len(cmd_id):
        # Replace existing line
        i = simi.index(maxsim)
        netlist[i] = newline
    else:
        # Find a good index to insert the new line
        # (After the most similar line)
        i = np.argmax(simi) + 1
        netlist.insert(i, newline)

    return netlist

def netchange(netlist, *newlines):
    '''
    Pass any (potentially nested) list of strings and merge them with netlist
    Return the resulting merged netlist
    '''
    strings = flatten(newlines)
    return reduce(netinsert, strings, netlist)

def netchanger(netlist):
    ''' Closure that remembers the input netlist, and allows you to modify it by passing partial netlists '''
    changer = partial(netchange, netlist)
    return changer

def paramchange(netlist, paramdict=None, **kwargs):
    '''
    If you only want to change .PARAMS, you can pass a dict of them to this function
    Or pass them as keyword arguments, or both
    '''
    newparams = []
    if paramdict is not None:
        newparams += [param(k, v) for k,v in paramdict.items()]
    if kwargs:
        newparams += [param(k, v) for k,v in kwargs.items()]
    newnet = netchange(netlist, newparams)
    return newnet

def set_title(netlist, title):
    '''
    First line is always the title?
    Needs its own function because netinsert won't know how to identify and replace the title line
    '''
    return [title] + netlist[1:]

def flatten(nested):
    ''' flatten a tree of strings '''
    for i in nested:
            if isinstance(i, Iterable) and not isinstance(i, str):
                for subc in flatten(i):
                    yield subc
            else:
                yield i

### Spice directives
def param(name, value):
    return f'.PARAM {name}={value}'

def function(funcdef):
    funcdef = funcdef.replace(' ', '')
    return f'.FUNC {funcdef}'

def element(name, cathode, anode, val):
    '''
    For now we do not distinguish the element types.
    Spice will use the first letter of the name to decide what kind of element it is
    TODO: Overwrite value without specifying cathode and anode
    TODO: Autoname if name not given.
    Don't know how this would work, as we would need to be aware of the netlist that it is getting applied to, but we already return a string before that happens.
    '''
    return f'{name} {cathode} {anode} {val}'

# TODO: make functions for common elements.
#def resistor():
#def capacitor():
#def inductor():

def transient(start=0, stop=1, maxstep=1e-4, stopsteady=False):
    cmd = f'.tran 0 {stop} {start} {maxstep}'
    if stopsteady:
        cmd += ' steady'
    return cmd

def initial_condition(name, value):
    return f'.ic {name}={value}'

### Spice waveforms
# TODO add some useful functions that translate into these (e.g. triangle..)
def sine(freq, amp, offset=0, delay=0, phase=0, damping=0, ncycles=None):
    ''' Phase in degrees '''
    if ncycles is None:
        ncycles = ''
    return f'SINE({offset} {amp} {freq} {delay} {damping} {phase} {ncycles})'

def pulse(Voff, Von, trise, ton, tfall, period=None, delay=0, ncycles=None):
    if period is None:
        period = trise + ton + tfall + delay
    if ncycles is None:
        ncycles = ''
    return f'PULSE({Voff} {Von} {delay} {trise} {tfall} {ton} {period} {ncycles})'

def PWL(t, v):
    ''' Piecewise Linear waveform. Should probably use wav file instead if this gets long.'''
    interleaved = (val for pair in zip(t, v) for val in pair)
    interleaved_str = ' '.join(format(v) for v in interleaved)
    return f'PWL({interleaved_str})'

if 0:
    # Try changing all parameters by ±50%
    datalist = []
    for name, value in get_params(netlist).items():
        for v in np.linspace(0.5*value, 1.5*value, 5):
            data = runspice(netchange(netlist, param(name, v)))
            datalist.append(data)

    plt.figure()
    for data in datalist:
        plt.plot(data['time'], data['I(R1)'])

    #df = pd.DataFrame(datalist)


# coding: utf-8

import sys
read = sys.stdin.readline
write = sys.stdout.write

def is_palindrom(numbers):
    idx = len(numbers)//2
    for i in range(1, idx+1):
        if numbers[i-1] != numbers[-i]:
            return "0"
    return "1"

n = int(input())
numbers = list(map(int, input().split()))

m = int(input())
result = []
for _ in range(m):
    s, e = map(int, read().split())
    p = is_palindrom(numbers[s-1:e])
    result.append(p)

for r in result:
    write(r)
    write("\n")


# -*- coding: utf-8 -*-
"""
Created on Tue May 18 22:16:23 2021

@author: vtac
"""

#Compare convexity of NNs
import pickle
import numpy as np
import matplotlib.pyplot as plt

model_name = 'P1C1_s'

fsize=10
pltparams = {'legend.fontsize': 'large',
          'figure.figsize': (10,5),
          'axes.labelsize': fsize*1.5,
          'axes.titlesize': fsize*1.5,
          'xtick.labelsize': fsize*1.25,
          'ytick.labelsize': fsize*1.25,
          'axes.titlepad': 25,
          "mathtext.fontset": 'dejavuserif'}
plt.rcParams.update(pltparams)
plt.rcParams['axes.prop_cycle'] = plt.cycler('color', plt.cm.inferno(np.linspace(0.2, 0.8,2)))
plt.rcParams["mathtext.fontset"] = 'dejavuserif'

with open('savednet/' + model_name + '_history.pkl', 'rb') as f:
    conv_history = pickle.load(f)
with open('savednet/' + model_name + '_history_nonconv.pkl', 'rb') as f:
    nonconv_history = pickle.load(f)

fig = plt.figure()
gs = fig.add_gridspec(1,2, wspace=0.3, hspace=0.4) #nrows, ncols

ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(   conv_history['sigma_loss'], label='Convex Model')
ax1.plot(nonconv_history['sigma_loss'], label='Non-Convex Model')
ax1.legend()
ax1.set_xlabel('Iteration')
ax1.set_ylabel('Loss on $\sigma$')

symmetry = np.array(conv_history['symmetry'])
conv1 = np.array(conv_history['convexity'])
conv_convexity = symmetry + 10*conv1
symmetry = np.array(nonconv_history['symmetry'])
conv1 = np.array(nonconv_history['convexity'])
nonconv_convexity = symmetry + 10*conv1

ax2 = fig.add_subplot(gs[0, 1])
ax2.plot(conv_convexity, label='Convex Model')
ax2.plot(nonconv_convexity, label='Non-Convex Model')
ax2.set_xlabel('Iteration')
ax2.set_ylabel('Convexity')


import requests
import os
from dotenv import load_dotenv

load_dotenv()

def telegram_send_message(message):
    send_text = (
        "https://api.telegram.org/bot"
        + os.getenv("BOTTOKEN")
        + "/sendMessage?chat_id="
        + os.getenv("CHATID")
        + "&parse_mode=Markdown&text="
        + message
    )

    response = requests.get(send_text)

    return response.json()


# Creating a tuple using ()
t = (1, 5, 25, 415)

#Empty tuple
tp = ()

# t1 = (1) # wrong way to declare a tuple with single element

#tuple with single elements
t1 = (52,)

#printing the elements of a tuple
print(t[0])

# cannot update the values of a tuple
# t[0] = 50  # therows an error


# -*- coding: utf-8 -*-
import os
from json import dumps

from django import template
from django.conf import settings
from django.template.base import TemplateSyntaxError, kwarg_re, Node
from django.utils.encoding import smart_text
from django.utils.safestring import mark_safe
from django.utils.six import text_type
from django.utils.translation import ugettext as _

from accounts.account_helper import get_current_account
from common.models import UpdateNotification
from documents.models import Document

register = template.Library()

@register.simple_tag(takes_context=True)
def acc_document(context, pk, *args, **kwargs):
    return Document.objects.filter(account=get_current_account(context['request']), group__pk=pk).order_by('-created_at')

@register.tag()
def acc_url(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("'%s' takes at least one argument"
                                  " (path to a view)" % bits[0])
    try:
        viewname = parser.compile_filter(bits[1])
    except TemplateSyntaxError as exc:
        exc.args = (exc.args[0] + ". "
                                  "The syntax of 'url' changed in Django 1.5, see the docs."),
        raise
    args = []
    kwargs = {}
    asvar = None
    bits = bits[2:]
    if len(bits) >= 2 and bits[-2] == 'as':
        asvar = bits[-1]
        bits = bits[:-2]

    if len(bits):
        for bit in bits:
            match = kwarg_re.match(bit)
            if not match:
                raise TemplateSyntaxError("Malformed arguments to url tag")
            name, value = match.groups()
            if name:
                kwargs[name] = parser.compile_filter(value)
            else:
                args.append(parser.compile_filter(value))

    return URLNode(viewname, args, kwargs, asvar)

@register.filter
def bool_to_checked(value):
    return value and "checked" or ""

@register.filter
def check_choice_value(choice_field, value):
    return choice_field.valid_value(value)

@register.filter
def folder_display_name(folder, membership):
    try:
        if folder.is_account_root:
            return _(u'Documents')
        elif folder.membership_id == membership.id:
            return _(u'My Documents')
        else:
            return unicode(folder)
    except:
        return ''

@register.simple_tag(takes_context=True)
def update_notifications_for_user(context):
    request = context['request']
    user = request.user

    if user.is_anonymous:
        return []
    else:
        return list(UpdateNotification.objects.filter(is_active=True, publish_date__gte=user.date_notifications_read).order_by('publish_date'))

class URLNode(Node):
    def __init__(self, view_name, args, kwargs, asvar):
        self.view_name = view_name
        self.args = args
        self.kwargs = kwargs
        self.asvar = asvar

    def render(self, context):
        from django.core.urlresolvers import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([(smart_text(k, 'ascii'), v.resolve(context))
                       for k, v in self.kwargs.items()])

        kwargs['url'] = get_current_account(context['request']).url

        view_name = self.view_name.resolve(context)

        if not view_name:
            raise NoReverseMatch("'url' requires a non-empty first argument. "
                                 "The syntax changed in Django 1.5, see the docs.")

        # Try to look up the URL twice: once given the view name, and again
        # relative to what we guess is the "main" app. If they both fail,
        # re-raise the NoReverseMatch unless we're using the
        # {% url ... as var %} construct in which case return nothing.
        url = ''
        current_app = context['request'].resolver_match.app_name
        try:
            url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
        except NoReverseMatch as e:
            if settings.SETTINGS_MODULE:
                project_name = settings.SETTINGS_MODULE.split('.')[0]
                try:
                    url = reverse(project_name + '.' + view_name,
                                  args=args, kwargs=kwargs,
                                  current_app=current_app)
                except NoReverseMatch:
                    if self.asvar is None:
                        # Re-raise the original exception, not the one with
                        # the path relative to the project. This makes a
                        # better error message.
                        raise e
            else:
                if self.asvar is None:
                    raise e

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            return url

@register.filter
def attrs(value, arg):
    """
    DANGER! This tag alters original widget object. It's handy but can't be used with
    dynamic class switching.
    """
    attrs = value.field.widget.attrs

    kvs = arg.split(',')

    for string in kvs:
        kv = string.split(':')
        attrs[kv[0].strip()] = kv[1].strip()

    rendered = str(value)

    return rendered

@register.simple_tag()
def field_errors(field):
    if field and field.errors:
        return mark_safe("""

                %s

            """ % (field.auto_id, field.errors[0]))
    else:
        return ""

@register.simple_tag()
def field_errors_with_field_name(field):
    """
    Formats errors for field, including it's name. Useful for displaying hidden field errors.
    """
    if field.errors:
        return mark_safe("""

                    %s: %s

            """ % (field.auto_id, text_type(field.label), field.errors[0]))
    else:
        return ""

@register.simple_tag
def get_item(dictionary, key):
    return dictionary.get(key)

@register.simple_tag
def get_social_mapping(key):
    return settings.SOCIAL_MAPPING.get(key)

@register.simple_tag
def get_social_profile_icon(sauth):
    if sauth.provider:
        return sauth.provider.split('-', 1)[0]
    return None

@register.simple_tag
def get_social_profile_name(sauth):

    if sauth.provider == 'google-oauth2':
        return sauth.uid

    elif sauth.provider == 'twitter' and sauth.extra_data:
        return sauth.extra_data.get('access_token', {}).get('screen_name')

    elif sauth.provider == 'linkedin-oauth2' and sauth.extra_data:
        fn = sauth.extra_data.get('first_name', u'')
        ln = sauth.extra_data.get('last_name', u'')
        name = u"%s %s" % (fn, ln)
        return name.strip()

    return None

@register.simple_tag
def get_social_profile_url(sauth):

    if sauth.provider == 'google-oauth2':
        return "mailto:%s" % (sauth.uid)

    elif sauth.provider == 'twitter' and sauth.extra_data:
        sn = sauth.extra_data.get('access_token', {}).get('screen_name')
        return "https://twitter.com/%s" % (sn)

    return None

@register.filter
def min_for_prod(resource):
    if settings.DEBUG:
        return resource
    else:
        return resource.replace('.js', '.min.js').replace('.css', '.min.css')

@register.filter
def json(data):
    return mark_safe(dumps(data))

@register.filter
def file_basename(file):
    """
    :func: remove file extension
    :param file: for example file="Financial Report.pdf"
    :return: "Financial Report"
    """
    name, extension = os.path.splitext(file)
    return name

@register.filter
def custom_social_name(social_name):
    if 'Google' in social_name:
        return 'Google'
    return social_name


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        lvs = defaultdict(list)
        q = deque()
        q.append((root, 0))
        lastLv = 0

        while q:
            cur, lv = q.popleft()

            if not cur:
                continue

            lvs[lv].append(cur.val)

            if cur.left:
                q.append((cur.left, lv + 1))
            if cur.right:
                q.append((cur.right, lv + 1))

        return [lvs[i] for i in range(len(lvs))]


from pandas import read_csv
from pickle import dump
from glob import glob
from tqdm import tqdm

HEADERS = ["DATE", "NAME", "LATITUDE", "LONGITUDE", "MIN", "MAX", "PRCP", "PRCP_ATTRIBUTES", "SNDP", "FRSHTT"]
TYPES = {"NAME": str, "LATITUDE": float, "LONGITUDE": float, "MIN": float, "MAX": float, "PRCP": float, "PRCP_ATTRIBUTES": str, "SNDP": float, "FRSHTT": str}

data = []

files = glob('stations/*.csv')
for i, file in enumerate(tqdm(files)):
    df = read_csv(file, dtype=TYPES, parse_dates=["DATE"])[HEADERS]
    # Ignore any stations without a name
    if df["NAME"].isnull().any():
        continue
    # Convert to dictionary for faster operations
    df = df.to_dict()
    data.append(df)

with open('weather.pickle', 'wb') as f:
    dump(data, f)


import cv2
import numpy as np
webcam = cv2.VideoCapture(0)
webcam.set(3,640)
webcam.set(4,480)
webcam.set(10,100)
marea =400
count=0
face_cascade = cv2.CascadeClassifier('Resources/haarcascades/haarcascade_russian_plate_number.xml')
while True:
    ret, frame = webcam.read()
    imageGray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    plates = face_cascade.detectMultiScale(imageGray, 1.3, 5)
    for (x,y,w,h) in plates:
        if (w*h)>marea:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
            cv2.putText(frame,"This is number Plate",(x,y+5),cv2.FONT_ITALIC,3,(0,255,255),2)
            numberplateimage=frame[y:y+h,x:x+w]
            cv2.imshow("The number Plate",numberplateimage)
    cv2.imshow("Webcam",frame)
    if cv2.waitKey(1) & 0xff==ord('s'):
        count+=1
        cv2.imwrite('Resources'+str(count)+'.jpg',imageRegionofInterest)
        cv2.rectangle(webcamimage,(0,200),(640,300),(0,255,255),cv2.FILLED)
        cv2.putText(webcamimage,"Saved",(150,265),cv2.FONT_HERSHEY_COMPLEX,2,(255,0,255),1)
        cv2.imshow("Result",webcamimage)
        cv2.waitKey(100)


# -*- coding: utf-8 -*-
"""
pnlp-4_preprocessing-regular_expression.py

Source: Python Natural Language Processing
Advanced machine learning and deep learning techniques for natural language processing
Jalaj Thanaki

파이썬 자연어 처리의 이론과 실제
효율적인 자연어 처리를 위한 머신 러닝과 딥러닝 구현하기
04. 전처리 > 기본 전처리 > 정규 표현식
pp.125~135

regex or regular expression
Basic flag
  re.I  Ignore-case
  re.M  Multi-line
        In the textbook, re.M is given, but actually it's not necessary for the
        given inputs.
"""

import re

#%%#######################
# re.search vs. re.match #
##########################

def search_vs_match():  # p.127
    line = 'I love animals.'

    #############
    # re.search #
    #############
    # is more forgiving.
    #search_obj = re.search(r'animals', line, re.M | re.I)
    search_obj = re.search(r'animals', line, re.I)
    if search_obj:
        print('search_obj:' , search_obj.group() )
    else:
        print('Nothing found!')
#   searchObj: animals

    ############
    # re.match #
    ############
    # is very strict.
    #match_obj = re.match(r'animals', line, re.M | re.I)
    match_obj = re.match(r'animals', line, re.I)
    if match_obj:
        print('match_obj:', match_obj.group() )
    else:
        print('No match!')
#   No match!

#%%########################
# Examples of basic regex #
###########################
def basic_regex():
    line         = 'This is a test sentence and the test sentence is also a sentence.'
    contact_info = 'Doe, John: 1111-1212'
    phone        = '1111-2222-3333 # This is a phone number.'

    ##############
    # re.findall #
    ##############
    # Find all occurences of sentence from line.
    findall_obj = re.findall(r'sentence', line)
    print( findall_obj )
#   ['sentence', 'sentence', 'sentence']

    ########################
    # re.search with regex #
    ########################
    # Search 'something, something: ' from contact_info.
    group_wise_obj = re.search(r'(\w+), (\w+): (\S+)', contact_info)  # \S+ is correct, \s+ isn't!
    # r'(\w+), (\w+): (\S+)' means(?) 'word 1 or more, word 1 or more: Not space 1 or more.'
    print('group(1) =', group_wise_obj.group(1) )
    print('group(2) =', group_wise_obj.group(2) )
    print('group(3) =', group_wise_obj.group(3) )
#   group(1) = Doe
#   group(2) = John
#   group(3) = 1111-1212

    ######################
    # re.sub to replaces #
    ######################
    # Replace John to Peter in contact_info
    contact_info_revised = re.sub(r'John', 'Peter', contact_info)
    print('contact_info_revised =', contact_info_revised)
#   contact_info_revised = Doe, Peter: 1111-1212

    ####################
    # re.sub to delete #
    ####################
    # Delete the Python-style comment at the end of the sentence
    # That is, delete '# This is a phone number.' from phone.
    num = re.sub(r'#.*$', '', phone)
    # #.*$ means(?) # followed by a character (.) and all (*) from the end ($)
    print('num =', num)
#   num = 1111-2222-3333 # This is a phone number.

    # Note: the following expressions don't work!
    #num = re.sub(r'#*$', '', phone)
    #num = re.sub(r'#\s*$', '', phone)

#%%################################################
# Advanced regex: Positive vs. Negative Lookahead #
###################################################
def advanced_regex():
    text = 'I play on playground. it is the best ground.'

    ######################
    # Positive Lookahead #
    ######################

    #####################
    # r'play(?=ground)' #
    #####################
    #positive_lookahead = re.findall(r'play(?=ground)', text, re.M| re.I)
    positive_lookahead = re.findall(r'play(?=ground)', text, re.I)
    print('positive_lookahead =', positive_lookahead)
#   positive_lookahead = ['play']

    positive_lookahead = re.search(r'play(?=ground)', text, re.I)
    print('positive_lookahead character index =', positive_lookahead.span() )
#   positive_lookahead character index = (10, 14)

    ######################
    # r'(?<=play)ground' #
    ######################
    positive_lookahead = re.findall(r'(?<=play)ground', text, re.I)
    print('positive_lookahead =', positive_lookahead)
#   positive_lookahead = ['ground']

    positive_lookahead = re.search(r'(?<=play)ground', text, re.I)
    print('positive_lookahead character index =', positive_lookahead.span() )
#   positive_lookahead character index = (14, 20)

    ######################
    # Negative Lookahead #
    ######################

    #####################
    # r'play(?!ground)' #
    #####################
    negative_lookahead = re.findall(r'play(?!ground)', text, re.I)
    print('negative_lookahead =', negative_lookahead)
#   negative_lookahead = ['play']

    negative_lookahead = re.search(r'play(?!ground)', text, re.I)
    print('negative_lookahead character index =', negative_lookahead.span() )
#   negative_lookahead character index = (2, 6)

    ######################
    # r'(?<=play)ground' #
    ######################
    negative_lookahead = re.findall(r'(?<=play)ground', text, re.I)
    print('negative_lookahead =', negative_lookahead)
#   negative_lookahead = ['ground']

    negative_lookahead = re.search(r'(?<=play)ground', text, re.I)
    print('negative_lookahead character index =', negative_lookahead.span() )
#   negative_lookahead character index = (14, 20)

if __name__ == '__main__':
    print('re.match() vs. re.search()')
#   re.match() vs. re.search()

    search_vs_match()
#   re.match() vs. re.search()
#   searchObj: animals
#   No match!

    basic_regex()
#   ['sentence', 'sentence', 'sentence']
#   group(1) = Doe
#   group(2) = John
#   group(3) = 1111-1212
#   contact_info_revised = Doe, Peter: 1111-1212
#   num = 1111-2222-3333

    advanced_regex()
#   positive_lookahead = ['play']
#   positive_lookahead character index = (10, 14)
#   positive_lookahead = ['ground']
#   positive_lookahead character index = (14, 20)
#   negative_lookahead = ['play']
#   negative_lookahead character index = (2, 6)
#   negative_lookahead = ['ground']
#   negative_lookahead character index = (14, 20)


import csv
import pandas as pd
import pathlib
import os.path
from validate import validate_date

# leeg sold.csv aanmaken
def create_soldcsv():
    with open(
        pathlib.Path(__file__).parent / "sold.csv", "w", newline=""
    ) as soldFile:
        writer = csv.writer(soldFile)
        writer.writerow(
            [
                "id",
                "buyid",
                "selldate",
                "product",
                "sellamount",
                "sellprice",
                "expirydate",
            ]
        )

# def checkexpdate(productsold):

def append_buyid(productsold):
    check_file = os.path.isfile("sold.csv")
    if not check_file:
        create_soldcsv()
    # Gekochte producten krijgen een 'buyid'.
    # Ieder verkocht product krijgt een eigen id en op basis
    # van productnaam en expirydate het buyid van de bijbehorende
    # inkoopbatch.
    # Hiervoor wordt eerst gekeken hoeveel er nog in voorraad is.

    # Lijst genereren met gekochte producten, aantal sommeren
    # op product en expirydate
    dfb = pd.read_csv("bought.csv", index_col="buyid")
    dfbgroup = dfb.groupby(["buyid", "product", "expirydate"])[
        "buyamount"
    ].sum()

    # Lijst genereren met verkochte producten, aantal sommeren
    # op product en expirydate
    dfs = pd.read_csv("sold.csv", index_col="id")
    dfsgroup = dfs.groupby(["buyid", "product", "expirydate"])[
        "sellamount"
    ].sum()

    # deze gegevens mergen op buyid
    inventory = pd.merge(
        dfbgroup.reset_index(), dfsgroup, how="left", on=["buyid"]
    ).fillna(0)

    # kolom toevoegen om aantal producten nog in voorraad uit te rekenen
    inventory["in_stock"] = inventory["buyamount"] - inventory["sellamount"]

    # ingevoerde product opzoeken in lijst om expirydate erbij te zoeken
    inv_productsold = inventory[
        inventory["product"].str.match(productsold[1])
    ]
    if inv_productsold.empty:
        print(
            "Product not in stock, or this amount not available.\n"
            "Check productname, sellamount"
        )
        exit()
    if len(inv_productsold) == 1 & (inv_productsold["in_stock"].sum(axis=0)
                                    < productsold[2]):
        available = inv_productsold["in_stock"].sum(axis=0)
        if available == 0:
            print("Product sold out")
        else:
            print(
                "Only "
                + str(available)
                + " items available, check input of sold product:"
                " productname or sellamount.\n"
                "Product NOT added to bought.csv"
            )
            exit()
    if len(inv_productsold) == 1 & (inv_productsold["in_stock"].sum(axis=0)
                                    >= productsold[2]):
        if inv_productsold.iat[0, 2] < productsold[0]:
            print("Product expired, product NOT added to sold.csv")
        else:
            buyid = inv_productsold.iat[0, 0]
            expdate = inv_productsold.iat[0, 2]
            prodlist = [buyid] + productsold + [expdate]
            append_prodlist(prodlist)
    if len(inv_productsold) > 1:
        print(inv_productsold)
        expdate = input("More expirydates available for this product, type "
                        "expirydate of your product:")
        validate_date(expdate)
        productsold = productsold + [expdate]
        appendbuyid_morexpdate(productsold)
# Er kunnen op meerdere dagen producten zijn ingekocht met
# dezelfde productnaam en eenzelfde expirydate of dezelfde productnaam
# en meerdere expirydates.
# Met behulp van bovenstaande functie wordt gecheckt of er bij een
# ingevoerd product meerdere expirydatums horen en laat die zien.
# De gebruiker moet de juiste expirydate invoeren.

# Hierna wordt een 2e functie gestart die eventueel nog een keer
# gestart kan worden als er producten worden verkocht die verdeeld moeten
# worden over meerdere inkoopbatches.
# Eerst wordt het de eerste batch getoond en daar wordt de
# de hoeveelheid gekochte producten vanaf gehaald. Is er dan
# nog over, worden die van de volgende batch afgehaald.
# Is het product dan uitverkocht, wordt hier melding van gemaakt.

def appendbuyid_morexpdate(productsold):
    # Begin van de functie is hetzelfde als de hierbovenstaande functie
    dfb = pd.read_csv("bought.csv", index_col="buyid")
    dfbgroup = dfb.groupby(["buyid", "product", "expirydate"])[
        "buyamount"
    ].sum()

    # Lijst met verkochte producten, aantal sommeren op product en expirydate
    dfs = pd.read_csv("sold.csv", index_col="id")
    dfsgroup = dfs.groupby(["buyid", "product", "expirydate"])[
        "sellamount"
    ].sum()

    # deze gegevens mergen op buyid
    inventory = pd.merge(
        dfbgroup.reset_index(), dfsgroup, how="left", on=["buyid"]
    ).fillna(0)

    # kolom toevoegen om aantal producten nog in voorraad uit te rekenen
    inventory["in_stock"] = inventory["buyamount"] - inventory["sellamount"]
    inv_productsold = inventory[
            inventory["product"].str.match(productsold[1])
            & (inventory["expirydate"].str.match(productsold[4]))
            & (inventory["in_stock"] > 0)]
    # Als er te weinig producten in voorraad zijn tov het ingegeven
    # aantal producten, komt er een melding.
    if inv_productsold["in_stock"].sum(axis=0) < productsold[2]:
        available = inv_productsold["in_stock"].sum(axis=0)
        print(
            "Only "
            + str(available)
            + " items available, check input of sold product:"
            " productname, sellamount and/or expirydate.\n"
            "Product NOT added to bought.csv"
        )
# Als er genoeg items in voorraad zijn, wordt buyid van 1e batch
# toegevoegd aan het verkochte product en aan bought.csv toegevoegd
    else:
        buyid = (inv_productsold.head(1)).iat[0, 0]
        instock_buyid = (inv_productsold.head(1)).iat[0, 5]
        if instock_buyid >= productsold[2]:
            prodlist = [buyid] + productsold
            append_prodlist(prodlist)
# Als er producten van een 2e inkoopbatch afgehaald moeten worden,
# wordt dat in het volgende stukje van de functie gedaan en wordt
# de functie herstart om met nieuwe voorraadgegevens te werken en
# de juiste inkoopbatch te gebruiken.
        elif instock_buyid < productsold[2]:
            prodlist = ([buyid] + productsold[:2] + [instock_buyid]
                        + productsold[3:])
            append_prodlist(prodlist)
            restamount = productsold[2] - instock_buyid
            if restamount == 0:
                print("Product out of stock.")
            else:
                restprodlist = productsold[:2] + [restamount] + productsold[3:]
                productsold = restprodlist
                appendbuyid_morexpdate(productsold)
    # Er komt een melding als het product is uitverkocht.
        if instock_buyid == productsold[2]:
            print("Last product sold, product out of stock.")
        else:
            pass

# # Met deze functie worden de producten toegevoegd aan de sold.csv
# # Eerst wordt gecontroleerd of er een sold.csv bestaat.
# # Afhankelijk daarvan wordt een 1e record toegevoegd met id 1
# # of gezocht naar hoogste id en die automatisch met 1 verhoogd.
def append_prodlist(prodlist):
    maxb_id = 0
    check_file = os.path.isfile("sold.csv")
    if check_file:
        dfb = pd.read_csv("sold.csv", index_col="id")
        if dfb.empty:
            prodlist = [1] + prodlist
            with open("sold.csv", "a", newline="") as productFile:
                productFilewriter = csv.writer(productFile)
                productFilewriter.writerow(prodlist)
                print("Product " + str(prodlist) + " is added to sold.csv")
        else:
            maxb_id = max(dfb.index)
            maxb_id += 1
            prodlist = [maxb_id] + prodlist
            with open("sold.csv", "a", newline="") as productFile:
                productFilewriter = csv.writer(productFile)
                productFilewriter.writerow(prodlist)
                print("Product " + str(prodlist) + " is added to sold.csv")
    if not check_file:
        create_soldcsv()
        append_prodlist(prodlist)

if __name__ == "__main__":
    create_soldcsv()


import controller
import time
import datetime

start_time = time.time()

####define com ports for controller and baudrate (keep at 115200)
# port = '/dev/ttyACM0' # Linux
port = "COM5"  # Windows
baud_rate = 115200

setup = controller.Setup(port, baud_rate)
setup.connect()

#################### Fluidics parameters ###########################
wait = 10
move = controller.Motor()
power = controller.MainPower()

# Parameters related to peristaltic pumps
p1_new = [
    13.712609063042798,
    0.977763871750637,
    4.104248850640944e-05,
    -4.143399187088928e-08,
]
p1_default = [
    19.801938114061617,
    0.964367848880719,
    1.167139063529185e-05,
    -2.873709837738213e-09,
]
p2_default = [
    11.765533598083050,
    0.994151183002726,
    -2.200584843815698e-05,
    5.268389857671134e-09,
]
p_linear = [0, 1, 0, 0]

########### start of script! #################################################

# Main Power ON
print("\n----MAIN POWER ON----")
power.state("ON")
time.sleep(5)

# Homming
print("\n----NOZZLES HOMING----")
message_home2 = bytes("<homeDisp,0,0>", "UTF-8")
move.send(message_home2)
time.sleep(wait + 12)

print("\n----GANTRY HOMING----")
message_home1 = bytes("<homeGantry,0,0>", "UTF-8")
move.send(message_home1)
time.sleep(wait + 7)

######## Move to the cell being used for the failed test #############
print("\n----Moving to cell 2----")
pos = controller.Position_in_cell(2)  ### Change it to 2 or 3 ###
pos.run()
time.sleep(wait + 5)

### Initial Electrode Rinsing #################################################################
## "wait_time" in Rinse function (0 will skip the step, and below is the sequence)
## (1) Down / [LOOP start [ (2) suction / (3) flush / (4) suction] LOOP end] / (5) Up
## = [16, 12, 15, 12, 16]
rinse = controller.Rinse(
    loop=3, wait_time=[16, 12, 15, 12, 16]
)  # change the number of loops
rinse.run()
time.sleep(5)

### Electrode strong rinsing / bubbling / drying (SR) ###############################################
# (SR1) Filling reservoir with solvent
print("\n----\033[31m Filling reservoir with solvent \033[0m----")
filling_only = controller.Rinse(loop=1, wait_time=[16, 0, 15, 0, 16])
filling_only.run()

message_move1_back = bytes("<X,1000,-800>", "UTF-8")  # -870
move.send(message_move1_back)
time.sleep(10)

# (SR2) Argon bubbling
print("\n----\033[31mN2 bubbling\033[0m----")
n2_bubbling = controller.N2(loop=1, nozzle=2, wait_time=[12, 3, 12], mode="dual")
n2_bubbling.run()
time.sleep(7)

# (SR3) Suction only
suction_only = controller.Rinse(loop=1, wait_time=[16, 12, 0, 0, 16])
suction_only.run()
time.sleep(7)

# (SR4) Argon drying
print("\n----\033[31mN2 drying\033[0m----")
n2_drying = controller.N2(loop=1, nozzle=1, wait_time=[12, 3, 12], mode="single")
n2_drying.run()
time.sleep(10)

### Main Power OFF ##################################################################################

print("\n----MAIN POWER OFF----")
power.state("OFF")
time.sleep(5)

print("Finished")
setup.disconnect()

print("\n----\033[31m Print the total time duration \033[0m----")
end_time = time.time()
total_time = end_time - start_time
total_time_list = str(datetime.timedelta(seconds=total_time)).split(".")
print(total_time_list[0])  # Hrs:Mins:Secs format


import webapp2
import cgi
import urllib,json

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.write("""

                  <link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />

                <title>Twetter App</title>

 YOUR RECENT TWEETS !!!

Your Twitter Name:

                  <form action="/sign" method = "post"

<input type="text" name="name" value="Your twitter user name" />

<input type="submit" /> <input type="reset" />

                 </form>

              </html
                    """)

class Tweets(webapp2.RequestHandler):
    def post(self):
        name = (cgi.escape(self.request.get('name')))
        self.response.headers['Content-Type'] = 'text/plain'
       	tweets = urllib.urlopen("https://api.twitter.com/1/statuses/user_timeline.json?screen_name="+name)
        tweets = tweets.read()
        tweets = json.loads(tweets)
        count = 0
        for tweet in tweets:
            if tweet["text"][0] != 'R' and count<10:
               self.response.out.write(tweet['text'])
               self.response.out.write("\n")
               count += 1
app = webapp2.WSGIApplication([('/', MainPage),('/sign', Tweets)], debug=True)


from fastai.vision import *
import pandas as pd

import glob
path_images = Path("../input/train")

path_lbl = path_images
path_test = Path("../input/test")
fn_list = glob.glob('../input/train/*[!_mask].tif') #создает список с именами img(x)

print(fn_list[:3])

print(fn_list[3])

len(fn_list)
lbl_names = glob.glob('../input/train/*_mask.tif') #создает список с именами mask(y)

print(lbl_names[:3])

len(lbl_names)
def get_y_fn(x):  # выдает y(имя маски) по x

    x = Path(x)

    return path_lbl/f'{x.stem}_mask{x.suffix}'
img_f = fn_list[3]

img = open_image(img_f)

img.show(figsize=(5,5))

print(img.size)

mask = open_mask(get_y_fn(img_f),div=True)

mask.show(figsize = (5,5))

print(mask.size)
def mask2rle(img):

    img = img.resize(420,580)

    print(img.size())

    tmp_1 = np.flipud(img)

    print(tmp_1.shape)

    tmp = np.rot90(tmp_1, k=3)

    print(tmp.shape)

    rle = []

    lastColor = 0;

    startpos = 0

    endpos = 0

    tmp = tmp.reshape(-1,1)

    for i in range( len(tmp) ):

        if (lastColor==0) and tmp[i]>0:

            startpos = i

            lastColor = 1

        elif (lastColor==1)and(tmp[i]==0):

            endpos = i-1

            lastColor = 0

            rle.append( str(startpos)+' '+str(endpos-startpos+1) )

    return rle
src_size = np.array(mask.shape[1:])

src_size,mask.data
filter_func = lambda x: str(x) in fn_list
from fastai.utils.mem import *

size = 128

bs=16
class SegLabelListCustom(SegmentationLabelList):

    def open(self, fn): return open_mask(fn, div=True)  # для каждого изображения x возврвщае маску(y)

class SegItemListCustom(SegmentationItemList):

    _label_cls = SegLabelListCustom # метка класса для этого изображения и есть маска

codes = ['0','1']

src = (SegItemListCustom.from_folder(path_images)  # path_images = Path("../input/train")

       .filter_by_func(filter_func) # Сохраняет только те элементы, для которых func возвращает True.filter_func = lambda x: str(x) in fnames х

       .split_by_rand_pct()  # Разделите элементы случайным образом, поместив valid_pct в набор проверки

       .label_from_func(get_y_fn,classes=codes))
type(src)
data = (src.transform(get_transforms(), size=size, tfm_y=True)

        .databunch(bs=bs)

        .normalize(imagenet_stats))

data.path = Path('.')
data.show_batch(rows=4, figsize=(14,10))
def dice_func(input, target):

    smooth = 0

    input = input[:,1,:,:]

    iflat = input.flatten().float()

    tflat = target.flatten().float()

    intersection = (iflat * tflat).sum()

    return ((2. * intersection + smooth) /

              (iflat.sum() + tflat.sum() + smooth))

def dice(input:Tensor, targs:Tensor, iou:bool=False)->Rank0Tensor:

    n = targs.shape[0]

    input = input.argmax(dim=1).view(n,-1)

    targs = targs.view(n,-1)

    intersect = (input * targs).sum().float()

    union = (input+targs).sum().float()

    if not iou: return (2. * intersect / union if union > 0 else union.new([1.]).squeeze())

    else: return intersect / (union-intersect+1.0)

learn = unet_learner(data, models.resnet152, metrics=[dice], wd=1e-3)
lr_find(learn)

learn.recorder.plot()
learn.fit_one_cycle(5,max_lr = 1e-5) # 20
learn.recorder.plot_lr(show_moms=True)
learn.recorder.plot_losses()
learn.recorder.plot_metrics()
learn.unfreeze()
learn.lr_find()

learn.recorder.plot()
learn.fit_one_cycle(15,max_lr = slice(6e-6,1e-4)) # 60
learn.recorder.plot_losses()
learn.recorder.plot_metrics()
# learn.save("trained_model")
df_1 = pd.read_csv("../input/sample_submission.csv")
def pred_rle(fn):

    a = learn.predict(open_image(fn))

    a_1 = a[0].data

    a_2 = open_mask_rle(rle_encode(a_1), (128, 128)).resize((1,420,580))

    a_3 = a_2.data

    a_3 = a_3.resize(420,580)

    print(a_3.size())

    a_3 = np.flipud(a_3)

    print(a_3.shape)

    a_3 = np.rot90(a_3, k=3)

    return rle_encode(a_3)
for i in df_1['img']:

    df_1['pixels'][df_1['img'] == i] = pred_rle('../input/test/' + str(i) + '.tif')
df_1.to_csv('submission.csv', index=False)


T=int(input())
for _ in range(T):
    List=[]
    for i in range(4):
        x,y=map(int,input().split())
        List.append([x,y])
    List=sorted(List,key=lambda x: [x[0],x[1]])
    print(List)
    if List[0][0]==List[1][0] and List[2][0]==List[3][0] and List[0][1]==List[2][1] and List[1][1]==List[3][1] and List[1][1]-List[0][1]==List[2][0]-List[0][0]:
        print(1)
    else: print(0)


import time as time
from datetime import timedelta
from functools import reduce

import dolfin as d
import ufl as ufl

from .gryphon_toolbox import gryphon_toolbox, linearStage, nonlinearStage

class backwardEuler(gryphon_toolbox):
    def __init__(self, T, u, f, bcs=[], tdf=[], tdfBC=[]):
        # The current backward Euler implementation does not provide
        # an estimate for the local error and does thus not support
        # adaptive step size selection.
        self.supportsAdaptivity = False

        # Call toolbox constructor
        gryphon_toolbox.__init__(self, T, u, f, bcs, tdf, tdfBC)

        self.parameters.add("method", "Backward Euler")
        self.parameters.set_range("method", {"Backward Euler"})

    def getLinearVariationalForms(self, X):
        # Generate copies of time dependent functions
        self.tdfButcher = [[] for i in range(len(self.tdf))]
        for j in range(0, len(self.tdf)):
            if self.tdf[j].__class__.__name__ == "CompiledExpression":
                self.tdfButcher[j].append(d.Expression(self.tdf[j].cppcode, t=self.tstart))
            else:
                self.tdfButcher[j].append(self.tdf[j])

        if self.n == 1:
            # Add differential equation
            L = [self.U * self.Q * d.dx - self.u * self.Q * d.dx]
            R = {}
            for k in range(0, len(self.tdf)):
                R[self.tdf[k]] = self.tdfButcher[k][0]

            L[0] -= self.DT * ufl.replace(self.f[0], R)

        else:
            # Add differential equations
            L = [reduce((lambda x, y: x + y),
                        [self.U[alpha] * self.Q[alpha] * d.dx - self.u[alpha] * self.Q[alpha] * d.dx for alpha in
                         range(self.n)])]
            for alpha in range(0, self.n):
                R = {}
                for k in range(0, len(self.tdf)):
                    R[self.tdf[k]] = self.tdfButcher[k][0]

                L[0] -= self.DT * ufl.replace(self.f[alpha], R)
        return L

    def getNonlinearVariationalForms(self, X):
        # Generate copies of time dependent functions
        self.tdfButcher = [[] for i in range(len(self.tdf))]
        for j in range(0, len(self.tdf)):
            if self.tdf[j].__class__.__name__ == "CompiledExpression":
                self.tdfButcher[j].append(d.Expression(self.tdf[j].cppcode, t=self.tstart))
            else:
                self.tdfButcher[j].append(self.tdf[j])

        if self.n == 1:
            # Add differential equations
            L = [X[0] * self.Q * d.dx - self.u * self.Q * d.dx]
            replaceDict = {self.u: X[0]}
            for k in range(0, len(self.tdf)):
                replaceDict[self.tdf[k]] = self.tdfButcher[k][0]
            L[0] -= self.DT * replace(self.f[0], replaceDict)
        else:
            # Add differential equations
            L = [reduce((lambda x, y: x + y),
                        [X[0][alpha] * self.Q[alpha] * d.dx - self.u[alpha] * self.Q[alpha] * d.dx for alpha in
                         range(self.n)])]
            for alpha in range(self.n):
                replaceDict = {self.u: X[0]}
                for k in range(len(self.tdf)):
                    replaceDict[self.tdf[k]] = self.tdfButcher[k][j]
                L[0] -= self.DT * ufl.replace(self.f[alpha], replaceDict)
        return L

    def solve(self):
        super(backwardEuler, self).solve()

        # Array for storing the stage values
        X = [self.u.copy(deepcopy=True)]

        # Get the variational linear/nonlinear variational forms
        # and embed them in respective solver class
        if self.linear:
            l = self.getLinearVariationalForms(X)
            p = [linearStage(d.lhs(l[0]), d.rhs(l[0]), self.bcs, self.solver)]
        else:
            l = self.getNonlinearVariationalForms(X)
            a = [d.derivative(l[0], X[0], self.U)]
            p = [nonlinearStage(a[0], l[0], self.bcs)]

        # Initialize save/plot of function(s)
        self.figureHandling(Init=True)

        # Time stepping loop
        while True:
            timestepStart = time.time()

            # Update time dependent functions
            for i in range(len(self.tdfButcher)):
                for j in range(0, 1):
                    self.tdfButcher[i][j].t = self.t + self.dt

            # Update time dependent functions on boundary
            for F in self.tdfBC:
                F.t = self.t + self.dt

            # Solve for implicit stages
            if self.linear:
                p[0].solve(X[0].vector())
            else:
                self.solver.solve(p[0], X[0].vector())

            # Constant step size integration
            self.u.vector()[:] = X[0].vector()[:]
            self.t += self.dt
            self.nAcc += 1
            if self.parameters['verbose']:
                self.printProgress(self.estimateRuntime)

            # Update / save plots
            self.figureHandling(Update=True)

            # Break if this is final time step
            if self.breakTimeLoop:
                terminateReason = "Success"
                break

            self.timestepTimer = time.time() - timestepStart
            self.verifyStepsize()

        super(backwardEuler, self).terminateTimeLoop(terminateReason)

    def estimateRuntime(self):
        steps = (self.tend - self.t) / self.dt
        return str(timedelta(seconds=round(self.timestepTimer * steps)))


# Aula 12 – Estrutura de repetição for
from time import sleep
#n = int(input('Escreva um número: '))
#for c in range(n, 0, -1):
#    print(c)
#    sleep(0.4)
#print('\033[1;31mFim\033[m')

#i = int(input('Início: '))
#f = int(input('Fim: '))
#p = int(input('Passo: '))
#for c in range(i, f+1, p):
#    print(c)
#    sleep(0.8)
#print('Fim')

s = 0
for c in range(0, 4):
    sleep(0.8)
    n = int(input('Digite um valor: '))
#   s = s + n
    s += n
print('O somatório de todos os números é {}.'.format(s))


import urllib

class Parse:
    def __init__(self):
        pass

    def URI2query(self, request):
        """
        Takes an HTTP request and splits to
        -request
        -query represented as dictionary
        Query split:
            Example - "123?var1=value1&var2=value2" => {"var1":"value1", "var2:"value2"}

        Resources:
        http://www.w3.org/Protocols/rfc1341/4_Content-Type.html

        :return: requested file, vars
        """
        request = urllib.unquote(request).decode('utf8')  # Decode the Percent-encoding
        slitted = str(request).split("?", 1)
        URI = slitted[0]
        dic = {}
        if len(slitted) > 1:  # If there is query split the parameters else keep empty
            query = slitted[1].split("&")
            for pair in query:
                var = pair.split("=")
                if var[0] not in dic:
                    dic.update({var[0]: var[1]})
        return URI, dic

    def headers2dict(self, headers):
        """
        Receive headers and
        :param headers:
        :return:
        """
        headers = headers.split("\r\n")[:-1]
        return dict([(x.split(":", 1)[0].strip(), x.split(":", 1)[1].strip()) for x in headers if x.index(": ")])

    def query2table(self, query):
        data = '
' \
               '
' \
               'parameter	value	' \
               '
'
        for pair in query:
            data += "
"
            data += "{}	{}	".format(pair, query[pair])
            data += "
"
        data += '
'
        return data