import pandas as pd
import seaborn as sn
import scipy
import numpy as np
import plotly.express as px
from statsmodels.distributions.empirical_distribution import ECDF
import streamlit as st

@st.cache
def cargamos_base_datos():

    esi = pd.read_csv("/Users/pipe/Documents/repos/esi2019-modelos/datos/esi-2019.csv",
                      sep=';', encoding='latin')
    region_comuna = pd.read_csv("/Users/pipe/Documents/repos/esi2019-modelos/datos/region_comuna.csv",
                                sep=';')

    esi = pd.merge(esi, region_comuna, left_on='r_p_c', right_on='Código Comuna 2018', how='left')
    esi.drop(['region'], axis=1, inplace=True)

    columns_map = {
    'id_identificacion': 'id_hogar',
    'idrph': 'id_persona',
    'tipo': 'tipo_estrato',
    't_muestra': 'tipo_muestra',
    'd1_monto': 'sueldo_neto',
    'Nombre Región': 'region',
    'Nombre Provincia': 'provincia',
    'Nombre Comuna': 'comuna',
    'b1': 'grupo_ocupacion',
    'cise': 'categoria_empleo',
    'b8': 'tiene_contrato',
    'b12': 'est_subcontratado',
    'b13_rev4cl_cae': 'rubro',
    'c1': 'tipo_jornada',
    }

    esi = esi.rename(columns=columns_map)

    values_map = {
    'parentesco': {
        1: 'Jefe de hogar',
        2: 'Cónyuge',
        3: 'Conviviente',
        4: 'Hijo(a) / Hijastro(a)',
        5: 'Yerno / Nuera',
        6: 'Nieto(a)',
        7: 'Hermano(a) / Cuñado(a)',
        8: 'Padres / Suegros',
        9: 'Otro pariente',
        10: 'No pariente',
        11: 'Servicio doméstico',
        12: 'Fuera del hogar',
        13: 'Fallecido',
    }
    ,

    'nivel': {
        0: 'Nunca estudió',
        1: 'Sala cuna',
        2: 'Kínder',
        3: 'Básica o primaria 4 Media común',
        5: 'Media técnico profesional 6 Humanidades',
        7: 'Centro formación técnica 8 Instituto profesional',
        9: 'Universitario 10 Postítulo',
        11: 'Magíster',
        12: 'Doctorado',
        14: 'Normalista',
        99: 'Nivel ignorado',
        999: 'Nivel ignorado',
    }
    ,

    'tipo_estrato': {
        1: 'Ciudad',
        2: 'Resto area urbana',
        3: 'Rural'
    }
    ,

    'sexo': {
        1: 'Hombre',
        2: 'Mujer'
    }
    ,

    'termino_nivel': {
        1: "Si",
        2: "No"
    }
    ,

    'cine': {
        1: "Nunca estudió",
        2: "Educación preescolar",
        3: 'Educación primaria (nivel 1)',
        4: 'Educación primaria (nivel 2)',
        5: 'Educación secundaria',
        6: 'Educación técnica',
        7: 'Educación universitaria',
        8: 'Postítulo y maestría',
        9: 'Doctorado',
        999: None
    }
    ,

    'est_conyugal': {
        0: None,
        1: "Casade",
        2: "Coviviente",
        3: "Soltere",
        4: "Viude",
        5: "Separade",
        6: "Divorciade"
    }
    ,

    #'nacionalidad': {}

    }

    for variable, mapping in values_map.items():
        esi[variable] = esi[variable].map(mapping)

    def procesar_monto(x):
        try:
            if ',' in x:
                x = x.replace(',', '.')
            return float(x)
        except:
            return x

    esi['sueldo_neto'] = esi['sueldo_neto'].apply(procesar_monto)
    return esi


import math

## PARAMETERS FOR DTW-MT ##

ALPHA_T = 0.0075   # meters
ALPHA_R = math.radians(3.75)
BETA = 1.
GAMMA = 4.

## ENABLES ROS-based FUNCTIONS ##
# will affect metric computation slightly.
# If you do not plan to install ROS and still be able to use tools in this directory,
#  disable following parameter.
USE_ROS = True


import requests
from bs4 import BeautifulSoup
import csv
from datetime import datetime
from multiprocessing import Pool

def get_html_text(url):
    """
    Функция, возвращающая html страницу
    """
    try:
        res = requests.get(url, timeout=30)
        return res.text

    except requests.ConnectionError:
        print("Connection Error")

    except requests.Timeout:
        print("Timeout Error")

    except requests.RequestException:
        print("Request Exception")

def get_all_news_from_page(html):
    """
    Функция, возвращающая список сслылок на новости на одной странице
    """
    soup = BeautifulSoup(html, 'lxml')
    links = soup.find_all('header', class_='entry-header')
    l_links = []
    for i in links:
        a = i.find('a').get('href')
        l_links.append(a)
    return l_links

def get_content(html):
    """
    Функция, возвращающая текст и залоговок новости
    """
    soup = BeautifulSoup(html, 'lxml')
    try:
        text = soup.find('div', class_='entry-content').text.strip()
    except:
        text = ''
    try:
        title = soup.find('h1', class_='entry-title').text.strip()
    except:
        title = ''
    data = {'text': text, 'title': title}

    return data

def pool_func(url):
    """
    Функция для выполнения мультипроцессинга
    """
    html = get_html_text(url)
    data = get_content(html)
    write_csv(data)

def write_csv(data):
    """
    Функция, записывающая данные в csv файл
    """
    with open('panorama_news_satire.csv', 'a', encoding='utf8') as f:
        writer = csv.writer(f)
        writer.writerow((data['text'], data['title']))
        print(data['title'])
        print('--------------------------------')
        print()

def main():
    start = datetime.now()
    for i in range(1, 511):  # итерация по количеству страниц на сайте
        print(i)
        url = 'https://panorama.pub/page/{}?s'.format(i)
        all_links = get_all_news_from_page(get_html_text(url))

        with Pool(20) as pool:
            pool.map(pool_func, all_links)

        end = datetime.now()
        t = end - start
        print(str(t))

if __name__ == '__main__':
    main()

data/Парсер новостей (на примере сайта ИА Панорама).py


from django.urls import path
# vistas importadas
from . import views

urlpatterns = [

    path('home/', views.IndexView.as_view()),
    path('lista/', views.PruebaListviwe.as_view()),
    path('lista-prueba/', views.ModeloPruebaListView.as_view()),
    path(
        'add-prueba/',
        views.PruebaCreateView.as_view(),
        name='prueba_add'),
    path(
        'resume-foundation/',
        views.ResumeFoundationView.as_view(),
        name='resume_foundation'),
]


top = '.'
out = 'build'

def options(opt):
	opt.load('compiler_c')

def configure(cnf):
	cnf.load('compiler_c')
	cnf.check(features='c cprogram cshlib', cflags=['-Wall','-g'], defines=['var=foo'])
	cnf.check_cfg(package='wayland-client', args='--cflags --libs', uselib_store='SH_LIBS', mandatory=True)
	cnf.check_cfg(package='wayland-cursor', args='--cflags --libs', uselib_store='SH_LIBS', mandatory=True)
	cnf.check_cfg(package='xkbcommon', args='--cflags --libs', uselib_store='SH_LIBS', mandatory=True)
	cnf.check_cfg(package='egl', args='--cflags --libs', mandatory=False)
	if cnf.env.LIB_EGL:
		cnf.check_cfg(package='cairo-gl', args='--cflags --libs', uselib_store='SH_LIBS', mandatory=True)
		cnf.check_cfg(package='wayland-egl', args='--cflags --libs', uselib_store='SH_LIBS', mandatory=True)
	else:
		cnf.check_cfg(package='cairo', args='--cflags --libs', uselib_store='SH_LIBS', mandatory=True)

	cnf.write_config_header('config.h')

def build(bld):
	if bld.env.LIB_EGL:
		source='src/egl.c '
	else:
		source='src/shm.c '

	bld(features='c cprogram',
		source=source+'src/draw.c src/main.c src/ui.c src/util.c',
		cflags=['-Wall','-g', '-I./'],
		use=['SH_LIBS','EGL'],
		target='wl_term')


import numpy as np
import os
import pyqtgraph as pg

from core.module import Connector
from gui.colordefs import QudiPalettePale as palette
from gui.guibase import GUIBase
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy import uic

class AomMainWindow(QtWidgets.QMainWindow):

    """ Create the Main Window based on the *.ui file. """

    def __init__(self, **kwargs):
        # Get the path to the *.ui file
        this_dir = os.path.dirname(__file__)
        ui_file = os.path.join(this_dir, 'ui_aom.ui')

        # Load it
        super().__init__(**kwargs)
        uic.loadUi(ui_file, self)
        self.show()

