import torch

from .base import EnergyFunction

class ActivityNeuron(EnergyFunction):
    """
    Activity regularisation at the neuron level to avoid quiescent neurons as in Zenke (2021).
    """
    def __init__(self, lamda=None, nu=None):
        super().__init__()
        self.lamda = lamda
        self.nu = nu

    def forward(self, output, target, meta_model, state):
        if all(key in meta_model.meta_learner for key in ["activity_neuron_lambda", "activity_neuron_nu"]):
            loss = [
                l * torch.relu(nu - torch.sum(s, dim=1))**2
                for s, l, nu in zip(
                    state["spiking"],
                    meta_model.meta_learner["activity_neuron_lambda"],
                    meta_model.meta_learner["activity_neuron_nu"])
            ]
        else:
            loss = [
                self.lamda * torch.relu(self.nu - torch.sum(s, dim=1))**2
                for s in state["spiking"]
            ]

        return torch.mean(torch.cat(loss))

class ActivityPopulation(EnergyFunction):
    """
    Activity regularisation at the population level to limit average activity as in Zenke (2021).
    """
    def __init__(self, l_p=2, lamda=None, nu=None):
        """
        Args:
            l_p: order of regularisation used (usually L1 or L2)
        """
        super().__init__()
        self.l_p = l_p
        self.lamda = lamda
        self.nu = nu

        self.lamda_key = "activity_population_lambda_l{}".format(str(l_p))
        self.nu_key = "activity_population_nu_l{}".format(str(l_p))

    def forward(self, output, target, meta_model, state):
        if all(key in meta_model.meta_learner for key in [self.lamda_key, self.nu_key]):
            loss = [
                l * torch.relu(torch.mean(torch.sum(s, dim=1), dim=1) - nu)**self.l_p
                for s, l, nu in zip(
                    state["spiking"],
                    meta_model.meta_learner[self.lamda_key],
                    meta_model.meta_learner[self.nu_key])
            ]
        else:
            loss = [
                self.lamda * torch.relu(torch.mean(torch.sum(s, dim=1), dim=1) - self.nu)**self.l_p
                for s in state["spiking"]
            ]

        return torch.mean(torch.cat(loss))

class MeanFiringRate(EnergyFunction):
    """
    Activity regularisation at the population level as in Bellec (2018).
    """
    def __init__(self, target, strength):
        super().__init__()
        self.target = target
        self.strength = strength

    def forward(self, output, target, meta_model, state):
        loss = [
            (self.strength * (torch.mean(s) - self.target)**2).view(-1)
            for s in state["spiking"]
        ]

        return torch.mean(torch.cat(loss))

class ElasticRegularizer(EnergyFunction):
    def __init__(self, l2_strength=None):
        super().__init__()
        self.l2_strength = l2_strength

    def forward(self, output, target, meta_model, state):
        if "l2_strength" in meta_model.meta_learner:
            loss = [
                (torch.exp(lamda) * (omega - p)**2).view(-1)
                for p, lamda, omega in zip(
                    meta_model.base_parameters(),
                    meta_model.meta_learner["l2_strength"].parameters(),
                    meta_model.meta_learner["omega"].parameters()
                )
            ]
        else:
            loss = [
                (self.l2_strength * (omega - p)**2).view(-1)
                for p, omega in zip(
                    meta_model.base_parameters(),
                    meta_model.meta_learner["omega"].parameters()
                )
            ]

        return torch.sum(torch.cat(loss))

class L2Regularizer(EnergyFunction):
    def __init__(self, l2=None):
        super().__init__()
        self.l2 = l2

    def forward(self, output, target, meta_model, state):
        if "l2" in meta_model.meta_learner:
            # If hyperparams contain l2 strengths, use them
            loss = [
                (l2 * p**2).view(-1)
                for p, l2 in zip(meta_model.base_parameters(), meta_model.meta_learner["l2"])
            ]
        else:
            # Otherwise use default l2 strength defined upon init
            loss = [
                (self.l2 * p**2).view(-1)
                for p in meta_model.base_parameters()
            ]

        return torch.sum(torch.cat(loss))

class L1Spikes(EnergyFunction):
    """
    L1 loss on total number of spikes.
    """
    def forward(self, output, target, meta_model, state):
        loss = [
            l1 * torch.mean(torch.sum(s, dim=(1, 2)))
            for s, l1 in zip(state["spiking"], meta_model.meta_learner["l1_spike"])
        ]

        return torch.mean(torch.stack(loss))

class L2Spikes(EnergyFunction):
    """
    L2 loss on spikes per neuron.
    """
    def forward(self, output, target, meta_model, state):
        loss = [
            l2 * torch.mean(torch.sum(s, dim=1)**2)
            for s, l2 in zip(state["spiking"], meta_model.meta_learner["l2_spike"].parameters())
        ]

        return torch.mean(torch.stack(loss))


from django.shortcuts import render,get_object_or_404
from webmash.models import Category,AboutUs,Post,PostTags,Writer
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from random import shuffle
from django.http import HttpResponse,JsonResponse
from webmash import serializers

def main(request):
	query=Post.objects.all().order_by('heading')
	main_post=query[:4]
	remaining_post=query
	writer=Writer.objects.all()
	latest=Post.objects.all().order_by('post_date')[:4]
	query2=list(Post.objects.all()[:4])

	shuffle(query2)
	print(query2)
	popular=query2
	aboutus=AboutUs.objects.all()
	tag=PostTags.objects.all().order_by('text')
	catt=Category.objects.all().order_by('text')
	page = request.GET.get('page', 1)
	paginator = Paginator(remaining_post, 1)
	try:
		users = paginator.page(page)
	except PageNotAnInteger:
		users = paginator.page(1)
	except EmptyPage:
		users = paginator.page(paginator.num_pages)
	return render(request,'main.html',{'mainp':main_post,'writer':writer,
		'latest':latest,'popular':popular,'tag':tag,'catt':catt,'cat':users,'a':aboutus})

def category(request):
	query=Category.objects.all().order_by('text').distinct()
	aboutus=AboutUs.objects.all()
	return render(request,'category.html',{'cat':query,'a':aboutus})

def posttags(request):
	query=PostTags.objects.all().order_by('text').distinct()
	aboutus=AboutUs.objects.all()
	return render(request,'posttags.html',{'cat':query,'a':aboutus})

def catdetail(request,arg):
	test=get_object_or_404(Category,text=arg)
	querys=Post.objects.filter(Category__text=arg)
	aboutus=AboutUs.objects.all()
	page = request.GET.get('page', 1)
	paginator = Paginator(querys, 2)
	try:
		users = paginator.page(page)
	except PageNotAnInteger:
		users = paginator.page(1)
	except EmptyPage:
		users = paginator.page(paginator.num_pages)
	return render(request,'category_detail.html',{'cat':users,'a':aboutus,'arg':arg
		})

def api_category_detail(request,cat):
	test=get_object_or_404(Category,id=cat)
	querys=Post.objects.filter(Category__id=cat).prefetch_related('writer')
	return JsonResponse({'category':test.text ,'posts':serializers.NewPostSerializers(querys)})

def api_tagdetail(request,tag):
	test=get_object_or_404(PostTags,id=tag)
	querys=Post.objects.filter(posttags__id=tag).prefetch_related('writer')
	return JsonResponse({'tag':test.text,'posts':serializers.NewPostSerializers(querys)})

def postdetail(request,pkid):
	query=get_object_or_404(Post,id=pkid)
	past=Post.objects.none()
	nextt=Post.objects.none()
	if Post.objects.filter(id=pkid-1).exists():
		past=Post.objects.get(id=pkid-1)
	if Post.objects.filter(id=pkid+1).exists():
		nextt=Post.objects.get(id=pkid+1)
	aboutus=AboutUs.objects.all()
	return render(request,'postdetail.html',{'cat':query,'a':aboutus,'p':past,'n':nextt})

def api_writer(request):
	query=Writer.objects.all()
	res={
	'id':query[0].id,
	'name':query[0].name,
	'bio':query[0].bio,
	'pic':query[0].ProfilePic.url
	}
	return JsonResponse({'writer':res})

def api_mainpost(request,pkid):
	query=get_object_or_404(Post,id=pkid)
	past=Post.objects.none()
	nextt=Post.objects.none()
	pastpost={}
	if Post.objects.filter(id=pkid-1).exists():
		past=Post.objects.get(id=pkid-1)
		pastpost['id']=past.id
		pastpost['headline']=past.heading
	nextpost={}
	if Post.objects.filter(id=pkid+1).exists():
		nextt=Post.objects.get(id=pkid+1)
		nextpost['id']=nextt.id
		nextpost['headline']=nextt.heading
	lol=Post.objects.filter(id=pkid).prefetch_related('posttags','writer')
	return JsonResponse({
		"post":serializers.APIPostSerializer(lol),
		"prev":pastpost,
		"next":nextpost
		})

def tagdetail(request,arg):
	test=get_object_or_404(PostTags,text=arg)
	querys=Post.objects.filter(posttags__text=arg)
	aboutus=AboutUs.objects.all()
	page = request.GET.get('page', 1)
	paginator = Paginator(querys, 4)
	try:
		users = paginator.page(page)
	except PageNotAnInteger:
		users = paginator.page(1)
	except EmptyPage:
		users = paginator.page(paginator.num_pages)
	return render(request,'post_detail.html',{'cat':users,'a':aboutus,'arg':arg
		})

def search(request):
	if request.method=="POST":
		p,c,t=GetSearchResults(request.POST['search_input'])
		return render(request,'search.html',{'p':p,'c':c,'t':t})
	else:
		return HttpResponse("Invalid Action!!!")

def GetSearchResults(query):
	post_result=Post.objects.filter(heading__icontains=query)
	category_result=Category.objects.filter(text__icontains=query)
	tag_result=PostTags.objects.filter(text__icontains=query)
	return post_result,category_result,tag_result

def api_main(request):
	remaining_post=Post.objects.all().order_by('heading')
	page = request.GET.get('page', 1)
	paginator = Paginator(remaining_post, 1)
	try:
		users = paginator.page(page)
	except PageNotAnInteger:
		users = paginator.page(1)
	except EmptyPage:
		users = paginator.page(paginator.num_pages)
	return JsonResponse({
		'main_post':serializers.PostSerializers(users.object_list),
		'pages':paginator.num_pages
		})
def api_categories(request):
	query=Category.objects.all().order_by('text').distinct()
	return JsonResponse({'categories':serializers.CategorySerializer(query)})

def api_posttags(request):
	query=PostTags.objects.all().order_by('text').distinct()
	return JsonResponse({'posttags':serializers.PostTagsSerializer(query)})


