import scrapy
from scrapy import log
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from rcbi.items import Part

import copy
import json
import re

import os.path
import urlparse
import urllib

VARIANT_JSON_REGEX = re.compile("product: ({.*}),")
MANUFACTURERS = []
CORRECT = {"Cobra Motors": "Cobra", "Immersion RC": "ImmersionRC"}
STRIP_PREFIX = []

class MiniQuadBrosSpider(CrawlSpider):
  name = "miniquadbros"
  allowed_domains = ["miniquadbros.com"]
  start_urls = ["http://www.miniquadbros.com/collections/frontpage"]

  rules = (
    Rule(LinkExtractor(restrict_css=[".thumbnail"]), callback='parse_item'),
  )

  def parse_item(self, response):
    item = Part()
    item["site"] = self.name

    variant = {}
    item["variants"] = [variant]

    parsed = urlparse.urlparse(response.url)
    filename = "/products/" + os.path.basename(parsed[2])
    base_url = urlparse.urlunparse((parsed[0], parsed[1], filename,
                                          parsed[3], parsed[4], parsed[5]))

    # Find the json info for variants.
    body = response.body_as_unicode()

    m = VARIANT_JSON_REGEX.search(body)
    if m:
      shopify_info = json.loads(m.group(1))
      global_title = shopify_info["title"]
      preorder = False
      if global_title.endswith("Pre Order"):
        global_title = global_title[:-len("Pre Order")].strip()
        variant["stock_state"] = "backordered"
        preorder = True

      if "vendor" in shopify_info:
        if shopify_info["vendor"] in MANUFACTURERS:
          item["manufacturer"] = shopify_info["vendor"]
          if global_title.startswith(item["manufacturer"]):
            global_title = global_title[len(item["manufacturer"]):].strip(" -")
        elif shopify_info["vendor"] in CORRECT:
          item["manufacturer"] = CORRECT[shopify_info["vendor"]]
          if global_title.startswith(shopify_info["vendor"]):
            global_title = global_title[len(shopify_info["vendor"]):].strip(" -")
        for strip in STRIP_PREFIX:
          if global_title.startswith(strip):
            global_title = global_title[len(strip):].strip(" -")

      for v in shopify_info["variants"]:
        if v["title"] != "Default Title":
          item["name"] = (global_title + " " + v["title"]).strip()
          variant["url"] = base_url + "?variant=" + str(v["id"])
        else:
          item["name"] = global_title
          variant["url"] = base_url
        variant["price"] = "${:.2f}".format(v["price"] / 100)
        if not preorder:
          if v["inventory_quantity"] <= 0:
            if v["inventory_policy"] == "deny":
              variant["stock_state"] = "out_of_stock"
            else:
              variant["stock_state"] = "backordered"
          else:
            variant["stock_state"] = "in_stock"

        yield item
        item = copy.deepcopy(item)
        variant = item["variants"][0]


import argparse
import json
import os
import tempfile
from pathlib import Path

import openai
from dotenv import load_dotenv
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.llm import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import TextLoader
from langchain.prompts import PromptTemplate
from transformers import AutoTokenizer, pipeline

load_dotenv()

from newsfeed.datatypes import BlogInfo, BlogSummary
from newsfeed.extract_articles import sanitize_filename

def summarize_text(blog_post_path, local_model=None, sum_type="tech"):
    api_key = os.getenv("OPENAI_API_KEY")
    openai.api_key = api_key
    # loading text as langchain document
    loader = TextLoader(blog_post_path)
    blog_post = loader.load()

    if local_model == "gpt2":
        # just text for local models
        blog_post_text = json.loads(blog_post[0].page_content)["blog_text"]

        checkpoint = "distilgpt2"
        tokenizer = AutoTokenizer.from_pretrained(checkpoint)  # this selects GPT2TokenizerFast

        # max token length is 1024
        # limit input tokens to allow enough space for generation
        tokens_text = tokenizer.tokenize(blog_post_text)
        tokens_tldr = tokenizer.tokenize("\n\nTL;DR:\n")
        tokens = tokens_text[:800] + tokens_tldr

        # convert back to string for pipeline
        query = tokenizer.convert_tokens_to_string(tokens)

        # pipeline uses tokenizer GPT2TokenizerFast and model GPT2LMHeadModel
        pipe = pipeline(
            "text-generation",
            model=checkpoint,
            max_new_tokens=(1024 - len(tokens)),
            temperature=1.5,  # higher value softens output distribution (reducing confidence in predictions, adding more randomness)
        )
        pipe_out = pipe(query)
        summary = pipe_out[0]["generated_text"][len(query) :]

    elif local_model == "t5":
        # just text for local models
        blog_post_text = json.loads(blog_post[0].page_content)["blog_text"]

        checkpoint = "t5-small"
        tokenizer = AutoTokenizer.from_pretrained(checkpoint)  # T5TokenizerFast

        # maximum sequence length for model is 512
        tokens = tokenizer.tokenize(blog_post_text, max_length=512, truncation=True)
        tokens = tokens[:509]  # for some reason pipeline sees 515 tokens
        query = tokenizer.convert_tokens_to_string(tokens)

        # pipeline uses tokenizer T5TokenizerFast and model T5ForConditionalGeneration
        pipe = pipeline("summarization", model=checkpoint, temperature=1.5, do_sample=True)
        pipe_out = pipe(query, max_length=257)
        summary = pipe_out[0]["summary_text"]

    elif local_model == None:
        prompt = select_prompt(sum_type)

        # define what LLM to use
        # using OpenAI chat LLM API requires env variable OPEN_AI_KEY to be set with API key
        llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo-16k")

        # create a "chain" object for running queries against a specified LLM, with customizable prompt
        llm_chain = LLMChain(llm=llm, prompt=prompt)

        # send document to the llm_chain
        # StuffDocumentsChain "stuffs" list of documents + prompt into single call
        # MapReduceChain splits it into several combines and then combines output
        # document_variable_name can be used to customize where in the prompt the documents are inserted?
        stuff_chain = StuffDocumentsChain(llm_chain=llm_chain, document_variable_name="text")
        summary = stuff_chain.run(blog_post)

    else:
        raise NotImplementedError(
            f"Local model {local_model} not implemented. Please choose between 'gpt2' and 't5'"
        )

    return summary

def select_prompt(sum_type):
    if sum_type == "tech":
        prompt_template = """Write a concise summary for an AI researcher of the following:
        "{text}"
        CONCISE SUMMARY:"""
    elif sum_type == "ntech":
        prompt_template = """Write a very simple summary, suitable for children, of the following:
        "{text}"
        SIMPLE SUMMARY:"""
    elif sum_type == "swe":
        prompt_template = """Skriv en sammanfattning på svenska av följande text:
        "{text}"
        Sammanfattning:"""
    else:
        raise NotImplementedError(
            f"Summarization type {sum_type} not implemented. Please choose 'tech', 'ntech', or 'swe'"
        )

    prompt = PromptTemplate.from_template(prompt_template)
    return prompt

# main takes the argument --source aws, or --source mit
def main(source, local_model=None, sum_type="tech"):
    path_article_dir = Path(f"data/data_warehouse/{source}/articles")
    path_summary_dir = Path(f"data/data_warehouse/{source}/summarized_articles")

    if local_model:
        path_summary_dir = path_summary_dir / local_model
    else:
        path_summary_dir = path_summary_dir / sum_type

    path_summary_dir.mkdir(parents=True, exist_ok=True)

    already_summarized = set(os.listdir(path_summary_dir))

    file_list = os.listdir(path_article_dir)
    new_articles = []

    for file_name in file_list:
        summary_filename_check = f"Summary_of_{file_name}"

        if summary_filename_check in already_summarized:
            print(f"Skipping already summarized article: {file_name}")
            continue

        # if new summary is generated, add to list
        new_articles.append(file_name)
        # file path for the article that's being summarized/looked at
        current_article_path = path_article_dir / file_name
        summary_text = summarize_text(current_article_path, local_model, sum_type)
        print(f"Generated summary for {file_name}")

        blog_summary = BlogSummary(
            unique_id=f"summary_{file_name}",
            title=f"Summary of {Path(file_name).stem}",
            text=summary_text,
        )
        # gets the name of the article
        summary_filename = blog_summary.get_filename()
        summary_filename = sanitize_filename(summary_filename)

        with open(path_summary_dir / summary_filename, "w") as f:
            f.write(blog_summary.json())
        already_summarized.add(summary_filename)

    return new_articles