class AomGui(GUIBase):

    """ FIXME: Please document
    """
    _modclass = 'aomgui'
    _modtype = 'gui'

    # declare connectors
    aomlogic = Connector(interface='AomLogic')

    sigPsatFinished = QtCore.Signal()
    sigAomChange = QtCore.Signal()

    def __init__(self, config, **kwargs):
        super().__init__(config=config, **kwargs)

    def on_activate(self):
        """ Definition and initialisation of the GUI.
        """

        self._aom_logic = self.get_connector('aomlogic')

        # Use the inherited class 'CounterMainWindow' to create the GUI window
        self._mw = AomMainWindow()

        self.psat_image = pg.PlotDataItem(self._aom_logic.powers,
                                          self._aom_logic.psat_data,
                                          pen=pg.mkPen(palette.c1, style=QtCore.Qt.DotLine),
                                          symbol='o',
                                          symbolPen=palette.c1,
                                          symbolBrush=palette.c1,
                                          symbolSize=7)

        self.psat_fit_image = pg.PlotDataItem(self._aom_logic.psat_fit_x,
                                              self._aom_logic.psat_fit_y,
                                              pen=pg.mkPen(palette.c2))

        # Add the display item to the xy and xz ViewWidget, which was defined in the UI file.
        self._mw.psat_plot_PlotWidget.addItem(self.psat_image)
        self._mw.psat_plot_PlotWidget.addItem(self.psat_fit_image)
        self._mw.psat_plot_PlotWidget.setLabel(axis='left', text='Fluoresence', units='c/s')
        self._mw.psat_plot_PlotWidget.setLabel(axis='bottom', text='Power', units='W')
        self._mw.psat_plot_PlotWidget.showGrid(x=True, y=True, alpha=0.8)
        self._mw.setPower.setValue(self.get_power())
        self._mw.setPower.valueChanged.connect(self.set_power)
        self._mw.setPower.setMaximum(self._aom_logic.current_maximum_power()*1000)
        self._mw.set_to_psat.clicked.connect(self.set_power_to_psat)
        self._aom_logic.power_available.connect(self.update_power_available)

        #####################
        # Connecting user interactions
        self._mw.run_psat_Action.triggered.connect(self.run_psat_clicked)
        self._mw.save_psat_Action.triggered.connect(self.save_clicked)

        ##################
        # Handling signals from the logic
        self._aom_logic.psat_updated.connect(self.update_data)
        self._aom_logic.psat_fit_updated.connect(self.update_fit)
        self._aom_logic.aom_updated.connect(self.update_aom)

        return 0

    def show(self):
        """Make window visible and put it above all other windows.
        """
        QtWidgets.QMainWindow.show(self._mw)
        self._mw.activateWindow()
        self._mw.raise_()
        return

    def on_deactivate(self):
        """ Deactivate the module
        """
        # disconnect signals
        self._mw.run_psat_Action.triggered.disconnect()
        self._mw.save_psat_Action.triggered.disconnect()
        self._aom_logic.psat_updated.disconnect()
        self._mw.close()
        return

    def update_aom(self):
        self._mw.setPower.blockSignals(True)
        self._mw.setPower.setValue(self.get_power())
        self._mw.setPower.blockSignals(False)

    def set_power_to_psat(self):
        self._aom_logic.set_power(self._aom_logic.fitted_Psat)

    def update_data(self):
        """ The function that grabs the data and sends it to the plot.
        """

        """ Refresh the plot widgets with new data. """
        # Update psat plot
        self.psat_image.setData(self._aom_logic.powers, self._aom_logic.psat_data)

        return 0

    def set_power(self,power):
        self._aom_logic.set_power(power/1000)

    def get_power(self):
        return self._aom_logic.get_power()*1000

    def update_fit(self):
        """ Refresh the plot widgets with new data. """
        if self._aom_logic.psat_fit_available():
            # Update psat plot
            self.psat_fit_image.setData(self._aom_logic.psat_fit_x, self._aom_logic.psat_fit_y)
            self._mw.Isat_display.setText("{:.2f}".format(self._aom_logic.fitted_Isat/1000))
            self._mw.Psat_display.setText("{:.2f}".format(self._aom_logic.fitted_Psat*1000))
            self._mw.bg_display.setText("{:.2f}".format(self._aom_logic.fitted_offset/1000))

    def run_psat_clicked(self):
        """ Handling the Start button
        """
        self.log.info("Running psat")
        self._aom_logic.run_psat()
        return self._aom_logic.module_state()

    def save_clicked(self):
        """ Handling the save button to save the data into a file.
        """
        if self._aom_logic.psat_available():
            self._aom_logic.save_psat()
        return self._aom_logic.module_state()

    def update_max_power(self, count_length):
        """Function to ensure that the GUI displays the current value of the logic

        @param int count_length: adjusted count length in bins
        @return int count_length: see above
        """
        self._mw.setPower.blockSignals(True)
        self._mw.count_length_SpinBox.setValue(count_length)
        self._pw.setXRange(0, count_length / self._counting_logic.get_count_frequency())
        self._mw.count_length_SpinBox.blockSignals(False)
        return count_length

    def update_power_available(self, state):
        pass

    def update_saving_Action(self, start):
        pass


# operate(token, arg1, arg2) - returns the appropriate operation depending on the type of token
def operate(token, arg1, arg2) -> int:
  if (token == '^'):
    return pow(arg1, arg2)
  elif (token == '/'):
    return arg1 / arg2
  elif (token == '*'):
    return arg1 * arg2
  elif (token == '+'):
    return arg1 + arg2
  else:
    return arg1 - arg2

# check_format(expr) - checks the format and determines whether the equation is in infix, postfix or prefix notation
def check_format(expr) -> int:
  temp_list = expr.split()
  if len(temp_list) < 2:
    return expr

  token1, token2 = temp_list[-1], temp_list[-2]
  if token1 in operations:
    print("POSTFIX:")
    return postfix(expr)
  elif token1 == ')' or token2 in operations:
    print("INFIX:")
    return infix(expr)
  elif token2.isdigit():
    print("PREFIX:")
    return prefix(expr)

  print('EXPRESSION ERROR')
  return -1

# postfix(expr) - returns the answer of the postfix function
# O(n) - time complexity
# O(n) - space complexity
def postfix(expr) -> int:
  token_list = expr.split()
  for token in token_list:
    if token in operations:
      arg1 = stack.pop()
      arg2 = stack.pop()
      result = operate(token, arg1, arg2)
      stack.append(result)
    elif token == '(' or token == ')':
      continue
    else:
      stack.append(int(token))

  return stack.pop()

# prefix(expr) - returns the answer of the prefix function. Same as postfix, but reverses the expression first
def prefix(expr) -> int:
  return postfix(expr[::-1])

# infix(expr) - returns the answer of the infix function. Replace every ^ with **
def infix(expr) -> int:
  expr = expr.replace('^', '**')
  return eval(expr)

operations = ['^', '/', '*', '+', '-']

while True:
  expr = input('Enter an equation:\n')
  stack = []
  print(check_format(expr), '\n-------------')


# SPACE WAR GAME
# 07/01/2020
# Python 3.9
# MADE BY @TampellaGiacomo - credits: @TokyoEdTech

import os
import random
import turtle
import winsound
import time
import platform

turtle.fd(0)
turtle.speed(0)
turtle.bgcolor("black")
turtle.bgpic("bgp.gif")
turtle.ht()
turtle.setundobuffer(1)
turtle.tracer(0)

wn = turtle.Screen()
wn.title("Space Wars")
wn.register_shape("enemy.gif")
wn.register_shape("ally.gif")
wn.register_shape("player.gif")

# PLAY SOUND
def play_sound(sound_file, time = 0):
    winsound.PlaySound(sound_file, winsound.SND_ASYNC)

# SETTINGS
settings_pen = turtle.Turtle()
settings_pen.color("white")
settings_pen.penup()
settings_pen.setposition(-300, -370)
settingsstring = "Red: Enemies (HIT: +100pts, COLLISION: -100pts)\nOrange: Allies (HIT: -50pts)"
settings_pen.write(settingsstring, False, align="left", font=("Arial", 16, "bold"))
settings_pen.hideturtle()

class Sprite(turtle.Turtle):
    def __init__(self, spriteshape, color, startx, starty):
        turtle.Turtle.__init__(self, shape = spriteshape)
        self.speed(0)
        self.penup()
        self.color(color)
        self.fd(0)
        self.goto(startx, starty)
        self.speed = 1

    def move(self):
        self.fd(self.speed)

        # BOUNDARY DETECTION
        if self.xcor() > 290:
            self.setx(290)
            self.rt(60)

        if self.xcor() < -290:
            self.setx(-290)
            self.rt(60)

        if self.ycor() > 290:
            self.sety(290)
            self.rt(60)

        if self.ycor() < -290:
            self.sety(-290)
            self.rt(60)

    def is_collision(self, other):
        if (self.xcor() >= (other.xcor() - 20)) and \
        (self.xcor() <= (other.xcor() + 20)) and \
        (self.ycor() >= (other.ycor() - 20)) and \
        (self.ycor() <= (other.ycor() + 20)):
            return True
        else:
            return False

class Player(Sprite):
    def __init__(self, spriteshape, color, startx, starty):
        Sprite.__init__(self, spriteshape, color, startx, starty)
        self.speed = 4
        self.lives = 3

    def move_left():
        player.speed = -0.6

    def move_right():
        player.speed = 0.6

    def move_player():
        x = player.xcor()
        x += player.speed
        if x < -280:
            x = -280
        player.setx(x)
        if x > 280:
            x = 280
        player.setx(x)

    def accelerate(self):
        self.speed += 1

    def decelerate(self):
        self.speed -= 1

class Enemy(Sprite):
    def __init__(self, spriteshape, color, startx, starty):
        Sprite.__init__(self, spriteshape, color, startx, starty)
        self.speed = 6
        self.setheading(random.randint(0, 360))

class Ally(Sprite):
    def __init__(self, spriteshape, color, startx, starty):
        Sprite.__init__(self, spriteshape, color, startx, starty)
        self.speed = 8
        self.setheading(random.randint(0, 360))

    def move(self):
        self.fd(self.speed)

        # BOUNDARY DETECTION
        if self.xcor() > 290:
            self.setx(290)
            self.rt(60)

        if self.xcor() < -290:
            self.setx(-290)
            self.rt(60)

        if self.ycor() > 290:
            self.sety(290)
            self.rt(60)

        if self.ycor() < -290:
            self.sety(-290)
            self.rt(60)

class Missile(Sprite):
    def __init__(self, spriteshape, color, startx, starty):
        Sprite.__init__(self, spriteshape, color, startx, starty)
        self.shapesize(stretch_wid=0.3, stretch_len=0.4, outline=None)
        self.speed = 20
        self.status = "ready"
        self.goto(-1000, 1000)

    def fire(self):
        if self.status == "ready":
            # PLAY MISSILE SOUND
            play_sound("laser.wav")
            self.goto(player.xcor(), player.ycor())
            self.setheading(player.heading())
            self.status = "firing"

    def move(self):
        if self.status == "ready":
            self.goto(-1000, 1000)

        if self.status == "firing":
            self.fd(self.speed)

        # BORDER CHECK
        if self.xcor() < -290 or self.xcor() > 290 or \
            self.ycor() < -290 or self.ycor() > 290:
                self.goto(-1000, 1000)
                self.status = "ready"

class Game():
    def __init__(self):
        self.level = 1
        self.score = 0
        self.state = "playing"
        self.pen = turtle.Turtle()
        self.lives = 3

    def draw_border(self):
        #DRAW BORDER
        self.pen.speed(0)
        self.pen.color("white")
        self.pen.pensize(3)
        self.pen.penup()
        self.pen.goto(-300, 300)
        self.pen.pendown()
        for side in range (4):
            self.pen.fd(600)
            self.pen.rt(90)
        self.pen.penup()
        self.pen.ht()
        self.pen.pendown()

    def show_status(self):
        self.pen.undo()
        msg = "Score: %s" %(self.score)
        self.pen.penup()
        self.pen.goto(-450, 210)
        self.pen.write(msg, font=("Arial", 16, "normal"))