# descriptions from https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
from Data_Structures.Entry.Entry import *

class Map():
    def __init__(self, size):
        self.array = [None] * size
        self.size = size
        self.count = 0

    # Associates the specified value with the specified key in this map (optional operation).
    def put(self, key, value):
        hashVal = hash(key) % self.size
        if (self.array[hashVal] == None):
            self.array[hashVal] = Entry(key, value)
        else:
            curr = self.array[hashVal]
            while (curr.next != None):
                if (curr.key == key):
                    oldVal = curr.val
                    curr.val = value
                    return oldVal
                curr = curr.next
            curr.next = Entry(key, value)
        self.count = self.count + 1

    # Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
    def getOrDefault(self, key, defaultVal):
        hashVal = hash(key) % self.size
        if (self.array[hashVal] == None):
            return defaultVal
        else:
            curr = self.array[hashVal]
            while (curr != None):
                if (curr.key == key):
                    return curr.val
                else:
                    curr = curr.next
            return defaultVal

    # Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
    def get(self, key):
        hashVal = hash(key) % self.size
        if (self.array[hashVal] == None):
            return None
        else:
            curr = self.array[hashVal]
            while (curr != None):
                if (curr.key == key):
                    return curr.val
                else:
                    curr = curr.next
            return None

    # Returns true if this map contains a mapping for the specified key.
    def containsKey(self, key):
        hashVal = hash(key) % self.size
        if (self.array[hashVal] == None):
            return False
        else:
            curr = self.array[hashVal]
            while(curr != None):
                if (curr.key == key):
                    return True
                curr = curr.next
        return False

    # Returns true if this map maps one or more keys to the specified value.
    def containsValue(self, value):
        for item in self.array:
            if (item != None):
                curr = item
                while(curr != None):
                    if (curr.val == value):
                        return True
                    curr = curr.next
        return False

    # Removes the mapping for a key from this map if it is present (optional operation).
    def remove(self, key):
        hashVal = hash(key) % self.size

    # Removes all of the mappings from this map (optional operation).
    def clear(self):
        self.array.clear()
        self.array = [None] * self.size

    # Returns true if this map contains no key-value mappings.
    def isEmpty(self):
        return self.count > 0

    def size(self):
        return self.count


from tkinter import *

tk=Tk()
tk.title("Tic Tac Toe")
#for changing alternet X and O
change = True

#for draw condition
check  =0

#for winner at last button click
abc = True

#for printing X winner
def winner():
     messageVar = Message(tk, text='x is winner')
     messageVar.grid(row=5, column=2)

#for printing O is winner
def winner_1():
     messageVar = Message(tk, text='O is winner')
     messageVar.grid(row=5, column=2)

#for checking winner
def tictactoe(buttons):

     global change
     global check
     global abc

     if buttons["text"] == " " and change == True:
         buttons["text"] = "X"
         change = False
         check=check+1

     elif buttons["text"] == " " and change == False:
          buttons["text"] = "O"
          change = True
          check=check+1

     if(button1['text'] == 'X' and button2['text'] == 'X' and button3['text'] == 'X'):
          winner()
          abc = False
     elif(button4['text'] == 'X' and button5['text'] == 'X' and button6['text'] == 'X'):
          winner()
          abc = False

     elif(button7['text'] =='X' and button8['text'] == 'X' and button9['text'] == 'X'):
          winner()
          abc = False

     elif(button1['text'] =='X' and button5['text'] == 'X' and button9['text'] == 'X'):
          winner()
          abc = False

     elif(button3['text'] == 'X' and button5['text'] == 'X' and button7['text'] == 'X'):
          winner()
          abc = False

     elif(button1['text'] == 'X' and button2['text'] == 'X' and button3['text'] == 'X'):
          winner()
          abc = False

     elif(button1['text'] == 'X' and button4['text'] == 'X' and button7['text'] == 'X'):
          winner()
          abc = False

     elif(button2['text'] == 'X' and button5['text'] == 'X' and button8['text'] == 'X'):
          winner()
          abc = False

     elif(button3['text'] == 'X' and button6['text'] == 'X' and button9['text'] == 'X'):
          winner()
          abc = False

     elif(button1['text'] == 'O' and button2['text'] == 'O' and button3['text'] == 'O'or
          button4['text'] == 'O' and button5['text'] == 'O' and button6['text'] == 'O'or
          button7['text'] == 'O' and button8['text'] == 'O' and button9['text'] == 'O'or
          button1['text'] == 'O' and button5['text'] == 'O' and button9['text'] == 'O'or
          button3['text'] == 'O' and button5['text'] == 'O' and button7['text'] == 'O'or
          button1['text'] == 'O' and button2['text'] == 'O' and button3['text'] == 'O'or
          button1['text'] == 'O' and button4['text'] == 'O' and button7['text'] == 'O'or
          button2['text'] == 'O' and button5['text'] == 'O' and button8['text'] == 'O'or
          button3['text'] == 'O' and button6['text'] == 'O' and button9['text'] == 'O'):
          winner_1()
          abc = False

     if (check == 9 and abc):
          messageVar = Message(tk, text='TIE')
          messageVar.grid(row=5, column=2)

if __name__ == "__main__":

     buttons=StringVar()

     button1 = Button(tk,text=" ", fg='black', height=5, width=8,command= lambda:tictactoe(button1))
     button1.grid(row=1, column=0)

     button2 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button2))
     button2.grid(row=1, column=1)

     button3 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button3))
     button3.grid(row=1, column=2)

     button4 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button4))
     button4.grid(row=2,column=0)

     button5 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button5))
     button5.grid(row=2,column=1)

     button6 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button6))
     button6.grid(row=2,column=2)

     button7 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button7))
     button7.grid(row=3,column=0)

     button8 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button8))
     button8.grid(row=3,column=1)

     button9 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button9))
     button9.grid(row=3,column=2)

     tk.mainloop()


"""
These scripts set up three DAGs for collecting, storing and backing up financial market data, including stock data and cryptocurrency data.
The DAG for stock data collection and storage consists of three tasks:

get_stocks: retrieves the symbol of the top 5 stocks accordingly with market performance
get_stock_data: retrieves detailed information of the stocks retrieved in task 1
store_stock_data_in_database: stores the stock data in a database
The DAG for cryptocurrency data collection and storage consists of two tasks:

get_crypto_data: retrieves data for the top 5 cryptocurrencies accordingly with market performance
store_crypto_data_in_database: stores the cryptocurrency data in a database
Both DAGs run at 11 PM, as specified by the schedule_interval parameter. Task dependencies are established such that get_stocks (for the stock data DAG) and get_crypto_data (for the cryptocurrency data DAG) must complete before their respective downstream tasks. Similarly, get_stock_data must complete before store_stock_data for the stock data DAG.

The data_collection_storage_stocks DAG is scheduled to run everyday at 11 PM from Monday to Friday, as specified by the schedule_interval parameter. On the other hand, the data_collection_storage_crypto DAG is scheduled to run everyday at 11 PM, without any day-of-week restrictions.
Task dependencies are established such that get_stocks must complete before get_stock_data, and get_stock_data must complete before store_stock_data. Similarly, get_crypto_data must complete before store_crypto_data.

The third DAG, backup_data, is created for backing up the data from the database to S3 on the last day of every month at 11:59 PM.

The script makes use of PythonOperator to define the tasks, and passes output of one task to the input of the next using op_kwargs and op_args parameters. The get_stocks_data, get_crypto_data and backup_data tasks have no dependencies on any previous tasks.
"""

from airflow.operators.python import PythonOperator
from airflow.models import DAG
from datetime import datetime, timedelta
from data_collection_storage import (
    get_stocks, get_stock_data, store_stock_data,
    get_crypto_data, store_crypto_data, backup_data
)

# Define default arguments for the DAGs
default_args_stocks = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2023, 3, 15),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 0,
}

default_args_cryptos = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2023, 3, 15),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 0,
}

default_args_backup = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2023, 3, 15),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 0,
}

# Create the DAG for stock data collection and storage
dag_stocks = DAG(
    'data_collection_storage_stocks',
    default_args=default_args_stocks,
    schedule_interval='0 23 * * 1-5', # Schedule to run everyday at 11 PM from Monday to Friday
    description='Collect and store stock data' # Add description for the DAG
)

# Create the DAG for cryptocurrency data collection and storage
dag_cryptos = DAG(
    'data_collection_storage_crypto',
    default_args=default_args_cryptos,
    schedule_interval='0 23 * * *', # Schedule to run everyday at 11 PM
    description='Collect and store cryptocurrency data' # Add description for the DAG
)

# Create the DAG for backup
dag_backup = DAG(
    'backup_data',
    default_args=default_args_backup,
    description='Extract and store data from database to S3 monthly',
    schedule_interval='59 23 L * *',  # Run on the last day of every month at 11:59 PM
)

# Define the tasks for stock data collection and storage
get_stocks_task = PythonOperator(
    task_id='get_stocks',
    python_callable=get_stocks,
    dag=dag_stocks,
)

get_stock_data_task = PythonOperator(
    task_id='get_stock_data',
    python_callable=get_stock_data,
    op_kwargs={'symbols': get_stocks_task.output},
    dag=dag_stocks,
)

store_stock_data_task = PythonOperator(
    task_id='store_stock_data',
    python_callable=store_stock_data,
    op_kwargs={'data': get_stock_data_task.output},
    dag=dag_stocks,
)

# Define the tasks for cryptocurrency data collection and storage
get_crypto_data_task = PythonOperator(
    task_id='get_crypto_data',
    python_callable=get_crypto_data,
    dag=dag_cryptos,
)

store_crypto_data_task = PythonOperator(
    task_id='store_crypto_data',
    python_callable=store_crypto_data,
    op_args=[get_crypto_data_task.output],
    dag=dag_cryptos,
)

# Define task for database backup
backup_task = PythonOperator(
    task_id='backup_data',
    python_callable=backup_data,
    op_kwargs={'bucket_name': 'marketdata6498'},  #replace with your bucket name
    dag=dag_backup
)


import os
import sys
import stat
import torch
import numpy as np
from sklearn.metrics import classification_report

def rename(path):
    '''
    outputs of ais_bench end with "_0.txt",
    it would cause outputs files can not match label files,
    rename and remove "_0" could fix it.
    '''
    file_names = os.listdir(path)
    for file_name in file_names:
        if not file_name.endswith('.txt'):
            continue
        idx = file_name.split('_')[0]
        src_path = os.path.join(path, file_name)
        dist_path = os.path.join(path, idx + '.txt')
        os.rename(src_path, dist_path)