blog_names = ["mit", "aws", "openai"]

# run python summarize.py --source mit OR aws
def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--source",
        type=str,
        choices=blog_names,
        default="mit",
        help=f"Blog source to summarize, allowed arguments are: {blog_names}.",
    )
    parser.add_argument(
        "--model",
        type=str,
        choices=["t5", "gpt2"],
        # default="",
        help=f"Use local model for summarization",
    )
    parser.add_argument(
        "--stype",
        type=str,
        choices=["tech", "ntech", "swe"],
        default="tech",
        help=f"What type of summarization do you want (techincal 'tech', non-technical 'ntech', or swedish 'swe')",
    )
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    main(source=args.source, local_model=args.model, sum_type=args.stype)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 03:15:21 2019

@author: ishan
"""

import matplotlib.pyplot as plt
import numpy as np

show_animation = True

# Creating obstacle map
ox,oy = [],[]
explore_x,explore_y = [],[]
backtrack = []
obstacle = np.zeros(shape=(250,150))
for x in range (0,250):
    for y in range(0,150):

# Equations for rectangle
        f1 = -y + 67.5
        f2 =  y - 112.5
        f3 =  -x + 50
        f4 =  x - 100

 #Equations for circle
        f5 = (x - 190)**2 + (y - 130)**2 - (15)**2

 #Equation for ellipse
        f6 = (1/225) * ((x - 140)**2) + (1/36) * ((y - 120)**2) - 1

 #Equation for polygon-triangle 1
        f7 = 38*x + 23*y - 8530
        f8 = -y +52
        f9 = -38*x + 7*y +5830

#Equation for polygon-traingle 2
        f10 = 2*x + 19*y - 1314
        f11 = -41*x -25*y + 6525
        f12 = 37*x -13*y -5355

#Equation for polygon-part 3
        f13 = y - 52
        f14 = 37*x - 20*y - 6101
        f15 = -y + 15
        f16 = -37*x + 13*y + 5355
        if (f1<=0 and f2<=0 and f3<=0 and f4<=0 or f5<=0 or f6<=0 or (f7<=0 and f8<=0 and f9<=0) or (f10<=0 and f11<=0 and f12<=0) or (f13<=0 and f14<=0 and f15<=0 and f16<=0)):
            obstacle[x][y] = 1
            ox.append(x)
            oy.append(y)

for i in range(250):
        ox.append(i)
        oy.append(0)
        obstacle[i][0] = 1
for i in range(250):
        ox.append(i)
        oy.append(150)
        obstacle[i][149] = 1
for i in range(150):
        ox.append(0)
        oy.append(i)
        obstacle[0][i] = 1
for i in range(150):
        ox.append(250)
        oy.append(i)
        obstacle[249][i] = 1

#plotting the obstacle map
plt.plot(ox,oy,".k")
plt.ylim((0,150))
plt.xlim((0,250))


#!/usr/bin/env python3
import argparse
import sys

import pyperclip
from tabulate import tabulate
from tqdm import tqdm

import lime_comb
from lime_comb.commands.config import ConfigCommand
from lime_comb.commands.decrypt import DecryptCommand
from lime_comb.commands.encrypt import EncryptCommand
from lime_comb.commands.keys import KeysCommand
from lime_comb.config import EmptyConfigError, config
from lime_comb.logger.logger import logger
from lime_comb.validators.email import lc_validate_email

def base_parser(input_args):
    parser = argparse.ArgumentParser(description="lime comb tool.")

    parser.add_argument(
        "--version",
        dest="version",
        required=False,
        action="store_true",
        help="show current version",
    )
    parser.add_argument(
        "--log-lvl",
        dest="log_lvl",
        required=False,
        default="WARNING",
        action="store",
        choices=("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
        help="log level",
    )

    subparsers = parser.add_subparsers(
        help="use --help to check help for sub-command",
        title="commands",
        description="Top level supported commands",
        required=False,
        dest="top_command",
    )
    keys_cmd = KeysCommand(subparsers)
    enc_cmd = EncryptCommand(subparsers)
    dec_cmd = DecryptCommand(subparsers)
    conf_cmd = ConfigCommand(subparsers)
    args = parser.parse_args(input_args)
    parse_common(parser, args)
    return args, keys_cmd, enc_cmd, dec_cmd, conf_cmd

# TODO provide class for config and keys

def parse_common(parser, args):
    logger.setLevel(args.log_lvl)
    logger.info(f"log lvl {logger.getEffectiveLevel()}")
    if args.version:
        print(f"version: {lime_comb.__version__}")
        sys.exit(0)
    elif not args.top_command:
        parser.print_help()
        sys.exit(0)

def get_recipients(args):
    if not getattr(args, "recipients", None):
        logger.info("No recipients. Asking user to type in")
        args.recipients = input("please specify recipients(space separated)\n").split()
        for email in args.recipients:
            try:
                lc_validate_email(email)
            except Exception as e:
                logger.critical(e)
                sys.exit(1)
    return args.recipients

def get_message(args):
    if args.files:
        for fn in args.files:
            logger.debug(f"adding content of {fn} to messages")
            with open(fn, "r") as f:
                args.messages.append(f.read())
    if not args.messages:
        logger.warning("No message to encrypt")
        sys.exit(1)
    return args.messages

def dec_exec(args, cmd):
    if args.top_command in cmd.aliases:
        decrypted = []
        for m in tqdm(cmd(get_message(args)), desc="decrypting"):
            decrypted.append(m)
        decrypted = "\n---\n".join(decrypted)
        pyperclip.copy(decrypted)
        return decrypted

def enc_exec(args, cmd):
    if args.top_command in cmd.aliases:
        encrypted = []
        for m in tqdm(
            cmd(get_message(args), get_recipients(args), merge=args.merge_messages),
            desc="encrypting",
        ):
            encrypted.append(m)
        encrypted = "\n---\n".join(encrypted)
        pyperclip.copy(encrypted)
        return encrypted

def keys_exec(args, cmd):
    if args.top_command in cmd.aliases:
        keys = list(tqdm(cmd(args), desc="keys"))
        return tabulate(keys)

def conf_exec(args, cmd):
    if args.top_command in cmd.aliases:
        return tabulate(list(cmd(args)))

def main(cmdline_args):
    args, k_cmd, e_cmd, d_cmd, c_cmd = base_parser(cmdline_args)
    try:
        for action in (
            dec_exec(args, d_cmd),
            enc_exec(args, e_cmd),
            keys_exec(args, k_cmd),
            conf_exec(args, c_cmd),
        ):
            if action:
                print(action)
    except EmptyConfigError:
        config._gen_config()

def run():
    main(sys.argv[1:])

if __name__ == "__main__":
    run()


import os
from copy import deepcopy

import numpy as np
import argparse
from .utils import load_data
from .model import Model
import torch

def initialize_data(config, train=False, test=False):
    print("Initializing data source...")
    train_source, test_source = load_data(**config['data'], cache=(train or test))
    if train:
        print("Loading training data...")
        train_source.load_all_data()
    if test:
        print("Loading test data...")
        test_source.load_all_data()
    print("Data initialization complete.")
    return train_source, test_source

def initialize_model(config, train_source, test_source):
    print("Initializing model...")
    data_config = config['data']
    model_config = config['model']
    model_param = deepcopy(model_config)
    model_param['train_source'] = train_source
    model_param['test_source'] = test_source
    model_param['train_pid_num'] = data_config['pid_num']
    model_param['profiling'] = config['profiling']
    model_param['start_step'] = config['start_step']
    model_param['stop_step'] = config['stop_step']
    batch_size = int(np.prod(model_config['batch_size']))
    model_param['save_name'] = '_'.join(map(str,[
        model_config['model_name'],
        data_config['dataset'],
        data_config['pid_num'],
        data_config['pid_shuffle'],
        model_config['hidden_dim'],
        model_config['margin'],
        batch_size,
        model_config['hard_or_full_trip'],
        model_config['frame_num'],
    ]))

    m = Model(**model_param)
    print("Model initialization complete.")
    return m, model_param['save_name']

def initialization(config, train=False, test=False):
    print("Initialzing...")
    WORK_PATH = config['WORK_PATH']
    os.chdir(WORK_PATH)
    os.environ["ASCEND_VISIBLE_DEVICES"] = config["ASCEND_VISIBLE_DEVICES"]
    train_source, test_source = initialize_data(config, train, test)
    return initialize_model(config, train_source, test_source)


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 18:13:27 2015

@author: NigmatullinR
"""
#пример связ с Гаусовским импульсом
import numpy as np
import pylab as plb
import scipy.signal as sgn