# CREATE GAME OBJECT
game = Game()
# DRAW THE GAME BORDER
game.draw_border()

# SHOW THE GAME STATUS
game.show_status()

#CREATE MY SPRITES
player = Player("triangle", "white", 0, 0)
# enemy = Enemy("circle", "red", -100, 0)
missile = Missile("triangle", "yellow", 0, 0)
# ally = Ally("square", "green", 100, 0)

enemies = []
for i in range(6):
    enemies.append(Enemy("enemy.gif","red", -100, 0))
    #enemies.shape("enemy.gif")

allies = []
for i in range(6):
    allies.append(Ally("ally.gif", "green", 100, 0))

# KEYBOARD BINDINGS
turtle.onkeypress(player.turn_left, "Left")
turtle.onkeypress(player.turn_right, "Right")
turtle.onkeypress(player.accelerate, "Up")
turtle.onkeypress(player.decelerate, "Down")
turtle.onkeypress(missile.fire, "space")

turtle.listen()
#MAIN GAME LOOP
while True:
    turtle.update()
    time.sleep(0.05)

    player.move()
    missile.move()
    for enemy in enemies:
        enemy.move()

        # CHECK FOR A COLLISION BETWEEN THE PLAYER AND THE ENEMY
        if player.is_collision(enemy):
            play_sound("explosion.wav")
            x = random.randint(-250, 250)
            y = random.randint(-250, 250)
            enemy.goto(x, y)
            game.score -= 100
            game.show_status()

            # CHECK FOR A COLLISION BETWEEN THE MISSILE AND THE ENEMY
        if missile.is_collision(enemy):
            play_sound("explosion.wav")
            x = random.randint(-250, 250)
            y = random.randint(-250, 250)
            enemy.goto(x, y)
            missile.status = "ready"
            # INCREASE THE SCORE
            game.score += 100
            game.show_status()

    for ally in allies:
        ally.move()

        # CHECK FOR A COLLISION BETWEEN THE MISSILE AND THE ALLY
        if missile.is_collision(ally):
            play_sound("explosion.wav")
            x = random.randint(-250, 250)
            y = random.randint(-250, 250)
            ally.goto(x, y)
            missile.status = "ready"
            # DECREASE THE SCORE
            game.score -= 50
            game.show_status()

delay = raw_input("Press enter to finish. > ")


class TreeNode:
    def __init__(self, *arr):
        self.val = 0
        self.left = None
        self.right = None

        values = []
        for i in arr:
            values.append(i)

        queue = []
        self.val = values.pop(0)
        queue.append(self)

        while len(values) > 0:
            size = len(values)
            for i in range(0, size):
                if (len(values)) == 0:
                    break

                node = queue.pop(0)
                if node is not None:
                    leftValue = values.pop(0)
                    if leftValue is not None:
                        node.left = TreeNode(leftValue)
                        queue.append(node.left)

                    rightValue = values.pop(0)
                    if rightValue is not None:
                        node.right = TreeNode(rightValue)
                        queue.append(node.right)

    def showTree(self):
        result = []
        tmp = self

        queue = []
        queue.append(tmp)

        while len(queue) > 0:
            size = len(queue)
            innerList = []

            for i in range(0, size):
                current = queue.pop(0)
                innerList.append(current.val)

                if current.left is not None:
                    queue.append(current.left)

                if current.right is not None:
                    queue.append(current.right)

            result.append(innerList)

        return result

    def showFlatTree(self):
        result = []

        queue = []
        queue.append(self)

        while len(queue) > 0:
            size = len(queue)
            for i in range(0, size):
                current = queue.pop(0)

                if current is not None:
                    result.append(current.val)

                    queue.append(current.left)
                    queue.append(current.right)
                else:
                    result.append("None")

        lastNone = -1
        for k, val in enumerate(result):
            if val == 'None':
                if lastNone == -1:
                    lastNone = k
            else:
                lastNone = -1

        if lastNone != -1:
            result = result[:lastNone]

        return result


# -*- coding: utf-8 -*-
#from https://stackoverflow.com/questions/2490334/simple-way-to-encode-a-string-according-to-a-password
key = 'FYLÄ,Xäcu2bÄLU!GECö3Qowo-lAfU7Pö'
import base64
def encode(clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc))

def decode(enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)


from pyrogram import Client, filters

import os

import jikanpy

# Create a new Pyrogram client object and connect to the Telegram API

app = Client(

    "Obanai_iguru_bot",

    api_id=os.environ.get("API_ID"),

    api_hash=os.environ.get("API_HASH"),

    bot_token=os.environ.get("BOT_TOKEN")

)

# Create a new Jikan API client object

jikan = jikanpy.Jikan()

# Handle the /start command

@app.on_message(filters.command("start"))

def start_handler(client, message):

    client.send_message(message.chat.id, "Hello, I am Obanai iguru Bot!")

# Handle the /anime and /manga commands

@app.on_message(filters.command(["anime", "manga"]))

def anime_handler(client, message):

    query = message.text.split(" ", 1)[1]

    anime = jikan.search("anime", query)["results"][0]

    title = anime["title"]

    synopsis = anime["synopsis"]

    url = anime["url"]

    response = f"{title}\n\n{synopsis}\n\n{url}"

    client.send_message(message.chat.id, response)

# Run the bot

app.run()


#calculating factorial
def fact(n):
    if(n==0):
        return 1
    return fact(n-1)*n

#using formula
def nCr(n,r):
    num=fact(n)
    den=fact(r)*fact(n-r)
    return num/den

#using recursion
def NCR(n,r):
    if(n==r or r==0):
        return 1
    return NCR(n-1,r-1)+NCR(n-1,r)

n=5
r=1
print(nCr(n,r))
print(NCR(n,r))


import matplotlib.pyplot as plt
import numpy as np

plt.style.use("seaborn")

f = open("./data/ethereum.csv", "r")

count = dict()
for line in f:
    count[line] = count.get(line, 0) + 1

raw_data = []
for k in count.values():
    raw_data.append(k)
data = [x / sum(raw_data) for x in raw_data]

top5 = sorted(count.items(), key=lambda item: item[1], reverse=True)[:5]

num_bins = 150

fig, ax = plt.subplots()

# the histogram of the data
n, bins, patches = ax.hist(data, num_bins, density=False)

# label
label = ["Ethermine", "f2pool2", "Hiveon Pool", "Spark Pool", "Nanopool"]
"""
for ((k, v), label_text) in zip(top5, label):
    x = v / sum(raw_data)
    y = -1
    ax.text(
        x,
        y,
        label_text,
        fontsize=5,
        horizontalalignment="center",
        verticalalignment="center",
    )
"""

# add a 'best fit' line
# mu = np.mean(data)
# sigma = np.std(data)
# y = (1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu)) ** 2)
# ax.plot(bins, y, "--")

# add a 'best fit' line
ax.set_xlabel("Ratio of hashing power (resource)", fontsize=24)
ax.set_ylabel("The number of participants", fontsize=24)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)

# exp = lambda x: 10 ** (x)
# log = lambda x: np.log(x)
# ax.set_yscale("function", functions=(exp, log))

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
fig.savefig("./results/ethereum_resource_distribution.png")
# plt.show()


from simtrees._setup_cfg import paths
from simfiles.configs.APOSTLE import (
    res_str,
    vol_str,
    phys_str,
    snap_id,
    machine,
)
from itertools import product

path_bases = {
    "cosma": "/cosma6/data/dp004/lg/snapshots_all/Merger_Trees",
}

snap = 127
for res, vol, phys in product(range(1, 4), range(1, 13), ["hydro", "DMO"]):
    if (res == 1) and (
        ((phys == "hydro") and (vol not in [1, 4, 6, 10, 11]))
        or ((phys == "DMO") and (vol not in [1, 4, 11]))
    ):
        continue

    fpath = "{:s}/{:s}_{:s}_{:s}/snapshots/treedir_{:03d}/".format(
        path_bases[machine], vol_str[vol], res_str[res], phys_str[phys], snap
    )
    fbase = "tree_{:03d}".format(snap)
    sfbase = "subfind_{:03d}".format(snap)
    paths[snap_id(res=res, phys=phys, vol=vol, snap=snap)] = (
        fpath,
        fbase,
        sfbase,
    )


import xml.etree.ElementTree as ET
from pathlib import Path

import fire
import pandas as pd
from tqdm import tqdm

# pd.set_option("display.max_colwidth", None)
pd.set_option("display.unicode.east_asian_width", True)
pd.set_option("display.unicode.ambiguous_as_wide", True)
pd.set_option("display.max_rows", None)
# pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", 15)

TAGNAMES = {
    "d": "Disease",
    "a": "Anatomical",
    "f": "Feature",
    "c": "Change",
    "timex3": "TIMEX3",
    "t-test": "TestTest",
    "t-key": "TestKey",
    "t-val": "TestVal",
    "m-key": "MedicineKey",
    "m-val": "MedicineVal",
    "cc": "ClinicalContext",
    "r": "Remedy",
    "p": "Pending",
}

# TODO: Relation!

def len_null(a):
    """Return length of the input even if it is None (=> 0)."""
    return 0 if a is None else len(a)

def get_plain_text(root):
    """Get a plain, bare text of an XML-tagged text."""
    return "".join(root.itertext()).lstrip()

def root_to_df(root, plain_text):
    """Convert an XML object to Table."""
    data = []
    data_r = []
    # NOTE: assume that non-PRISM tags don't appear between <root>...<[first PRISM tag]>
    root.text = root.text.lstrip() if root.text else None
    root.tail = None
    csr = len(root.text) if root.text else 0
    for e in root.iter():
        if e.tag.lower() in TAGNAMES:
            st, ed = csr, csr + len(e.text) if e.text else csr
            orig_snip = plain_text[st:ed]
            tag_datum = [
                e.tag,
                e.attrib,
                e.text,
                e.tail,
                st,
                ed,
                repr(orig_snip),
                e.text == orig_snip,
            ]
            if "tid" in e.attrib:
                tag_datum.insert(0, int(e.attrib["tid"][1:]))
                del e.attrib["tid"]
            data.append(tag_datum)
            csr += len_null(e.text) + len_null(e.tail)
        if e.tag == "brel":
            data_r.append(
                [
                    int(e.attrib["rid"][1:]),
                    e.attrib["reltype"],
                    int(e.attrib["arg1"][1:]),
                    int(e.attrib["arg2"][1:]),
                ]
            )
        # else:
        #     # some unknown tags exist
        #     # TODO: to make this procedure robust
    header = [
        "tag",
        "attrib",
        "text",
        "tail",
        "start_pos",
        "end_pos",
        "orig",
        "matchOrig",
    ]
    if len(header) + 1 == len(data[0]):
        header.insert(0, "tid")
    df = pd.DataFrame(data, columns=header)
    assert df["matchOrig"].all(), "\n" + str(df)
    header_r = ["rid", "reltype", "arg1", "arg2"]
    df_r = pd.DataFrame(data_r, columns=header_r)
    return df, df_r