def load_output_to_results(path):
    file_names = os.listdir(path)
    results = []
    for file_name in file_names:
        if not file_name.endswith('.txt'):
            continue
        file_name = os.path.join(path, file_name)
        with open(file_name) as f:
            for l in f:
                data = list(map(float, l.strip().split()))
                pred = torch.tensor(data).argmax(axis=-1).cpu().numpy()
                results.append(int(pred))

    return results

def load_labels(path):
    file_names = os.listdir(path)
    labels = []
    for file_name in file_names:
        file_name = os.path.join(path, file_name)
        with open(file_name) as f:
            for l in f:
                data = l.strip()
                labels.append(int(data))

    return labels

if __name__ == '__main__':
    output_path, label_path = sys.argv[1], sys.argv[2]
    rename(output_path)
    preds = load_output_to_results(output_path)
    true_labels = load_labels(label_path)
    eval_result = classification_report(true_labels,
                                        preds,
                                        digits=4)
    print(f'Results: {eval_result}')
    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
    modes = stat.S_IWUSR | stat.S_IRUSR
    with os.fdopen(os.open('result.txt', flags, modes), 'w') as main_f:
        main_f.write(eval_result)


import logging
import os
import shutil
import stat
import tarfile
import re

from concurrent.futures import ProcessPoolExecutor
from sos.utilities import file_is_binary

# python older than 3.8 will hit a pickling error when we go to spawn a new
# process for extraction if this method is a part of the SoSObfuscationArchive
# class. So, the simplest solution is to remove it from the class.
def extract_archive(archive_path, tmpdir):
    archive = tarfile.open(archive_path)
    path = os.path.join(tmpdir, 'cleaner')
    # set extract filter since python 3.12 (see PEP-706 for more)
    # Because python 3.10 and 3.11 raises false alarms as exceptions
    # (see #3330 for examples), we can't use data filter but must
    # fully trust the archive (legacy behaviour)
    archive.extraction_filter = getattr(tarfile, 'fully_trusted_filter',
                                        (lambda member, path: member))
    archive.extractall(path)
    archive.close()
    return os.path.join(path, archive.name.split('/')[-1].split('.tar')[0])

class SoSObfuscationArchive():
    """A representation of an extracted archive or an sos archive build
    directory which is used by SoSCleaner.

    Each archive that needs to be obfuscated is loaded into an instance of this
    class. All report-level operations should be contained within this class.
    """

    file_sub_list = []
    total_sub_count = 0
    removed_file_count = 0
    type_name = 'undetermined'
    description = 'undetermined'
    is_nested = False
    skip_files = []
    prep_files = {}

    def __init__(self, archive_path, tmpdir):
        self.archive_path = archive_path
        self.final_archive_path = self.archive_path
        self.tmpdir = tmpdir
        self.archive_name = self.archive_path.split('/')[-1].split('.tar')[0]
        self.ui_name = self.archive_name
        self.soslog = logging.getLogger('sos')
        self.ui_log = logging.getLogger('sos_ui')
        self.skip_list = self._load_skip_list()
        self.is_extracted = False
        self._load_self()
        self.archive_root = ''
        self.log_info(
            "Loaded %s as type %s"
            % (self.archive_path, self.description)
        )

    @classmethod
    def check_is_type(cls, arc_path):
        """Check if the archive is a well-known type we directly support"""
        return False

    @property
    def is_sos(self):
        return 'sos' in self.__class__.__name__.lower()

    @property
    def is_insights(self):
        return 'insights' in self.type_name

    def _load_self(self):
        if self.is_tarfile:
            self.tarobj = tarfile.open(self.archive_path)

    def get_nested_archives(self):
        """Return a list of ObfuscationArchives that represent additional
        archives found within the target archive. For example, an archive from
        `sos collect` will return a list of ``SoSReportArchive`` objects.

        This should be overridden by individual types of ObfuscationArchive's
        """
        return []

    def get_archive_root(self):
        """Set the root path for the archive that should be prepended to any
        filenames given to methods in this class.
        """
        if self.is_tarfile:
            toplevel = self.tarobj.firstmember
            if toplevel.isdir():
                return toplevel.name
            else:
                return os.sep
        return os.path.abspath(self.archive_path)

    def report_msg(self, msg):
        """Helper to easily format ui messages on a per-report basis"""
        self.ui_log.info("{:<50} {}".format(self.ui_name + ' :', msg))

    def _fmt_log_msg(self, msg):
        return "[cleaner:%s] %s" % (self.archive_name, msg)

    def log_debug(self, msg):
        self.soslog.debug(self._fmt_log_msg(msg))

    def log_info(self, msg):
        self.soslog.info(self._fmt_log_msg(msg))

    def _load_skip_list(self):
        """Provide a list of files and file regexes to skip obfuscation on

        Returns: list of files and file regexes
        """
        return [
            'proc/kallsyms',
            'sosreport-',
            'sys/firmware',
            'sys/fs',
            'sys/kernel/debug',
            'sys/module'
        ]

    @property
    def is_tarfile(self):
        try:
            return tarfile.is_tarfile(self.archive_path)
        except Exception:
            return False

    def remove_file(self, fname):
        """Remove a file from the archive. This is used when cleaner encounters
        a binary file, which we cannot reliably obfuscate.
        """
        full_fname = self.get_file_path(fname)
        # don't call a blank remove() here
        if full_fname:
            self.log_info("Removing binary file '%s' from archive" % fname)
            os.remove(full_fname)
            self.removed_file_count += 1

    def format_file_name(self, fname):
        """Based on the type of archive we're dealing with, do whatever that
        archive requires to a provided **relative** filepath to be able to
        access it within the archive
        """
        if not self.is_extracted:
            if not self.archive_root:
                self.archive_root = self.get_archive_root()
            return os.path.join(self.archive_root, fname)
        else:
            return os.path.join(self.extracted_path, fname)

    def get_file_content(self, fname):
        """Return the content from the specified fname. Particularly useful for
        tarball-type archives so we can retrieve prep file contents prior to
        extracting the entire archive
        """
        if self.is_extracted is False and self.is_tarfile:
            filename = self.format_file_name(fname)
            try:
                return self.tarobj.extractfile(filename).read().decode('utf-8')
            except KeyError:
                self.log_debug(
                    "Unable to retrieve %s: no such file in archive" % fname
                )
                return ''
        else:
            try:
                with open(self.format_file_name(fname), 'r') as to_read:
                    return to_read.read()
            except Exception as err:
                self.log_debug(f"Failed to get contents of {fname}: {err}")
                return ''

    def extract(self, quiet=False):
        if self.is_tarfile:
            if not quiet:
                self.report_msg("Extracting...")
            self.extracted_path = self.extract_self()
            self.is_extracted = True
        else:
            self.extracted_path = self.archive_path
        # if we're running as non-root (e.g. collector), then we can have a
        # situation where a particular path has insufficient permissions for
        # us to rewrite the contents and/or add it to the ending tarfile.
        # Unfortunately our only choice here is to change the permissions
        # that were preserved during report collection
        if os.getuid() != 0:
            self.log_debug('Verifying permissions of archive contents')
            for dirname, dirs, files in os.walk(self.extracted_path):
                try:
                    for _dir in dirs:
                        _dirname = os.path.join(dirname, _dir)
                        _dir_perms = os.stat(_dirname).st_mode
                        os.chmod(_dirname, _dir_perms | stat.S_IRWXU)
                    for filename in files:
                        fname = os.path.join(dirname, filename)
                        # protect against symlink race conditions
                        if not os.path.exists(fname) or os.path.islink(fname):
                            continue
                        if (not os.access(fname, os.R_OK) or not
                                os.access(fname, os.W_OK)):
                            self.log_debug(
                                "Adding owner rw permissions to %s"
                                % fname.split(self.archive_path)[-1]
                            )
                            os.chmod(fname, stat.S_IRUSR | stat.S_IWUSR)
                except Exception as err:
                    self.log_debug("Error while trying to set perms: %s" % err)
        self.log_debug("Extracted path is %s" % self.extracted_path)

    def rename_top_dir(self, new_name):
        """Rename the top-level directory to new_name, which should be an
        obfuscated string that scrubs the hostname from the top-level dir
        which would be named after the unobfuscated sos report
        """
        _path = self.extracted_path.replace(self.archive_name, new_name)
        self.archive_name = new_name
        os.rename(self.extracted_path, _path)
        self.extracted_path = _path

    def get_compression(self):
        """Return the compression type used by the archive, if any. This is
        then used by SoSCleaner to generate a policy-derived compression
        command to repack the archive
        """
        if self.is_tarfile:
            if self.archive_path.endswith('xz'):
                return 'xz'
            return 'gz'
        return None

    def build_tar_file(self, method):
        """Pack the extracted archive as a tarfile to then be re-compressed
        """
        mode = 'w'
        tarpath = self.extracted_path + '-obfuscated.tar'
        compr_args = {}
        if method:
            mode += ":%s" % method
            tarpath += ".%s" % method
            if method == 'xz':
                compr_args = {'preset': 3}
            else:
                compr_args = {'compresslevel': 6}
        self.log_debug("Building tar file %s" % tarpath)
        tar = tarfile.open(tarpath, mode=mode, **compr_args)
        tar.add(self.extracted_path,
                arcname=os.path.split(self.archive_name)[1])
        tar.close()
        return tarpath

    def compress(self, method):
        """Execute the compression command, and set the appropriate final
        archive path for later reference by SoSCleaner on a per-archive basis
        """
        try:
            self.final_archive_path = self.build_tar_file(method)
        except Exception as err:
            self.log_debug("Exception while re-compressing archive: %s" % err)
            raise
        self.log_debug("Compressed to %s" % self.final_archive_path)
        try:
            self.remove_extracted_path()
        except Exception as err:
            self.log_debug("Failed to remove extraction directory: %s" % err)
            self.report_msg('Failed to remove temporary extraction directory')

    def remove_extracted_path(self):
        """After the tarball has been re-compressed, remove the extracted path
        so that we don't take up that duplicate space any longer during
        execution
        """
        def force_delete_file(action, name, exc):
            os.chmod(name, stat.S_IWUSR)
            if os.path.isfile(name):
                os.remove(name)
            else:
                shutil.rmtree(name)
        self.log_debug("Removing %s" % self.extracted_path)
        shutil.rmtree(self.extracted_path, onerror=force_delete_file)

    def extract_self(self):
        """Extract an archive into our tmpdir so that we may inspect it or
        iterate through its contents for obfuscation
        """

        with ProcessPoolExecutor(1) as _pool:
            _path_future = _pool.submit(extract_archive,
                                        self.archive_path, self.tmpdir)
            path = _path_future.result()
            return path

    def get_symlinks(self):
        """Iterator for a list of symlinks in the archive"""
        for dirname, dirs, files in os.walk(self.extracted_path):
            for _dir in dirs:
                _dirpath = os.path.join(dirname, _dir)
                if os.path.islink(_dirpath):
                    yield _dirpath
            for filename in files:
                _fname = os.path.join(dirname, filename)
                if os.path.islink(_fname):
                    yield _fname

    def get_file_list(self):
        """Iterator for a list of files in the archive, to allow clean to
        iterate over.

        Will not include symlinks, as those are handled separately
        """
        for dirname, dirs, files in os.walk(self.extracted_path):
            for filename in files:
                _fname = os.path.join(dirname, filename.lstrip('/'))
                if os.path.islink(_fname):
                    continue
                else:
                    yield _fname

    def get_directory_list(self):
        """Return a list of all directories within the archive"""
        dir_list = []
        for dirname, dirs, files in os.walk(self.extracted_path):
            dir_list.append(dirname)
        return dir_list

    def update_sub_count(self, fname, count):
        """Called when a file has finished being parsed and used to track
        total substitutions made and number of files that had changes made
        """
        self.file_sub_list.append(fname)
        self.total_sub_count += count

    def get_file_path(self, fname):
        """Return the filepath of a specific file within the archive so that
        it may be selectively inspected if it exists
        """
        _path = os.path.join(self.extracted_path, fname.lstrip('/'))
        return _path if os.path.exists(_path) else ''

    def should_skip_file(self, filename):
        """Checks the provided filename against a list of filepaths to not
        perform obfuscation on, as defined in self.skip_list

        Positional arguments:

            :param filename str:        Filename relative to the extracted
                                        archive root
        """

        if (not os.path.isfile(self.get_file_path(filename)) and not
                os.path.islink(self.get_file_path(filename))):
            return True

        for _skip in self.skip_list:
            if filename.startswith(_skip) or re.match(_skip, filename):
                return True
        return False

    def should_remove_file(self, fname):
        """Determine if the file should be removed or not, due to an inability
        to reliably obfuscate that file based on the filename.

        :param fname:       Filename relative to the extracted archive root
        :type fname:        ``str``

        :returns:   ``True`` if the file cannot be reliably obfuscated
        :rtype:     ``bool``
        """
        obvious_removes = [
            r'.*\.gz$',  # TODO: support flat gz/xz extraction
            r'.*\.xz$',
            r'.*\.bzip2$',
            r'.*\.tar\..*',  # TODO: support archive unpacking
            r'.*\.txz$',
            r'.*\.tgz$',
            r'.*\.bin$',
            r'.*\.journal$',
            r'.*\~$'
        ]

        # if the filename matches, it is obvious we can remove them without
        # doing the read test
        for _arc_reg in obvious_removes:
            if re.match(_arc_reg, fname):
                return True

        _full_path = self.get_file_path(fname)
        if os.path.isfile(_full_path):
            return file_is_binary(_full_path)
        # don't fail on dir-level symlinks
        return False

