from django.shortcuts import redirect, render
from django.urls import reverse
from django.db import transaction

from .models import  *
from .forms import *
from .utils import parse_date_time

def index(request):
    news = News.objects.all()
    context = {
        "news": news
    }
    return render(request,"simpleforms/list.html", context)

def create(request):
    form = NewsForm()

    if request.method=="POST":
        form = NewsForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect(reverse("news-list"))

    context = {
        "form":form
    }

    return render(request,"simpleforms/create.html",context)

def update(request, pk):
    news = News.objects.filter(id=pk)

    if not news.exists():
        return redirect(reverse("news-list"))
    else:
        news = news.first()

    form = NewsForm(instance=news)

    if request.method=="POST":
        news = NewsForm(request.POST, request.FILES, instance = news)
        if news.is_valid():
            news.save()
            return redirect(reverse("news-list"))

    context = {
        "form":form
    }

    return render(request,"simpleforms/update.html", context)

def delete(request, pk):
    try:
        news = News.objects.get(id=pk)
        news.delete()
    except News.DoesNotExist:
        pass
    return redirect(reverse("news-list"))

def home(request):
    filials = Filial.objects.all()
    context = {
        "filials":filials
    }
    return render(request, "simpleforms/home.html", context)

def create_director(request):
    director_form = DirectorForm()
    filial_form = FilialForm()

    if request.method == "POST":
        director_form = DirectorForm(request.POST, request.FILES)
        filial_form = FilialForm(request.POST)

        if director_form.is_valid() and  filial_form.is_valid():
            filial = filial_form.save(commit=False)
            director = director_form.save(commit=False)

            director.filial = filial

            filial.save()
            director.save()

            return redirect(reverse("home"))

    context = {
        "filial_form":filial_form,
        "director_form":director_form
    }
    return render(request, "simpleforms/create_director.html", context)

def update_director(request, pk):
    try:
        filial = Filial.objects.get(id=pk)
    except:
        return redirect(reverse("home"))

    director_form = DirectorForm(instance=filial.director)
    filial_form = FilialForm(instance=filial)

    if request.method=="POST":
        director_form = DirectorForm(request.POST, instance=filial.director)
        filial_form = FilialForm(request.POST,instance=filial)

        if director_form.is_valid() and  filial_form.is_valid():
            filial = filial_form.save(commit=False)
            director = director_form.save(commit=False)

            director.filial = filial

            filial.save()
            director.save()

            return redirect(reverse("home"))

    context = {
        "director_form":director_form,
        "filial_form":filial_form
    }
    return render(request,"simpleforms/update_director.html", context)

def delete_director(request, pk):
    try:
        Filial.objects.get(id=pk).delete()
    except:
        pass
    return redirect(reverse("home"))


def addMultiDict(ddict,val1,val2):
	if val1 not in ddict:
		ddict[val1] = ({ val2 : 1})
	else:
		if val2 not in ddict[val1]:
			ddict[val1].update({ val2 : 1})
		else:
			ddict[val1][val2] += 1
			#ddict[val1].update({val2 : ddict[val1][val2] + 1})
	return ddict

def extendMultiDict(dict1,key1,dict2,key2):
	if key1 not in dict1:
		dict1.update({key1 : dict1[key2]})
	else:
		#dict1 for hero
		for heroid in dict1[key2]:
			if heroid not in dict1[key1]:
				print("---------------------------")
				print(key1)
				print(key2)
				print(heroid)
				print(dict1)
				dict1[key1].update({heroid : dict1[key2][heroid]})
				print(dict1)
				print("---------------------------")
			else:
				#dict1[key1][heroid] += dict1[key2][heroid]
				dict1[key1].update({heroid : dict1[key2][heroid] + 1})
	return dict1


from dataclasses import dataclass
from functools import cached_property
from typing import Protocol, TYPE_CHECKING

from pylatex import Section
from quantities import Quantity, GPa, MPa, ksi

from structure_scripts.aisc.helpers import _member_slenderness_limit
from structure_scripts.shared.latex_helpers import (
    save_single_entry,
    _dataframe_table_columns,
    _process_quantity_entry_config,
)
from structure_scripts.shared.data import extract_input_dataframe
from structure_scripts.shared.report_config import config_dict

class IsotropicMaterial(Protocol):
    modulus_linear: Quantity
    modulus_shear: Quantity
    poisson_ratio: float
    yield_stress: Quantity

    def table(self, filter_names: list[str] = None):
        return extract_input_dataframe(
            obj=self,
            extraction_type=IsotropicMaterial,
            filter_names=filter_names,
        )

    @cached_property
    def data_table_df(self):
        return self.table(filter_names=["poisson_ratio"])

    @cached_property
    def latex(self):
        return MaterialLatex(self)

@dataclass(frozen=True)
class IsotropicMaterialUserDefined(IsotropicMaterial):
    modulus_linear: Quantity
    modulus_shear: Quantity
    poisson_ratio: float
    yield_stress: Quantity
    density: Quantity | None = None

@dataclass
class MaterialLatex:
    material: "IsotropicMaterial"

    def resume(self):
        save_single_entry(content=self.data_table, file_name="shared.tex")

    @cached_property
    def resume_latex(self):
        return Section(title="Material", data=self.data_table_latex)

    @cached_property
    def data_table_latex(self):
        return _dataframe_table_columns(
            df=self.material.data_table_df,
            unit_display="cell",
            include_description=True,
        )

    @cached_property
    def data_table(self):
        return _dataframe_table_columns(
            df=self.material.data_table_df,
            unit_display="cell",
            include_description=True,
        ).dumps()

    @cached_property
    def modulus_linear(self):
        return _process_quantity_entry_config(
            entry=self.material.modulus_linear,
            print_config=config_dict.modulus_linear,
        )

    @cached_property
    def modulus_shear(self):
        return _process_quantity_entry_config(
            entry=self.material.modulus_shear,
            print_config=config_dict.modulus_shear,
        )

    @cached_property
    def yield_stress(self):
        return _process_quantity_entry_config(
            entry=self.material.yield_stress,
            print_config=config_dict.yield_stress,
        )

# Commonly used materials
steel355MPa = IsotropicMaterialUserDefined(
    modulus_linear=200 * GPa,
    modulus_shear=77 * GPa,
    poisson_ratio=0.3,
    yield_stress=355 * MPa,
)

steel250MPa = IsotropicMaterialUserDefined(
    modulus_linear=200 * GPa,
    modulus_shear=77 * GPa,
    poisson_ratio=0.3,
    yield_stress=250 * MPa,
)

steel50ksi = IsotropicMaterialUserDefined(
    modulus_linear=200 * GPa,
    modulus_shear=77 * GPa,
    poisson_ratio=0.3,
    yield_stress=50 * ksi,
)


import sqlite3
import datetime

#now = datetime.datetime.now()
#print('now', now)
#
#nowDatetime = now.strftime('%Y-%m-%d %H:%M:%S')
#print('nowDatetime', nowDatetime)

con = sqlite3.connect('moya.db')
cur = con.cursor()
#insertQuery = """INSERT INTO 'worklog'(date) VALUES(?);"""
#cur.execute(insertQuery,('select datetime ('now', 'localtime')'))
cur.execute("INSERT INTO worklog3 ('number') VALUES('null')")
con.commit()
cur.close()
con.close()


cache = {"start":["","end"], "end":["start",""]}

def remove(a):
    left, right = cache[a]
    cache[left][1] = right
    cache[right][0] = left
def add(a):
    recent = cache["end"][0]
    cache[a] = [recent, "end"]
    cache[recent][1] = a
    cache["end"][0] = a

def solution(cacheSize, cities):

    if not cacheSize:
        return 5*len(cities)

    cacheSize += 2
    ans = 0

    for city in cities:
        city = city.lower()

        if city in cache:
            remove(city)
            add(city)
            ans += 1
        elif len(cache) < cacheSize:
            add(city)
            ans += 5
        else:
            oldest = cache["start"][1]
            remove(oldest)
            cache.pop(oldest)
            add(city)
            ans += 5

    return ans

프로그래머스/캐시.py


import math

eps = 0.1 # задаем точность вычислений
a = 0    # число из которого будет извлекаться корень
xk = xk1 = 0  #промежуточные результаты

while True:
    # ввод и проверка условий
    str_a = input("Введите число, для выхода введите '0':")
    if str_a.startswith('-'):      # если начинается со знака минус
        print("Нельзя извлекать корень из отрицательного числа")
        continue # повторяем запрос ввода
    if not str_a.isdigit():
        print("Нужно ввести положительное целое число!")
        continue
    a = int(str_a)
    if not a : break #если ввели 0 - выходим
    # основной цикл
    xk1 = a / 2 # первое приближение пусть будет половина от а, можно взять любое
    while(math.fabs(xk1 - xk) > eps) :   #пока еще точность не достугнута
        xk = xk1
        xk1 = 0.5 * (xk + a/xk)
    print("Квадратный корень из числа %d равен %g с точностью %g" % (a, round(xk1, 2), eps))


import tensorflow as tf
import cv2
import random, math
import numpy as np
from collections import deque
import util
from gym import  spaces
from copy import copy
import gym
from gym import wrappers
import gym_ple
from PIL import Image
import png

# -- possible network flavor types -----------------------------------
__DEEP_RECURRENT_Q_NETWORK_LSTM = 'deepRecurrentQNetwork'
__DEEP_Q_NETORK = "deepQNetwork"
logs_path = '/home/tf/tensorflow_logs/example'
saved_networks_path = '/home/tf/saved_networks/'
#logs_path = '/tmp/'
#saved_networks_path = '/tmp/'
# -------------------------------------------------------------------