def row_to_tagstr(row):
    """Convert a Table row to ANN's Tag format"""
    id_ = row.tid if "tid" in row else row.name
    if "\n" not in row.text:  # assume #\n == 1 (more than that is illegal)
        return f"T{id_}\t{TAGNAMES[row.tag.lower()]} {row.start_pos} {row.end_pos}\t{row.text}"
    n_pos = row.text.find("\n")
    fend_pos = row.start_pos + n_pos
    sstart_pos = fend_pos + 1
    text_ = row.text.replace("\n", " ")
    return f"T{id_}\t{TAGNAMES[row.tag.lower()]} {row.start_pos} {fend_pos};{sstart_pos} {row.end_pos}\t{text_}"

def df_to_tagstrs(df):
    """Convert all entities in a whole Table to ANN-formatted strings."""
    return df.apply(
        row_to_tagstr,
        axis=1,
    ).to_list()

def row_to_attrstr(row):
    """Convert a Table row to ANN's Attribute format"""
    id_ = row.tid if "tid" in row else row["index"]
    key, val = list(row.attrib.items())[0]
    return f"A{row.name + 1}\t{key} T{id_} {val}"

def df_to_attrstrs(df):
    """Convert all attribute info in a whole Table to ANN-formatted strings."""
    return (
        df[df.attrib != {}]
        .reset_index()  # to generate attr IDs
        .apply(
            row_to_attrstr,
            axis=1,
        )
        .to_list()
    )

def row_to_relstr(row):
    """Convert a Table row to ANN's Relation format"""
    return f"R{row.rid}\t{row.reltype} Arg1:T{row.arg1} Arg2:T{row.arg2}"

def df_to_relstrs(df_r):
    """Convert all relations to ANN-formatted strings."""
    return df_r.apply(row_to_relstr, axis=1).to_list()

def get_first_child(elem):
    """Get the first child of an XML Element"""
    it = elem.iter()
    next(it)  # == elem itself
    return next(it)

def get_real_root(elem):
    """Get the 'real' root element.
    This returns the direct parent that contains the PRISM tags.
    """
    child = get_first_child(elem)
    return elem if child.tag.lower() in TAGNAMES.keys() else get_real_root(child)

def main(dirpath, output_path, trav=False):
    """MAIN."""
    p = Path(dirpath)
    assert p.is_dir()
    p_lst = list(p.iterdir())
    outp = Path(output_path)
    if not outp.exists():
        outp.mkdir()
    for i in tqdm(p_lst):
        if i.name.startswith("."):
            continue
        if i.is_file() and i.suffix == ".xml":
            try:
                root = ET.parse(i).getroot()
                # if wrapped further by metadata elements like PERSON, ARTICLE
                # need to find the real "root"
                root = get_real_root(root)
            except ET.ParseError:
                with open(i, "r") as f:
                    cont = f.read()
                try:
                    root = ET.fromstring(f"<root>{cont}</root>")
                except ET.ParseError as e:
                    print()
                    print()
                    print("Error occured in:", i)
                    raise e
            plain_text = get_plain_text(root)
            try:
                df, df_r = root_to_df(root, plain_text)
            except AssertionError as e:
                print()
                print()
                print("Error occured in:", i)
                raise e
            tagstrs = df_to_tagstrs(df)
            attrstrs = df_to_attrstrs(df)
            relstrs = df_to_relstrs(df_r)
            with open(outp / i.with_suffix(".ann").name, "w") as outf:
                outf.write("\n".join(tagstrs + attrstrs + relstrs))
            with open(outp / i.with_suffix(".txt").name, "w") as outf:
                outf.write(plain_text)
        if i.is_dir() and trav:
            print("Dig into a child folder:", str(i))
            main(str(i), output_path)

if __name__ == "__main__":
    fire.Fire(main)
    # NOTE: only compatible with the 1-doc-per-file format


class Solution:
    def buddyStrings(self, A: str, B: str) -> bool:
        if len(A) != len(B):
            return False

        dup = set()
        if A == B:
            for a in A:
                if a in dup:
                    return True

                dup.add(a)

            return False

        ilist = []
        for i in range(len(A)):
            if A[i] != B[i]:
                ilist += [i]

        if len(ilist) > 2:
            return False

        if A[ilist[0]] == B[ilist[1]] and A[ilist[1]] == B[ilist[0]]:
            return True

        return False