# vim: set et ts=4 sw=4 :


import sys

input = sys.stdin.readline
Q = int(input())
numdict = dict()

for _ in range(Q):
    q = list(input().split())
    if len(q) == 2:
        x = int(q[1])
        if x not in numdict:
            numdict[x] = 1
        else:
            numdict[x] += 1

    elif len(q) == 3:
        x, c = int(q[1]), int(q[2])
        if x in numdict:
            if numdict[x] <= c:
                numdict.pop(x)
            else:
                numdict[x] -= c

    else:
        print(max(numdict)-min(numdict))


import threading
import time
import random

count = 0
class MyThread(threading.Thread):
    def __init__(self, lock, threadName):
        super(MyThread, self).__init__(name=threadName)
        self.lock = lock

    def run(self):
        global count
        self.lock.acquire()#将当前线程锁定 使其他线程无法访问全局变量count
        for i in range(100):
            count = count + 1
            time.sleep(0.3)
            print(self.getName(), count)
        self.lock.release()#线程执行完毕 释放该线程 使其他线程可以继续操作

Lock = threading.Lock()
for i in range(50):
    MyThread(Lock, "MythreadName:" + str(i)).start()


import json
import logging
import os
from typing import Dict, Optional, Iterable

import jsonschema
import yaml

from .artifact import ArtifactDefinition, make_artifact
from .variables import KnowledgeBase
from .definitions import OS_TYPES

LOGGER = logging.getLogger(__name__)

class Registry:

    def __init__(self):
        self.artifacts: Dict[str, ArtifactDefinition] = {}
        self.artifact_schema = None

        self._load_schema()

    def read_folder(self, folder: str, os_filter: Optional[Iterable[str]] = None) -> None:
        """
        Reads all artifact definition files in a local folder and adds them to the registry.
        Search is not recursive
        """
        input_files = [f for f in os.listdir(folder) if f.endswith('.yaml')]
        LOGGER.debug("Reading files from %s: %s", folder, input_files)
        for input_file in input_files:
            self.read_file(os.path.join(folder, input_file), os_filter)

    def read_file(self, file: str, os_filter: Optional[Iterable[str]] = None) -> None:
        """ Reads a single YAML file and adds the contained artifacts to the registry """
        if not os_filter:
            os_filter = OS_TYPES
        with open(file, 'r') as definition_file:
            try:
                artifacts = list(yaml.safe_load_all(definition_file))
            except yaml.YAMLError as err:
                LOGGER.error("Could not load %s: %s", file, err)
                return
        for artifact_dict in artifacts:
            if self.verify_structure(artifact_dict):
                artifact = make_artifact(artifact_dict)
                if artifact:
                    if artifact.supported_os and not any(os_name in os_filter for os_name in artifact.supported_os):
                        continue
                    self.artifacts[artifact.name] = artifact

            else:
                LOGGER.error("Not adding %s due to validation error", artifact_dict.get('name', '!ERR_NO_NAME'))

    def get_knowledge_base(self) -> KnowledgeBase:
        return KnowledgeBase(self.artifacts)

    def verify_structure(self, artifact_dict: dict) -> bool:
        """ Checks if an artifact definition is valid can be parsed into a definition object """
        try:
            jsonschema.validate(artifact_dict, self.artifact_schema)
            return True
        except jsonschema.exceptions.ValidationError as err:
            LOGGER.error("Artifact is not valid: %s", err)
            return False

    def get_artifact(self, title: str) -> Optional[ArtifactDefinition]:
        """ Return the artifact with the supplied name, if present in the registry """
        return self.artifacts.get(title, None)

    def _load_schema(self):
        my_path = os.path.dirname(os.path.realpath(__file__))
        my_schema = os.path.join(my_path, 'artifact_schema.json')
        with open(my_schema, 'r') as schema:
            self.artifact_schema = json.load(schema)


import logging
from ucloud.core import exc
from ucloud.client import Client
import json

logger = logging.getLogger("ucloud")
logger.setLevel(logging.WARN)
import re
import requests
# 从config文件导入public_key 和private_key
from config import *
from loguru import logger

# 不需要备份的DBId
exclude_DBId_list = [
    # "udbv-hfhtjegj",#"backend_1",
    # "udbhhjarfegion",#"backend_data_v1",
    # "udbfs-glblqh0rq",#backend-dev
]

def get_every_preject(public_key, private_key):
    client = Client({
        "public_key": public_key,
        "private_key": private_key,
        "base_url": "https://api.ucloud.cn"
    })

    try:
        resp = client.uaccount().get_project_list({
        })
    except exc.UCloudException as e:
        print(e)

    projects = resp.get("ProjectSet")
    for project in projects:
        project = project.get("ProjectId")
        yield project

def get_udb_id(project_id):
    client = Client({
        "region": "cn-bj2",
        "public_key": public_key,
        "private_key": private_key,
        "project_id": project_id,
        "base_url": "https://api.ucloud.cn"
    })
    try:
        resp = client.udb().describe_udb_instance({
            "ClassType": "SQL",
            "Offset": 0,
            "Limit": 30
        })
    except exc.UCloudException as e:
        print(e)
    else:
        # print(resp)
        DBId_dict_list = resp.get("DataSet")
        for DBId_dict in DBId_dict_list:
            DBId = DBId_dict.get("DBId")
            DBName = DBId_dict.get("Name")
            yield DBId, DBName

def get_udb_BackupId(project_id, DBId):
    client = Client({
        "region": "cn-bj2",
        "public_key": public_key,
        "private_key": private_key,
        "project_id": project_id,
        "base_url": "https://api.ucloud.cn"
    })

    try:
        resp = client.udb().describe_udb_backup({
            "Offset": 0,
            "Limit": 30,
            "DBId": DBId,

        })
    except exc.UCloudException as e:
        print(e)
    else:
        # print(resp)
        BackupId = resp.get("DataSet")[0].get("BackupId")
        # logger.info(BackupId)
        return BackupId

def get_udb_backup_url(ProjectId, DBId, BackupId):
    client = Client({
        "region": "cn-bj2",
        "public_key": public_key,
        "private_key": private_key,
        "project_id": ProjectId,
        "base_url": "https://api.ucloud.cn"
    })

    try:
        resp = client.udb().describe_udb_instance_backup_url({
            "DBId": DBId,
            "BackupId": BackupId,

        })
    except exc.UCloudException as e:
        print(e)
    else:
        # print(resp)
        BackupURL = resp.get("BackupPath")
        InnerBackupPath = resp.get("InnerBackupPath")
        # logger.info(InnerBackupPath)
        # logger.info(BackupURL)
        return InnerBackupPath, BackupURL

if __name__ == '__main__':
    # 获得所有的项目ID
    p_id = get_every_preject(public_key, private_key)
    for project_id in p_id:
        logger.info(project_id)
        # 获得该项目下的所有 DBId和DBName
        DBId_Name_list = get_udb_id(project_id)
        for DBId, DBName in DBId_Name_list:
            if DBId not in exclude_DBId_list:  # 排除本次不需要备份的udb_id
                # 根据DBId获得BackupId
                BackupId = get_udb_BackupId(project_id, DBId)
                # 根据DBId、BackupId得到 backup_url(外网)
                backup_url = get_udb_backup_url(project_id, DBId, BackupId)[0]  # 内网
                # backup_url = get_udb_backup_url(project_id,DBId,BackupId)[1] #外网
                pattern = r'(http|https)://(.*?)/(.*?)/(.*?)\?'
                name_re = re.match(pattern, backup_url)
                # logger.info(name_re)
                filename = path + project_id + "." + DBName + "." + name_re.group(4)
                logger.info(filename)
                r = requests.get(backup_url, stream=True)
                with open(filename, "wb") as f:
                    count = 0
                    for chunk in r.iter_content(chunk_size=102400):  # 1024 bytes
                        if chunk:
                            count += 1
                            print(count)
                            f.write(chunk)
            else:
                logger.warning("该DB在不备份列表中，不需要备份")