class DDQN():

    def __init__(self,
                 modelType="DDQN",
                 gameEnv=None,
                 agentClass=None,
                 epsilon=1,
                 epsilonDecay=.99,
                 gamma=.99,
                 numTraining=1000,
                 batchSize=32,
                 framePerAction=1,
                 numActions=2,
                 replayMemory=40000,
                 game='flappyBird',
                 learningRate=1e-3,
                 learningDecay=1.0,
                 numStepsBeforeSaveModel=10000,
                 numEpisodesRun=10,
                 mode='cpu',
                 displayGraphics=False,
                 numEpsilonCycle=7,
                 updateTargetNetworkAfterIterations=10000,
                 useRewardClippingMode=False,
                 useRMSOptimizer=False
                 ):

        self.gameEnv = gameEnv
        self.modelType = modelType
        self.epsilon = epsilon  # uses random action or predicted action based on epsilon value
        self.epsilon0 = epsilon
        self.epsilonDecay = epsilonDecay  # decay rate for epsilon
        self.gamma = gamma  # reward factor
        self.numTraining = numTraining  #  number of examples for training
        self.batchSize = batchSize  # number of data points descent
        self.framePerAction = framePerAction
        self.numActions = numActions
        self.game = game
        self.explore = self.numTraining  # frames over which to anneal epsilon
        self.replayMemory = replayMemory  # number of previous steps to store
        self.learningRate = learningRate  # learning rate optimization algorithm(RMS/ADAM etc)
        self.learningDecay = learningDecay
        self.numStepsBeforeSaveModel = numStepsBeforeSaveModel  # save model after these number of steps
        self.numEpisodesRun = numEpisodesRun  # total number of episodes we want to execute
        self.mode = mode
        # self.agent = util.lookup(agentClass, globals())(actionFn=self.getLegalActions)
        self.displayGraphics = displayGraphics
        self.numEpsilonCycle = .5 + numEpsilonCycle  # number of time epsilon will decay to 0 throughout the training cycle
        self.updateTargetNetworkAfterIterations = updateTargetNetworkAfterIterations
        self.debug = False  # will log some extra print statements to standard out
        self.useRewardClippingMode = useRewardClippingMode
        self.useRMSOptimizer=useRMSOptimizer
        print("-------- BASIC MODEL HYPER PARAMS USED TO RUN THE MODEL -------------------")

        print("STARTING DDQN MODEL WITH FOLLOWING PARAMS: \n 1. episilon = ", self.epsilon, \
              " \n 2. epsilonDecay=", self.epsilonDecay, \
              " \n 3. gamma = ", self.gamma, \
              " \n 4. numTraining = ", self.numTraining , \
              " \n 5. batchSize = ", self.batchSize , \
              " \n 6. numActions = ", self.numActions , \
              " \n 7. learningRate = ", self.learningRate , \
              " \n 8. numStepsBeforeSaveModel = ", self.numStepsBeforeSaveModel, \
              " \n 9. numEpisodesRun = ", self.numEpisodesRun, \
              " \n 10. numEpsilonCycle = ", self.numEpsilonCycle , \
              " \n 11. updateTargetNetworkAfterIterations = ", self.updateTargetNetworkAfterIterations,
              " \n 12 . useRewardClippingMode = ", self.useRewardClippingMode,
              " \n 13 . useRMSOptimizer =",self.useRMSOptimizer
              )
        print("----------------------------------------------------------------------------")

    # ------------- OPEN AI RELATED METHODS-------------------------------

    def getAction(self, observation):
        return self.agent.getAction(observation)

    def getLegalActions(self, state=None):
        if isinstance(self.gameEnv.action_space, spaces.discrete.Discrete):
            return tuple(range(self.gameEnv.action_space.n))
        raise Exception('Action type not supported: %s' % type(self.gameEnv.action_space))

    def observeTransition(self, old_obs, action, observation, reward):
        self.agent.observeTransition(old_obs, action, observation, reward)

    def prepareState(self, observation):

        if isinstance(self.gameEnv.observation_space, spaces.discrete.Discrete):
            pass

        elif isinstance(self.gameEnv.observation_space, spaces.box.Box):
            observation = tuple(observation)

        else:
            raise Exception('Observation type not supported: %s' % type(self.gameEnv.observation_space))

        return observation

    # ------------- END OF OPEN AI RELATED METHODS-------------------------------

    def solve_network(self):
        print('start solving network')

    def weight_variable(self, shape):
        initial = tf.truncated_normal(shape, stddev=0.01)
        return tf.Variable(initial)

    def bias_variable(self, shape):
        initial = tf.constant(0.01, shape=shape)
        return tf.Variable(initial)

    def conv2d(self, x, W, stride):
        return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding="SAME")

    def max_pool_2x2(self, x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")

    def updateTargetNetwork(self):
        for targetVariableName in self.targetToSourceVariableNames:
            sourceTensorVariableName = self.targetToSourceVariableNames[targetVariableName]
            sourceWeight = self.sess.run(self.sourceNameToVariableDict[sourceTensorVariableName])
            if len(sourceWeight.shape) == 4 and self.debug :
                print('Source variable :{} value being applied to target {} : \n'.
                      format(sourceTensorVariableName, sourceWeight[0, 0, 0, :]))
            self.sess.run(self.t_w_assign_op[targetVariableName], feed_dict={self.t_w_input[targetVariableName] : sourceWeight})

            if len(sourceWeight.shape) == 4 and self.debug :
                print('Target Variable : {} after update from source weights {} :\n'.
                      format(targetVariableName, self.sess.run(self.targetNameToVariableDict[targetVariableName])[0, 0, 0, :]))

    def createNetwork(self):

        with tf.device('/cpu:0' if self.mode == 'cpu' else '/gpu:0'):

            with tf.variable_scope('prediction') :
                # input layer
                self.inputImageVector = tf.placeholder("float", [None, 80, 80, 4])
                # hidden layers
                h_conv1 = tf.layers.conv2d(self.inputImageVector, 32, 8, 4, activation=tf.nn.relu, use_bias=True, name="CONV1")
                h_conv2 = tf.layers.conv2d(h_conv1, 64, 4, 2, activation=tf.nn.relu, use_bias=True, name="CONV2")
                h_conv3 = tf.layers.conv2d(h_conv2, 64, 3, 1, activation=tf.nn.relu, use_bias=True, name="CONV3")
                flatten = tf.reshape(h_conv3, [-1, 2304])
                # fully connected layers
                h_fc1 = tf.layers.dense(flatten, 512, activation=tf.nn.relu, use_bias=True, name="FC1")
                self.fc_out = tf.layers.dense(h_fc1, 2, activation=None, use_bias=True, name="FC_OUT")
                self.fc_out_action = tf.argmax(self.fc_out, dimension=1)

            with tf.variable_scope('target'):

                self.inputImageVector_target = tf.placeholder("float", [None, 80, 80, 4])
                h_conv1_target = tf.layers.conv2d(self.inputImageVector_target, 32, 8, 4, activation=tf.nn.relu, use_bias=True, name="CONV1_TARGET")
                h_conv2_target = tf.layers.conv2d(h_conv1_target, 64, 4, 2, activation=tf.nn.relu, use_bias=True, name="CONV2_TARGET")
                h_conv3_target = tf.layers.conv2d(h_conv2_target, 64, 3, 1, activation=tf.nn.relu, use_bias=True, name="CONV3_TARGET")
                flatten_target = tf.reshape(h_conv3_target, [-1, 2304])
                # fully connected layers
                h_fc1_target = tf.layers.dense(flatten_target, 512, activation=tf.nn.relu, use_bias=True, name="FC1_TARGET")
                self.fc_out_target = tf.layers.dense(h_fc1_target, 2, activation=None, use_bias=True, name="FC_OUT_TARGET")

                self.target_q_idx = tf.placeholder('int32', [None, None], 'outputs_idx')
                self.target_q_with_idx = tf.gather_nd(self.fc_out_target, self.target_q_idx)

                self.sourceToTargetVariableNames = { 'prediction/CONV1/kernel:0' : 'target/CONV1_TARGET/kernel:0',
                               'prediction/CONV2/kernel:0' : 'target/CONV2_TARGET/kernel:0',
                               'prediction/CONV3/kernel:0' : 'target/CONV3_TARGET/kernel:0',
                               'prediction/FC1/kernel:0'   : 'target/FC1_TARGET/kernel:0' ,
                               'prediction/FC_OUT/kernel:0': 'target/FC_OUT_TARGET/kernel:0'
                            }

                self.targetToSourceVariableNames = {}
                for sourceVariableName, targetVariableName in self.sourceToTargetVariableNames.items():
                    self.targetToSourceVariableNames[targetVariableName] = sourceVariableName

                self.sourceNameToVariableDict = {}
                for sVariable in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='prediction'):
                    if sVariable.name in self.sourceToTargetVariableNames:
                        self.sourceNameToVariableDict[sVariable.name] = sVariable

                self.targetNameToVariableDict = {}
                print(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='target'))
                for tVariable in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='target'):
                    if tVariable.name in self.targetToSourceVariableNames:
                        self.targetNameToVariableDict[tVariable.name] = tVariable

            with tf.variable_scope('optimizer'):

                self.predictedActionScoreVector = tf.placeholder("float", [None, self.numActions])  # min_batch_size * numActions
                self.predictedScore = tf.reduce_sum(tf.multiply(self.fc_out, self.predictedActionScoreVector), axis=1)  # scalar
                self.targetQ = tf.placeholder("float", [None])  # scalar value  --> this will be calculated by the

                if  self.useRewardClippingMode:
                    self.loss = tf.reduce_mean(self.clipped_error(self.targetQ - self.predictedScore))
                else :
                    self.loss = tf.reduce_mean(tf.square(self.targetQ - self.predictedScore))

                tf.summary.scalar("loss", self.loss)  # Create predictedActionScoreVector summary to monitor cost tensor
                tf.summary.scalar("Predicted_Q-Value", tf.reduce_mean(self.predictedScore))
                tf.summary.scalar("Actual_Q-Value", tf.reduce_mean(self.targetQ))
                self.merged_summary_op = tf.summary.merge_all()  # Merge all summaries into predictedActionScoreVector single operation
                if self.useRMSOptimizer:
                    self.optimizer= tf.train.RMSPropOptimizer(self.learningRate).minimize(self.loss)
                else :
                    self.optimizer = tf.train.AdamOptimizer(self.learningRate).minimize(self.loss)  # TODO make this configurable

            with tf.variable_scope('pred_to_target') :

                self.t_w_input = {}
                self.t_w_assign_op = {}
                namePrefix = "variable"
                num = 1
                for targetVariableName in self.targetToSourceVariableNames:
                    self.t_w_input[targetVariableName] = tf.placeholder('float32', self.targetNameToVariableDict[targetVariableName].get_shape().as_list(), name=namePrefix + str(num))
                    self.t_w_assign_op[targetVariableName] = self.targetNameToVariableDict[targetVariableName].assign(self.t_w_input[targetVariableName])
                    num += 1

    ## --- Finished creating model ----------------------------------

    def trainNetwork(self):

        # ----------------- tensor flow related setup -------------------

        saver = tf.train.Saver()  # saving and loading networks .. this will by default save all tensor flow Variables (placeholders)
        self.sess.run(tf.global_variables_initializer())  # initialize session for  tensor flow
        summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())  # op to write logs to Tensor board

        checkpoint = tf.train.get_checkpoint_state(saved_networks_path)  # set up to save and load  networks
        if checkpoint and checkpoint.model_checkpoint_path:
            saver.restore(self.sess, checkpoint.model_checkpoint_path)
            self.updateTargetNetwork()
            print("Successfully loaded:", checkpoint.model_checkpoint_path)
        else:
            print("Could not find old network weights")

        # --------------------------------start training ----------------

        replayMemoryQueue = deque()  # this will store all the event for replay memory
        numIterations = 0  # number of iterations
        avgReward = 0
        updateTargetThresh = 10000
        for episodeNum in range(self.numEpisodesRun + 100):  # TODO : number of episodes can be tuned

            # ---- open-ai game emulator integration  with initial bootstrapping------

            initialColoredObservation = self.gameEnv.reset()
            self.gameEnv.render(close=not self.displayGraphics)
            gameAction = random.choice(self.getLegalActions(initialColoredObservation))  # choose predictedActionScoreVector scalar randomly from predictedActionScoreVector set of legal actions

            initialColoredObservation, _, _, _ = self.gameEnv.step(gameAction)  # pass in scalar action to get output
            imageBackgroundGray = self.convertImageBackgroundToGray(initialColoredObservation)  # do pre-processing on image
            currentLastFourImageFrames = np.stack((imageBackgroundGray, imageBackgroundGray, imageBackgroundGray, imageBackgroundGray), axis=2)

            episode_pos_reward = 0  # count the number of positive rewards received
            done = False
            modelSaved = False

            while not done :

                actionVector = np.zeros([self.numActions])
                action_index = 0

                if random.random() <= self.epsilon:  # we will gradually decrease epsilon as we explore
                    action_index = random.randrange(self.numActions)
                    actionVector[action_index] = 1
                else:
                    yout_t = self.sess.run(self.fc_out, feed_dict={self.inputImageVector: [currentLastFourImageFrames]})  # <-- get action from current state prediction
                    action_index = np.argmax(yout_t)
                    actionVector[action_index] = 1

                nextColoredImageObservation, reward, isEpisodeDone, _ = self.gameEnv.step(action_index)  # <--run the selected action and observe next state and reward

                if reward != 0:  # <-- process reward to be [-1, 0, 1]
                    reward /= math.fabs(reward)

                nextImageBackgroundGray = self.convertImageBackgroundToGray(nextColoredImageObservation)  # <-- do pre-processing on image
                nextImageBackgroundGray = np.reshape(nextImageBackgroundGray, (80, 80, 1))
                nextLastFourImageFrames = np.append(nextImageBackgroundGray, currentLastFourImageFrames[:, :, 0:3], axis=2)  # <-- stack last 4 image frames for next state

                replayMemoryQueue.append((currentLastFourImageFrames, actionVector, reward, nextLastFourImageFrames, 1 if isEpisodeDone else 0))  # <-- store the transition in replayMemoryQueue

                if len(replayMemoryQueue) > self.replayMemory:
                    replayMemoryQueue.popleft()

                done = isEpisodeDone

                if numIterations > self.numTraining:  # <-- only train/optimize if done observing [ if iterations > numTraining threshold -x option]

                    minibatch = random.sample(replayMemoryQueue, self.batchSize)  # min-batch to perform optimization
                    current_state_image_minibatch = [d[0] for d in minibatch]  # get batch of stacked image frames
                    current_action_minibatch = [d[1] for d in minibatch]  # min batch for actions performed on each stacked image frame
                    current_rewards_minibatch = [d[2] for d in minibatch]  # min batch for rewards
                    next_state_image_minibatch = [d[3] for d in minibatch]  # get next batch of stacked image frames

                    targetQ = []
                    if self.useRewardClippingMode :
                        current_rewards_minibatch = np.clip(current_rewards_minibatch, -1, 1)

                    next_state_reward_eval = self.sess.run(self.fc_out_action, feed_dict={self.inputImageVector: next_state_image_minibatch})  # <-- get the next state reward
                    next_state__reward_dqn_eval = self.sess.run(self.target_q_with_idx, feed_dict={  # <----------------------------- Double Q Learning , we don't do max
                                                           self.inputImageVector_target: next_state_image_minibatch,
                                                           self.target_q_idx: [[idx, pred_a] for idx, pred_a in enumerate(next_state_reward_eval)]
                    })
                    batchEpisodeDone = [d[4] for d in minibatch]
                    targetQ = (1. - np.array(batchEpisodeDone)) * self.gamma * next_state__reward_dqn_eval + current_rewards_minibatch
                    _, _, _, summary = self.sess.run([self.optimizer, self.fc_out, self.loss, self.merged_summary_op], feed_dict={  # <-- Do the optimization step
                                              self.targetQ: targetQ,  # and summary nodes
                                              self.predictedActionScoreVector: current_action_minibatch,
                                              self.inputImageVector: current_state_image_minibatch
                                           })
                    summary_writer.add_summary(summary, numIterations - self.numTraining + 1)  #  <-- tensor board stuff

                    # hyperparameter based on paper https://deepmind.com/research/dqn/
                    if numIterations == updateTargetThresh:
                        print('------Updating target network ---------------')
                        self.updateTargetNetwork()
                        updateTargetThresh += int((avgReward+1) * 750 + 9000)

                # update the old values
                currentLastFourImageFrames = nextLastFourImageFrames
                # currentColoredImageObservation = nextColoredImageObservation

                # update numIterations to track how many training or observations sampled
                numIterations += 1

                # save progress every epsilon cycle
                if not modelSaved  and (episodeNum + int(self.numEpisodesRun / self.numEpsilonCycle / 2)) % int(self.numEpisodesRun / self.numEpsilonCycle + 1) == 0:
                    print("****** Saving Model at episode ", episodeNum, " iteration ", numIterations, " epsilon ", self.epsilon, " ******")
                    saver.save(self.sess, saved_networks_path + self.game + '-ddqn', global_step=numIterations)
                    modelSaved = True

                # print info
                state = ""
                if numIterations <= self.numTraining:
                    state = "observe"
                elif numIterations > self.numTraining and numIterations <= self.numTraining + self.explore:
                    state = "explore"
                else:
                    state = "train"

                if reward > 0:
                    episode_pos_reward += 1

            # --------------- End of Episode -----------------------------#
            print("EPISODE", episodeNum, \
                    "/ POSITIVE REWARDS", episode_pos_reward, \
                    "/ STATE", state, \
                    "/ EPSILON", self.epsilon, \
                    "/ Iteration number", numIterations , \
                    "/ RUNNING AVERAGE REWARDS", avgReward)
            avgReward = .99 * avgReward + .01 * episode_pos_reward
            # scale down epsilon as we train ( epsilon oscillating decay formula)
            if state != "observe":
                self.epsilon = self.epsilon0 * np.power(self.epsilonDecay, episodeNum) * \
                (1 + np.cos(2 * np.pi * episodeNum / (self.numEpisodesRun / self.numEpsilonCycle))) / 2 + .001

            if episodeNum > self.numEpisodesRun:
                self.epsilon = 0
        # ---- all done , close game environment ----
        self.gameEnv.close()

    def playGame(self):
        self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))
        self.createNetwork()
        self.trainNetwork()

    def convertImageBackgroundToGray(self, currentImageOutputColored):
        imgGray = cv2.cvtColor(currentImageOutputColored, cv2.COLOR_BGR2GRAY)
        block_size = 3
        imgGaussGray = cv2.adaptiveThreshold(imgGray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
                    cv2.THRESH_BINARY, block_size, 2)
        imgResize = cv2.resize(imgGaussGray, (80, 80))
        imgNormalized = np.divide(imgResize, 255)
        return imgNormalized

    def updateTargetNetworkSlowlyButFrequently(self):
        print('--- This updates the target network to source network ---')

    def clipped_error(self,x):
        return tf.where(tf.abs(x) < 1.0, 0.5 * tf.square(x), tf.abs(x) - 0.5)

    def main(self):
        self.playGame()