M=2 # decimation factor

t = np.linspace(-0.75, 0.75, 2 * 100, endpoint=False)#носитель на кот строится ГИ
g = sgn.gausspulse(t, fc=5, bw=0.3, retquad=False, retenv=False)#Гаус импульс
plb.plot(t, g)
plb.title('Original signal')

plb.figure()
plb.plot(abs(np.fft.fft(g)[:len(g)/2]))#преобр Ф
plb.title('Original signal FFT')

ind2=range(0,len(g),2)
g2=g[ind2]

plb.figure()
plb.plot(g2)
plb.title('Signal after decimation')

plb.figure()
plb.plot(abs(np.fft.fft(g)[:len(g2)/2]))
plb.title('Decimation signal FFT')

g3=np.zeros((M*len(g)))#массив заполн нулями

ind3=range(0,len(g3),M)

g3[ind3]=g#вставляем

plb.figure()
plb.plot(g3)
plb.title('Signal after upsampling')#отображ

plb.figure()
plb.plot(abs(np.fft.fft(g)[:len(g3)/2]))#взяли пр Ф
plb.title('Upsampling signal FFT')


import os
from Nude import Nude

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description='Detect nudity in images.')
    parser.add_argument('files', metavar='image', nargs='+',
                        help='Images you wish to test')
    parser.add_argument('-r', '--resize', action='store_true',
                        help='Reduce image size to increase speed of scanning')
    parser.add_argument('-v', '--visualization', action='store_true',
                        help='Generating areas of skin image')

    args = parser.parse_args()

    for fname in args.files:
        if os.path.isfile(fname):
            n = Nude(fname)
            if args.resize:
                n.resize(maxheight=800, maxwidth=600)
            n.parse()
            if args.visualization:
                n.showSkinRegions()
            print(n.result, n.inspect())
        else:
            print(fname, "is not a file")


import sys      # 기본적으로 가져와야함, 시스템 쉘 정보등을 담고있음.

# QTWidgets 에 대부분의 기본 기능을 갖고있음. 버튼, 툴팁텍스트 추가 등등
from PyQt5.QtWidgets import QApplication, QWidget   # 기본적으로 가져와야 할 2가지 모듈

# QWidget 을 상속받아 클래스 생성. (나만의 창을 만들기 위한)
class Exam(QWidget):
    # 생성자 만들기
    def __init__(self):
        super().__init__()           # super(): 상위 계층이 생성됨.
        self.initUI()                # 내가 사용할 함수, Method 매서드를 만듬
    def initUI(self):
        self.show()                 # 사용자가 볼 수 있도록 출력 (기본적으로 만들기)

# app : 어플리케이션 객체생성
# sys.argv : 시스템의 명령을 받아서 진행할때
app = QApplication(sys.argv)        # 모든 Qt5의 어플리케이션은 반드시 QApplication object를 생성해야 한다. (기본적인 사항)

w = Exam()      # w라는 객체 생성 내가만든 class를 이용해서

# app.exec_() : Main 루프를 실행 이벤트가 발생할 때까지 실행. 사용자가 프로그램을 종료를하면  sys.exit() 으로 깨끗하게 종료시킴.
sys.exit(app.exec_())

1_기본 위젯창 만들기, 창 이름설정, 버튼만들기, 마우스 테그 만들기/1_가장 기본 위젯창 만들기.py

1_가장 기본 위젯창 만들기.py


import torch
import os
import argparse
import random
import numpy as np
from datetime import datetime
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as ddp
import logging
import sys
import time

from utils.data.data_dir import default_dir
from utils.data.augment import hard_trans
from utils.data.dataset import MyDataset
from torch.utils.data import DataLoader
from utils.log import logger_init
from utils.seed_init import rand_seed

from ea_nas.res_supernet import resnet_nas, choose_rand
import utils.models as models
import utils.optimizers as optimizers

def run(args, encoder, fc, criterion, optimizer, scheduler, trainloader, validloader, logger):
    # train
    for i_epoch in range(args.max_epoch):
        encoder.train()
        fc.train()
        trainloader.sampler.set_epoch(i_epoch)
        correct = torch.tensor(0.0).cuda()
        total = torch.tensor(0.0).cuda()
        start_time = time.time()

        for i_iter, data in enumerate(trainloader):
            img, label = data[:2]
            img, label = img.cuda(), label.cuda()

            choose = epoch_choose(i_epoch)

            optimizer.zero_grad()
            f = encoder(img, choose)
            s = fc(f)
            loss = criterion(s, label)
            loss.backward()
            optimizer.step()

            # acc
            _, predicted = torch.max(s.data, 1)
            correct += predicted.eq(label.data).sum()
            total += label.size(0)

            # print info
            log_fre = len(trainloader) if args.log_fre == -1 else args.log_fre
            if (i_iter + 1) % log_fre == 0:
                correct_tmp = correct.clone()
                total_tmp = total.clone()
                dist.reduce(correct_tmp, dst=0, op=dist.ReduceOp.SUM)
                dist.reduce(total_tmp, dst=0, op=dist.ReduceOp.SUM)
                if args.local_rank == 0:
                    eta = (time.time() - start_time) / 60.
                    logger.info("Training: Epoch[{:0>3}/{:0>3}] "
                                "Iter[{:0>3}/{:0>3}] "
                                "lr: {:.5f} "
                                "Loss: {:.4f} "
                                "Acc:{:.2%} "
                                "Run-T:{:.2f}m".format(
                        i_epoch + 1, args.max_epoch,
                        i_iter + 1, len(trainloader),
                        optimizer.state_dict()['param_groups'][0]['lr'],
                        loss.cpu().item() / dist.get_world_size(),
                        correct.cpu().item() / total.cpu().item(),
                        eta))

        scheduler.step()
        if args.local_rank == 0:
            torch.save(encoder.state_dict(), '%s/encoder.pth' % args.log_dir)
            torch.save(fc.state_dict(), '%s/fc.pth' % args.log_dir)

        # valid
        if i_epoch % 10 == 0:
            choose_valid = epoch_choose(0)
            valid(args, encoder, fc, validloader, logger, choose_valid)