"""Add watering timestamp

Revision ID: a4aa0f43b257
Revises: 56a2f2c760af
Create Date: 2021-01-05 17:08:24.522331

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "a4aa0f43b257"
down_revision = "56a2f2c760af"
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("plants", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column(
                "last_watering",
                sa.DateTime(),
                server_default=sa.text("CURRENT_TIMESTAMP"),
                nullable=False,
            )
        )

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("plants", schema=None) as batch_op:
        batch_op.drop_column("last_watering")

    # ### end Alembic commands ###


import pygame
import random
from forme import *

pygame.font.init()

# Variables
WIDTH = 1080
HEIGHT = 720
running = True
click = False
clock = pygame.time.Clock()

# colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (220, 0, 0)
GREEN = (0, 220, 0)
BLUE = (0, 0, 255)
DARKGRAY = (40, 40, 40)
PURPLE = (120, 0, 120)
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')

# Information fusée C pour le coefficient et S la surface sur la base de notre fusée à eau
cubeC = 0.8
cubeS = 0.10**2
cubeVolume = (0.10**2) * 0.38 #La même hauteur que la bouteille
cube = Forme(cubeC,cubeS,cubeVolume)

balleC = 0.3
balleS = 3.1415 * 0.05**2
balleVolume = 3.1415 * (0.05**2) * 0.30 + 1/3 * 3.1415 * 0.08 * 0.05**2
balle = Forme(balleC,balleS,balleVolume)

coneC = 0.5
coneS = 3.1415 * 0.05**2
coneVolume = 3.1415 * 0.38 * 0.05**2
cone = Forme(coneC,coneS,coneVolume)

cylindreC = 0.85
cylindreS = 3.1415 * 0.05**2
cylindreVolume = 3.1415 * (0.05**2) * 0.38
cylindre = Forme(cylindreC,cylindreS,cylindreVolume)

sphereC = 0.47
sphereS = 3.1415 * 0.05**2
sphereVolume = 4/3 * 3.1415 * 0.05**3
sphere = Forme(sphereC,sphereS,sphereVolume)

pyramideC = 1.55
pyramideS = 0.10**2
pyramideVolume = 1/3 * (0.10**2) * 0.38
pyramide = Forme(pyramideC,pyramideS,pyramideVolume)

bouteilleC = 0.52
bouteilleS =3.1415 * 0.05**2
bouteilleVolume = 0.002
bouteille = Forme(bouteilleC,bouteilleS,bouteilleVolume)

# charcher les polices
police = pygame.font.Font(None, 50)
police_subtitle = pygame.font.Font(None, 25)
mini_police = pygame.font.Font(None, 20)
mega_police = pygame.font.Font(None, 150)
FONT = pygame.font.Font(None, 32)

# charcher les images
rocket_img = pygame.image.load('img/rocket_bouteille.png')
rocket_img_bouteille = pygame.image.load('img/rocket_bouteille.png')
rocket_img_balle = pygame.image.load('img/rocket_balle.png')
rocket_img_cone = pygame.image.load('img/rocket_cone.png')
rocket_img_cube = pygame.image.load('img/rocket_cube.png')
rocket_img_sphere = pygame.image.load('img/rocket_sphere.png')
rocket_img_cylindre = pygame.image.load('img/rocket_cylindre.png')
rocket_img_pyramide = pygame.image.load('img/rocket_pyramide.png')

# Tranformations des images
rocket_img_bouteille = pygame.transform.scale(rocket_img_bouteille, (64, 64))
rocket_img_balle = pygame.transform.scale(rocket_img_balle, (64, 64))
rocket_img_cone = pygame.transform.scale(rocket_img_cone, (64, 64))
rocket_img_cube = pygame.transform.scale(rocket_img_cube, (64, 64))
rocket_img_sphere = pygame.transform.scale(rocket_img_sphere, (64, 64))
rocket_img_cylindre = pygame.transform.scale(rocket_img_cylindre, (64, 64))
rocket_img_pyramide = pygame.transform.scale(rocket_img_pyramide, (64, 64))

sky_img = pygame.image.load('img/SKY.png')
dirt_img = pygame.image.load('img/dirt.png')

rocket_imgX, rocket_imgY = rocket_img.get_size()
dirt_imgX, dirt_imgY = dirt_img.get_size()

# Variables pour le placement des images
dirt_placementY = 410
rocket_placementX = 450

def draw_text(text, font, color, surface, x, y):
    # modules pour afficher du texte

    textobj = font.render(text, 1, color)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

class InputBox:
    # Inputbox de SKRX trouver sur GitHub
    def __init__(self, x, y, w, h, text=''):
        self.rect = pygame.Rect(x, y, w, h)
        self.color = COLOR_INACTIVE
        self.text = text
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the user clicked on the input_box rect.
            if self.rect.collidepoint(event.pos):
                # Toggle the active variable.
                self.active = not self.active
            else:
                self.active = False
            # Change the current color of the input box.
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    print(self.text)
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode
                # Re-render the text.
                self.txt_surface = FONT.render(self.text, True, self.color)

    def update(self):
        # Resize the box if the text is too long.
        width = max(200, self.txt_surface.get_width()+10)
        self.rect.w = width

    def draw(self, screen):
        # Blit the text.
        screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
        # Blit the rect.
        pygame.draw.rect(screen, self.color, self.rect, 2)

particles = []
def Particles(x, y, surface, color):
    # classe particules

    particles.append([[x, y], [random.randint(0, 20) / 10 - 1.5, + 4], random.randint(4, 6)])
    for particle in particles:
        particle[0][0] += particle[1][0]
        particle[0][1] += particle[1][1]
        particle[2] -= 0.1
        particle[1][1] += 0.1
        pygame.draw.circle(surface, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
        if particle[2] <= 0:
            particles.remove(particle)

class buttons():
    def __init__(self, x, y, nomMethode, list, text=''):
        self.rect = pygame.Rect(x, y , 30, 30)
        self.nomMethode = nomMethode
        self.color = WHITE
        self.text = text
        self.list = list
        self.active = 0

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the user clicked on the box rect.
            if self.rect.collidepoint(event.pos) and self.active == 0:
                # Toggle the active variable.
                self.color = GREEN
                self.active = 1
                self.list.append(self.nomMethode)

            elif self.rect.collidepoint(event.pos) and self.active == 1:
                self.color = WHITE
                self.list.remove(self.nomMethode)
                self.active = 0

    def draw(self, screen):
        # Blit the text.
        draw_text(self.text, police_subtitle, WHITE, screen, self.rect.x - 10, self.rect.y + 40)
        # Blit the rect.
        pygame.draw.rect(screen, self.color, self.rect)

def Rot_center(image, angle):
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image


import sys, getopt
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import socket

def main(argv):
	type = 0	#1=ICMP, 2=SYN
	portString = "80"
	host = argv[len(argv)-1]
	argv = argv[:((len(argv))-1)]

	#Convert host to an IP if it isn't
	hostCheckArr = host.split(".")
	if(len(hostCheckArr) != 4):
		#This is a domain name: Convert to IP
		try:
			host = socket.gethostbyname(host)
		except:
			sys.exit("Invalid host domain")
		#Prepare to check if found IP is valid
		hostCheckArr = host.split(".")
	#Check formatting of IP Address
	if(len(hostCheckArr) == 4):
		isValidIP = True
		validNum = 256
		for num in hostCheckArr:
			num = num.strip()
			try:
				#Convert String to Integer (If it is one)
				validNum = int(num)
			except:
				print("Part of IP is not an int - Failure:", sys.exc_info()[0])
				isValidIP = False
				break
			if(not(validNum >= 0 and validNum < 256)):
				print("IP part not within range of 0-255 - Failure")
				isValidIP = False
				break
		if(not isValidIP):
			sys.exit("Invalid host IP or Domain")
	else:
		sys.exit("Invalid Host IP or domain")
	#IP must be valid if code gets here
	#begin parsing other arguments
	try:
		opts, args = getopt.getopt(argv,"",["p=", "ICMP","SYN"])
	except getopt.GetoptError:
		sys.exit("INVALID INPUT: Correct arguments and try again")

	for opt, arg in opts:
		if opt == "--ICMP":
			if type != 0:
				sys.exit("Invalid Input: Only chose ICMP OR SYN")
			type=1
		elif opt == "--SYN":
			if type != 0:
				sys.exit("Invalid Input: Only chose ICMP OR SYN")
			type=2
		elif opt == "--p":
			portString = arg
	if type == 0:
		sys.exit("Invalid Input: Specify ICMP OR SYN")

	if type == 1:
		#Non-Stealth Scan
		try:
			p=sr1(IP(dst=host)/ICMP(), timeout=10)
			if p:
				print("ICMP scan: Machine Found")
			else:
				print("ICMP scan: Machine Not Found")

		except Exception:
			#port Closed
			print("ICMP scan: Machine Not Found")
	else:
		portSets = portString.split(',')
		trimedPortSets = []
		for part in portSets:
			trimedPortSets.append(part.strip())
		#Open ports will be put here
		openPorts = []
		#Run through all ports wanted
		for ports in trimedPortSets:
			if '-' in ports:
				nums = ports.split("-")
				start = nums[0]
				end = nums[1]
				#range of ports
				for testPort in range(int(start), (int(end)+1)):
					if(checkPort(testPort, host)):
						openPorts.append(testPort)
			else:
				#Just a single port number
				if(checkPort(int(ports), host)):
					openPorts.append(int(ports))
		print("Open Ports:", openPorts)

#Takes destination port, destination IP, and scan type and checks if port is open (1-ICMP, 2=SYN)
def checkPort(port, ip):

	dst_ip = ip
	src_port = RandShort()
	dst_port=port
	isItOpen = False

	#Stealth Scan
	stealth_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=3)
	if(stealth_scan_resp==None):
		#Filtered
		print("Port Closed: ", dst_port)
	elif(stealth_scan_resp.haslayer(TCP)):
		if(stealth_scan_resp.getlayer(TCP).flags == 0x12):
			send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="R"),timeout=3)
			#Port is Open
			print("Port Open ", dst_port)
			isItOpen = True
		elif (stealth_scan_resp.getlayer(TCP).flags == 0x14):
			#Port Closed
			print("Port Closed: ", dst_port)
	elif(stealth_scan_resp.haslayer(ICMP)):
		if(int(stealth_scan_resp.getlayer(ICMP).type)==3 and int(stealth_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
			#Filtered
			print("Port Open: ", dst_port)
			isItOpen = True
	#retuns whether stealth scan method found the port to be open
	return isItOpen

if __name__ == "__main__":
	main(sys.argv[1:])


import moviepy.editor as mp
import logging
import os

from app.settings.config import settings

async def convert_video(input_filename: str, output_format: str, temp_folder: str, name_file: str) -> str:
    """
    Функція, що конвертує файл в розширення output_format та повертає шлях до результуючого файлу
    :param input_filename: шлях до файлу
    :param output_format: розширення, в яке потрібно конвертувати
    :return: шлях до конвертованого файла
    """
    try:
        video = mp.VideoFileClip(input_filename)
        output_file = f"{temp_folder}{name_file}.{output_format}"
        video.write_videofile(output_file, codec=(lambda output_format: {
                                'mp4': 'libx264',
                                'ogv': 'libtheora',
                                'webm': 'libvpx',
                                'ogg': 'libtheora',
                                'mp3': 'pcm_s16le',
                                'wav': 'libvorbis',
                                'm4a': 'libfdk_aac',
                            }.get(format, 'libx264'))(output_format))
        logging.info('Відео файл було конвертовано успішно')

        return output_file

    except Exception as e:
        logging.error(f'Файл {input_filename} не був конвертований, detils: {e}')
        return None


a, b = map(int, input().split())
ans = 0

def select_button(a, b):
    ten = abs(abs(b-a)-10)
    five = abs(abs(b-a)-5)
    one = abs(abs(b-a)-1)

    return min(ten, five, one)

def neg(a, b):
    if b>a:
        return -1
    else:
        return 1

while abs(b-a)!=0:
    ans += 1
    a = b+select_button(a, b)

print(ans)


from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import six

from google.appengine.ext import ndb

from dashboard import alerts
from dashboard.api import api_request_handler
from dashboard.api import utils as api_utils
from dashboard.common import descriptor
from dashboard.common import timing
from dashboard.common import utils
from dashboard.models import anomaly
from dashboard.models import graph_data
from dashboard.models import histogram

# These limits should prevent DeadlineExceededErrors.
# TODO(benjhayden): Find a better strategy for staying under the deadline.
DIAGNOSTICS_QUERY_LIMIT = 10000
HISTOGRAMS_QUERY_LIMIT = 1000
ROWS_QUERY_LIMIT = 20000

COLUMNS_REQUIRING_ROWS = {'timestamp', 'revisions',
                          'annotations'}.union(descriptor.STATISTICS)

from flask import request

def _CheckUser():
  pass

@api_request_handler.RequestHandlerDecoratorFactory(_CheckUser)
def TimeSeries2Post():
  desc = descriptor.Descriptor(
      test_suite=request.values.get('test_suite'),
      measurement=request.values.get('measurement'),
      bot=request.values.get('bot'),
      test_case=request.values.get('test_case'),
      statistic=request.values.get('statistic', None),
      build_type=request.values.get('build_type'))
  min_revision = request.values.get('min_revision')
  min_revision = int(min_revision) if min_revision else None
  max_revision = request.values.get('max_revision')
  max_revision = int(max_revision) if max_revision else None
  query = TimeseriesQuery(
      desc,
      request.values.get('columns').split(','), min_revision, max_revision,
      api_utils.ParseISO8601(request.values.get('min_timestamp', None)),
      api_utils.ParseISO8601(request.values.get('max_timestamp', None)))
  try:
    result = query.FetchSync()
  except AssertionError as e:
    # The caller has requested internal-only data but is not authorized.
    six.raise_from(api_request_handler.NotFoundError, e)
  return result

class TimeseriesQuery:

  def __init__(self,
               desc,
               columns,
               min_revision=None,
               max_revision=None,
               min_timestamp=None,
               max_timestamp=None):
    self._descriptor = desc
    self._columns = columns
    self._min_revision = min_revision
    self._max_revision = max_revision
    self._min_timestamp = min_timestamp
    self._max_timestamp = max_timestamp
    self._statistic_columns = []
    self._unsuffixed_test_metadata_keys = []
    self._test_keys = []
    self._test_metadata_keys = []
    self._units = None
    self._improvement_direction = None
    self._data = {}
    self._private = False

  @property
  def private(self):
    return self._private

  @timing.TimeWall('fetch')
  @timing.TimeCpu('fetch')
  def FetchSync(self):
    return self.FetchAsync().get_result()

  @ndb.tasklet
  def FetchAsync(self):
    """Returns {units, improvement_direction, data}.

    Raises:
      api_request_handler.NotFoundError when the timeseries cannot be found.
      AssertionError when an external user requests internal-only data.
    """
    # Always need to query TestMetadata even if the caller doesn't need units
    # and improvement_direction because Row doesn't have internal_only.
    # Use tasklets so that they can process the data as it arrives.
    self._CreateTestKeys()
    futures = [self._FetchTests()]
    if COLUMNS_REQUIRING_ROWS.intersection(self._columns):
      futures.append(self._FetchRows())
    elif 'histogram' in self._columns:
      futures.append(self._FetchHistograms())
    if 'alert' in self._columns:
      self._ResolveTimestamps()
      futures.append(self._FetchAlerts())
    if 'diagnostics' in self._columns:
      self._ResolveTimestamps()
      futures.append(self._FetchDiagnostics())
    yield futures
    raise ndb.Return({
        'units':
            self._units,
        'improvement_direction':
            self._improvement_direction,
        'data': [[datum.get(col)
                  for col in self._columns]
                 for _, datum in sorted(self._data.items())],
    })

  def _ResolveTimestamps(self):
    if self._min_timestamp and self._min_revision is None:
      self._min_revision = self._ResolveTimestamp(self._min_timestamp)
    if self._max_timestamp and self._max_revision is None:
      self._max_revision = self._ResolveTimestamp(self._max_timestamp)

  def _ResolveTimestamp(self, timestamp):
    query = graph_data.Row.query(
        graph_data.Row.parent_test.IN(self._test_keys),
        graph_data.Row.timestamp <= timestamp)
    query = query.order(-graph_data.Row.timestamp)
    row_keys = query.fetch(1, keys_only=True)
    if not row_keys:
      return None
    return row_keys[0].integer_id()

  def _CreateTestKeys(self):
    desc = self._descriptor.Clone()

    self._statistic_columns = [
        col for col in self._columns if col in descriptor.STATISTICS
    ]
    if desc.statistic and desc.statistic not in self._statistic_columns:
      self._statistic_columns.append(desc.statistic)

    desc.statistic = None
    unsuffixed_test_paths = desc.ToTestPathsSync()
    self._unsuffixed_test_metadata_keys = [
        utils.TestMetadataKey(path) for path in unsuffixed_test_paths
    ]

    test_paths = []
    for statistic in self._statistic_columns:
      desc.statistic = statistic
      test_paths.extend(desc.ToTestPathsSync())

    self._test_metadata_keys = [
        utils.TestMetadataKey(path) for path in test_paths
    ]
    self._test_metadata_keys.extend(self._unsuffixed_test_metadata_keys)
    test_paths.extend(unsuffixed_test_paths)

    test_old_keys = [utils.OldStyleTestKey(path) for path in test_paths]
    self._test_keys = test_old_keys + self._test_metadata_keys

  @ndb.tasklet
  def _FetchTests(self):
    # Don't fetch OldStyleTestKeys. The Test model has been removed. Only fetch
    # TestMetadata entities.
    with timing.WallTimeLogger('fetch_tests'):
      tests = yield [key.get_async() for key in self._test_metadata_keys]
    tests = [test for test in tests if test]
    if not tests:
      raise api_request_handler.NotFoundError

    improvement_direction = None
    for test in tests:
      if test.internal_only:
        self._private = True

      test_desc = yield descriptor.Descriptor.FromTestPathAsync(
          utils.TestPath(test.key))
      # The unit for 'count' statistics is trivially always 'count'. Callers
      # certainly want the units of the measurement, which is the same as the
      # units of the 'avg' and 'std' statistics.
      if self._units is None or test_desc.statistic != 'count':
        self._units = test.units
        improvement_direction = test.improvement_direction

    if improvement_direction == anomaly.DOWN:
      self._improvement_direction = 'down'
    elif improvement_direction == anomaly.UP:
      self._improvement_direction = 'up'
    else:
      self._improvement_direction = None

  def _Datum(self, revision):
    return self._data.setdefault(revision, {'revision': revision})

  @ndb.tasklet
  def _FetchRows(self):
    yield [self._FetchRowsForTest(test_key) for test_key in self._test_keys]

  @staticmethod
  def Round(x):
    return round(x, 6)

  def _RowQueryProjection(self, statistic):
    limit = ROWS_QUERY_LIMIT
    projection = None

    # revisions and annotations are not in any index, so a projection query
    # can't get them.
    if 'revisions' in self._columns or 'annotations' in self._columns:
      return projection, limit

    # Disable projection queries for timestamp for now. There's just an index
    # for ascending revision, not descending revision with timestamp.
    if 'timestamp' in self._columns:
      return projection, limit

    # There is no index like (parent_test, -timestamp, revision, value):
    self._ResolveTimestamps()

    # If statistic is not None, then project value. _CreateTestKeys will
    # generate test keys for the other statistics in columns if there are any.
    # If statistic is None and the only statistic is avg, then project value.
    # If statistic is None and there are multiple statistics, then fetch full
    # Row entities because we might need their 'error' aka 'std' or
    # 'd_'-prefixed statistics.
    if ((statistic is not None)
        or (','.join(self._statistic_columns) == 'avg')):
      projection = ['revision', 'value']
      if 'timestamp' in self._columns:
        projection.append('timestamp')
      limit = None

    return projection, limit

  @ndb.tasklet
  def _FetchRowsForTest(self, test_key):
    test_desc = yield descriptor.Descriptor.FromTestPathAsync(
        utils.TestPath(test_key))
    projection, limit = self._RowQueryProjection(test_desc.statistic)
    query = graph_data.Row.query(projection=projection)
    query = query.filter(graph_data.Row.parent_test == test_key)
    query = self._FilterRowQuery(query)

    with timing.WallTimeLogger('fetch_test'):
      rows = yield query.fetch_async(limit)

    with timing.CpuTimeLogger('rows'):
      for row in rows:
        # Sometimes the dev environment just ignores some filters.
        if self._min_revision and row.revision < self._min_revision:
          continue
        if self._min_timestamp and row.timestamp < self._min_timestamp:
          continue
        if self._max_revision and row.revision > self._max_revision:
          continue
        if self._max_timestamp and row.timestamp > self._max_timestamp:
          continue
        datum = self._Datum(row.revision)
        if test_desc.statistic is None:
          datum['avg'] = self.Round(row.value)
          if hasattr(row, 'error') and row.error:
            datum['std'] = self.Round(row.error)
        else:
          datum[test_desc.statistic] = self.Round(row.value)
        for stat in self._statistic_columns:
          if hasattr(row, 'd_' + stat):
            datum[stat] = self.Round(getattr(row, 'd_' + stat))
        if 'timestamp' in self._columns:
          datum['timestamp'] = row.timestamp.isoformat()
        if 'revisions' in self._columns:
          datum['revisions'] = {
              attr: value
              for attr, value in row.to_dict().items()
              if attr.startswith('r_')
          }
        if 'annotations' in self._columns:
          datum['annotations'] = {
              attr: value
              for attr, value in row.to_dict().items()
              if attr.startswith('a_')
          }

    if 'histogram' in self._columns and test_desc.statistic == None:
      with timing.WallTimeLogger('fetch_histograms'):
        yield [self._FetchHistogram(test_key, row.revision) for row in rows]

  def _FilterRowQuery(self, query):
    if self._min_revision or self._max_revision:
      if self._min_revision:
        query = query.filter(graph_data.Row.revision >= self._min_revision)
      if self._max_revision:
        query = query.filter(graph_data.Row.revision <= self._max_revision)
      query = query.order(-graph_data.Row.revision)  # pylint: disable=invalid-unary-operand-type
    elif self._min_timestamp or self._max_timestamp:
      if self._min_timestamp:
        query = query.filter(graph_data.Row.timestamp >= self._min_timestamp)
      if self._max_timestamp:
        query = query.filter(graph_data.Row.timestamp <= self._max_timestamp)
      query = query.order(-graph_data.Row.timestamp)
    else:
      query = query.order(-graph_data.Row.revision)  # pylint: disable=invalid-unary-operand-type
    return query

  @ndb.tasklet
  def _FetchAlerts(self):
    anomalies, _, _ = yield anomaly.Anomaly.QueryAsync(
        test_keys=self._test_keys,
        max_start_revision=self._max_revision,
        min_end_revision=self._min_revision)
    for alert in anomalies:
      if alert.internal_only:
        self._private = True
      datum = self._Datum(alert.end_revision)
      # TODO(benjhayden) bisect_status
      datum['alert'] = alerts.AnomalyDicts([alert], v2=True)[0]

  @ndb.tasklet
  def _FetchHistograms(self):
    yield [self._FetchHistogramsForTest(test) for test in self._test_keys]

  @ndb.tasklet
  def _FetchHistogramsForTest(self, test):
    query = graph_data.Row.query(graph_data.Row.parent_test == test)
    query = self._FilterRowQuery(query)
    with timing.WallTimeLogger('fetch_histograms'):
      row_keys = yield query.fetch_async(HISTOGRAMS_QUERY_LIMIT, keys_only=True)
      yield [
          self._FetchHistogram(test, row_key.integer_id())
          for row_key in row_keys
      ]

  @ndb.tasklet
  def _FetchHistogram(self, test, revision):
    query = histogram.Histogram.query(
        histogram.Histogram.test == utils.TestMetadataKey(test),
        histogram.Histogram.revision == revision)
    hist = yield query.get_async()
    if hist is None:
      return
    if hist.internal_only:
      self._private = True
    self._Datum(hist.revision)['histogram'] = hist.data

  @ndb.tasklet
  def _FetchDiagnostics(self):
    with timing.WallTimeLogger('fetch_diagnosticss'):
      yield [
          self._FetchDiagnosticsForTest(test)
          for test in self._unsuffixed_test_metadata_keys
      ]

  @ndb.tasklet
  def _FetchDiagnosticsForTest(self, test):
    query = histogram.SparseDiagnostic.query(
        histogram.SparseDiagnostic.test == test)
    if self._min_revision:
      query = query.filter(
          histogram.SparseDiagnostic.start_revision >= self._min_revision)
    if self._max_revision:
      query = query.filter(
          histogram.SparseDiagnostic.start_revision <= self._max_revision)
    query = query.order(-histogram.SparseDiagnostic.start_revision)
    diagnostics = yield query.fetch_async(DIAGNOSTICS_QUERY_LIMIT)
    for diag in diagnostics:
      if diag.internal_only:
        self._private = True
      datum = self._Datum(diag.start_revision)
      datum_diags = datum.setdefault('diagnostics', {})
      datum_diags[diag.name] = diag.data


#import stdin from sys to take faster input
from sys import stdin
input = stdin.readline

#run a for loop for the amount of 3 by 3 squares
for _ in range(int(input())):
    square = [] #set an array to store the numbers in every square
    for row in range(3): #append the 3 rows into the array
        square.append(list(map(int, input().split())))
    for i in range(3): #run a for-else loop that runs three times
        if square[i][0]-square[i][1] == square[i][1]-square[i][2]: #check if i-th row is arithmetic
            if square[0][i]-square[1][i] == square[1][i]-square[2][i]: #check if i-th column is arithmetic
                continue #if both conditions pass, move onto next row and column
        print('NO') #otherwise print NO and break
        break
    else: #if for loop never broke, then all rows and columns are arithmetic, so print YES
        print('YES')


import csv

def findPos(gameState, number):
    for i in range(0, 16):
        if gameState[i] == number:
            return i
    return -1

with open("output.csv", "w+", newline='') as csvfile:
    fieldnames = ["ID", "STATE", "Blank position", "Top row", "Bottom row", "Manhattan", "First column", "Last column", "Neighbours"]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for jj in range(1, 101):
        if jj == 14 or jj == 17 or jj == 22 or jj == 49 or jj == 60 or jj == 82 or jj == 99:
            continue
        row = {"ID": str(jj)}
        file_path = "runs-00001-00100/00"
        if jj < 100:
            file_path += "0"
            if jj < 10:
                file_path += "0"
        file_path += str(jj) + "/run.log"
        file = open(file_path, "r")
        lines = file.readlines()
        lines = lines[-6:-2]
        gameState = []
        for i in range(0, 4):
            gameState.append(int(lines[i][1:3]))
            gameState.append(int(lines[i][4:6]))
            gameState.append(int(lines[i][7:9]))
            gameState.append(int(lines[i][10:12]))
        row["STATE"] = ', '.join(map(str, gameState))

        # 0 middle, edge or corner
        zeroPos = findPos(gameState, 0)
        if zeroPos == 0 or zeroPos == 3 or zeroPos == 12 or zeroPos == 15:
            row["Blank position"] = "corner"
        elif zeroPos < 4 or zeroPos > 11:
            row["Blank position"] = "edge"
        else:
            row["Blank position"] = "middle"

        # average top and bottom row
        avgTop = (gameState[0] + gameState[1] + gameState[2] + gameState[3]) / 4
        avgBottom = (gameState[12] + gameState[13] + gameState[14] + gameState[15]) / 4
        row["Top row"] = avgTop
        row["Bottom row"] = avgBottom

        # Manhattan distance
        totalDist = 0
        for pos in range(0, 16):
            val = gameState[pos]
            yCurr = int(pos/4)
            xCurr = pos - yCurr * 4
            yGoal = int(val/4)
            xGoal = val - yGoal * 4
            totalDist += abs(yCurr - yGoal) + abs(xCurr - xGoal)
        totalDist = totalDist / 16
        row["Manhattan"] = totalDist

        # first and last column modulo 4
        firstColumn = 0
        lastColumn = 0
        for i in range(0, 4):
            firstColumn += gameState[i * 4] % 4
            lastColumn += gameState[i * 4 + 3] % 4
        firstColumn = firstColumn / 4
        lastColumn = lastColumn / 4
        row["First column"] = firstColumn
        row["Last column"] = lastColumn

        # differences to neighbours
        differences = 0
        for i in range(0, 16):
            if not i % 4 == 0:    # left
                differences += abs(gameState[i] - gameState[i-1])
            if not i < 4:   # down
                differences += abs(gameState[i] - gameState[i - 4])
        differences = differences / 24
        row["Neighbours"] = differences
        writer.writerow(row)
        print("Done with: " + str(jj))

python parser + raw data/project/parser.py


def calculate_flange_coupling(power, speed, service_factor):
    # Given permissible stresses
    shear_stress_shaft_bolt_key = 50  # MPa
    crushing_stress_bolt_key = 80  # MPa
    shear_stress_cast_iron = 8  # MPa

    # Handling zero speed input
    while speed == 0:
        print("Speed cannot be zero. Please enter a non-zero value.")
        speed = float(input("Enter speed (rpm): "))

    # Handling zero service factor input
    while service_factor == 0:
        print("Service factor cannot be zero. Please enter a non-zero value.")
        service_factor = float(input("Enter service factor: "))

    # Calculating torque and bending moment
    torque_Nm = (1000 * power) / (speed * (1 / 60) * service_factor)

    # Ensure positive power and service factor
    if power <= 0:
        print("Power must be a positive value. Please enter a valid power value.")
        return None
    if service_factor <= 0:
        print("Service factor must be a positive value. Please enter a valid service factor.")
        return None

    bending_moment_Nmm = torque_Nm * 1000 / 2  # Assuming evenly distributed load

    # Calculating diameter of the shaft (d) in mm
    d = ((16 * bending_moment_Nmm) / (shear_stress_shaft_bolt_key * (3.14 / 16))) ** (1 / 3)

    # Calculating number of bolts required
    num_bolts = round(2 * d / 10)

    # Calculating diameter of the bolt (db) and key (dk) in mm
    db = ((16 * torque_Nm) / (shear_stress_shaft_bolt_key * (3.14 / 4))) ** (1 / 3)
    dk = ((2 * bending_moment_Nmm) / (crushing_stress_bolt_key * (3.14 / 64))) ** (1 / 3)

    # Calculating diameter of the hub (dh) in mm
    dh = d + 2 * db

    # Calculating diameter of the flange (df) in mm
    df = 2 * dh

    return d, num_bolts, db, dk, dh, df

def main():
    print("Design a cast iron protective type flange coupling.")
    print("Enter values 10 times to calculate for different inputs.\n")

    for i in range(1, 11):
        print("Input {}:".format(i))
        power = float(input("Enter power (kW): "))
        speed = float(input("Enter speed (rpm): "))
        service_factor = float(input("Enter service factor: "))

        # Calculate the dimensions of the flange coupling
        flange_dimensions = calculate_flange_coupling(power, speed, service_factor)

        # Check for None (indicating invalid input) and skip the iteration
        if flange_dimensions is None:
            continue

        # Unpack the dimensions
        d, num_bolts, db, dk, dh, df = flange_dimensions

        # Display the dimensions of the flange coupling
        print("\nDimensions of the flange coupling:")
        print("Diameter of the shaft (d): {:.2f} mm".format(d))
        print("Number of bolts required: {}".format(num_bolts))
        print("Diameter of the bolt (db): {:.2f} mm".format(db))
        print("Width of the key (dk): {:.2f} mm".format(dk))
        print("Diameter of the hub (dh): {:.2f} mm".format(dh))
        print("Diameter of the flange (df): {:.2f} mm".format(df))
        print()

if __name__ == "__main__":
    main()


import time
from ...utils.main.base_page import BasePage
from ...utils.assertions import MainPageAssertion

class TestMainPage:

    def test_check_title (self, browser):
        link = "https://onepage.io/"
        page = BasePage(browser)
        page.open(link)
        assertion = MainPageAssertion(browser)
        assertion.assert_should_be_main_page()


import pygame
import sys, os

# sys.path.append(os.getcwd())

from internal.PygameApp import PygameApp, Screen
from widgets.BasicMenuBar import BasicMenuBar

# screen paths here
from screens.MapMakerScreen import map_maker_screen

clock = pygame.time.Clock()
size, screen = None, None

def action():
    print('action executed')

'''
    I mainly made these classes for annotations ahead of functions so ik what i'm doing

    @PygameApp:
        Creates the window and initializes everything for you
        Supports function based windows that can be added on to each other

    @Screen:
        Verifies that the function parameters are set correctly
        Validates the new function-based screen
'''

class HomeScreenNavResults:
    mapmaker = 'mapmaker'
    quit = 'quit'
    newgame = 'newgame'
    loadgame = 'loadgame'

def nav_to_newgame():
    return HomeScreenNavResults.newgame

def nav_to_loadgame():
    return HomeScreenNavResults.loadgame

def nav_to_mapmaker():
    return HomeScreenNavResults.mapmaker

def nav_to_quit():
    return HomeScreenNavResults.quit

@PygameApp
@Screen
def main_screen(sizep=None, screenp=None):
    size, screen = sizep, screenp
    print(f'this is the current screen {screen}')

    menu_width, menu_height = 600, 300
    menu_rect = pygame.rect.Rect(size[0] // 2 - menu_width // 2, size[1] // 2 - menu_height // 2, menu_width,
                                 menu_height)
    menu_padding = {
        't': 40,
        'b': 10
    }

    menu_items = ['new game', 'load game', 'map maker', 'quit']
    menu_actions = [nav_to_newgame, nav_to_loadgame, nav_to_mapmaker, nav_to_quit]

    menu = BasicMenuBar(screen, menu_width, menu_height, pos_x=(size[0] // 2) - (menu_width // 2),
                        pos_y=(size[1] // 2) - (menu_height // 2), menu_items=menu_items,
                        menu_actions=menu_actions, menu_title='Welcome!', menu_padding=menu_padding,
                        font_color=(0, 0, 0), font_size=25, title_font_size=35, menu_item_spacing=15, cursor=True)

    running, result = True, None

    while 1:
        clock.tick(60)

        # background
        screen.fill((0, 0, 0))

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    result = menu.execute_action_cursor(1)
                    running = False

        menu.render()
        pygame.display.flip()

        if not running and result == HomeScreenNavResults.quit:
            pygame.quit()
            break
        else:
            running = True

        if result == HomeScreenNavResults.mapmaker:
            return map_maker_screen(size, screen)


import RPi.GPIO as GPIO
import time

def decimal2binary(value):

     return [int(bit) for bit in bin(value)[2:].zfill(8)]

GPIO.setmode(GPIO.BCM)

dac = [26, 19, 13, 6, 5, 11, 9, 10]
GPIO.setup(dac, GPIO.OUT)

try:
    while True:
        print("Введите целое число от 0 до 255")
        n = input()
        if n == "q":
            quit()
        if n.isdigit():
            n = int(n)
            if n < 0 or n > 255:
                print("Вы ввели число, выходящее из заданного дипозона. Повторите ввод)")

            else:
                GPIO.output(dac, decimal2binary(n))
                Vout = 3.3 * n / 256
                print("Предполагаемое значение напряжения на выходе:", Vout)

        else:
            print("Вы ввели неправильный тип данных. Повторите ввод)")
finally:
    GPIO.output(dac, 0)
    GPIO.cleanup()


'''
Created on Sep 13, 2016

@author: Juan Manuel Acevedo Valle
'''

if __name__ == '__main__':
    import os,sys
    sys.path.append(os.getcwd())

    import numpy as np
    from matplotlib.pyplot  import draw, show

    from exploration.models.GeneralModels.Trash.ILGMM_GREC import ILGMM
    from exploration.data.PlotTools import initializeFigure

    # Number of samples per component
    n_samples = 500

    # Generate random sample, two components
    np.random.seed(0)
    C = np.array([[0., -0.1], [1.7, .4]])
    X = np.r_[np.dot(np.random.randn(n_samples, 2), C),
              .7 * np.random.randn(n_samples, 2) + np.array([-6, 3])]

    model = ILGMM(min_components=3)
    model.train(X)

    #Model computed with three Gaussians
    fig1, ax1 = initializeFigure()
    ax1 = model.plot_gmm_projection(0,1,axes=ax1)

    model.mergeGaussians(0,2)

    #Model merging similar Gaussians
    fig2, ax2 = initializeFigure()
    ax2 = model.plot_gmm_projection(0, 1, axes=ax2)

    #Model computed with two Gaussians
    model = ILGMM(min_components=2)
    model.train(X)
    fig3, ax3 = initializeFigure()
    ax3 = model.plot_gmm_projection(0, 1, axes=ax3)

    ax1.relim()
    ax1.autoscale_view()
    ax2.relim()
    ax2.autoscale_view()
    ax3.relim()
    ax3.autoscale_view()

    draw()
    show()


def cluster():
    trump_tweets = load_file('trump_tweets.txt')
    hillary_tweets = load_file('hillary_tweets.txt')

    trump_tweets1 = [t for t in trump_tweets if 'user' in t]
    hillary_tweets1 = [t for t in hillary_tweets if 'user' in t]

    for t in trump_tweets1:
        G.add_node(t['user']['screen_name'])
    for h in hillary_tweets1:
        G.add_node(h['user']['screen_name'])

    nx.draw()
    plt.savefig('graph.png')

def girvan_newman(G, most_valuable_edge=None):
    if G.number_of_edges() == 0:
        yield tuple(nx.connected_components(G))
        return
    if most_valuable_edge is None:
        def most_valuable_edge(G):
            betweenness = nx.edge_betweenness_centrality(G)
            return max(betweenness, key=betweenness.get)
    g = G.copy().to_undirected()
    g.remove_edges_from(g.selfloop_edges())
    while g.number_of_edges() > 0:
        yield _without_most_central_edges(g, most_valuable_edge)

def _without_most_central_edges(G, most_valuable_edge):
    original_num_components = nx.number_connected_components(G)
    num_new_components = original_num_components
    while num_new_components <= original_num_components:
        edge = most_valuable_edge(G)
        G.remove_edge(*edge)
        new_components = tuple(nx.connected_components(G))
        num_new_components = len(new_components)
    return new_components


from __future__ import absolute_import
import unittest
from io import BytesIO

from py_trace_event.trace_event_impl import perfetto_trace_writer

class PerfettoTraceWriterTest(unittest.TestCase):
  """ Tests functions that write perfetto protobufs.

  TODO(crbug.com/944078): Switch to using python-protobuf library
  and implement proper protobuf parsing then.
  """
  def setUp(self):
    perfetto_trace_writer.reset_global_state()

  def testWriteThreadDescriptorEvent(self):
    result = BytesIO()
    perfetto_trace_writer.write_thread_descriptor_event(
        output=result,
        pid=1,
        tid=2,
        ts=1556716807306000,
    )
    expected_output = b"".join([
        b'\n\x1b@\x80\xec\xea\xda\x83\xb6\xa4\xcd\x15P\x80\x80@',
        b'\xc8\x02\x01\xe2\x02\x04\x08\x01\x10\x02\xd0\x03@'
    ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteTwoEvents(self):
    result = BytesIO()
    perfetto_trace_writer.write_thread_descriptor_event(
        output=result,
        pid=1,
        tid=2,
        ts=1556716807306000,
    )
    perfetto_trace_writer.write_event(
        output=result,
        ph="M",
        category="category",
        name="event_name",
        ts=1556716807406000,
        args={},
        tid=2,
    )
    expected_output = b"".join([
        b'\n\x1b@\x80\xec\xea\xda\x83\xb6\xa4\xcd\x15P\x80\x80@',
        b'\xc8\x02\x01\xe2\x02\x04\x08\x01\x10\x02\xd0\x03@\n;@',
        b'\x80\xb0\xc2\x8a\x84\xb6\xa4\xcd\x15P\x80\x80@Z\x08',
        b'\x18\x012\x04\x08\x01\x10Mb\x1e\n\x0c\x08\x01\x12\x08',
        b'category\x12\x0e\x08\x01\x12\nevent_name\xd0\x03@'
    ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteMetadata(self):
    result = BytesIO()
    perfetto_trace_writer.write_metadata(
        output=result,
        benchmark_start_time_us=1556716807306000,
        story_run_time_us=1556716807406000,
        benchmark_name="benchmark",
        benchmark_description="description",
        story_name="story",
        story_tags=["foo", "bar"],
        story_run_index=0,
        label="label",
    )
    expected_output = b"".join([
        b'\nG\x82\x03D\x08\x90\xf6\xc2\x82\xb6\xfa\xe1',
        b'\x02\x10\xb0\x83\xc9\x82\xb6\xfa\xe1\x02\x1a\tbenchmark"',
        b'\x0bdescription*\x05label2\x05story:\x03foo:\x03bar@\x00'
        ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteArgs(self):
    result = BytesIO()
    perfetto_trace_writer.write_thread_descriptor_event(
        output=result,
        pid=1,
        tid=2,
        ts=0,
    )
    perfetto_trace_writer.write_event(
        output=result,
        ph="M",
        category="",
        name="",
        ts=0,
        args={'int': 123, 'double': 1.23, 'string': 'onetwothree'},
        tid=2,
    )
    expected_output = b"".join([
        b'\n\x13@\x00P\x80\x80@\xc8\x02\x01\xe2\x02\x04\x08\x01\x10',
        b'\x02\xd0\x03@\nT@\x00P\x80\x80@Z;\x18\x01"\x07R\x03int {"\x11',
        b'R\x06double)\xaeG\xe1z\x14\xae\xf3?"\x15R\x06string2\x0bonetwothree2',
        b'\x04\x08\x01\x10Mb\x0c\n\x04\x08\x01\x12\x00\x12\x04\x08\x01\x12\x00',
        b'\xd0\x03@'
    ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteChromeMetadata(self):
    result = BytesIO()
    perfetto_trace_writer.write_chrome_metadata(
        output=result,
        clock_domain='FOO',
    )
    expected_output = b'\n\x17*\x15\x12\x13\n\x0cclock-domain\x12\x03FOO'
    self.assertEqual(expected_output, result.getvalue())

  def testWriteClockSnapshot(self):
    result = BytesIO()
    perfetto_trace_writer.write_clock_snapshot(
        output=result,
        tid=1,
        telemetry_ts=1234.567,
        boottime_ts=7654.321,
    )
    expected_output = b"".join([
       b'\n\x172\x11\n\x06\x08@\x10\x87\xadK\n\x07\x08\x06\x10',
       b'\xb1\x97\xd3\x03P\x80\x80@'
    ])
    self.assertEqual(expected_output, result.getvalue())


#!/usr/bin/python

import sys
import string

def encode(n):
	s = ''
	for x in bin(n)[2:]:
		if x == '0': s = s + '\0'
		else: s = s + '\t'
	return s + '\v'

def decode(s):
	news = '0b'
	for c in s:
		if c == '\x00': news = news + '0'
		if c == '\t': news = news + '1'
	return chr(int(news, 2))

normchars = string.ascii_letters + string.digits + string.punctuation

with open(sys.argv[1]) as f:
	words = f.read().split(' ')

with open(sys.argv[1], 'w') as f:
	if sys.argv[2] == 'e':
		for word in words:
			for char in word:
				f.write(encode(ord(char)))
			f.write(' ')

	elif sys.argv[2] == 'd':
		for word in words[:-1]:
			for char in word.split('\v')[:-1]:
				f.write(decode(char))
			f.write(' ')


import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

class Test(unittest.TestCase):
    def setUp(self):
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.close()

    def testSearchAtYouTube(self):
        self.browser.get('http://www.youtube.com')
        elem = self.browser.find_element_by_name('search_query')
        elem.send_keys('webdriver' + Keys.RETURN)
        time.sleep(0.2) # For now isn't in API.
        self.browser.find_element_by_css_selector('p.num-results')

    def testSearchAtGoogleImages(self):
        self.browser.get('http://images.google.com')
        elem = self.browser.find_element_by_name('q')
        elem.send_keys('webdriver' + Keys.RETURN)
        time.sleep(0.2) # For now isn't in API.
        self.browser.find_element_by_css_selector('div#resultStats')

if __name__ == '__main__':
    unittest.main()


from math import inf
def solution(n, results):
    answer = 0
    distance=[[inf] *(n+1) for _ in range(n+1)]

    for start,end in results:
        distance[start][end]=1

    for k in range(1,n+1):
        for i in range(1,n+1):
            for j in range(1,n+1):
                distance[i][j]=min(distance[i][j],distance[i][k]+distance[k][j])

    for i in range(1,n+1):
        count=0
        for j in range(1,n+1):
            if distance[i][j] != inf or distance[j][i]!=inf:
                count+=1

        if count==n-1:
            answer+=1

    return answer

if __name__ == "__main__":
    n_vertex,n_edges=0,0
    results=[]
    with open("level3_2.txt","r") as file:
        n_vertex,n_edges=map(int,file.readline().split())
        results=[list(map(int,file.readline().split())) for _ in range(n_edges)]
    print(solution(n_vertex,results))


from subprocess import Popen, PIPE

# Retrieves version from GIT version control
def get_version():
    try:
        p = Popen(["git", "describe", "--abbrev=4"],
                stdout=PIPE, stderr=PIPE)
        p.stderr.close()
        line = p.stdout.readlines()[0]
        return line.strip()
    except:
        return None

__author__ = "Rongzhou Shen"
__contact__ = "anticlockwise5@gmail.com"
__version__ = get_version()


import unittest
from MooseDocs.common import slugify

class TestSlugify(unittest.TestCase):

    INVALID = [':', '\\', '.', '[', ']', '(', ')', '!', '"', "'", '*', '?', '<', '>', '|']

    def testBasic(self):
        """
        Test basic conversion and invalid characters.
        """
        self.assertEqual(('Foo_Bar', True), slugify('Foo Bar'))
        for x in self.INVALID:
            string = 'Foo{}Bar'.format(x)
            self.assertEqual((string, False), slugify(string))

    def testReplace(self):
        """
        Test replacement.
        """
        for x in self.INVALID:
            string = 'Foo{}Bar'.format(x)
            replaced = 'FooXBar'.format(x)
            self.assertEqual((replaced, True), slugify(string, (x, 'X')))

if __name__ == '__main__':
    unittest.main(verbosity=2)