number_of_bad_grades = int(input())
task_name = str(input())
grade = int(input())
bad_grades_counter = 0

sum_grades = 0
number_of_tasks = 0
last_task_name = "" \
                 ""
while task_name != "Enough" and bad_grades_counter != number_of_bad_grades:
    if grade <= 4:
        bad_grades_counter += 1
        if bad_grades_counter == number_of_bad_grades:
            break
    sum_grades += grade
    number_of_tasks += 1
    last_task_name = task_name
    task_name = str(input())
    if task_name == "Enough":
        break
    grade = int(input())

if task_name == "Enough":
    average_score = sum_grades / number_of_tasks
    print(f'Average score: {average_score:.2f}')
    print(f'Number of problems: {number_of_tasks}')
    print(f'Last problem: {last_task_name}')
elif bad_grades_counter == number_of_bad_grades:

    print(f'You need a break, {bad_grades_counter} poor grades.')


# python learing
# author:TNT
class Student(object):
    # __init__是一个特殊方法用于在创建对象时进行初始化操作
    # 通过这个方法我们可以为学生对象绑定name和age两个属性
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def study(self,course_name):
        print('%s正在学习%s.' %(self.name,course_name))

    # PEP 8要求标识符的名字用全小写多个单词用下划线连接
    # 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)

    def watch_movie(self):
        if self.age<19:
            print('%s只能看<<熊出没>>.'%self.name)
        else:
            print('%s正在看岛国爱请动作片'%self.name)

def main():
    #创建学生对象并指定姓名和年龄
    stu1 = Student('刘浩峰',28)
    #给对象study发消息
    stu1.study('金品梅')
    # 给对象study发消息
    stu1.watch_movie()
    stu2 = Student('张传龙',17)
    stu2.study('思想品德')
    stu2.watch_movie()

if __name__ == '__main__':
    main()


a = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a)
print(x)
# The sorted() function returns a sorted list of the specified iterable object.
#
# You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)
# SYNTAX
# sorted(iterable, key=key, reverse=reverse)

# L = ["cccc", "b", "dd", "aaa"]
#
# print("Normal sort :", sorted(L))
#
# print("Sort with len :", sorted(L, key=len))


__author__ = 'Michael Maeder'
__date__ = "04.10.2021"
__version__ = "1.1"
__email__ = "michael.maeder@hefr.ch"
__userid__ = "michael.maeder"

import cv2
import numpy as np
import urllib.request

URL = 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/'

def download_image(img_nbr: int, path: str, verbose_print: bool = False):
    """
    Downloads a specific pokemon image in PNG format. The function gets a index number and downloads the corresponding
    image. The PNG-converted image will be written to the given filesystem path

    :argument
        img_nbr         -- the number of the image (1 .. 898)
        path            -- the path where the image will be written to
        verbose_print   -- selector if some debugging information should be printed or not

    :exception
        urllib.error.HTTPError  -- will be raised by the request library. The exception will be forwarded to the caller
    """

    try:
        # creation of the request object with the given URL
        req = urllib.request.Request(URL + '{:03d}'.format(img_nbr) + '.png')
        response = urllib.request.urlopen(req)                          # response contains the raw response data
        raw_image_data = response.read()                                # get the bytes of the image
        image = np.asarray(bytearray(raw_image_data), dtype="uint8")    # convert it to an array of uint8s
        image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED)               # the code the array as an image
        cv2.imwrite(path + "/" + '{:03d}'.format(img_nbr) + ".png", image)  # finally write the PNG to the given path
        if verbose_print:
            print("Saved " + '{:03d}'.format(img_nbr) + ".png")
    except Exception as e:
        print("Error occured for Pokemon " + '{:03d}'.format(img_nbr))
        raise e                                                         # forward the exception to the caller