def epoch_choose(i_epoch, s_epoch=60, times=1):
    epoches = [1 * times, 1 * times, 1 * times, 1 * times, 1 * times,
               4 * times, 4 * times, 4 * times, 4 * times, 4 * times,
               2 * times,
               1 * times, 1 * times]
    epoches = np.array(epoches)
    epoches = np.cumsum(epoches)
    if i_epoch < s_epoch:
        stages = (tuple(range(6, 5, -1)),
                  tuple(range(8, 7, -1)),
                  tuple(range(12, 11, -1)),
                  tuple(range(6, 5, -1)))
        channel_scales = (1.5,)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[0]:
        stages = (tuple(range(6, 5, -1)),
                  tuple(range(8, 7, -1)),
                  tuple(range(12, 11, -1)),
                  tuple(range(6, 5, -1)))
        channel_scales = (1.5, 1.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[1]:
        stages = (tuple(range(6, 5, -1)),
                  tuple(range(8, 7, -1)),
                  tuple(range(12, 11, -1)),
                  tuple(range(6, 5, -1)))
        channel_scales = (1.5, 1.25, 1.0)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[2]:
        stages = (tuple(range(6, 5, -1)),
                  tuple(range(8, 7, -1)),
                  tuple(range(12, 11, -1)),
                  tuple(range(6, 5, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[3]:
        stages = (tuple(range(6, 5, -1)),
                  tuple(range(8, 7, -1)),
                  tuple(range(12, 11, -1)),
                  tuple(range(6, 5, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[4]:
        stages = (tuple(range(6, 5, -1)),
                  tuple(range(8, 7, -1)),
                  tuple(range(12, 11, -1)),
                  tuple(range(6, 5, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[5]:
        stages = (tuple(range(6, 4, -1)),
                  tuple(range(8, 6, -1)),
                  tuple(range(12, 10, -1)),
                  tuple(range(6, 4, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[6]:
        stages = (tuple(range(6, 3, -1)),
                  tuple(range(8, 5, -1)),
                  tuple(range(12, 9, -1)),
                  tuple(range(6, 3, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[7]:
        stages = (tuple(range(6, 2, -1)),
                  tuple(range(8, 4, -1)),
                  tuple(range(12, 8, -1)),
                  tuple(range(6, 2, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[8]:
        stages = (tuple(range(6, 1, -1)),
                  tuple(range(8, 3, -1)),
                  tuple(range(12, 7, -1)),
                  tuple(range(6, 1, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[9]:
        stages = (tuple(range(6, 0, -1)),
                  tuple(range(8, 2, -1)),
                  tuple(range(12, 6, -1)),
                  tuple(range(6, 0, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[10]:
        stages = (tuple(range(6, 0, -1)),
                  tuple(range(8, 1, -1)),
                  tuple(range(12, 5, -1)),
                  tuple(range(6, 0, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[11]:
        stages = (tuple(range(6, 0, -1)),
                  tuple(range(8, 1, -1)),
                  tuple(range(12, 4, -1)),
                  tuple(range(6, 0, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    elif i_epoch < s_epoch + epoches[12]:
        stages = (tuple(range(6, 0, -1)),
                  tuple(range(8, 1, -1)),
                  tuple(range(12, 3, -1)),
                  tuple(range(6, 0, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    else:
        stages = (tuple(range(6, 0, -1)),
                  tuple(range(8, 1, -1)),
                  tuple(range(12, 2, -1)),
                  tuple(range(6, 0, -1)))
        channel_scales = (1.5, 1.25, 1.0, 0.75, 0.5, 0.25)
        kernels = [(1, 3), (1, 5), (1, 7)]
    choose = choose_rand(stages, channel_scales, kernels)
    return choose

def valid(args, encoder, fc, validloader, logger, choose_valid):
    with torch.no_grad():
        encoder.eval()
        fc.eval()
        correct = torch.tensor([0.0]).cuda()
        total = torch.tensor([0.0]).cuda()
        for data in validloader:
            img, label = data[:2]
            img, label = img.cuda(), label.cuda()

            feature = encoder(img, choose_valid)
            s = fc(feature)

            # acc
            _, predicted = torch.max(s.data, 1)
            correct += predicted.eq(label.data).sum()
            total += label.size(0)
        dist.reduce(correct, dst=0, op=dist.ReduceOp.SUM)
        dist.reduce(total, dst=0, op=dist.ReduceOp.SUM)
        if args.local_rank == 0:
            logger.info('valid-acc:{:.2%}'.format(correct.cpu().item() / total.cpu().item()))
            logger.info('--------------------------')

def main(args):
    # dist init
    torch.cuda.set_device(args.local_rank)
    torch.distributed.init_process_group(backend='nccl', init_method='env://')

    # dataloader
    train_dir, valid_dir = default_dir[args.dataset]
    train_trans, valid_trans = hard_trans(args.img_size)

    trainset = MyDataset(train_dir, transform=train_trans)
    train_sampler = torch.utils.data.distributed.DistributedSampler(trainset)
    trainloader = DataLoader(trainset, batch_size=args.bs, shuffle=False,
                             num_workers=8, pin_memory=True, sampler=train_sampler)

    validset = MyDataset(valid_dir, transform=valid_trans)
    valid_sampler = torch.utils.data.distributed.DistributedSampler(validset)
    validloader = DataLoader(validset, batch_size=args.bs, shuffle=False,
                             num_workers=8, pin_memory=True, sampler=valid_sampler)

    # model
    supernet_choose = choose_rand(([6], [8], [12], [6]), (1.5,), [(1, 7)])
    supernet = resnet_nas(supernet_choose)
    fc = models.__dict__['cos'](trainloader.dataset.n_classes, supernet.emb_size, 100.0)
    criterion = models.__dict__['cross_entropy'](1.0)
    supernet = supernet.cuda()
    fc = fc.cuda()
    criterion = criterion.cuda()

    # optimizer
    optimizer = optimizers.__dict__['sgd']((supernet, fc), args.optim_lr)
    scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, args.optim_step, gamma=0.1)

    # ddp
    supernet = torch.nn.SyncBatchNorm.convert_sync_batchnorm(supernet)
    supernet = ddp(supernet, device_ids=[args.local_rank], find_unused_parameters=True)
    fc = ddp(fc, device_ids=[args.local_rank], find_unused_parameters=True)

    # log
    if args.local_rank == 0:
        time_str = datetime.strftime(datetime.now(), '%y-%m-%d-%H-%M-%S')
        args.log_dir = os.path.join('logs', args.dataset + '_' + time_str)
        if not os.path.exists(args.log_dir):
            os.makedirs(args.log_dir)
        logger = logger_init(args.log_dir)
    else:
        logger = None
    if args.local_rank == 0:
        logger.info(args)
        logger.info('n_classes:%d' % trainloader.dataset.n_classes)

    # train and valid
    run(args, supernet, fc, criterion, optimizer, scheduler, trainloader, validloader, logger)
    if args.local_rank == 0:
        logger.info(args.log_dir)

if __name__ == "__main__":
    # -------------------   参数读取   ------------------------------
    parser = argparse.ArgumentParser("finetuning with Pytorch")
    # data
    parser.add_argument('--dataset', type=str, default='image3403',
                        help='The dataset_name')
    parser.add_argument('--img_size', type=int, default=224,
                        help='Input image size.')
    parser.add_argument('--bs', type=int, default=64,
                        help='The batch-size of single-gpu training and validating.')

    # optimizer
    parser.add_argument('--optim', type=str, default='sgd',
                        help='optimizer type.')
    parser.add_argument('--optim_lr', type=float, default=2e-1,
                        help='The init learning rate.')
    parser.add_argument('--optim_step', type=list, default=[100, 160, 200],
                        help='optim step.')
    parser.add_argument('--max_epoch', type=int, default=250,
                        help='max epoch.')

    # GPU
    parser.add_argument("--local_rank", default=0, type=int,
                        help='master rank')

    # info
    parser.add_argument('--log_fre', type=int, default=50,
                        help='log show fre.')

    args = parser.parse_args()
    rand_seed(0)
    main(args)


from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.template import loader
from django.http import Http404
from django.utils.translation import gettext as _

#models
from ..models import Streamer
from ..models import Game

#utility
import pprint
from ..utility.util import getGameRankData,getStreamerRank,getVideoRank,video_setup, getGameRankData, getSeoSetting,getCommonSetting
#from ..utility.util import video_setup,getGameStreamerRank,getNewVideosWithRating,getRecommendVideos,getMostViewVideos

def ranking(request, type, sort_id, category,page):

    if type == 'streamer':

        if sort_id not in ['all','growing','subscriber']:
            raise Http404("404 Invalid Sort Id")

        if category not in ['all','male','female']:
            raise Http404("404 Invalid Catgory")

        context = streamerRank(request, sort_id, category, page)
        return render(request, 'streamer/ranking_streamer.html', context)

    elif type == 'video':

        if sort_id not in ['all','toprate','new','views']:
            raise Http404("404 Invalid Sort Id")

        if category not in ['all','pc','mobile','console']:
            raise Http404("404 Invalid Catgory")

        context = videoRank(request, sort_id, category , page)
        return render(request, 'streamer/ranking_video.html', context)
    else:
        raise Http404("404 Invalid Type")

def streamerRank(request, sort_id, category, page):

    #sort_id
    sort_id_list = {
        'all' : 1,
        'growing' : 2,
        'subscriber' : 3,
    }
    sord_id_int = sort_id_list[sort_id]

    #sort_id
    category_id_list = {
        'all' : 10,
        'male' : 1,
        'female' : 2,
    }
    category_id = category_id_list[category]

    #h1 title
    h1_sort = {
        1: _('Total Views'),
        2: _('Growing'),
        3: _('Total Subscriber'),
    }
    h1_category = {
        10: "",
        1: _('Male '),
        2: _('Female '),
    }
    h1_streamer_title = {
        1: _('Game Streamer '),
        2: _('Game Streamer '),
        3: _('Game Streamer '),
    }

    h1_sort = h1_sort[sord_id_int]
    h1_streamer_title = h1_streamer_title[sord_id_int]
    h1_category = h1_category[category_id]

    #Get Streamer Rank Data
    results_per_page = 100
    streamer_ranks = getStreamerRank(sord_id_int, category_id, results_per_page, page)

    #Get Popular Games
    popular_games = getGameRankData(10,20)

    #Rank Start
    rank_start = results_per_page * (page - 1)

    #seo_settings
    seo_settings = getSeoSetting(request)
    common_settings = getCommonSetting(request)

    context = {
        'sort_id' : sort_id,
        'h1_sort' : h1_sort,
        'h1_streamer_title' : h1_streamer_title,
        'category' : category,
        'h1_category' : h1_category,
        'streamer_ranks' : streamer_ranks,
        'popular_games': popular_games,
        'rank_start': rank_start,
        'seo_settings': seo_settings,
        'common_settings': common_settings,
    }

    return context

def videoRank(request, sort_id, category , page):

    #sort_id
    sort_id_list = {
        'all' : 2,
        'toprate' : 3,
        'new' : 1,
        'views' : 4,
    }
    sord_id_int = sort_id_list[sort_id]

    #sort_id
    category_id_list = {
        'all' : 10,
        'pc' : 1,
        'mobile' : 2,
        'console' : 3,
    }
    category_id = category_id_list[category]

    #h1 title
    h1_sort = {
        1: _('New'),
        2: _('Total Views last 48hour'),
        3: _('Top Rate'),
        4: _('Total Views'),
    }

    h1_category = {
        10: "",
        1: "PC ",
        2: _('Mobile '),
        3: _('Console '),
    }

    h1_sort = h1_sort[sord_id_int]
    h1_category = h1_category[category_id]

    #Get Streamer Rank Data
    exlude_game_id=1
    video_ranks = getVideoRank(sord_id_int, category_id, 100 , page ,exlude_game_id )
    for v in video_ranks:
        v = video_setup(v)

    #Get Popular Games
    popular_games = getGameRankData(10,20)

    #seo_settings
    seo_settings = getSeoSetting(request)
    common_settings = getCommonSetting(request)

    context = {
        'sort_id' : sort_id,
        'category' : category,
        'h1_sort' : h1_sort,
        'h1_category' : h1_category,
        'video_ranks' : video_ranks,
        'popular_games': popular_games,
        'seo_settings': seo_settings,
        'common_settings' : common_settings,
    }

    return context


"""
Este problema foi utilizado em 94 Dojo(s).
Dado uma letra ('A' a 'Z'), exiba um diamante iniciando em 'A' e tendo a letra fornecida com o ponto mais distante.
Por exemplo, dado a letra 'E' temos:
    A
   B B
  C   C
 D     D
E       E
 D     D
  C   C
   B B
    A

Dado a letra 'C' temos:
  A
 B B
C   C
 B B
  A

# print(len(alfabeto)) = 26
"""

import string
import curses

alfabeto = list(string.ascii_uppercase)

def diamante(letra):
	indice = alfabeto.index(letra)
	lista = [item for item in alfabeto[:indice+1]]
	lista += lista[indice-1::-1]
	for item in lista:
		if item == 'A':
			print(' '*(lista.index(letra)-lista.index(item))+item)
		else:
			print(' '*(lista.index(letra)-lista.index(item))+item+(' '*((lista.index(item)*2)-1))+item)

running = True

while running:
	letra_escolhida = input("\nEscolha uma letra do alfabeto: ")
	if letra_escolhida.isalpha():
		diamante(letra_escolhida.upper())
	else:
		print("Você não digitou uma letra correspondente ao alfabeto!\nTente novamente.\n")
	# continuar = input("Digite uma letra para continuar ou ESC para sair")
	print("Digite uma letra para continuar ou ESC para sair: ")
	stdscr = curses.initscr()
	stdscr.getch()
	key = stdscr.getch()
	# key = continuar
	if key == 27:
		running = False
		curses.endwin()
		break
	else:
		curses.endwin()
		continue


# Импортирование модулей
from aiogram import Dispatcher, Bot, types, executor
from aiogram.types import ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton
from aiogram.types.input_file import InputFile
import configure

# Создание экземпляра бота
bot = Bot(configure.config['API'])
update = Dispatcher(bot)

# Начальный текст
START_COMMAND = """
Здравствуйте, флешка!
Я бот для ЕГЭ по Информатике.
Я помогу сдать тебе ЕГЭ на 💯!!!
Для начало работы нажми на кнопку задания.
Данный бот создан в целях научить вас информатики, а не найти ответ на задачу😁😄😉
"""
ZADANIE_TEXT = """
Нажми на кнопку с соответствующим заданием.
"""
ZADANIE_1 = """
Название задания первого номера:
Структурирование информации и информационные модели
Ссылка на сайт: https://labs-org.ru/ege-1/
Перейдя по ссылке можно будет подробно ознакомится с решением данного задания
На фото представлен вид задания
"""
ZADANIE_2 = """
Название задания второго номера:
Построение таблиц истинности логических выражений
На фото представлена программа для решения данного задания.
"""
ZADANIE_3 = """
Название задания третьего номера:
Базы данных
Ссылка на сайт: https://labs-org.ru/ege-3/
Перейдя по ссылке можно будет подробно ознакомится с решением данного задания
На фото представлен вид задания
"""
ZADANIE_4 = """
Название задания четвёртого номера
Базы данных
Ссылка на сайт: https://labs-org.ru/ege-4/
Перейдя по ссылке можно будет подробно ознакомится с решением данного задания
На фото представлен вид задания
"""
async def start_command(message: types.Message):
    # Создание клавиатуры
    keyboard = ReplyKeyboardMarkup(resize_keyboard=True)
    # Добавление кнопок
    button1 = KeyboardButton('/zadanie')
    button2 = KeyboardButton('/1')
    button3 = KeyboardButton('/2')
    button4 = KeyboardButton('/3')
    button5 = KeyboardButton('/4')
    keyboard.add(button1)
    keyboard.add(button2, button3)
    keyboard.add(button4, button5)
    # Отправка сообщения с клавиатурой
    await bot.send_message(chat_id=message.chat.id, text=START_COMMAND, reply_markup=keyboard)
    await message.delete()

# Определение фукций-обработчиков команд
# async def start_command(message: types.message):
#     """
#     Функция-обработчик команды /start
#     Отправляет приветственное сообщение с инструкцией
#     """
#     await bot.send_message(chat_id=message.chat.id, text=START_COMMAND)
#     await message.delete()

async def zadanie_command(message: types.message):
    """
    Функция-обработчик команды /zadanie
    Отправляет сообщение с инструкцией по выбору задания
    """
    await bot.send_message(chat_id=message.chat.id, text=ZADANIE_TEXT)
    await message.delete()

async def number1_command(call):
    """
    Функция-обработчик команды /1
    Отправляет описание первого задания и прикреплённое к нему изображение
    """
    await bot.send_message(chat_id=call.chat.id, text=ZADANIE_1)
    await bot.send_photo(chat_id=call.chat.id, photo="https://code-enjoy.ru/posts/264/zadanie_1_ege_po_informatike_demoversiya_2022.jpg")
    await call.delete()

async def number2_command(message):
    """
    Функция-обработчик команды /2
    Отправляет описание второго задания и прикреплённое к нему изображение
    """
    await bot.send_message(chat_id=message.chat.id, text=ZADANIE_2)
    #await bot.send_photo(chat_id=message.chat.id) # photo
    await message.delete()

async def number3_command(message):
    """
    Функция-обработчик команды /3
    Отправляет описание третьего задания и прикреплённое к нему изображение
    """
    await bot.send_message(chat_id=message.chat.id, text=ZADANIE_3)
    await bot.send_photo(chat_id=message.chat.id, photo='https://labs-org.ru/wp-content/uploads/2017/06/1_11-28.png')
    await message.delete()

async def number4_command(message):
    """
    Функция-обработчик команды /4
    Отправляет описание четвёртого задания и прикреплённое к нему изображение
    """
    await bot.send_message(chat_id=message.chat.id, text=ZADANIE_4)
    await bot.send_photo(chat_id=message.chat.id, photo='https://code-enjoy.ru/posts/289/ege_po_informatike_2022_zadanie_4_derevo_fano_5.jpg')
    await message.delete()

# Регистрация команд
if __name__ == '__main__':
    print("running...")

    update.register_message_handler(start_command, commands=['start'])
    update.register_message_handler(zadanie_command, commands=['zadanie'])
    update.register_message_handler(number1_command, commands=['1'])
    update.register_message_handler(number2_command, commands=['2'])
    update.register_message_handler(number3_command, commands=['3'])
    update.register_message_handler(number4_command, commands=['4'])

    executor.start_polling(update, skip_updates=False)


import pygame as pg
import random
import os
import threading

# INFO: This code is a little bit messy
# TODO: Optimize code or cleaning
pg.init()

screen = pg.display.set_mode((800, 800))

clock = pg.time.Clock()

running = True

dt = 0

width = screen.get_width()
height = screen.get_height()
player_pos = pg.Vector2(width - (width / 2), height - (height / 10))
y_pos = 0
speed = 5
score = 0
high_score = 0
miss = 0
ctime = 0

x_pos = random.randint(10, width - 20)

white = (255, 255, 255)
pg.font.init()
font = pg.font.SysFont('firacode', 22)

with open('highScore.txt','r') as f:
    high_score =int( f.read() )

# fonts = pg.font.get_fonts()
# for f in fonts:
#    print(f)
#
sunny = pg.image.load(os.path.join('resource', 'sunny.png'))
boat = pg.image.load(os.path.join('resource', 'boat.png'))
sea = pg.image.load(os.path.join('resource', 'sea.jpg'))
sunny = pg.transform.scale(sunny,(50,50))
boat = pg.transform.scale(boat,(100,60))

choper = pg.mixer.music.load(os.path.join('resource', 'choper.mp3'))
theme = pg.mixer.music.load(os.path.join('resource', 'theme.mp3'))
pg.mixer.music.play(-1)

def effect(sounds,chan):
    # m=pg.mixer.Sound(os.path.join('resource', sounds))
    pg.mixer.Channel(chan).play(pg.mixer.Sound(os.path.join('resource', sounds))
)

t2 = threading.Thread(target=effect, args=('theme.mp3',0,))
t2.start()

while running:

    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

    # ctime = time.time()
    screen.blit(sea,(0,0))
    # pg.draw.rect(screen, "blue",(player_pos,(100,30)) )
    screen.blit(boat, player_pos)
    # txt_time= font.render(f"{ctime} ", True, white)
    txt_score= font.render(f"Score : {score} ", True, white)
    txt_speed = font.render(f"Speed : {speed} ", True, white)
    txt_miss = font.render(f"Misses : {miss}", True, white)
    txt_high= font.render(f"High Score : {high_score}", True, white)
    # screen.blit(txt_time,(10,20))
    screen.blit(txt_score,(10,50))
    screen.blit(txt_speed,(10,80))
    screen.blit(txt_miss,(10,110))
    screen.blit(txt_high,(10,140))

    ball = pg.Vector2(x_pos, y_pos)

    if score >= 80:
        speed = 7
    if score >= 150:
        speed = 10

    if ball.y <= height:
       y_pos +=  speed

    else:

        t1 = threading.Thread(target = effect, args=("nami.mp3",1))
        t1.start()
        t1.join()
        y_pos = 0
        x_pos = random.randint(10, width - 20)
        miss+= 1
        if score > 0:
            score -= 20
        if score < 0:
            score = 0

    if ball.y >= player_pos.y - 50 and \
       ball.y <= player_pos.y and \
       ball.x >= player_pos.x and \
       ball.x <= player_pos.x + 100:
        y_pos = 0
        x_pos = random.randint(10, width - 20)
        t1 = threading.Thread(target = effect, args=("recieve.mp3",2))
        t1.start()
        t1.join()

        if score >= 300:
            score += 20
        elif score >=80 and score < 300:
            score += 15
        else:
            score += 10

    # pg.draw.rect(screen, "yellow", (ball, (5,50)))
    screen.blit(sunny, ball)
    keys = pg.key.get_pressed()

    # TODO: need to implement more function
    # if keys[pg.K_k]:
    #     player_pos.y -= 300 * dt
    # if keys[pg.K_j]:
    #     player_pos.y += 300 * dt
    if (keys[pg.K_h] or keys[pg.K_LEFT]) and player_pos.x >= 0:
        player_pos.x -= 500 * dt

    if (keys[pg.K_l] or keys[pg.K_RIGHT]) and player_pos.x <= (width - 100):
        player_pos.x += 500 * dt

    if score > high_score:
        high_score = score
        with open("highScore.txt", 'w') as f:
            f.write(str(score))

    # if miss >= 10:
    #     running = False
    pg.display.update()
    dt = clock.tick(60) / 1000
pg.quit()


from django.urls import path
from . import api

app_name = 'api'

urlpatterns = [
    #path('apps/', api.app),
    path('apps/<int:pk>/', api.app_details, name='api'),
    path('all/', api.all_apps, name='all_api')
]


import xml.etree.ElementTree as etree

maxdepth = 0

def depth(elem: etree.Element, level: int):
    global maxdepth
    currentDepth = level + 1
    maxdepth = max(maxdepth, currentDepth)
    for child in elem:
        depth(child, currentDepth)

standard_input = """6
<feed xml:lang='en'>
    <title>HackerRank</title>
    <subtitle lang='en'>Programming challenges</subtitle>
    <link rel='alternate' type='text/html' href='http://hackerrank.com/'/>
    <updated>2013-12-25T12:00:00</updated>
</feed>"""

if __name__ == '__main__':
    n = int(input())
    xml = ""
    for i in range(n):
        xml = xml + input() + "\n"
    tree = etree.ElementTree(etree.fromstring(xml))
    depth(tree.getroot(), -1)
    print(maxdepth)


import requests
from flask import Flask
from flask import request
import os
import json

app = Flask(__name__)

## переносим таблицы с телефона локально
def get_remote_table():

   r = requests.post(url = "http://192.168.0.72:8095/?mode=SQLQueryText&query=SELECT * FROM RS_barcodes&params=",   #SELECT name FROM sqlite_master WHERE type='table'
                     headers={'Content-Type': 'Application/json; charset=utf-8'})  #

   if r.status_code == 200:
        r.encoding = 'utf-8'
        #jdata = json.loads(r.text.encode("utf-8"))
        print(r.text)
#get_remote_table()

@app.route('/post', methods=['POST'])
def post():
    path = os.getcwd()

    for filename in request.files:
        file = request.files[filename] #rightscan
        if file:
            file.save(path + '\\'+ filename + '.db')
            print('file uploaded')
    return '200'

@app.route('/unload_log', methods=['POST'])
def unload_log():
    path = os.getcwd()
    data = request.get_json()
    if data:
        with open(os.path.join(path, 'rs_log.json'), 'w', encoding='utf-8') as f:
            json.dump(json.loads(data), f, ensure_ascii=False, indent=2)
            print('file uploaded')
        return '200'

if __name__ == '__main__':
    #ui_global.init()
    app.run(host='0.0.0.0', port=2444, debug=True)


import torch
import os
from glob import glob
import cv2
from torchvision import transforms
import numpy as np
from itertools import chain

class dataset(torch.utils.data.IterableDataset):
    def __init__(self,config,mode='train'):

        self.mode = mode
        self.config = config
        self.basepath = config.basepath

        sequences = glob(os.path.join(self.basepath,"raw/sequences/*"))

        image_2_seqs = {}
        image_3_seqs = {}

        image_2_seqs_test = {}
        image_3_seqs_test = {}
        calibs = {}

        count_train = 0
        count_test = 0

        self.test_seqs = config.test_seqs
        self.train_seqs = config.train_seqs

        for seq in sequences:
            seq_num = seq.split('/')[-1]
            if seq_num in self.test_seqs:

                image_2_seqs_test[seq_num] = sorted(glob(seq + "/image_2/*"))
                image_3_seqs_test[seq_num] = sorted(glob(seq + "/image_3/*"))
                count_test+=len(image_2_seqs_test[seq_num])
                count_test+=len(image_3_seqs_test[seq_num])

            else:
                image_2_seqs[seq_num] = sorted(glob(seq + "/image_2/*"))
                image_3_seqs[seq_num] = sorted(glob(seq + "/image_3/*"))

                count_train+=len(image_2_seqs[seq_num])
                count_train+=len(image_2_seqs[seq_num])

            calibs[seq_num] = os.path.join(self.basepath,"raw","sequences",seq_num,"calib.txt")

        self.image_2_seqs = image_2_seqs
        self.image_3_seqs = image_3_seqs
        self.image_2_seqs_test = image_2_seqs_test
        self.image_3_seqs_test = image_3_seqs_test
        self.count_train = count_train
        self.count_test = count_test
        self.calibs = calibs

    def get_intrinsics(self,filepath,cid=2):

        with open(filepath, 'r') as f:
            C = f.readlines()
        def parseLine(L, shape):
            data = L.split()
            data = np.array(data[1:]).reshape(shape).astype(np.float32)
            return data
        proj_c2p = parseLine(C[cid], shape=(3,4))
        proj_v2c = parseLine(C[-1], shape=(3,4))
        filler = np.array([0, 0, 0, 1]).reshape((1,4))
        proj_v2c = np.concatenate((proj_v2c, filler), axis=0)
        intrinsics = proj_c2p[:3, :3]

        return intrinsics

    def scale_intrinsics(self, mat, sx, sy):
        out = np.copy(mat)
        out[0,0] *= sx
        out[0,2] *= sx
        out[1,1] *= sy
        out[1,2] *= sy
        return out

    def __iter__(self):
        if self.mode == 'train':
            im2_seq = self.image_2_seqs
            im3_seq = self.image_3_seqs
        else:
            im2_seq = self.image_2_seqs_test
            im3_seq = self.image_3_seqs_test

        for img_number in range(0,2):

            if img_number == 0:
                img_num_used = im2_seq
            else:
                img_num_used = im3_seq

            for seq_number_idx, v in img_num_used.items():
                sequence = img_num_used[seq_number_idx]
                for time_stamp_idx in range(1,len(sequence)-len(sequence)%3 -3):
                    img0 = sequence[time_stamp_idx-1]
                    img1 = sequence[time_stamp_idx]
                    img2 = sequence[time_stamp_idx+1]

                    transform = transforms.Compose([
                        transforms.ToPILImage(),
                        transforms.ToTensor(),
                        transforms.Normalize(std=(0.5,),mean=(0.5,))
                        ])

                    img0 = cv2.imread(img0)
                    img1 = cv2.imread(img1)
                    img2 = cv2.imread(img2)

                    h,w,_ = img0.shape

                    zoom_x, zoom_y = self.config.w/w, self.config.h/h

                    intrinsics = self.get_intrinsics(self.calibs[seq_number_idx])
                    intrinsics = self.scale_intrinsics(intrinsics,zoom_x,zoom_y)

                    img0 = transform(cv2.resize(img0, (self.config.w, self.config.h)))
                    img1 = transform(cv2.resize(img1, (self.config.w, self.config.h)))
                    img2 = transform(cv2.resize(img2, (self.config.w, self.config.h)))
                    datum = {"t0":img0, "t1":img1, "t2":img2, "intrinsics":intrinsics}

                    yield datum

    def __len__(self):
        if self.mode == 'train':
            return self.count_train
        else:
            return self.count_test


from django.urls import path

from .views import index, contato, produto, consulta1

urlpatterns = [
    path('', index, name='index'),
    path('contato/', contato, name='contato'),
    path('produto/', produto, name='produto'),
    path('consulta/<int:pk>', consulta1, name='consulta1'),

]


#!/usr/bin/env python
# Code samples for blog post
# http://mikethetechie.com/post/6975966936/controlling-the-environment-cloud-control-apis
#
# Note - I couldn't get this to work. For more info, see http://mikethetechie.com/private/6969971577/tumblr_lng0mzd5bg1qf6p57
import secrets # import user name RACKSPACE_USER and API key RACKSPACE_KEY

from libcloud.storage.types import Provider
from libcloud.storage.providers import get_driver
from pprint import pprint

Driver = get_driver(Provider.CLOUDFILES_UK)
conn2 = Driver(secrets.RACKSPACE_USER, secrets.RACKSPACE_KEY, 'https://lon.auth.api.rackspacecloud.com/v1.0')

containers = conn2.list_containers()
container_objects = conn2.list_container_objects(containers[0])

pprint(containers)
pprint(container_objects)

cont = conn2.create_container('Testlibcloudcontainer')
obj = cont.create_object('t.html')
obj.content_type = 'text/html'

#Finally for some data.
obj.write('
Hello world!')


import pyqrcode
import os
import wx
from tkfilebrowser import askopenfilename
from profile import Profile

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        super(MainWindow, self).__init__()
        self.parent = parent

        self.png = pyqrcode.QRCode
        self.bitmap = wx.StaticBitmap
        self.qrprofile = Profile

        topsizer = wx.BoxSizer(wx.VERTICAL)
        button_sizer = wx.BoxSizer(wx.HORIZONTAL)

        wx.Frame.__init__(self, parent, wx.ID_ANY, title=title, size=(250, 300))
        self.control = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_PROCESS_ENTER)
        self.label = wx.StaticText(self, wx.ID_ANY, style=wx.TE_CENTER)
        self.label.SetBackgroundColour("white")
        self.resetIdList = wx.Button(self, wx.ID_ANY, "ID-Liste zurücksetzen")
        self.loadQR = wx.Button(self, wx.ID_ANY, "QR-Code prüfen")

        topsizer.Add(self.control, 1, wx.ALIGN_CENTER)
        topsizer.Add(self.label, 1, wx.ALIGN_CENTER)
        # StaticText um DateOfPurchase zu zeigen
        button_sizer.Add(self.resetIdList, 0, wx.ALL, 10)
        topsizer.Add(button_sizer, wx.SizerFlags(0).Center())
        self.SetSizerAndFit(topsizer)
        self.CreateStatusBar()

        #  Verknüpfen der Buttons mit Funktionen
        self.Bind(wx.EVT_TEXT_ENTER, self.onEnter, self.control)
        self.Bind(wx.EVT_BUTTON, self.onClickedReset, self.resetIdList)
        self.Bind(wx.EVT_BUTTON, self.onClickedLoadQR, self.loadQR)

        self.Show(True)

    #  Event beim klicken des Laden-Buttons: lade QRCode.png
    def onClickedLoadQR(self, e):
        file_path = askopenfilename(initialdir="C:\\", initialfile="tmp",
                                    filetypes=[("Pictures", "*.png"), ("All Files", "*")])
        print(file_path)
        self.png = wx.Image(file_path, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, self.png, (10, 5),
                                      (self.png.GetWidth(), self.png.GetHeight()))
        self.Update()

    # Event beim klicken des Löschen-Buttons: instanz des Objekts löschen
    def onClickedDelete(self, e):
        del self.qrprofile

    # Event beim klicken des Reset-Buttons: idList.txt zurücksetzen
    def onClickedReset(self, e):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        os.remove(dir_path + '\\idList.txt')
        with open("idList.txt", "w") as reset_list:
            reset_list.write("")

    #  Event beim Drücken der Enter-Taste: Instanz des Objekts profile erzeugen und QRCode generieren und .png erstellen
    def onEnter(self, e):
        name = str(self.control.GetValue())
        self.qrprofile = Profile(name)
        self.png = wx.Image(self.qrprofile.getFileName(), wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, self.png, (10, 5), (150, 150))
        self.bitmap.SetPosition((0, 50))
        self.Update()

def main():
    app = wx.App(False)
    frame = MainWindow(None, "QRCode Ticketautomat")
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()


import json
import re
import urllib.request

from Bot.Plugins.Base import PluginBase

class YouTubePlugin(PluginBase):
    """
    This plugin annotates links to YouTube videos with their title in channel messages. The channel message is modified
    so that plugins that are executed at any later stage receive the annotated message.

    configuration options for config.json:
    "kleest": {
        "yt": {
          "api_key": "XXX"
        }
    }
    """

    YT_REGEX = re.compile(r"(?:https?://|www\.|https?://www\.)youtu(?:be\.(?:com|de)|\.be)/(?:attribution)?(?:"
                          r"([A-Za-z0-9_-]{11})|"
                          r".*?v=([A-Za-z0-9_-]{11})|"
                          r"v/([A-Za-z0-9_-]{11})|"
                          r"watch/([A-Za-z0-9_-]{11}))")
    YT_REQUEST_URI = \
        "https://www.googleapis.com/youtube/v3/videos?key={key}&id={ytid}&part=snippet&fields=items(snippet/title)"
    CONFIG_NAMESPACE = "kleest"

    def __init__(self, bot_instance):
        super().__init__(bot_instance)

        self.api_key = bot_instance.get_user_setting(YouTubePlugin.CONFIG_NAMESPACE + ".yt.api_key")
        if self.api_key is None:
            raise AttributeError(str(self.__class__.__name__), "No API key set")

    def on_channel_text(self, event):
        """!
        @brief Parses YouTube video IDs from a channel text.

        Supports multiple video IDs in one message!

        @param event Teamspeak event
        @return None
        """
        msg = event.args[0]["msg"]
        cid = event.args[0]["cid"]

        matches = re.finditer(YouTubePlugin.YT_REGEX, msg)
        ytids = []
        if matches:
            for match in matches:
                for group in match.groups():
                    if group is not None:
                        ytids.append(group)

        if len(ytids) > 0:
            for ytid in ytids:
                self.received_youtube_link(event, ytid, cid)

    def received_youtube_link(self, event, ytid, cid):
        """!
        @brief Handles a received YouTube video link.

        Detailed steps:
        - Queries YouTube API
        - Sends a text message containing the video's title to the channel
        - Modifies the event's message, so that later plugins received the altered version

        @param event Teamspeak event
        @param ytid YouTube video ID
        @param cid Channel ID
        @return None
        """
        title = self.query_yt_api(ytid)

        self.bot_instance.send_text_to_channel(cid, title)
        event.args[0]["msg"] += " (" + title + ")"

    def query_yt_api(self, ytid):
        """!
        @brief Queries the YouTube API for the video's title.

        @param ytid YouTube video ID
        @return Title as string
        """
        data = urllib.request.urlopen(YouTubePlugin.YT_REQUEST_URI.format(ytid=ytid, key=self.api_key)).read().decode()
        data = json.loads(data)
        title = data["items"][0]["snippet"]["title"]

        return title


#https://codingcompetitions.withgoogle.com/codejam/round/0000000000876ff1/0000000000a4621b

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

filename = "input/input00.txt"
f=open(filename,'r')

# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys

if  "f" in locals():
    sys.stdin = f
else:
    inputA=sys.stdin

# Will work in pypy

from collections import defaultdict,deque
from bisect import bisect_left
def resolve():
    m, = tuple(list(map(lambda x: int(x),input().split())))
    ls2  = list(map(lambda x: int(x),input().split()))
    n, =  tuple(list(map(lambda x: int(x),input().split())))
    ls1 = list(map(lambda x: int(x),input().split()))
    kls= [ls2[0]]
    for i in range(1,m):
        if ls2[i] == kls[-1]:continue
        kls.append(ls2[i])
    m = len(kls)
    lls =[[] for _ in range(2501)]
    for i,a in enumerate(ls1):
        lls[a].append(i)
    st =deque([])
    for a in lls[kls[0]]:
        st.append((0,a,0))
    #print(kls)
    visited ={}
    mx = 10**19
    while st:
        #print(st)
        cost,a,idx = st.popleft()
        if (a,idx) in visited and cost > visited[(a,idx)]:continue
        if idx ==m-1:
            mx = min(mx,cost)
            continue
        b = kls[idx+1]
        bidx = bisect_left(lls[b],a)
        if bidx>0:
            if (lls[b][bidx-1],idx+1) not in visited or visited[(lls[b][bidx-1],idx+1)] > cost + abs(lls[b][bidx-1]-a) :
                st.append((cost + abs(lls[b][bidx-1]-a),lls[b][bidx-1],idx+1))
                visited[(lls[b][bidx-1],idx+1)] =cost + abs(lls[b][bidx-1]-a)
        if bidx < len(lls[b]):
            if (lls[b][bidx],idx +1) not in visited or visited[(lls[b][bidx],idx +1)] >cost +abs(lls[b][bidx]-a):
                st.append((cost +abs(lls[b][bidx]-a),lls[b][bidx],idx +1))
                visited[(lls[b][bidx],idx +1)] =cost +abs(lls[b][bidx]-a)
    return str(mx)

def op(caseidx):
    ret= resolve()
    print("Case #"+str(caseidx+1)+": " + ret)

for i in range(int(input())):
    op(i)


import datetime
import hashlib
import sys
import uuid
from typing import List, Tuple

from api.schemas.internal import (
    Article,
    ImportStockUpdate,
    Product,
    ProductArticle,
    StockUpdate,
)

def _hash_name(value: str) -> str:
    """Helper for hashing product to numeric string"""
    return str(
        int.from_bytes(
            bytes.fromhex(hashlib.md5(value.encode()).hexdigest()[:16]),
            sys.byteorder,
            signed=True,
        )
    )

def get_stock_updates(article_stocks: dict, import_state: List[ImportStockUpdate]):
    """Function preparing StockUpdates for database insertion based on current Article Stocks adn data from import"""
    return [
        StockUpdate(
            value=state["current"] - article_stocks.get(state["article_id"], 0),
            update_id=uuid.uuid4(),
            article_id=state["article_id"],
            created_at=datetime.datetime.now(),
            sale_id=None,
        )
        for state in import_state
    ]

def transform_import_data(
    json_content: dict,
) -> Tuple[List[Article], List[Product], List[ProductArticle], List[ImportStockUpdate]]:
    """Transform incoming data to internal representations."""
    articles = []
    products = []
    stock_updates = []
    products_articles = []

    for item in json_content.get("inventory", []):
        articles.append(Article(article_id=item["article_id"], name=item["name"]))
        stock_updates.append(
            ImportStockUpdate(article_id=item["article_id"], current=item["stock"])
        )

    for product in json_content.get("products", []):
        product_id = _hash_name(product["name"])
        products.append(Product(product_id=product_id, name=product["name"]))
        for article_relation in product["contain_articles"]:
            products_articles.append(
                ProductArticle(
                    product_id=product_id,
                    article_id=article_relation["article_id"],
                    amount=article_relation["amount"],
                )
            )

    return articles, products, products_articles, stock_updates