# https://atcoder.jp/contests/arc097/tasks/arc097_b

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rank = [0]*(n+1)

    def find(self, x):
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return 0
        elif self.rank[x] > self.rank[y]:
            self.root[x] += self.root[y]
            self.root[y] = x
        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

    def isSame(self, x, y):
        return self.find(x) == self.find(y) or x==y

def solve():
    n, m = map(int, input().split())
    p = list(map(int, input().split()))
    ids = [0] * (n+1)
    for i in range(n):
        ids[p[i]] = i+1
    uf=UnionFind(n)
    for _ in range(m):
        x, y = map(int, input().split())
        uf.unite(x,y)

    print(sum(uf.isSame(i,ids[i])for i in range(1,n+1)))

if __name__=="__main__":
    solve()


# -*- coding: utf-8 -*-
# Author: XuMing <xuming624@qq.com>
# Brief:

from model.nlp import corrector

input_datas = ['少先队员因该为老人让坐',
               '人公智能有希望吗']
model = corrector.Corrector()

for input_data in input_datas:
    check_ret = model.check(input_data)
    print(check_ret)


'''
Functions for model evaluation (loss)
'''
import torch
import torch.nn as nn

class WeightedLikelihood(nn.Module):
    def __init__(self):  # log_codon_freq : np.ndarray):
        super().__init__()

        # self.prior = nn.Embedding( 64, 1)
        # self.prior.weight = nn.Parameter( torch.Tensor( log_codon_freq ),
        #                                  requires_grad=False)

        self.nllloss = nn.NLLLoss(reduction='none')

    def forward(self, logprob_by_codon, obs_codons, weight):
        '''
        logprob_by_codons: tensor of size (batch_size,seq_len,codons)
        obs_codons: tensor of size (batch_size,seq_len)
        '''

        neg_logLs = self.nllloss(logprob_by_codon.transpose(1, -1), obs_codons)  # Should be size ( B, L )
        mask = neg_logLs != 0.0
        loss = torch.sum(weight * neg_logLs) / torch.sum(weight * mask)

        return loss

def calc_accuracy(targets: torch.Tensor,
                  log_probabilities: torch.Tensor) -> float:
    '''
    For a given set of targets and a probability matrix, calculate the accuracy
    '''

    _, max_idx_class = log_probabilities.max(dim=-1)  # [ B, n_classes ] -> [ B ]
    n = targets.flatten().size(0)
    accuracy = torch.sum(max_idx_class == targets).item() / n
    return accuracy


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

# In[1]:

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

def CO2_Prediction(valueco2):

    dataset = pd.read_csv('BackEnd_Code/DataSet/co2-annmean-mlo_csv.csv', parse_dates=['Year'])
    date = dataset["Year"]
    means = dataset.iloc[:, 1].values
    year_ppm=[]
    for i in range(len(date)):
        year_ppm.append(date[i].year)
    dataset = pd.read_csv('BackEnd_Code/DataSet/co2-gr-mlo_csv.csv', parse_dates=['Year'])
    date = dataset["Year"]
    increase = dataset.iloc[:, 1].values
    year_inc=[]
    for i in range(len(date)):
        year_inc.append(date[i].year)
    dataset_2 = pd.read_csv('BackEnd_Code/DataSet/Seasonal_Annual.csv', parse_dates=['YEAR'])
    date_2 = dataset_2["YEAR"]
    annu = dataset_2.iloc[:, 1].values
    year_temp=[]
    for i in range(len(date_2)):
        year_temp.append(date_2[i].year)
    year_temp = np.array(year_temp)
    year_temp = year_temp.reshape(-1, 1)
    X_train,X_test,y_train,y_test= train_test_split(year_temp,annu,test_size=0.1,random_state=10)
    poly_reg = PolynomialFeatures(degree = 3)
    year_temp_poly = poly_reg.fit_transform(year_temp)
    poly_reg.fit(year_temp_poly, annu)
    lin_reg_2 = LinearRegression()
    lin_reg_2.fit(year_temp_poly, annu)
    year = int(valueco2)
    prediction = lin_reg_2.predict(poly_reg.fit_transform([[year]]))

    return prediction

# In[5]:

def O3_Prediction(valueo3):
    dataset = pd.read_csv('BackEnd_Code/DataSet/o3.csv', parse_dates=['Date Local'])
    date = dataset["Date Local"]
    means = dataset.iloc[:, 2].values

    def wrangle(df):
        df["Date Local"]=pd.to_datetime(df["Date Local"])
        df["Month"]=df["Date Local"].dt.month
        df["Year"]=df["Date Local"].dt.year
        df=df.drop("Date Local",axis=1)
        df=df.drop("Month",axis=1)
        df=df[df.Year>=1850]
        df=df.set_index(['Year'])
        df=df.dropna()
        return df

    dataset = wrangle(dataset)

    dataset = dataset.drop(columns=['O3 Units'],axis=1)

    year_temp=[]
    for i in range(len(date)):
        year_temp.append(date[i].year)
    year_temp = np.array(year_temp)
    year_temp = year_temp.reshape(-1, 1)

    X_train,X_test,y_train,y_test= train_test_split(year_temp,means,test_size=0.1,random_state=10)

    poly_reg = PolynomialFeatures(degree = 3)
    year_temp_poly = poly_reg.fit_transform(year_temp)
    poly_reg.fit(year_temp_poly, means)

    lin_reg_2 = LinearRegression()
    lin_reg_2.fit(year_temp_poly, means)

    year = int(valueo3)
    prediction = lin_reg_2.predict(poly_reg.fit_transform([[year]]))
    return prediction