from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import imutils
import pickle
import cv2
import os
image = cv2.imread("examples/madhavi.jpeg")
print(image)
output = imutils.resize(image,width=400)
print (output)
image = cv2.resize(image, (96, 96))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
print("[INFO] loading network...")
model = load_model("Teeth")
mlb = pickle.loads(open("mlb.pickle", "rb").read())
print("[INFO] classifying image...")
proba = model.predict(image)[0]
idxs = np.argsort(proba)[::-1][:2]
for (i, j) in enumerate(idxs):
	label = "{}: {:.2f}%".format(mlb.classes_[j], proba[j] * 100)
	a= proba[j] * 100
	cv2.putText(output, label, (10, (i * 30) + 25),
		cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow("Output", output)
cv2.waitKey(0)


from math import floor

c = ''
n = 0
while True:
    n += 1
    o = input()
    if o == '=':
        break
    c += o
    if n == 3:
        c = str(floor(eval(c)))
        n = 1
print(eval(c))

백준/Bronze/5613. 계산기 프로그램/계산기 프로그램.py


#!/usr/bin/python

## @file
# Contains class BoundingBoxVisualization.

# import guacamole libraries
import avango
import avango.gua
import avango.script
from avango.script import field_has_changed

# import python libraries
import time

## Initializes a bounding box visualization of an object in the scene.
class BoundingBoxVisualization(avango.script.Script):

  # internal fields
  ## @var sf_node_mat
  # Matrix to represent the WorldTransform of the object to be handled.
  sf_node_mat = avango.gua.SFMatrix4()

  ## @var sf_enable_flag
  # Boolean field indicating if this bounding box visualization is activated.
  sf_enable_flag = avango.SFBool()

  ## Default constructor.
  def __init__(self):
    self.super(BoundingBoxVisualization).__init__()

  ## Custom constructor.
  # @param OBJECT Reference to an InteractiveObject instance to be handled.
  # @param SCENEGRAPH Reference to the scenegraph in which the object is located.
  # @param MATERIAL Material string to be used for the visualization.
  def my_constructor(self, NODE, SCENEGRAPH, MATERIAL):

    self.NODE = NODE

    ## @var SCENEGRAPH
    # Reference to the scenegraph in which the handled object is located.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var bb_thickness
    # Thickness of the bounding box lines in meters.
    self.bb_thickness	= 0.1

    # variables
    ## @var lf_node_mat
    # Last frame matrix of the handled object to detect changes.
    self.lf_node_mat = avango.gua.make_identity_mat()

    ## @var bb
    # The bounding box to be visualized.
    self.bb = None

    # init nodes
    _loader = avango.gua.nodes.TriMeshLoader()

    ## @var edge_group
    # Scenegraph transformation node to group all the bounding box edges.
    self.edge_group = avango.gua.nodes.TransformNode()

    ## @var edge1
    # Geometry node representing the first edge of the visualized bounding box.
    self.edge1 = _loader.create_geometry_from_file("edge1", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge1.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge1)

    ## @var edge2
    # Geometry node representing the second edge of the visualized bounding box.
    self.edge2 = _loader.create_geometry_from_file("edge2", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge2.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge2)

    ## @var edge3
    # Geometry node representing the third edge of the visualized bounding box.
    self.edge3 = _loader.create_geometry_from_file("edge3", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge3.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge3)

    ## @var edge4
    # Geometry node representing the fourth edge of the visualized bounding box.
    self.edge4 = _loader.create_geometry_from_file("edge4", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge4.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge4)

    ## @var edge5
    # Geometry node representing the fifth edge of the visualized bounding box.
    self.edge5 = _loader.create_geometry_from_file("edge5", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge5.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge5)

    ## @var edge6
    # Geometry node representing the sixth edge of the visualized bounding box.
    self.edge6 = _loader.create_geometry_from_file("edge6", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge6.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge6)

    ## @var edge7
    # Geometry node representing the seventh edge of the visualized bounding box.
    self.edge7 = _loader.create_geometry_from_file("edge7", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge7.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge7)

    ## @var edge8
    # Geometry node representing the eighth edge of the visualized bounding box.
    self.edge8 = _loader.create_geometry_from_file("edge8", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge8.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge8)

    ## @var edge9
    # Geometry node representing the nineth edge of the visualized bounding box.
    self.edge9 = _loader.create_geometry_from_file("edge9", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge9.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge9)

    ## @var edge10
    # Geometry node representing the tenth edge of the visualized bounding box.
    self.edge10 = _loader.create_geometry_from_file("edge10", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge10.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge10)

    ## @var edge11
    # Geometry node representing the eleventh edge of the visualized bounding box.
    self.edge11 = _loader.create_geometry_from_file("edge11", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge11.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge11)

    ## @var edge12
    # Geometry node representing the twelveth edge of the visualized bounding box.
    self.edge12 = _loader.create_geometry_from_file("edge12", "data/objects/cube.obj", MATERIAL, avango.gua.LoaderFlags.DEFAULTS)
    self.edge12.ShadowMode.value = avango.gua.ShadowMode.OFF
    self.edge_group.Children.value.append(self.edge12)

    # init field connection
    self.sf_node_mat.connect_from(NODE.WorldTransform)
    self.edge_group.Transform.connect_from(self.sf_node_mat)
    self.calc_bb()

  ## Called whenever sf_node_mat changes.
  @field_has_changed(sf_node_mat)
  def sf_node_mat_changed(self):

    #print "object moved"
    _lf_scale = self.lf_node_mat.get_scale()
    _scale = self.sf_node_mat.value.get_scale()

    '''
    if round(_lf_scale.x,5) != round(_scale.x,5) or round(_lf_scale.y,5) != round(_scale.y,5) or round(_lf_scale.z,5) != round(_scale.z,5): # scale has changed
      #self.update_bb_scale()
      self.calc_bb()
    '''

    self.lf_node_mat = self.sf_node_mat.value

  # functions
  ## Changes the material of the visualized bounding box.
  # @param MATERIAL The material string to be set and used.
  def set_material(self, MATERIAL):

    self.edge1.Material.value = MATERIAL
    self.edge2.Material.value = MATERIAL
    self.edge3.Material.value = MATERIAL
    self.edge4.Material.value = MATERIAL
    self.edge5.Material.value = MATERIAL
    self.edge6.Material.value = MATERIAL
    self.edge7.Material.value = MATERIAL
    self.edge8.Material.value = MATERIAL
    self.edge9.Material.value = MATERIAL
    self.edge10.Material.value = MATERIAL
    self.edge11.Material.value = MATERIAL
    self.edge12.Material.value = MATERIAL

  ## Calculates the bounding box of the current object.
  def calc_bb(self):

    self.SCENEGRAPH.update_cache()

    self.bb = self.NODE.BoundingBox.value
    #print _node.Name.value, len(_node.Children.value), self.bb.Min.value, self.bb.Max.value

    self.update_bb_scale()

  ## Computes and sets the correct transformations for the edges of the visualized bounding box.
  def update_bb_scale(self):

    if self.bb != None:

      _bb_min = avango.gua.make_inverse_mat(self.sf_node_mat.value) * self.bb.Min.value
      _bb_max = avango.gua.make_inverse_mat(self.sf_node_mat.value) * self.bb.Max.value

      _x_min	= _bb_min.x
      _x_max	= _bb_max.x
      _dist_x	= _x_max - _x_min
      _center_x	= _x_min + _dist_x * 0.5

      _y_min	= _bb_min.y
      _y_max	= _bb_max.y
      _dist_y	= _y_max - _y_min
      _center_y	= _y_min + _dist_y * 0.5

      _z_min	= _bb_min.z
      _z_max	= _bb_max.z
      _dist_z	= _z_max - _z_min
      _center_z	= _z_min + _dist_z * 0.5

      _world_mat = self.NODE.WorldTransform.value
      _scale = _world_mat.get_scale()

      # depth edges
      _scale_mat = avango.gua.make_scale_mat(self.bb_thickness/_scale.x, _dist_y + self.bb_thickness/_scale.y, self.bb_thickness/_scale.z)

      self.edge1.Transform.value = avango.gua.make_trans_mat(_x_min, _center_y, _z_min) * _scale_mat

      self.edge2.Transform.value = avango.gua.make_trans_mat(_x_max, _center_y, _z_min) * _scale_mat

      self.edge3.Transform.value = avango.gua.make_trans_mat(_x_min, _center_y, _z_max) * _scale_mat

      self.edge4.Transform.value = avango.gua.make_trans_mat(_x_max, _center_y, _z_max) * _scale_mat

      # width edges
      _scale_mat = avango.gua.make_scale_mat(_dist_x + self.bb_thickness/_scale.x, self.bb_thickness/_scale.y, self.bb_thickness/_scale.z)

      self.edge5.Transform.value = avango.gua.make_trans_mat(_center_x, _y_min, _z_min) * _scale_mat

      self.edge6.Transform.value = avango.gua.make_trans_mat(_center_x, _y_max, _z_min) * _scale_mat

      self.edge7.Transform.value = avango.gua.make_trans_mat(_center_x, _y_min, _z_max) * _scale_mat

      self.edge8.Transform.value = avango.gua.make_trans_mat(_center_x, _y_max, _z_max) * _scale_mat

      # height edges
      _scale_mat = avango.gua.make_scale_mat(self.bb_thickness/_scale.x, self.bb_thickness/_scale.y, _dist_z + self.bb_thickness/_scale.z)

      self.edge9.Transform.value = avango.gua.make_trans_mat(_x_min, _y_min, _center_z) * _scale_mat

      self.edge10.Transform.value = avango.gua.make_trans_mat(_x_min, _y_max, _center_z) * _scale_mat

      self.edge11.Transform.value = avango.gua.make_trans_mat(_x_max, _y_min, _center_z) * _scale_mat

      self.edge12.Transform.value = avango.gua.make_trans_mat(_x_max, _y_max, _center_z) * _scale_mat


import cv2  # cvzone==1.5.6
import os
from pathlib import Path
from ffpyplayer.player import MediaPlayer

def find_the_video(file_name, directory_name):
    files_found = []
    for path, subdirs, files in os.walk(directory_name):
        for name in files:
            if(file_name == name):
                file_path = os.path.join(path, name)
                files_found.append(file_path)
    print(files_found)
    return files_found[0]

video_name = input("Nome do arquivo que quer tocar:\n")
# luciano.mp4

video_directory_guess = input("Diretório que contém o arquivo:\n")
# C:\Workspace\Python\EasyVideoPlayer

video_path = find_the_video(video_name, video_directory_guess)
print(f"Video Path: {video_path}")

# Initialize the path of the image file

video_directory = Path(find_the_video(video_name, video_directory_guess))

# Initialize the parent directory of the image path

new_working_directory = video_directory.parent

# Change the working directory of the script

os.chdir(new_working_directory)

def play_video(video_path):
    video = cv2.VideoCapture(video_path)
    player = MediaPlayer(video_path)
    while True:
        grabbed, frame = video.read()
        audio_frame, val = player.get_frame()
        if not grabbed:
            print("End of video")
            break
        if cv2.waitKey(28) & 0XFF == ord("q"):
            break

        cv2.imshow("Video", frame)

        if val != 'eof' and audio_frame is not None:
            img, t = audio_frame

    video.release()
    cv2.destroyAllWindows()

play_video(video_path)


import numpy as np
from graphviz import Digraph
from typing import List, Optional, Union

class MarkovModel:
    def __init__(self, transition_matrix: Optional[np.ndarray] = None, initial_probabilities: Optional[np.ndarray] = None, states: Optional[List[str]] = None) -> None:
        self.states = states
        self.transition_matrix = transition_matrix
        self.initial_probabilities = initial_probabilities

    @property
    def check_transition_matrix(self) -> None:
        assert np.allclose(np.sum(self.transition_matrix, axis=1), np.ones(len(self.transition_matrix))), "Transition matrix rows should sum to 1"

    @property
    def check_states(self) -> None:
        assert len(self.transition_matrix) == len(self.states), "Transition matrix and states names should have the same length"

    def stationary_distribution(self,  n_steps: Optional[int] = None) -> np.ndarray:
        if self.transition_matrix is None:
            raise ValueError("Transition matrix is not provided")

        if not n_steps:
            eigenvalues, eigenvectors = np.linalg.eig(self.transition_matrix.T)
            index = np.argmin(np.abs(eigenvalues - 1))

            stationary_distribution = np.real(eigenvectors[:, index] / np.sum(eigenvectors[:, index]))

            return stationary_distribution
        else:
            return np.linalg.matrix_power(self.transition_matrix, n_steps)

    def train(self, sequence: List[str]) -> None:
        unique_elems = list(set(sequence))

        n_unique_elems = len(unique_elems)

        self.transition_matrix = np.zeros((n_unique_elems, n_unique_elems))

        for i in range(len(sequence) - 1):
            curr_elem = sequence[i]
            next_elem = sequence[i + 1]
            curr_idx = unique_elems.index(curr_elem)
            next_idx = unique_elems.index(next_elem)
            self.transition_matrix[curr_idx, next_idx] += 1

        self.transition_matrix[np.where(~self.transition_matrix.any(axis=1))[0]] = 1
        self.transition_matrix /= self.transition_matrix.sum(axis=1, keepdims=True)

        self.states = unique_elems

    def sample(self, n_steps: int = 10, current_state: Optional[Union[int, str]] = None, use_names: bool = True) -> List[Union[int, str]]:
        if self.transition_matrix is None:
            raise ValueError("Transition matrix is not provided")

        self.check_transition_matrix

        if not self.states:
            self.states = np.arange(len(self.transition_matrix))

        self.check_states

        if not current_state:
            current_state = np.random.choice(np.arange(len(self.transition_matrix)), p = self.initial_probabilities) #list(self.states.values())
        elif type(current_state) == str:
            current_state = self.states.index(current_state)

        sequence = [current_state]

        for _ in range(n_steps - 1):
            current_state = np.random.choice(np.arange(len(self.transition_matrix)), p=self.transition_matrix[current_state])
            sequence.append(current_state)

        if use_names is not None:
            return [self.states[i] for i in sequence]
        else:
            return sequence

    def render(self, view: bool = True, save_path: str = "markov-chain-viz", file_format: str = "png") -> None:
        dot = Digraph()

        n_states = len(self.states)
        for i in range(n_states):
            dot.node(str(i), label=str(self.states[i]))

        for i in range(n_states):
            for j in range(n_states):
                weight = self.transition_matrix[i, j]
                if weight > 0:
                    dot.edge(str(i), str(j), label=str(weight))

        dot.render(f'{save_path}', format=file_format, view=view)


import argparse
import time
import os
import requests
import json
import xlsxwriter
from requests_toolbelt.multipart.encoder import MultipartEncoder

parser = argparse.ArgumentParser(description='scan through all apks and produce excel output')
parser.add_argument("-p", required=True, type=str, help="Path to the APK folder")
parser.add_argument("-api", required=True, type=str, help="Mobsf API key")
parser.add_argument("-url", required=True, type=str, help="Mobsf URL e.g. localhost:8000")

args = parser.parse_args()
path = args.p
api_key = args.api
mobsf_server = args.url

# compile list of apk paths
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.apk' in file:
            files.append(os.path.join(r, file))

# create excel file
workbook = xlsxwriter.Workbook("output.xlsx")
result_worksheet = workbook.add_worksheet("result")
cell_format = workbook.add_format({"text_wrap": True, "valign": 'vcenter'})

# for every apk path, send to mobsf
row = 0
col = 0
result_worksheet.write(row, col, "filename")
result_worksheet.write(row, col+1, "Permissions")
result_worksheet.write(row, col+2, "Manifest Analysis")
row+=1

for f in files:
	apk_name = f[f.rfind("/")+1:]
	print("Uploading", apk_name)
	multipart_data = MultipartEncoder(fields={'file': (f, open(f, 'rb'), 'application/octet-stream')})
	headers = {"Content-Type": multipart_data.content_type, "Authorization": api_key}
	response = requests.post(mobsf_server + '/api/v1/upload', data=multipart_data, headers=headers)
	resp_dict = json.loads(response.text)
	print("Uploaded", apk_name)

	# scan apk
	print("Scanning", apk_name)
	resp_dict["re_scan"] = 1 # enable rescan of apk
	headers = {'Authorization': api_key}
	response = requests.post(mobsf_server + '/api/v1/scan', data=resp_dict, headers=headers)
	print("Scanned", apk_name)
	scan_dict = json.loads(response.text)

	if "file_name" in scan_dict.keys():
		# if scan passes, write to excel
		result_worksheet.write(row, col, scan_dict["file_name"])

		permissions_output = ""
		for key, val in scan_dict["permissions"].items():
			permissions_output += key + " \n"
			for title, content in val.items():
				permissions_output += title + ": " + content + " \n"
			permissions_output += "\n"
		result_worksheet.write(row, col+1, permissions_output, cell_format)

		manifest_analysis = ""
		for item in scan_dict["manifest_analysis"]:
			manifest_analysis += "name: " + item["name"] + "\n"
			manifest_analysis += "stat: " + item["stat"] + "\n"
			manifest_analysis += "desc: " + item["desc"] + "\n"
			manifest_analysis += "\n"
		result_worksheet.write(row, col+2, manifest_analysis, cell_format)
		result_worksheet.set_row(row, 20+(len(scan_dict["manifest_analysis"])*5))
	else:
		# fail output name and that it failed
		result_worksheet.write(row, col, apk_name)
		result_worksheet.write(row, col+1, "scan failed")

	row += 1
	time.sleep(1) # needed to prevent connection reset by peer

result_worksheet.set_column(col+1, col+1, 40)
result_worksheet.set_column(col+2, col+2, 100)
workbook.close()


from time import time

def Timer(func):
    def Timer_wrapper(*arg, rtrn = True, prnt = False, **args):
        """ Function Timing decorator """
        t0 = time()
        out = func(*arg, **args)
        if prnt == True:
            print( f"{str(func)}: {out}  -- {time()-t0}" )
        if rtrn:
            return out
    return Timer_wrapper

@ Timer
def parse(day,test, *arg, **args):
    """ parse the input """
    f = f"{f'test_{test}_' if test > 0 else ''}input.txt"
    with open(rf"Python Scripts\py39\AoC2020\Day{day}\{f}") as f:
        lines = [ line.strip().split(' ') for line in f.readlines() ]
        lines = [(line[0], int(line[1])) for line in lines]
    return lines

class Console:
    def __init__(self, instructions):
        """ another opp code like thing :S
            holds the instructions and the operations"""
        self.accumulator   = 0
        self.index         = 0
        self.instructions  = instructions
        self.visited = set()
        self.operations = {
            'nop' : self.nop,
            'acc' : self.acc,
            'jmp' : self.jmp
        }
        self.repair = {
            'nop' : 'jmp',
            'jmp' : 'nop'
        }

    def nop(self, n):
        """ increments index """
        self.index       += 1
        return True
    def acc(self, n):
        """ increments index by 1 and accumulator by n"""
        self.index       += 1
        self.accumulator += n
        return True
    def jmp(self,  n):
        """ jumps index by n """
        self.index += n
        return True

    @ Timer
    def part1(self, repair_index = None, **args):
        """ executes instructions till it starts repeating or till it exits.
            Can take a repair_index that will swap instructions at that index acording to self.repair dict
            Then returns tuple: (acc, exit)
            - With acc:  The accumulator
            - with exit: True if exit was normal or False if instruction index repeated """
        self.accumulator = 0
        self.index   = 0
        self.visited = set()
        while self.index not in self. visited and len(self.instructions) > self.index:
            self.visited.add(self.index)
            instr = self.instructions[self.index]
            instr, num = instr
            if self.index == repair_index:
                instr = self.repair[instr]
            self.operations[instr](num)
        return self.accumulator, self.index >= len(self.instructions)

    @ Timer
    def part2(self, inp, **args):
        """ Looks through the instructions till it finds a possibly broken instruction and tells the console to execute (part1 func for now) while 'repairing' said index """
        for i, (instr, _) in enumerate(inp):
            if instr in ['nop', 'jmp']:
                acc, truety = self.part1(repair_index=i)
                if truety:
                    return acc

if __name__ == "__main__":
    t0 = time()
    day = 8; test = 0; prnt = test != 0
    inp = parse(day,test, prnt=prnt)
    console = Console(inp)
    console.part1(prnt=True)
    console.part2(inp, prnt=True)
    print(f"Total time: {time()-t0}")


import zhinst.core
import zhinst.utils
import numpy as np

device = 'dev8416'  # device ID for G14.
daq = zhinst.core.ziDAQServer('localhost', 8004, 6) # Connect to the dataserver
daq.connectDevice(device, '1GbE') # Connect to device

# Generate waveform and marker

LENGTH = 1024
wave_a = np.sin(np.linspace(0, 10*np.pi, LENGTH))*np.exp(np.linspace(0,-5,LENGTH))
wave_b = np.sin(np.linspace(0, 20*np.pi, LENGTH))*np.exp(np.linspace(0,-5,LENGTH))
wave_c = np.sin(np.linspace(0, 30*np.pi, LENGTH))*np.exp(np.linspace(0,-5,LENGTH))
wave_d = np.sin(np.linspace(0, 40*np.pi, LENGTH))*np.exp(np.linspace(0,-5,LENGTH))

marker_a = np.concatenate([ 0b11*np.ones(32), np.zeros(LENGTH-32)]).astype(int)
marker_bc = np.concatenate([0b1111*np.ones(32), np.zeros(LENGTH-32)]).astype(int)

# Convert and send them to the instrument

marker_ab = np.concatenate([0b1111*np.ones(32), np.zeros(LENGTH-32)]).astype(int)
marker_cd = np.concatenate([0b1111*np.ones(32), np.zeros(LENGTH-32)]).astype(int)

wave_raw_ab = zhinst.utils.convert_awg_waveform(wave_a, wave_b, markers=marker_ab)
wave_raw_cd = zhinst.utils.convert_awg_waveform(wave_c, wave_d, markers=marker_cd)

set_cmd = [(f'/{device:s}/awgs/0/waveform/waves/10', wave_raw_ab),
           (f'/{device:s}/awgs/1/waveform/waves/10', wave_raw_cd)]

daq.set(set_cmd)


from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import telegram
import ephem
from datetime import *
import logging
import settings
import re
import operator
import russiancities

cities = list(russiancities.russian_cities)

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
    level=logging.INFO,
    filename='bot.log'
    )