# In[ ]:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Transform plain text to a sort of leet.
The table below is used to perform the translation

plain text | l33t
-----------|------
    ' '    |  ''
    'a'    |  '4'
    'b'    |  '6'
    'c'    | '('
    'e'    | '3'
    'i'    | '!'
    'l'    | '1'
    'o'    | '0'
    's'    | '5'
    't'    | '7'
    'z'    | '2'

"""
__author__ = "Benjamin Sientzoff"
__version__ = "0.1b"
__maintainer__ = "Benjamin Sientzoff (blasterbug)"
__license__ = "GNU GPL V2"

def char2leet( char ) :
    """
    Macth a regular char to a 133t one according to the matching array
    :param char: plain character to convert
    :return: matching leet character
    """
    return {
        ' ' : '',
        'a' : '4',
        'b' : '6',
        'c' : '(',
        'e' : '3',
        'i' : '!',
        'l' : '1',
        'o' : '0',
        's' : '5',
        't' : '7',
        'z' : '2',
    }.get( char , char ) # default case

def leet2char( char ) :
    """
    Macth a leet char to a plain one according to the matching array
    :param char: leet character to convert
    :return: matching plain character
    """
    return {
        '4' : 'a',
        '6' : 'b',
        '(' : 'c',
        '3' : 'e',
        '!' : 'i',
        '1' : 'l',
        '0' : 'o',
        '5' : 's',
        '7' : 't',
        '2' : 'z',
    }.get( char , char ) # default case

def plain2leet( string ) :
    """
    Transform a string to sort of 133t (leet)
    :param string: plain string to convert
    :return: matching leet string
    """
    if len(string) == 1 :
        return char2leet( string )
    else :
        return char2leet( string[0] ) +  plain2leet( string[1:] )

def leet2plain( string ) :
    """
    Transform a leet string to plein text
    :param string: leet string to convert
    :return: matching plain string
    """
    if len(string) == 1 :
        return leet2char( string )
    else :
        return leet2char( string[0] ) +  leet2plain( string[1:] )


from collections import namedtuple

import errno
import fnmatch
import logging
import os
import shutil

from guild import file_util
from guild import run_manifest

log = logging.getLogger("guild")

class MergeError(Exception):
    pass

class StopMerge(Exception):
    """Raised during a merge to indicate the operation stopped early."""
    def __init__(self, target_file, msg=None):
        super().__init__([target_file, msg])
        self.target_file = target_file
        self.msg = msg

RunMerge = namedtuple(
    "RunMerge",
    [
        "run",
        "target_dir",
        "copy_all",
        "skip_sourcecode",
        "skip_deps",
        "exclude",
        "to_copy",
        "to_skip",
    ],
)

CopyFile = namedtuple(
    "MergeFile",
    [
        "file_type",
        "run_path",
        "target_path",
    ],
)
CopyFile.__doc__ = """
Represents a merge file to be copied.

`file_type` is one of:

  s - source code file
  d - project-local dependency source
  o - 'other' file - i.e. a non-source and not a dependency, likely
      generated by the run
"""

SkipFile = namedtuple(
    "SkipFile",
    [
        "file_type",
        "run_path",
        "target_path",
        "reason",
    ],
)
SkipFile.__doc__ = """
Represents a merge file that is skipped rather than copied.

`file_type` is one of:

  s - source code file
  d - project-local dependency source
  o - 'other' file - i.e. a non-source and not a dependency, likely
      generated by the run

`reason` is a code indicating why the file is skipped.

  x   - path matches a user-provided exclude pattern
  s   - user opted to skip source code files
  d   - user opted to skip dependencies
  npd - file is a non-project dependencies (either from a non-project
        location or from a project-local unpacked archive)
  u   - file is unchanged
  ?   - file from manifest is unknown (not a source code file or
        dependency source)
"""

_ManifestEntry = namedtuple(
    "_ManifestEntry",
    [
        "file_type",
        "run_path",
        "file_hash",
        "source",
        "source_subpath",
    ],
)
_ManifestEntry.__doc__ = """
Represents an entry from the run manifest, which is used to record
known files at the time of run init.