current_question_num = 0

greeting_text = """Добрый день, {}! Я чатбот-астроном. Спросите про планету командой /planet"""

def main():

    updater = Updater(settings.TELEGRAM_API_KEY)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", greet_user))
    dp.add_handler(CommandHandler("planet", find_planet))
    dp.add_handler(CommandHandler("wordcount", word_count))
    dp.add_handler(CommandHandler("calc", calc))

    text_handler = MessageHandler(Filters.text, handle_text)
    dp.add_handler(text_handler)     # без регистрации будет работать,

    dp.add_handler(CommandHandler("calc", calc))

    updater.start_polling()
    updater.idle()

def handle_text(bot, update):

    text = update.message.text.lower()

    command = "когда ближайшее полнолуние после"

    my_date = ""
    if text[0:len(command)] == command:
        my_date = text[len(command)+1:]
        try:
            update.message.reply_text(str(ephem.next_full_moon(my_date)))
        except ValueError:
            update.message.reply_text("Какая-то странная дата: " + my_date)

    # playing cities game
    input_city = update.message.text
    print ("количество городов " + str(len(cities)))
    if input_city in cities:
        # This is our city
        last_letter = input_city[-1]
        for city in cities:
            if city[:1].lower() == last_letter:
                update.message.reply_text(city + ", ваш ход")
                cities.remove(input_city)
                cities.remove(city)
                return

def greet_user(bot, update):
    replay_back_text = greeting_text.format(update.message.chat.first_name)
    logging.info("Bot started")
    update.message.reply_text(replay_back_text)

def find_planet(bot, update):
    planet_name = get_planet_name(update.message.text)
    if planet_name == "":
        logging.info("Wrong format")
        update.message.reply_text('Пример использования команды: "/planet Mars"')
        return
    replay_back_text = get_constellation(planet_name)
    logging.info("Found planet")
    update.message.reply_text(replay_back_text)

def word_count(bot, update):
    text = get_command_text(update.message.text)
    words = re.split("[ .,;@#$%^&*(){}|?~]", text)
    update.message.reply_text(len(words))

def calc(bot, update):
    input_text = get_command_text(update.message.text)

    if input_text.lower() == "/calc":
        calc_keyboard = [['1', '2', '3'],
        ['4', '5', '6'],
        ['7', '8', '9'],
        ['0', '+', '-'],
        ['*', '/', '=']]

        reply_markup = telegram.ReplyKeyboardMarkup(calc_keyboard)
        bot.send_message(chat_id=update.message.chat_id,
            text="Calculator",
            reply_markup=reply_markup)

    # working on text expressions
    command_skolko = "сколько будет"

    text_expression = ""

    if input_text[0:len(command_skolko)].lower() == command_skolko:
        text_expression = input_text[len(command_skolko)+1:]
        expression_dic = {
            "один": "1",
            "два": "2",
            "три": "3",
            "четыре": "4",
            "пять": "5",
            "шесть": "6",
            "семь": "7",
            "восемь": "8",
            "девять": "9",
            "ноль": "0",
            "плюс": "+",
            "минус": "-",
            "умножить": "*",
            "разделить": "/",
            "и": "."
        }
        for i in expression_dic:
            text_expression = text_expression.replace(i, expression_dic[i])
        text_expression = text_expression.replace(" ", "")
        input_text = text_expression + "="

    if input_text[-1] != "=":
        update.message.reply_text("Expression should end with '='")
        return
    text = input_text[0:-1]

    # Split into arithmetical operations
    calc_array = re.split("[\+\-*/]", text)

    if len(calc_array)!=2:
        update.message.reply_text("Expression should look like 2+3=")
        return

    m = re.search("[\+\-*/]", text)
    operation = m.group(0)

    # calculate operation
    operations = {"+": operator.add,
              "-": operator.sub,
              "*": operator.mul,
              "/": operator.truediv
             }

    try:
        result = operations[operation](float(calc_array[0]), float(calc_array[1]))
    except ZeroDivisionError:
        update.message.reply_text("Деление на ноль")
        return
    except ValueError:
        update.message.reply_text("Expression should look like 2+3=")
        return

    update.message.reply_text(input_text + str(result))

def get_planet_name(command):
    command_list = command.split()
    if len(command_list) > 1:
        return command_list[1]
    else:
        return ""

def get_command_text(command):
    i = command.find(" ")+1
    return command[i:]

def get_constellation (planet_name):
    planets = {
    "Mercury": ephem.Mercury,
    "Venus": ephem.Venus,
    "Mars": ephem.Mars,
    "Jupiter": ephem.Jupiter,
    "Saturn": ephem.Saturn,
    "Uranus": ephem.Uranus,
    "Neptune": ephem.Neptune,
    "Pluto": ephem.Pluto,
    "Moon": ephem.Moon,
    }

    if planet_name in planets:
        planet = planets[planet_name](datetime.today())
        return ephem.constellation(planet)[1]
    else:
        return "Такой планеты в нашем космосе нет: " + planet_name

if __name__ == "__main__":
   main()


import torch.nn as nn
# Init NN model
class BasicClassifier(nn.Module):
    def __init__(self,input_dim,output_dim):
        super(BasicClassifier, self).__init__()
        self.input_layer    = nn.Linear(input_dim,128)
        self.hidden_layer1  = nn.Linear(128,64)
        self.output_layer   = nn.Linear(64,output_dim)
        self.relu = nn.ReLU()

    def forward(self,x):
        print(x.shape)
        out =  self.relu(self.input_layer(x))
        out =  self.relu(self.hidden_layer1(out))
        out =  self.output_layer(out)
        return out


import logging
from django.db.models import Q
from app_public.models import Doctor, Patient, Speciality, DoctorGroup, WorkPlace, Location
from app_public.app.Configuration import FILE_HANDLER

logger = logging.getLogger("django")
logger.setLevel(logging.INFO)

def search_doctor_by_name(search_text):
    q_req = Q()
    for word in search_text.split(' '):
        q_req = q_req | Q(user__first_name__icontains=word)
        q_req = q_req | Q(user__last_name__icontains=word)

    users = Doctor.objects.filter(q_req).order_by('user__last_name', 'user__first_name')

    return users

def search_patient_by_name(search_text):
    q_req = Q()
    for word in search_text.split(' '):
        q_req = q_req | Q(user__first_name__icontains=word)
        q_req = q_req | Q(user__last_name__icontains=word)

    users = Patient.objects.filter(q_req).order_by('user__last_name', 'user__first_name')

    return users

def search_doctor_by_distance(longitude, latitude, speciality):
    lon = str(longitude)
    lat = str(latitude)
    formula = "address__longitude - {} + address__latitude - {}".format(lon, lat)
    query = speciality.doctors.extra(select={'distance': formula}).order_by('-distance')
    return None

def search_speciality_by_name(search_text):
    q_req = Q()
    for word in search_text.split(' '):
        q_req = q_req | Q(name__icontains=word)

    query = Speciality.objects.filter(Q(validated=True) & q_req)

    return query

def search_group_by_name(search_text):
    q_req = Q()
    for word in search_text.split(' '):
        q_req = q_req | Q(name__icontains=word)

    query = DoctorGroup.objects.filter(q_req)

    return query


import backtrader as bt

class SmaCross(bt.Strategy):
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30   # period for the slow moving average
    )

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

    def next(self):
        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.buy()  # enter long

        elif self.crossover < 0:  # in the market & cross to the downside
            self.close()  # close long position


import argparse
import sys

import Levenshtein

from . import doc_split, usage, version
from .barcode import all_barcodes, filter_distance, filter_stretches

def make_barcodes(length, max_stretch, min_dist, distance):
    """Make a set of barcodes, filter them for mononucleotide stretches and for
    distances with other barcodes.

    :arg int length: Lenth of the barcodes.
    :arg int max_stretch: Maximum mononucleotide stretch length.
    :arg int min_dist: Minimum distance between the barcodes.
    :arg function distance: Distance function.
    """
    return filter_distance(
        filter_stretches(all_barcodes(length), max_stretch), min_dist)

def test_barcodes(barcodes, min_dist, distance, handle):
    """Test a set of barcodes.

    :arg list barcodes: List of barcodes.
    :arg int min_dist: Minimum distance between the barcodes.
    :arg function distance: Distance function.
    :arg steam handle: Open readable handle to a file.

    :returns int: The number of barcodes that violate the distance constraint.
    """
    good_subset = filter_distance(barcodes, min_dist)
    if handle:
        handle.write('\n'.join(good_subset))
        handle.flush()

    return len(barcodes) - len(good_subset)

def _arg_parser():
    """Command line argument parsing."""
    output_parser = argparse.ArgumentParser(add_help=False)
    output_parser.add_argument(
        'OUTPUT', type=argparse.FileType('w'), help='output file')
    input_parser = argparse.ArgumentParser(add_help=False)
    input_parser.add_argument(
        'INPUT', type=argparse.FileType('r'), help='input file')
    distance_parser = argparse.ArgumentParser(add_help=False)
    distance_parser.add_argument(
        '-d', dest='distance', type=int, default=3,
        help='minimum distance between the barcodes (int default=%(default)s)')
    distance_parser.add_argument(
        '-H', dest='hamming', default=False,
        action='store_true', help='use Hamming distance')

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=usage[0], epilog=usage[1])
    parser.add_argument('-v', action='version', version=version(parser.prog))
    subparsers = parser.add_subparsers(dest='subcommand')
    subparsers.required = True

    parser_make = subparsers.add_parser(
        'make', parents=[output_parser, distance_parser],
        description=doc_split(make_barcodes))
    parser_make.add_argument(
        '-l', dest='length', type=int, default=8,
        help='lenght of the barcodes (int default=%(default)s)')
    parser_make.add_argument(
        '-s', dest='stretch', type=int, default=2,
        help='maximum mononucleotide stretch length (int default=%(default)s)')

    parser_test = subparsers.add_parser(
        'test', parents=[input_parser, distance_parser],
        description=doc_split(test_barcodes))
    parser_test.add_argument(
        '-o', dest='output', type=argparse.FileType('w'),
        help='list of good barcodes')

    return parser

def main():
    """Main entry point."""
    parser = _arg_parser()

    try:
        args = parser.parse_args()
    except IOError as error:
        parser.error(error)

    dfunc = Levenshtein.distance
    if args.hamming:
        dfunc = Levenshtein.hamming

    if args.subcommand == 'make':
        args.OUTPUT.write('\n'.join(
            make_barcodes(args.length, args.stretch, args.distance, dfunc)))
        args.OUTPUT.write('\n')
        args.OUTPUT.flush()

    if args.subcommand == 'test':
        sys.stdout.write(
            '{} barcodes violate the distance contraint.\n'.format(
                test_barcodes(
                    list(map(lambda x: x.strip(), args.INPUT.readlines())),
                    args.distance, dfunc, args.output)))

if __name__ == '__main__':
    main()


### 입력 받기, 초기화 ###
n = int(input())

students = [[0]*5 for _ in range(n*n)] # n0: 학생, n1,n2,n3,n4: 좋아하는 친구들
for i in range(n*n):
    students[i] = list(map(int, input().split()))

attraction = [[-1]*n for _ in range(n)] # 비어있을 경우 -1로 초기화

### 로직 ###
# 1) 인접 칸 중 좋아하는 친구가 가장 많은 위치
# 2) 인접 칸 중 비어있는 칸이 가장 많은 위치
# 3) 행 번호가 작은 위치
# 4) 열 번호가 작은 위치

# attraction[i][j]의 인접한 자리에 대한 계산
def count(i, j, attraction, friends): # i: 행, j: 열
    cnt_friend = 0; cnt_empty = 0
    ### 상
    if 0 <= i-1:
        if attraction[i-1][j]==-1: # 비어있는지
            cnt_empty += 1
        else: # 비어있지 않다면, 그 자리에 좋아하는 친구가 있는지
            if attraction[i-1][j] in friends:
                cnt_friend += 1
    ### 하
    if i+1 <= n-1:
        if attraction[i+1][j]==-1: # 비어있는지
            cnt_empty += 1
        else: # 비어있지 않다면, 그 자리에 좋아하는 친구가 있는지
            if attraction[i+1][j] in friends:
                cnt_friend += 1
    ### 좌
    if 0 <= j-1:
        if attraction[i][j-1]==-1: # 비어있는지
            cnt_empty += 1
        else: # 비어있지 않다면, 그 자리에 좋아하는 친구가 있는지
            if attraction[i][j-1] in friends:
                cnt_friend += 1
    ### 우
    if j+1 <= n-1:
        if attraction[i][j+1]==-1: # 비어있는지
            cnt_empty += 1
        else: # 비어있지 않다면, 그 자리에 좋아하는 친구가 있는지
            if attraction[i][j+1] in friends:
                cnt_friend += 1
    res = (cnt_friend, cnt_empty)
    return res

### main ###
for idx in range(n*n):
    student = students[idx][0] # 탑승할 학생
    friends = students[idx] # 좋아하는 친구들 (n1,n2,n3,n4)

    seats = [] # 후보 자리들
    cnt_friend_max = 0; cnt_empty_max = 0 # 현재까지 나온 cnt의 최대값
    ### 놀이기구 자리를 완전 탐색 ###
    for i in range(0, n):
        for j in range(0, n):
            if attraction[i][j]==-1: # (i, j) 자리가 비어있는지
                # 우선 순위 1,2에 대한 계산
                cnt_friend, cnt_empty = count(i, j, attraction, friends)
                if cnt_friend_max == cnt_friend: # 인접한 친구 수가 기존 max값과 동일
                    if cnt_empty_max == cnt_empty: # 인접한 빈자리 수까지 동일
                        seats.append((i,j))
                    elif cnt_empty_max < cnt_empty: # 빈 자리 수가 기존 max값보다 더 큼
                        seats = [(i,j)]
                        cnt_empty_max = cnt_empty

                if cnt_friend_max < cnt_friend: # 인접한 친구 수가 기존 max값보다 더 큼
                    seats = [(i,j)]
                    cnt_friend_max = cnt_friend
                    cnt_empty_max = cnt_empty

    # 우선순위 1,2가 동일한 자리가 여러개인 경우 우선순위 3,4로 판단
    seats.sort(key=lambda x: (x[0], x[1]))
    r, c = seats[0]
    attraction[r][c] = student

# 학생 목록을 학생 번호순으로 재정렬
students.sort(key=lambda x:x[0])

# 최종 점수
ans = 0

### 정답 계산 ###
for i in range(n):
    for j in range(n):
        ans_student = 0 # 이 학생이 인접하고 있는 좋아하는 친구의 수
        student = attraction[i][j] # 학생
        friends = students[student-1] # 좋아하는 친구들
        ### 상
        if 0 <= i-1:
            if attraction[i-1][j] in friends:
                ans_student += 1
        ### 하
        if i+1 <= n-1:
            if attraction[i+1][j] in friends:
                ans_student += 1
        ### 좌
        if 0 <= j-1:
            if attraction[i][j-1] in friends:
                ans_student += 1
        ### 우
        if j+1 <= n-1:
            if attraction[i][j+1] in friends:
                ans_student += 1
        ### 이 학생에 대한 점수 계산
        score = [0,1,10,100,1000]
        ans += score[ans_student]

print(ans)