Expected values for `file_type` are 's' and 'd' for source code file
and project-local dependency respectively.
"""

def init_run_merge(
    run,
    target_dir,
    copy_all=False,
    skip_sourcecode=False,
    skip_deps=False,
    exclude=None,
    prefer_nonsource=False,
):
    manifest_index = _init_manifest_index(run)
    merge = RunMerge(
        run,
        target_dir,
        copy_all=copy_all,
        skip_sourcecode=skip_sourcecode,
        skip_deps=skip_deps,
        exclude=exclude,
        to_copy=[],
        to_skip=[],
    )
    _apply_run_files_to_merge(run, manifest_index, merge)
    _prune_overlapping_targets(merge, prefer_nonsource)
    return merge

def _init_manifest_index(run):
    """Returns a dict keyed by run path containing _ManifestEntry items."""
    try:
        manifest = run_manifest.manifest_for_run(run.dir)
    except FileNotFoundError as e:
        raise MergeError(f"run manifest does not exist for run {run.id}") from e
    else:
        index = {}
        for manifest_entry in manifest:
            index_entry = _manifest_index_entry(manifest_entry, run)
            if not index_entry:
                continue
            index[index_entry.run_path] = index_entry
        return index

def _manifest_index_entry(entry, run):
    if len(entry) not in (4, 5):
        log.warning("unexpected manfiest entry for run %s: %s", run.id, entry)
        return None
    file_type = entry[0]
    run_path = entry[1]
    file_hash = entry[2]
    source = entry[3]
    source_subpath = entry[4] if len(entry) == 5 else None
    return _ManifestEntry(file_type, run_path, file_hash, source, source_subpath)

def _apply_run_files_to_merge(run, manifest_index, merge):
    for run_path in sorted(_iter_run_files(run)):
        _apply_run_file_to_merge(run_path, manifest_index, merge)

def _iter_run_files(run):
    for path in file_util.find(
        run.dir, followlinks=True, includedirs=True, unsorted=True
    ):
        full_path = os.path.join(run.dir, path)
        if os.path.isfile(full_path):
            yield path

def _apply_run_file_to_merge(run_path, manifest_index, merge):
    normalized_run_path = run_manifest.normalize_path(run_path)
    manifest_entry = manifest_index.get(normalized_run_path)
    if manifest_entry:
        _apply_manifest_entry_to_merge(manifest_entry, merge)
    else:
        _apply_unknown_file_to_merge(normalized_run_path, merge)

def _apply_manifest_entry_to_merge(entry, merge):
    if entry.file_type == "s":
        _apply_sourcecode_entry(entry, merge)
    elif entry.file_type == "d":
        _apply_dep_entry(entry, merge)
    else:
        log.warning(
            "unknown manifest file type '%s' for run file '%s'",
            entry.file_type,
            entry.run_path,
        )
        _skip_unknown_path(entry.run_path, entry.source, entry.file_type, merge)

def _apply_sourcecode_entry(entry, merge):
    if merge.skip_sourcecode:
        _skip_sourcecode_entry(entry.run_path, entry.source, merge)
    elif _is_excluded_path(entry.source, merge):
        _skip_excluded(entry.run_path, entry.source, entry.file_type, merge)
    elif _is_unchanged(entry.run_path, entry.source, merge):
        _skip_unchanged(entry.run_path, entry.source, entry.file_type, merge)
    else:
        _copy_sourcecode_entry(entry, merge)

def _skip_sourcecode_entry(run_path, target_path, merge):
    merge.to_skip.append(SkipFile("s", run_path, target_path, "s"))

def _is_excluded_path(path, merge):
    if not merge.exclude:
        return False
    return any(fnmatch.fnmatch(path, pattern) for pattern in merge.exclude)

def _skip_excluded(run_path, target_path, file_type, merge):
    merge.to_skip.append(SkipFile(file_type, run_path, target_path, "x"))

def _is_unchanged(run_path, target_path, merge):
    """Returns True if a run path is unchanged in the target.

    Returns False if the merge is not configured with a target dir
    (i.e. `merge.target_dir` is None.
    """
    dest = os.path.join(merge.target_dir, target_path)
    if not os.path.isfile(dest):
        return False
    src = os.path.join(merge.run.dir, run_path)
    return not file_util.files_differ(src, dest)

def _skip_unchanged(run_path, target_path, file_type, merge):
    merge.to_skip.append(SkipFile(file_type, run_path, target_path, "u"))

def _copy_sourcecode_entry(entry, merge):
    merge.to_copy.append(CopyFile("s", entry.run_path, entry.source))

def _apply_dep_entry(entry, merge):
    if merge.skip_deps:
        _skip_dep_entry(entry, merge)
    else:
        target_path = _target_path_for_dep_entry(entry)
        if target_path:
            if _is_excluded_path(target_path, merge):
                _skip_excluded(entry.run_path, target_path, entry.file_type, merge)
            elif _is_unchanged(entry.run_path, target_path, merge):
                _skip_unchanged(entry.run_path, target_path, entry.file_type, merge)
            else:
                _copy_dep_entry(entry, target_path, merge)
        else:
            _skip_non_project_dep(entry.run_path, merge)

def _skip_dep_entry(entry, merge):
    merge.to_skip.append(
        SkipFile("d", entry.run_path, _target_path_for_dep_entry(entry), "d")
    )

def _target_path_for_dep_entry(entry):
    if not entry.source_subpath and entry.source.startswith("file:"):
        return entry.source[5:]
    return None

def _copy_dep_entry(entry, project_path, merge):
    merge.to_copy.append(CopyFile("d", entry.run_path, project_path))

def _skip_non_project_dep(path, merge):
    merge.to_skip.append(SkipFile("d", path, None, "npd"))

def _skip_unknown_path(run_path, target_path, file_type, merge):
    merge.to_skip.append(SkipFile(file_type, run_path, target_path, "?"))

def _apply_unknown_file_to_merge(run_path, merge):
    if _is_guildfile(run_path):
        return
    # We don't know anything about the file - assume it corresponds to
    # the path in the project for the purpose of mergine.
    target_path = run_path
    if not merge.copy_all:
        _skip_unknown_path(run_path, target_path, "o", merge)
    elif _is_excluded_path(run_path, merge):
        _skip_excluded(run_path, target_path, "o", merge)
    elif _is_unchanged(run_path, target_path, merge):
        _skip_unchanged(run_path, target_path, "o", merge)
    else:
        _copy_other_path(run_path, target_path, merge)

def _is_guildfile(path):
    return path.startswith(".guild")

def _copy_other_path(run_path, target_path, merge):
    merge.to_copy.append(CopyFile("o", run_path, target_path))

def apply_run_merge(merge, pre_copy=None):
    for cf in _sorted_copy_files(merge.to_copy):
        _apply_copy_file_for_merge(cf, merge, pre_copy)

def _sorted_copy_files(files):
    return sorted(files, key=lambda cf: cf.target_path)

def _apply_copy_file_for_merge(cf, merge, pre_copy):
    src = os.path.join(merge.run.dir, cf.run_path)
    dest = os.path.join(merge.target_dir, cf.target_path)
    _apply_pre_copy(pre_copy, merge, cf, src, dest)
    _copy_file(src, dest)

def _apply_pre_copy(pre_copy, merge, cf, src, dest):
    if not pre_copy:
        return
    pre_copy(merge, cf, src, dest)

def _copy_file(src, dest):
    try:
        _shutil_copy(src, dest)
    except IOError as e:
        if e.errno != errno.ENOENT:
            raise
        os.makedirs(os.path.dirname(dest))
        _shutil_copy(src, dest)

def _shutil_copy(src, dest):
    try:
        shutil.copy(src, dest)
    except shutil.SameFileError:
        pass

def _prune_overlapping_targets(merge, prefer_nonsource=False):
    """Removes merge `to_copy` files with overlapping target paths.

    Overlapping targets may occur because Guild supports two categries
    of files for merge: source code and non-source code. Non-source
    code files include dependencies and generated files.

    `merge.files` may be modified as a result of calling this function.

    By default, the pruning prefers source code files over non-source
    code files. In the default case, when a target path exists both as
    source code and as non-source code, the source code file is
    retained and the non-source code file is pruned.

    To prefer non-source code files over source code files, specify
    `prefer_nonsource=True`.
    """
    source_lookup = {cf.target_path for cf in merge.to_copy if cf.file_type == "s"}
    nonsource_lookup = {cf.target_path for cf in merge.to_copy if cf.file_type != "s"}
    merge.to_copy[:] = [
        cf for cf in merge.to_copy if _keep_for_prune_overlapping(
            cf,
            source_lookup,
            nonsource_lookup,
            prefer_nonsource,
        )
    ]

def _keep_for_prune_overlapping(cf, source_lookup, nonsource_lookup, prefer_nonsource):
    return (
        not (cf.target_path in source_lookup and cf.target_path in nonsource_lookup)
        or (cf.file_type != "s" if prefer_nonsource else cf.file_type == "s")
    )


#!/usr/local/bin/python3
import argparse
import os
import sys
import tempfile

import getpass
import iterfzf
from datetime import datetime, timezone
from pathlib import Path

import git_pki.gpg_wrapper
from git_pki import __version__
from git_pki.custom_types import AddIdentityRequest, KeyChange, ImportRequest, RevokeIdentityRequest, Request
from git_pki.exceptions import Git_PKI_Exception
from git_pki.git_wrapper import Git
from git_pki.utils import file_exists, format_key, mkdir, read_multiline_string, sha1_encode
from git_pki import gpg_wrapper

class KeyChangeListener:
    def __init__(self, gpg):
        self.__gpg = gpg

    def key_added(self, path):
        print(f"A {path}")
        self.__gpg.import_public_key(path)

    def key_updated(self, path):
        print(f"M {path}")
        self.__gpg.import_public_key(path)

    def key_removed(self, path):
        print(f"R {path}")
        fingerprint = self.__gpg.file_key_fingerprint(path)
        self.__gpg.remove_public_key(fingerprint)

class GPKI:
    def __init__(self, home):
        self.__file_gpghome = mkdir(f"{home}/vault/private", 0o700)
        self.__file_repository = mkdir(f"{home}/vault/public")
        self.__review_dir = mkdir(f"{home}/reviews")
        self.__gpg = git_pki.gpg_wrapper.GnuPGHandler(self.__file_gpghome)
        self.__git = Git(self.__file_repository)

        listener = KeyChangeListener(self.__gpg)
        self.__git.update(listener)

    def generate_identity(self, name, email, description, passphrase=None):
        existing_key = self.__gpg.private_key_fingerprint(name)
        if existing_key is not None:
            # If key exists, confirm removal of the private version and move public one to the archive
            response = input(f"Replace existing identity of {existing_key}? [yN] ")
            if response.lower() != "y":
                return
            self.revoke(priv_key_name=existing_key)

        fingerprint = self.__gpg.generate_key(name, email, description, passphrase=passphrase)
        if fingerprint is None:
            return

        key = self.__gpg.export_public_key(fingerprint)
        file = Path(f"{self.__git.identity_dir}/{name}/{fingerprint}")
        self.__export_key(key, Path(file))
        self.__git.push_branch(f"{name}/{fingerprint}", f"Publish key {name}/{fingerprint}")
        print(key)

    def revoke(self, priv_key_name=None):
        if priv_key_name is None:
            available_signatories = map(format_key, self.__gpg.private_keys_list())
            selection = iterfzf.iterfzf(available_signatories, prompt="Select private key to revoke ")
            to_revoke = None if selection is None else selection.split()[0]
            if to_revoke is None:
                return
            priv_key = self.__gpg.get_private_key_by_id(to_revoke)
        else:
            priv_key = self.__gpg.get_private_key_by_id(priv_key_name)

        passphrase = getpass.getpass(f"Specify passphrase for the existing key of [{priv_key.name}]: ")
        self.__gpg.remove_private_key(priv_key.fingerprint, passphrase)
        if input("Invalidate previous public key? [yN]\n").lower() == "y":  # remove this question, it's pointless to have public key when nobody has private key
            self.__gpg.remove_public_key(priv_key.fingerprint)
            ans = input("Specify expiration time in format YYYY-MM-DDTHH:mm:ss or leave empty to take current timestamp.")
            if ans == '':
                revocation_timestamp = datetime.now(timezone.utc)
            else:
                try:
                    revocation_timestamp = datetime.fromisoformat(ans)
                except ValueError:
                    Git_PKI_Exception(f"Unrecognized date: {ans}")
            revocation_timestamp = revocation_timestamp.replace(tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S%z')

            # make RevokeIdentityRequest
            revoke_file = Path(f"{self.__git.identity_dir}/{priv_key.name}/{priv_key.fingerprint}_revoked")
            mkdir(revoke_file.parent)
            with open(revoke_file, 'w') as f:
                f.write(revocation_timestamp)
            self.__git.push_branch(f"{priv_key.name}/{priv_key.fingerprint}_revoked", f"Revoke key {priv_key.name}/{priv_key.fingerprint}")

    def list_signatories(self):
        print("fingerprint                              created-on expires-on\tidentity\temail\tdescription")
        for key in self.__gpg.private_keys_list():
            # TODO (#25): align the text correctly
            print(f"{key}")

    def list_recipients(self):
        print("fingerprint                              created-on expires-on\tidentity\temail\tdescription")
        for key in self.__gpg.public_keys_list():
            # TODO (#25): align the text correctly
            print(f"{key}")

    def encrypt(self, source, target, passphrase=None, select_all_recipients=False):
        if target is not None and os.path.isfile(target):
            if input(f"Target file already exist, do you want to overwrite? [yN] ").lower() != 'y':
                return
        available_recipients = list(map(format_key, self.__gpg.public_keys_list()))
        if select_all_recipients:
            selection = available_recipients
        else:
            selection = iterfzf.iterfzf(available_recipients, prompt="Select recipients (use tab to selected entry): ", multi=True)
            if selection is None:
                return

        recipients = [item.split()[0] for item in selection]

        available_signatories = map(format_key, self.__gpg.private_keys_list())
        selection = iterfzf.iterfzf(available_signatories, prompt="Select signatory or press ctrl+d to not sign ")
        signatory = None if selection is None else selection.split()[0]

        if not passphrase:
            passphrase = getpass.getpass(f"Specify passphrase for [{selection[0]}]: ")

        self.__gpg.encrypt(recipients, signatory, source, target, passphrase)

    def decrypt(self, source, target, passphrase=None, sync=False):
        if sync:
            self.sync()
        if file_exists(target):
            if input(f"Target file already exist, do you want to overwrite? [yN] ").lower() != 'y':
                return

        if source is None:
            data = []
            print("Paste message, then press enter and ctrl+d")
            for line in sys.stdin:
                data.append(line)
            source = "".join(data)
            recipients = self.__gpg.get_recipients_from_message(source)
        elif os.path.isfile(source):
            with open(source, 'rb') as src_file:
                recipients = self.__gpg.get_recipients_from_file(src_file)
        else:
            print(f"Specified source file: {source} was not found, aborting.")
            return

        # Check if we have at least one private key to decrypt message
        priv_key = None
        for rec in recipients[::-1]:
            priv_key = self.__gpg.get_private_key_by_id(rec)
            if priv_key is not None:
                break

        if priv_key is None:
            raise Git_PKI_Exception("Could not find private key to decrypt message. Are you correct recipient?")
        if passphrase is None:
            passphrase = getpass.getpass(f"Specify passphrase for {priv_key.name}: ")

        self.verify_message(source, passphrase, sync)
        self.__gpg.decrypt(source, target, passphrase)

    def verify_message(self, message, passphrase, synced):
        valid_key_list = []
        revoked_key_list = []
        signature_verification = self.__gpg.verify_signature(message, passphrase)
        for signature in signature_verification:
            key = self.__gpg.get_public_key_by_id(signature.signatory_fingerprint)
            if key is None:
                if synced:
                    raise Git_PKI_Exception("Could not verify message: signatory from outside organisation.")
                else:
                    self.sync()
                    key = self.__gpg.get_public_key_by_id(signature.signatory_fingerprint)
                    if key is None:
                        raise Git_PKI_Exception("Could not verify message: signatory from outside organisation.")

            if self.is_key_revoked(key) and self.get_revocation_time(key) < datetime.fromtimestamp(float(signature.timestamp), tz=timezone.utc):
                revoked_key_list.append(key)
            else:
                valid_key_list.append(key)

        if len(revoked_key_list) == 0:
            return
        elif len(valid_key_list) != 0:
            if input(f"Message signed with revoked keys: {' '.join([key.name for key in revoked_key_list])}. Proceed anyways? [yN]\n").lower() != 'y':
                raise Git_PKI_Exception("Operation aborted by user.")
        else:
            raise Git_PKI_Exception(
                "Could not decrypt message signed with revoked key and message was signed after revocation time.")

    def import_keys(self, files):
        if not files:
            print("Paste the key and then press ctrl+d on an empty line")
            data = read_multiline_string()
            file = tempfile.mkstemp()[1]
            with open(file, "w") as output:
                output.write(data)
            files = [file]

        fingerprints = []
        imported = False
        for file in files:
            for fingerprint in self.__import_key(file):
                fingerprints.append(fingerprint)
                name = self.__gpg.public_key_name(fingerprint)
                file = f"{self.__git.identity_dir}/{name}/{fingerprint}"
                key = self.__gpg.export_public_key(fingerprint)
                self.__export_key(key, Path(file))
                imported = True

        if not imported:
            return
        branch_name = f'import/{sha1_encode("".join(fingerprints))}'
        message = f"Import keys {', '.join(fingerprints)}"
        self.__git.push_branch(branch_name, message)

    def export_keys(self, names, target_file, mode=None):
        if file_exists(target_file):
            if not mode:
                choices = ['append', 'cancel', 'overwrite']
                mode = iterfzf.iterfzf(choices, prompt=f"Output file: {target_file} already exists, select: <append> to add keys to the file, <overwrite> to remove existing file, or <cancel> to abort")
            if mode == 'overwrite':
                os.remove(target_file)
            if mode == 'cancel':
                return
        for name in names:
            key = self.__gpg.export_public_key(name)
            if not key:
                print(f"{name}: Failed\n")
            else:
                print(f"{name}:\n{key}\n")
                if target_file:
                    self.__export_key(key, Path(target_file))
                    print(f"{name}: exported to file: {target_file}")

    @staticmethod
    def __export_key(key, path):
        mkdir(path.parent)
        with open(path, "a") as file:
            file.write(key)

    def __import_key(self, path):
        if not file_exists(path):
            print(f"File {path} not found, aborting.")
            return []
        keys_from_file = self.__gpg.scan(path)
        if not keys_from_file:
            print(f"File {path} does not contain any key, aborting.")
            return []
        print(f"File {path} contains:")
        for key in keys_from_file:
            print(f"{key.fingerprint} key of {key.name} valid between {key.created_on} and {key.expires_on}")
        if input("is that OK? [yN] ").lower() != 'y':
            return []

        with open(path, 'rb') as file:
            imported = self.__gpg.import_public_key(file.read())

        successfully_imported_keys, is_import_successful = self.__get_successfully_imported_keys_and_status(imported)
        self.__print_import_summary(keys_from_file, imported)

        if not is_import_successful:
            print("\nThere were errors while importing keys, reverting changes.")
            self.remove_keys(successfully_imported_keys)
            keys_to_load = {key for key in keys_from_file if key.fingerprint in successfully_imported_keys}
            self.__load_keys_from_git(keys_to_load)
            return []

        return successfully_imported_keys

    @staticmethod
    def __print_import_summary(keys, imported_status):
        key_statuses = list(zip(keys, imported_status))
        succeded = [item for item in key_statuses if item[1]['ok'] == '1']
        unchanged = [item for item in key_statuses if item[1]['ok'] == '0' and item[1]['text'].endswith("Not actually changed\n")]
        failed = [key for key in key_statuses if key not in succeded and key not in unchanged]
        print("Import Summary:")
        if failed:
            print("\nFailed:")
            for fail in failed:
                print(f"{fail[1]['fingerprint']}, reason:  {fail[1]['text'].replace('Not actually changed', '').strip()}")
        if unchanged:
            print("\nUnchanged:")
            for unch in unchanged:
                print(format_key(unch[0]))
        if succeded:
            print("\nSucceded:")
            for succ in succeded:
                print(format_key(succ[0]))
        print('\n')

    @staticmethod
    def __get_successfully_imported_keys_and_status(imported_keys):
        import_successful = True
        successfully_imported = []
        for key_status in imported_keys:
            reason = key_status["text"]
            if key_status["ok"] == '0':
                if reason == 'Not actually changed\n':
                    continue
                import_successful = False
            else:
                successfully_imported.append(key_status['fingerprint'].lower())
        return successfully_imported, import_successful

    def __load_keys_from_git(self, key_list):
        backup_files = [self.__git.path_to(f"identity/{key.name}/{key.fingerprint}") for key in key_list]
        for file in backup_files:
            if file_exists(file):
                with open(file, "rb") as f:
                    self.__gpg.import_public_key(f.read())

    def remove_keys(self, fingerprint_list):
        for fingerprint in fingerprint_list:
            self.__gpg.remove_public_key(fingerprint)

    def review_requests(self):
        git = self.__git

        def map_change(change):
            if change.op == 'A':
                path = reviewed.path_to(change.path)
                return KeyChange(added=list(self.__gpg.scan(path)), removed=[])
            if change.op == 'R':
                path = git.path_to(change.path)
                return KeyChange(added=[], removed=list(self.__gpg.scan(path)))
            if change.op == 'M':
                removed = git.path_to(change.path)
                added = reviewed.path_to(change.path)
                return KeyChange(added, removed)

        self.merge_revoked()

        unmerged = list(git.list_branches_unmerged_to_remote_counterpart_of(git.current_branch()))
        if not unmerged:
            return
        for i, request in enumerate(unmerged):
            print(f"{i}) {request.title}")

        try:
            selected = int(input(f"Select request to review (0-{len(unmerged)-1}): "))
        except ValueError:
            raise Git_PKI_Exception("Please pass the integer value to select request.")

        request = git.get_specified_request(unmerged[selected])
        if not git.is_mergeable_to(self.__git.master_branch, request.branch.full_name):
            print("Warning, cannot perform `git merge` automatically")

        changes = list(git.file_diff(request.branch.full_name))
        with git.open_worktree(self.__review_dir, request.branch.full_name) as reviewed:
            for change in map(map_change, changes):
                self.__run_checks(change, request, reviewed)
            print("Requested changes:")
            for change in map(map_change, changes):
                print(change)

        msg = 'Approve this changes? Answer "y" to merge them.'
        if input(msg).lower() != 'y':
            if input(f"\nDelete branch {request.branch} [yN] ?").lower() == 'y':
                git.remove_remote_branch(request.branch.name)
                print(f'\nSuccessfully deleted branch {request.branch}')
        else:
            self.merge_changes(request)

    def merge_changes(self, request):
        print(f'Merging branch {request.branch.name} into master...')
        self.__git.merge(request.branch.full_name)
        self.__git.push(self.__git.master_branch)
        self.__git.remove_remote_branch(request.branch.name)

    def merge_revoked(self):
        self.__git.fetch()
        self.__git.merge(f'origin/{self.__git.master_branch}')
        unmerged_branches = list(self.__git.list_branches_unmerged_to_remote_counterpart_of(self.__git.current_branch()))
        for branch in unmerged_branches:
            request = self.__git.get_specified_request(branch)
            if isinstance(request, RevokeIdentityRequest):
                if self.__git.is_mergeable_to(self.__git.master_branch, request.branch.full_name):
                    self.merge_changes(request)
                    couterbranch_candidate = request.branch.full_name.replace('_revoked', '')
                    try:
                        self.__git.merge(couterbranch_candidate)
                    except EnvironmentError:
                        pass
                else:
                    print(f"Error: Cannot automerge branch {request.branch.name}")

    def is_key_expired(self, key):
        if not key:
            return True
        if key.expires_on is None:
            return False
        return datetime.now() > datetime.strptime(key.expires_on, "%Y-%m-%d")

    def is_any_key_valid(self, path):
        for key in self.__gpg.scan(path):
            if not self.is_key_expired(key):
                return True
        return False

    def does_fingerprint_match_file(self, path):
        key = self.__gpg.scan(path)
        if not key:
            return False
        else:
            return str(path).endswith(key[0].fingerprint)

    def __run_checks(self, change, request, reviewed):
        if isinstance(request, ImportRequest):
            name = change.added[0].name if change.added else change.removed[0].name
            fingerprint = change.added[0].fingerprint if change.added else change.removed[0].fingerprint
        else:
            name = request.name
            fingerprint = request.fingerprint
        filepath = reviewed.path_to(os.path.join('identities', name, fingerprint))
        if not self.does_fingerprint_match_file(filepath):
            raise Git_PKI_Exception('File name and fingerprint are no equal.')
        if not self.is_any_key_valid(filepath):
            raise Git_PKI_Exception(f"The file {filepath} does not contain any valid key, aborting.")

    def is_key_revoked(self, key):
        return os.path.isfile(self.__git.path_to(os.path.join('identities', key.name, key.fingerprint + '_revoked')))

    def get_revocation_time(self, key):
        path = self.__git.path_to(os.path.join('identities', key.name, key.fingerprint + '_revoked'))
        if os.path.isfile(path):
            with open(path, 'r') as revoke_file:
                return datetime.strptime(revoke_file.read().strip(), '%Y-%m-%d %H:%M:%S%z')
        else:
            return datetime.strptime('2000-01-01 00:00:00+00:00', '%Y-%m-%d %H:%M:%S%z')

    def sync(self, keep_rejected_keys=False):
        self.__git.fetch(prune=True)
        self.__git.merge(f'origin/{self.__git.master_branch}')

        for root, dirs, files in os.walk(os.path.join(self.__git.root_dir, 'identities')):
            for file in files:
                if "revoke" in file:
                    continue
                identity_path = os.path.join(root, file)
                with open(identity_path, "rb") as f:
                    self.__gpg.import_public_key(f.read())
                if gpg_wrapper.verbose:
                    print(f"Loaded key: name: {os.path.dirname(identity_path).split('/')[-1]}, fingerprint: {file}")
        print("Successfully loaded all valid keys.")

        remote_branches = [rbranch.replace('origin/', '') for rbranch in self.__git.get_remote_branches()]
        branches_to_check = [lbranch for lbranch in self.__git.get_local_branches() if lbranch not in remote_branches]
        for branch in branches_to_check:
            if not self.__git.is_merged_to(self.__git.master_branch, branch):
                if not keep_rejected_keys:
                    self.__revert_pr(branch)
                    self.__git.remove_local_branch(branch)

    def __revert_pr(self, branch):
        request = self.__git.get_specified_request(Request(branch, self.__git.commit_title(branch)))
        if isinstance(request, RevokeIdentityRequest):
            return
        else:
            with self.__git.open_worktree(self.__review_dir, request.branch.name) as work_tree:
                if isinstance(request, AddIdentityRequest):
                    keys_to_remove = self.__gpg.scan(work_tree.path_to(os.path.join('identities', request.name, request.fingerprint)))
                    passphrase = getpass.getpass(f"Specify passphrase to remove existing key of [{keys_to_remove[0].name}]: ")
                    self.__gpg.remove_public_key(keys_to_remove[0].fingerprint)
                    self.__gpg.remove_private_key(keys_to_remove[0].fingerprint, passphrase)
                else:
                    keys_to_remove = []
                    for root, _, files in os.walk(work_tree.path_to(os.path.join('identities'))):
                        for file in files:
                            if file in request.fingerprints:
                                keys_to_remove.extend(self.__gpg.scan(os.path.join(root, file)))
                    for key in keys_to_remove:
                        self.__gpg.remove_public_key(key.fingerprint)

def create_gpki_parser():
    common_args_parser = argparse.ArgumentParser(
        prog='git pki', argument_default=argparse.SUPPRESS, add_help=False)
    common_args_parser.add_argument('-h', '--help')
    common_args_parser.add_argument(
        '--version', '-v', action='version', version=f'%(prog)s version {__version__}')
    common_args_parser.add_argument('--verbose', action='store_true', default=False)

    cli_parser = argparse.ArgumentParser(
        prog='git pki',
        argument_default=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser]
    )

    subparsers = cli_parser.add_subparsers(dest='command')

    encrypt_parser = subparsers.add_parser(
        'encrypt',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])
    encrypt_parser.add_argument('--input', '-i', default=None)
    encrypt_parser.add_argument('--output', '-o', default=None)
    encrypt_parser.add_argument('--password', '-p', default=None)
    encrypt_parser.add_argument('--all', '-a', action='store_true', default=False)

    decrypt_parser = subparsers.add_parser(
        'decrypt',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])
    decrypt_parser.add_argument('--input', '-i', default=None)
    decrypt_parser.add_argument('--output', '-o', default=None)
    decrypt_parser.add_argument('--password', '-p', default=None)
    decrypt_parser.add_argument('--sync', '-s', action='store_true', default=False)

    new_identity_parser = subparsers.add_parser(
        'identity',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])
    new_identity_parser.add_argument('name', nargs='?')
    new_identity_parser.add_argument('--email', default=None)
    new_identity_parser.add_argument('--description', default=None)

    import_key_parser = subparsers.add_parser(
        'import',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])
    import_key_parser.add_argument('--input', '-i', nargs='+', default=None)

    export_key_parser = subparsers.add_parser(
        'export',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])
    export_key_parser.add_argument('key_names', nargs='+')
    export_key_parser.add_argument('--output', '-o', default=None)

    subparsers.add_parser(
        'recipients',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])

    subparsers.add_parser(
        'signatories',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])

    subparsers.add_parser(
        'review',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])

    sync_parser = subparsers.add_parser(
        'sync',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])
    sync_parser.add_argument('--keep-rejected-keys', action='store_true', default=False)

    subparsers.add_parser(
        'revoke',
        argument_default=argparse.SUPPRESS,
        usage=argparse.SUPPRESS,
        add_help=False,
        parents=[common_args_parser])

    return cli_parser

def launch(parsed_cli):
    gpg_wrapper.verbose = parsed_cli.verbose

    gpki = GPKI("/tmp/foobarbaz")
    cmd = parsed_cli.command

    if cmd == 'decrypt':
        gpki.decrypt(parsed_cli.input, parsed_cli.output, parsed_cli.password, parsed_cli.sync)
    elif cmd == 'encrypt':
        gpki.encrypt(parsed_cli.input, parsed_cli.output, parsed_cli.password, parsed_cli.all)
    elif cmd == 'identity':
        if 'name' not in parsed_cli:
            raise Git_PKI_Exception("Name is mandatory while creating new identity.")
        gpki.generate_identity(parsed_cli.name, parsed_cli.email, parsed_cli.description)
    elif cmd == 'import':
        gpki.import_keys(parsed_cli.input)
    elif cmd == 'export':
        gpki.export_keys(parsed_cli.key_names, parsed_cli.output)
    elif cmd == 'recipients':
        gpki.list_recipients()
    elif cmd == 'signatories':
        gpki.list_signatories()
    elif cmd == 'review':
        gpki.review_requests()
    elif cmd == 'sync':
        gpki.sync(parsed_cli.keep_rejected_keys)
    elif cmd == 'revoke':
        gpki.revoke()
    else:
        # Some help should be printed here
        raise Git_PKI_Exception(f"Command {cmd} is not a valid git-pki command.")

def main():
    args = sys.argv[1:]
    cli_parser: argparse.ArgumentParser = create_gpki_parser()
    parsed_cli = cli_parser.parse_args(args)
    launch(parsed_cli)

if __name__ == "__main__":
    main()


N, M = map(int, input().split())
lst = list(range(1, N+1))
rlt = []

def perm(i):
    if i == M:
        print(*rlt)
        return

    for j in lst:
        if j not in rlt:
            rlt.append(j)
            perm(i+1)
            rlt.pop()

perm(0)


from odoo import fields, models

class ResCompany(models.Model):
    _inherit = "res.company"

    show_internal_users_cc = fields.Boolean(
        string="Show Internal Users CC",
        default=True,
    )
    show_followers_message_sent_to = fields.Text(
        string="Text 'Sent to'",
        translate=True,
        default="This message has been sent to",
    )
    show_followers_partner_format = fields.Char(
        string="Partner format",
        default="%(partner_name)s",
        help="Supported parameters:\n"
        "%(partner_name)s = Partner Name\n"
        "%(partner_email)s = Partner Email\n"
        "%(partner_email_domain)s = Partner Email Domain",
    )
    show_followers_message_response_warning = fields.Text(
        string="Text 'Replies'",
        translate=True,
        default="Notice: Replies to this email will be sent to all recipients",
    )


from plone.app.testing import IntegrationTesting
from plone.app.testing import FunctionalTesting, PloneSandboxLayer
#from plone.app.testing import PLONE_FIXTURE

class MyLayer(PloneSandboxLayer):
#    defaultBases = (PLONE_FIXTURE,)

    def setUpZope(self, app, configurationContext):
        import collective.categories
        import Products.ATVocabularyManager
        import archetypes.linguakeywordwidget
        self.loadZCML(package=Products.ATVocabularyManager)
        self.loadZCML(package=archetypes.linguakeywordwidget)
        self.loadZCML(package=collective.categories)

    def setUpPloneSite(self, portal):
        self.applyProfile(portal, 'Products.ATVocabularyManager:default')
        self.applyProfile(portal, 'archetypes.linguakeywordwidget:default')
        self.applyProfile(portal, 'collective.categories:default')

FIXTURE = MyLayer()

INTEGRATION = IntegrationTesting(bases=(FIXTURE,),
                                 name="collective.categories:Integration")

FUNCTIONAL = FunctionalTesting(bases=(FIXTURE,),
                               name="collective.categories:Functional")


fig = plt.figure(facecolor = 'lightgray')

for i in range(1,7):
    ax = fig.add_subplot(2,3,i)
    ax.text(0.5, 0.5,
            s = str(i),
            ha = 'center',
            va = 'center',
            fontsize = 30)
    ax.set_yticks([])
    ax.set_xticks([])
    ax.set_title("Title",
                 fontsize = 12,
                 fontname = 'Times New Roman')

fig.suptitle('SupTitle')
fig.tight_layout(rect = (0,0,1,1)) # no change


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def add_layer(inputs, in_size, out_size, activation_fun=None):
    with tf.name_scope('layer'):
        with tf.name_scope('Weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name="W")
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
        Wx_plus_b = tf.matmul(inputs, Weights) + biases

        if activation_fun is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_fun(Wx_plus_b)

        return outputs

x = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x.shape)
y = np.square(x) + 0.5 + noise

#input
with tf.name_scope('inputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name="x_in")
    ys = tf.placeholder(tf.float32, [None, 1], name="y_in")

l1 = add_layer(xs, 1, 10, activation_fun=tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_fun=None)

with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))

with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer()
sess = tf.Session()
writer = tf.summary.FileWriter("d:\logs", sess.graph)
sess.run(init)


#!/usr/bin/env python3
import pydotplus
from sklearn import tree
from sklearn.datasets import load_iris
from sklearn.metrics import classification_report
#from sklearn import cross_validation
from sklearn.model_selection import train_test_split
import collections

X = [[165,19],[175,32],[136,35],[174,65],[141,28],[176,15],[131,32],
        [166,6],[128,32],[179,10],[136,34],[186,2],[126,25],[176,28],[112,38],
        [169,9],[171,36],[116,25],[196,25]]

Y = ['Man','Woman','Woman','Man','Woman','Man','Woman','Man','Woman',
        'Man','Woman','Man','Woman','Woman','Woman','Man','Woman','Woman','Man']
data_feature_names = ['height','length of hair']

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.40, random_state=5)

#After providing the dataset, we need to fit the model which can be done as follows −

clf = tree.DecisionTreeClassifier()
clf = clf.fit(X,Y)

#Predict
prediction = clf.predict([[133,37]])
print(prediction)

#We can visualize the decision tree with the help of the following Python code −

dot_data = tree.export_graphviz(clf,feature_names = data_feature_names,
                    out_file = None,filled = True,rounded = True)
graph = pydotplus.graph_from_dot_data(dot_data)
colors = ('orange', 'yellow')
edges = collections.defaultdict(list)

for edge in graph.get_edge_list():
    edges[edge.get_source()].append(int(edge.get_destination()))

    for edge in edges: edges[edge].sort()

    for i in range(1): dest = graph.get_node(str(edges[edge][i]))[0]
    dest.set_fillcolor(colors[i])
    graph.write_png('Decisiontree16.png')


import threading
import socket
import time
import os
from datetime import datetime
import json

CONST_MAX_PORTS = 65534
CONST_START_THREAD_TIMEOUT = 0.7
CONST_TCP_WAIT_TIMEOUT = 1
CONST_NETWORKS_FILE = "networks.txt"
CONST_LOG_FILE = "port_scan_log.txt"
CONST_RESULT_FILE = "result.json"
#TG_STR_1 = "wget -O /dev/null \"https://api.telegram.org/bot0000000000:KEY/sendMessage?chat_id=-11111111111111&disable_notification=true&text="
TG_STR_1 = "wget -O /dev/null \"https://api.telegram.org/bot000000000:KEY/sendMessage?chat_id=-111111111111&disable_notification=true&text="
TG_STR_2 = "\""

def log(log_string):
    file_name = CONST_LOG_FILE
    if log_string == "_INIT_":
        newfile = open(file_name, 'w')
        newfile.truncate()
        newfile.close()
    else:
        file_log = open(file_name, 'a')
        month_names = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
        dt = datetime.now()
        if dt.hour < 10:
            f_hour = f"0{dt.hour}"
        else:
            f_hour = f"{dt.hour}"
        if dt.minute < 10:
            f_minute = f"0{dt.minute}"
        else:
            f_minute = f"{dt.minute}"
        if dt.second < 10:
            f_second = f"0{dt.second}"
        else:
            f_second = f"{dt.second}"
        file_str = f"{f_hour}:{f_minute}:{f_second} {dt.day}-{month_names[dt.month - 1]}-{dt.year} ... {log_string} \n"
        file_log.write(file_str)
        file_log.close()

def cidr_to_addrlist(act_network):
    addresses = list()
    act_network.strip()
    slash_position = act_network.find("/")
    network_name = act_network[:slash_position]
    network_mask = int(act_network[slash_position + 1:])
    if network_mask == 32:
        addresses.append(network_name)
    else:
        host_num = 2 ** (32 - network_mask) - 2
        net_ip_arr_str = network_name.split(".")
        net_ip_arr_int = [int(net_ip_arr_str[0]), int(net_ip_arr_str[1]), int(net_ip_arr_str[2]), int(net_ip_arr_str[3])]
        net_binary = (net_ip_arr_int[0] << 24) + (net_ip_arr_int[1] << 16) + (net_ip_arr_int[2] << 8) + net_ip_arr_int[3]
        for i in range(0, host_num, 1):
            net_binary += 1
            oct1 = net_binary >> 24
            oct2 = (net_binary % 16777216) >> 16
            oct3 = (net_binary % 65536) >> 8
            oct4 = net_binary % 256
            addresses.append(f"{oct1}.{oct2}.{oct3}.{oct4}")
    return addresses

#def worker_pinger(ip_address):
#    r = os.popen(f"ping -c2 -W1 {ip_address}").read()
#    if (" 0% packet loss," in r) or (" 50% packet loss," in r) or (" 25% packet loss," in r) or (" 75% packet loss," in r):
#        log(f"{ip_address} is alive")
#        alive_hosts.add(ip_address)
#    pinged_hosts.add(ip_address)

def worker_scan(host_address, start_port, end_port):
    opened_ports = list()
    for port in range(start_port, end_port+1, 1):
        connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connection.settimeout(CONST_TCP_WAIT_TIMEOUT)
        is_opened = 0
        #print(f"{host_address}:{port}")
        try:
            connection.connect((host_address.strip(), port))
            is_opened = 1
            connection.close()
        except socket.error:
            pass
        if is_opened == 1:
            log(f"{host_address}:{port} is opened")
            opened_ports.append(port)
    if len(opened_ports) > 0:
        results[host_address] = opened_ports
    scanned_hosts.add(host_address)

# loading startup data
log("_INIT_")
log("START")
file = open(CONST_NETWORKS_FILE, "r")
networks_CIDR = file.read().strip().split()
file.close()
del file

# converting CIDR to set of IP addresses
ip_addresses = set()
for network_CIDR in networks_CIDR:
    ip_list = cidr_to_addrlist(network_CIDR)
    for ip in ip_list:
        ip_addresses.add(ip)
del ip
del ip_list

# pinging IP addresses
#ping_threads = set()
#pinged_hosts = set()
#alive_hosts = set()
#for ip in ip_addresses:
#    ping_threads.add(threading.Thread(target=worker_pinger, args=(ip, )))
#for pinger_thread in ping_threads:
#    pinger_thread.start()
#    time.sleep(CONST_START_THREAD_TIMEOUT)

#while len(pinged_hosts) != len(ip_addresses):
#    time.sleep(1)

#for pinger_thread in ping_threads:
#    pinger_thread.join()

#del ip_addresses
#del pinger_thread
#del pinged_hosts
#del ping_threads
#del ip

# scanning living hosts
scan_threads = set()
scanned_hosts = set()
results = dict()
for host in ip_addresses:
    scan_threads.add(threading.Thread(target=worker_scan, args=(host, 1, CONST_MAX_PORTS)))

for scan_thread in scan_threads:
    time.sleep(CONST_START_THREAD_TIMEOUT)
    scan_thread.start()

last_scanned_hosts = 0
while len(scanned_hosts) != len(ip_addresses):
    currently_scanned_hosts = len(scanned_hosts)
    if currently_scanned_hosts > last_scanned_hosts:
        log(f"scanned {currently_scanned_hosts} hosts")
        last_scanned_hosts = currently_scanned_hosts
    time.sleep(1)
del last_scanned_hosts
del currently_scanned_hosts

for scan_thread in scan_threads:
    scan_thread.join()

del scan_thread
del scan_threads
del scanned_hosts

# saving results
log("saving results")
first_time_scan = 0
if os.path.exists(CONST_RESULT_FILE):
    load = open(CONST_RESULT_FILE, "r")
    inner_dict = json.load(load)
    load.close()
else:
    inner_dict = dict()
    first_time_scan = 1

save = open(CONST_RESULT_FILE, "w")
json.dump(results, save, indent=4)
save.close()
#-------------------- Analyzing --------------------------------------
log("analysing the result")
old_dict = dict() # contains ips and ports closed since last scan
new_dict = dict() # contains ips and ports opened since last scan
for old_key in inner_dict.keys():
    if old_key not in results.keys():
        old_dict[old_key] = inner_dict[old_key]
for new_key in results.keys():
    if new_key not in inner_dict.keys():
        new_dict[new_key] = results[new_key]
    if (new_key in inner_dict.keys()) and (new_key in results.keys()):
        removed_ports = list()
        added_ports = list()
        for r_port in inner_dict[new_key]:
            if r_port not in results[new_key]:
                removed_ports.append(r_port)
        for a_port in results[new_key]:
            if a_port not in inner_dict[new_key]:
                added_ports.append(a_port)
        if len(removed_ports) > 0:
            old_dict[new_key] = list(removed_ports)
        if len(added_ports) > 0:
            new_dict[new_key] = list(added_ports)
        del removed_ports
        del added_ports

old_outstr = str()
for t_ip in old_dict:
    old_outstr += str(t_ip)
    old_outstr += ": "
    d_len = len(old_dict[t_ip])
    for t_port in old_dict[t_ip]:
        old_outstr += str(t_port)
        if t_port != old_dict[t_ip][d_len - 1]:
            old_outstr += ", "
    old_outstr += "\n"

new_outstr = str()
for t_ip in new_dict:
    new_outstr += str(t_ip)
    new_outstr += ": "
    d_len = len(new_dict[t_ip])
    for t_port in new_dict[t_ip]:
        new_outstr += str(t_port)
        if t_port != new_dict[t_ip][d_len - 1]:
            new_outstr += ", "
    new_outstr += "\n"

output_str = str()

if first_time_scan == 1:
    output_str = f"PORT SCANNER:\nFirst scan !!!\n{new_outstr}"
else:
    output_str = f"PORT SCANNER:\n"
    if len(old_outstr) > 0:
        output_str += f"closed since last scan:\n{old_outstr}\n"
    if len(new_outstr) > 0:
        output_str += f"opened since last scan:\n{new_outstr}\n"

wget_str = TG_STR_1 + output_str + TG_STR_2

if (len(old_outstr) > 0) or (len(new_outstr) > 0):
    r0 = os.popen(wget_str).read()
    time.sleep(1)
    del r0
#-------------------- End Analyzing ------------------------------------

log("END")


"""Constants common to the Specify Network Broker and Analyst API services."""
URL_ESCAPES = [[" ", r"\%20"], [",", r"\%2C"]]
ENCODING = "utf-8"

# Used in broker, so relative to the flask_app/broker or analyst directories
STATIC_DIR = "../../sppy/frontend/static"
ICON_DIR = f"{STATIC_DIR}/icon"
SCHEMA_DIR = f"{STATIC_DIR}/schema"

TEMPLATE_DIR = "../templates"
SCHEMA_FNAME = "open_api.yaml"


from kernel.chat_kernel import ChatKernel as CK
from kernel.chat_pack_message import PackMessage
from kernel.chat_protocol import ChatProtocol
from kernel.data_parser import DataParser

class ChatKernel(CK):
    async def send_error(self, connection, error_mode, mess=None, username=None):
        message = PackMessage.prepare_message('error', error_mode=error_mode, message=mess, username=username)
        await self.sender.send(connection, message)

    async def send_info(self, connection, info_mode, clear_data, userlist=None, username=None):
        message = PackMessage.prepare_message('info', info_mode=info_mode, clear_data=clear_data,
                                              userlist=userlist, username=username)
        await self.sender.send(connection, message)

    async def engine(self, request, writer, addr):
        if not request:
            await self.logout_engine(writer)
            return -1
        else:
            req_dict = self.validate_request(request, writer, addr)
            if type(req_dict) == DataParser:
                return await self.run_command(req_dict, writer)
            else:
                await self.send_error(writer, 'bad_request', mess=req_dict)
            return 0

    async def run_command(self, req_dict, connection):
        methods = self.prepare_run(req_dict, connection)
        protocol = ChatProtocol(**methods)
        state = await protocol.engine(req_dict.cmd)
        return state

    async def login_engine(self, connection, username):
        if self.sender.login(connection, username) == 0:
            message = PackMessage.prepare_message(mode='login', username=username, version=self.version)
            await self.sender.send_all(message)
        else:
            await self.send_error(connection, 'user_exist')

    async def logout_engine(self, connection):
        username = self.sender.get_name_by_connection(connection)
        if username != 0:
            message = PackMessage.prepare_message(mode='logout', username=username, version=self.version)
            await self.sender.send_all(message)
            await self.sender.logout(connection)

    async def send_message_engine(self, connection, username, message):
        user = self.sender.get_connection_by_name(username)
        if user is not None:
            message = PackMessage.prepare_message(mode='send_message', username=username, message=message,
                                                  sender=self.sender.get_name_by_connection(connection))
            await self.sender.send(user, message)
            await self.sender.send(connection, message)
        else:
            await self.send_error(connection, 'not_found', username=username)

    async def send_all_engine(self, connection, message):
        username = self.sender.get_name_by_connection(connection)
        message = PackMessage.prepare_message(mode='send_message_all', username=username, message=message)
        await self.sender.send_all(message)


import sys
import os
import glob
from PIL import Image, ImageDraw
import numpy as np

input_path = ""
output_path = ""
dir = "LEFT"

# Handle Command Line Inputs
args = sys.argv
for index, arg in enumerate(args):
    if arg == '-d':
        if len(args) > index + 1:
            dir = args[index + 1]
        else:
            print("Invald or Empty Direction. Possible values are 'FRONT', 'LEFT', 'TOP'")
            exit(1)

    if arg == '-i':
        if len(args) > index + 1:
            input_path = args[index + 1]
        else:
            print("Invald or Empty input path.")
            exit(1)

    if arg == '-o':
        if len(args) > index + 1:
            output_path = args[index + 1]
        else:
            print("Invald or Empty output path.")
            exit(1)

if(output_path == ""):
    print("No output path provided. Input path will be used.")
    output_path = input_path

print("Direction: " + dir)
print("Input Path: " + input_path)
print("Output Path: " + output_path)

if(os.path.isdir(input_path)):
    print("Input Path is a Folder. Scanning for OBJs")

if(os.path.isfile(input_path)):
    print("Input Path is a File. Using as Input file")

print("Found " + str(len(glob.glob(input_path + "*.obj"))) + " files.")

for file_name in glob.glob(input_path + "*.obj"):

    vertices = []
    faces = []

    print("Parsing " + file_name)

    with open(file_name) as obj_file:
        for line in obj_file:
            if(line.startswith('v ')):
                vertices.append(line.split(' '))

            if(line[0] == 'f'):
                faces.append(line.split(' '))

    if(len(vertices) == 0):
        print("No Vertices to Parse. Skipping")
        continue

    print("Loaded " + str(len(vertices)) + " vertices")
    print("Loaded " + str(len(faces)) + " faces")

    layers = []
    faces_full = []

    for item in faces:
        item.pop(0)
        new_item = []
        for set in item:
            new_item.append( [int(x) for x in set.split('/')] )

        faces_full.append(new_item)

    for line in faces_full:
        this_face = []
        for set in line:
            if(dir == "TOP"):
                index = int(set[0]) - 1
                vertice = vertices[index]
                this_face.append(vertice[1].strip('\n'))
                this_face.append(vertice[3].strip('\n'))

            if(dir == "LEFT"):
                index = int(set[0]) - 1
                vertice = vertices[index]
                this_face.append(vertice[1].strip('\n'))
                this_face.append(vertice[2].strip('\n'))

            if(dir == "FRONT"):
                index = int(set[0]) - 1
                vertice = vertices[index]
                this_face.append(vertice[2].strip('\n'))
                this_face.append(vertice[3].strip('\n'))

        layers.append("L " + ','.join(this_face))

    input_name = os.path.basename(file_name)

    f = open(output_path + input_name.split(".")[0] + ".plf", "w")
    f.write('########################\n')
    f.write('# Generated by OBJ2PLF #\n')
    f.write('#     Version 0.1      #\n')
    f.write('########################\n')
    f.write('\n'.join(layers))
    f.close()


import requests
import argparse
from bs4 import BeautifulSoup

def crawl(url, rdm):
    r = requests.get(url)
    if (r.status_code != 200):
        return rdm
    print(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    for link in soup.find_all('a', href=True):
        if (link['href'] != '../' and link['href'] != 'README'):
            rdm = crawl(url + link['href'], rdm)
        elif link['href'] == 'README':
            r2 = requests.get(url + 'README')
            if r2.status_code == 200:
                if r2.text not in rdm:
                    rdm.append(r2.text)
    return rdm

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("url_VM", help="the url given by the VM")
    args = parser.parse_args()
    url = args.url_VM + '.hidden/'
    rdm = list()
    rdm = crawl(url, rdm)
    print("Le flag se trouve dans une de ces strings:")
    for elem in rdm:
        print("\t-", elem, end="")