from typing import Any, Dict, Tuple
from django.db import models
from django.utils import timezone
from django.urls import reverse_lazy
from django.conf import settings

class Categoria(models.Model):
    nombre = models.CharField(max_length=60, null=False)

    def __str__(self):
        return self.nombre

class Articulo(models.Model):
    titulo = models.CharField(max_length=100, null= False)
    resumen = models.TextField(null=False)
    contenido = models.TextField(null=False)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    imagen = models.ImageField(null=True, blank=True, upload_to='articulo', default='articulo/imagen.jpg')
    estado = models.BooleanField(default=True)
    categoria = models.ForeignKey(Categoria, on_delete=models.SET_NULL, null=True, default=1)
    publicado = models.DateTimeField(default=timezone.now)
    calificacion_promedio = models.DecimalField(max_digits=3, decimal_places=2, default=0.00)

    class Meta:
        ordering = ('-publicado',)

    def __str__(self):
        return self.titulo

    def delete(self, using=None, keep_parents= False):
        self.imagen.delete(self.imagen.name)
        super().delete()

    def get_link_comentar(self):
        return reverse_lazy('apps.comentario:agregarComentario', args=[self.id])

class Calificacion(models.Model):
    articulo = models.ForeignKey('articulo.Articulo', on_delete=models.CASCADE, null=True, related_name= 'calificacion')
    usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='calificacion')
    valor = models.IntegerField(choices=[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5')], default=1)

    class Meta:
        unique_together = ('articulo', 'usuario')


import connection
from datetime import date
from discord.ext import commands

@commands.command()
async def cumple(ctx):
    discord_server = ctx.message.guild.name
    conn = connection.get_connection()
    cursor = conn.cursor()
    try:
        cursor.execute(f"SELECT discord_user, discord_id, fecha, cast(fecha + ((extract(year from age(fecha)) + 1) * interval '1' year) as date) as next_birthday from cumpleaños_fechas WHERE to_char(CURRENT_DATE,'MM') = to_char(cast(fecha + ((extract(year from age(fecha)) + 1) * interval '1' year) as date), 'MM') AND to_char(CURRENT_DATE,'DD') = to_char(cast(fecha + ((extract(year from age(fecha)) + 1) * interval '1' year) as date), 'DD')")
        cumpleañero_del_dia = cursor.fetchone()
        if cumpleañero_del_dia != None:
            cumpleañero_tag = f"<@{cumpleañero_del_dia[1]}>"
            await ctx.send(f'Hoy es el cumpleaños de {cumpleañero_tag}! С днем рождения товарищ!')
        else:
            cursor.execute(f"SELECT discord_user, discord_id, fecha, cast(fecha + ((extract(year from age(fecha)) + 1) * interval '1' year) as date) as next_birthday from cumpleaños_fechas WHERE discord_server = '{discord_server}' ORDER BY next_birthday asc LIMIT 1")
            cumpleaños_data = cursor.fetchone()
            cumpleañero = cumpleaños_data[0]
            cumpleañero_id = cumpleaños_data[1]
            cumple = cumpleaños_data[3]
            await ctx.send(f'El próximo cumpleaños es el de {cumpleañero} el {cumple.day} del {cumple.month}.')
    except:
        await ctx.send(f'Error gravísimo al consultar los cumpleaños.')
    finally:
        cursor.close()
        conn.close()

@commands.command()
async def addMiCumple(ctx,*,fecha):
    autor_name = ctx.message.author.name
    server_name = ctx.message.guild.name
    autor_id = autor = ctx.message.author.id
    today = date.today()
    fecha_array = []
    if '/' in fecha or '-' in fecha:
        if '/' in fecha:
            fecha_array = fecha.split('/')
        if '-' in fecha:
            fecha_array = fecha.split('-')
    else:
        await ctx.send(f'Cuchame una cosa no te haga el vive y poné una fecha válida día/mes/año en ese exacto formato o te liquido.')
    if (len(fecha_array) == 3 and len(fecha_array[0]) != 0 and len(fecha_array[1]) != 0 and len(fecha_array[2]) != 0):
        dias = int(fecha_array[0])
        mes = int(fecha_array[1])
        año = int(fecha_array[2])
        if (dias > 31 or dias < 1):
            await ctx.send(f'No te haga el vive y poné un día válido.')
        else:
            if (mes > 12 or mes < 1):
                await ctx.send(f'No te haga el vive y poné un mes válido.')
            else:
                if (año > today.year or año < 1800):
                    await ctx.send(f'No te haga el vive y poné un año válido.')
                else:
                    if validate_cumpleanios_exists(server_name, autor_id):
                        conn = connection.get_connection()
                        cursor = conn.cursor()
                        date_cumpleaños = date(año, mes, dias)
                        sql = (f"INSERT INTO cumpleaños_fechas(discord_user, fecha, discord_server, discord_id) VALUES ('{autor_name}','{date_cumpleaños}','{server_name}','{autor_id}')")
                        try:
                            result = cursor.execute(sql)
                            conn.commit()
                            await ctx.send("Cumpleaños agregado товарищ!")
                        except Exception as exc:
                            await ctx.send('No anda nada cuando guardo el cumpleaños: {}'.format(exc))
                        finally:
                            cursor.close()
                            conn.close()
                    else:
                        await ctx.send(f'Vos ya cargaste tu cumpleaños payase vola de acá o te reviento la gorra.')
    else:
        await ctx.send(f'Cuchame una cosa no te haga el vive y poné una fecha válida día/mes/año en ese exacto formato o te liquido.')

def validate_cumpleanios_exists(server_name, autor_id):
    conn = connection.get_connection()
    cursor = conn.cursor()
    try:
        cursor.execute(f"SELECT COUNT (*) FROM cumpleaños_fechas WHERE discord_server = '{server_name}' AND discord_id = '{autor_id}'")
        result = 0
        result = cursor.fetchone()[0]
        if result == 0:
            return True
        else:
            return False
    except Exception as exc:
        print('Error al validar el cumpleaños.')
    finally:
        cursor.close()
        conn.close()

async def setup(bot):
    bot.add_command(cumple)
    bot.add_command(addMiCumple)


import boto3
import json, sys

class LakeFormationController:

    def __init__(self, params):
        self.session = boto3.Session(profile_name='terraform')

        self.client = self.session.client(
            'lakeformation',
            region_name='us-east-2'
        )

        self.db_name = params["db_name"]
        self.account_id = params["account_id"]
        self.lf_admin = f"arn:aws:iam::{self.account_id}:user/{params['lf_admin']}"
        self.emr_instance_profile = f"arn:aws:iam::{self.account_id}:role/EMR_EC2_DefaultRole"
        self.s3_domain_locations = params["s3_domain_locations"]

    def create_lake_formation(self):
        self.add_administrator(self.lf_admin)
        self.grant_permissions(self.lf_admin, 'Database', ["ALL"], ["ALL"])
        self.grant_permissions(self.lf_admin, 'Table', ["ALL"], ["ALL"])
        self.grant_permissions(self.emr_instance_profile, 'Database', ["ALL"], ["ALL"])
        self.grant_permissions(self.emr_instance_profile, 'Table', ["ALL"], ['ALL'])
        self.register_all_resources(self.s3_domain_locations)

    def destroy_lake_formation(self):
        self.deregister_all_resources(self.s3_domain_locations)
        # self.remove_permissions(self.lf_admin, 'Database', ["ALL"], ["ALL"])
        self.remove_permissions(self.lf_admin, 'Table', ["ALL"], ["ALL"])
        self.remove_permissions(self.emr_instance_profile, 'Database', ["ALL"], ["ALL"])
        self.remove_permissions(self.emr_instance_profile, 'Table', ["ALL"], ['ALL'])
        # self.remove_administrator(self.lf_admin)

    def clear_administrators(self):
        response = self.client.put_data_lake_settings(
            DataLakeSettings={
                'DataLakeAdmins': []
            }
        )
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            print("Removed all Lake Formation Administrators")
        else:
            print(response)

    def add_administrator(self, lf_admin):
        data_lake_settings = self.client.get_data_lake_settings()
        current_administrators = data_lake_settings["DataLakeSettings"]["DataLakeAdmins"]
        if {'DataLakePrincipalIdentifier': lf_admin} not in current_administrators:
            current_administrators.append({'DataLakePrincipalIdentifier': lf_admin})
            response = self.client.put_data_lake_settings(DataLakeSettings=data_lake_settings["DataLakeSettings"])
            if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
                print(f"{lf_admin} is now an AWS Lake Formation Administrator")
            else:
                print(response)
        else:
            print(f"{lf_admin} is already a Lake Formation Administrator")

    def remove_administrator(self, lf_admin):
        data_lake_settings = self.client.get_data_lake_settings()
        administrators = data_lake_settings["DataLakeSettings"]["DataLakeAdmins"]
        try:
            administrators.remove({'DataLakePrincipalIdentifier': lf_admin})
        except ValueError:
            print(f"{lf_admin} was not an AWS Lake Formation Administrator")
        response = self.client.put_data_lake_settings(DataLakeSettings=data_lake_settings["DataLakeSettings"])
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            print(f"{lf_admin} is no longer an AWS Lake Formation Administrator")
        else:
            print(response)

    def grant_permissions(self, principal_arn, structure, permission_list=[], grant_permission_list=[]):
        # currently gives the principal access to all tables in specified db (if structure is table)
        resource = None

        if structure == 'Table':
            resource = {
                'Table': {
                    'DatabaseName': self.db_name,
                    'TableWildcard': {}
                }
            }

        elif structure == 'Database':
            resource = {
                'Database': {
                    'Name': self.db_name
                }
            }

        response = self.client.grant_permissions(
            Principal={
                'DataLakePrincipalIdentifier': principal_arn
            },
            Resource=resource,
            Permissions=permission_list,
            PermissionsWithGrantOption=grant_permission_list
        )

        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print(f"Permissions for {resource} granted to {principal_arn}")
        else:
            print(resource, response)

    def remove_permissions(self, principal_arn, structure, permission_list=[], grant_permission_list=[]):
        resource = None

        if structure == 'Table':
            resource = {
                'Table': {
                    'DatabaseName': self.db_name,
                    'TableWildcard': {}
                }
            }

        elif structure == 'Database':
            resource = {
                'Database': {
                    'Name': self.db_name
                }
            }

        try:
            response = self.client.revoke_permissions(
                Principal={
                    'DataLakePrincipalIdentifier': principal_arn
                },
                Resource=resource,
                Permissions=permission_list,
                PermissionsWithGrantOption=grant_permission_list
            )
            if response['ResponseMetadata']['HTTPStatusCode'] == 200:
                print(f"Permissions revoked from {principal_arn}")
            else:
                print(resource, response)
        except self.client.exceptions.InvalidInputException:
            print(f"Permissions for {principal_arn} to {resource} were not revoked because they did not exist")

    def register_all_resources(self, resource_list):
        for resource in resource_list:
            bucket_arn = f"arn:aws:s3:::{resource}"
            try:
                self.register_resource_location(bucket_arn)
            except self.client.exceptions.AlreadyExistsException:
                print(f"Resource {bucket_arn} already exists")

    def register_resource_location(self, bucket_arn):
        response = self.client.register_resource(
            ResourceArn=bucket_arn,
            UseServiceLinkedRole=True,
        )

        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print(f"{bucket_arn} successfully registered")
        else:
            print(response)

    def deregister_all_resources(self, resource_list):
        for resource in resource_list:
            bucket_arn = f"arn:aws:s3:::{resource}"
            try:
                self.deregister_resource_location(bucket_arn)
            except self.client.exceptions.EntityNotFoundException:
                print(f"Resource {bucket_arn} was not a registered resource")

    def deregister_resource_location(self, bucket_arn):
        response = self.client.deregister_resource(
            ResourceArn=bucket_arn,
        )

        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print(f"{bucket_arn} successfully deregistered")
        else:
            print(response)

if __name__ == "__main__":
    create_or_destroy = sys.argv[1]
    if sys.argv[2] == 'testing':
        params = json.loads(
            '{ "db_name": "datameshatndatameshcatalogue", '
            '"account_id":"233329490210", '
            '"lf_admin":"DataMeshPOC", '
            '"s3_domain_locations":['
            '"datamesh-atn-covid-domain/covid-italy",'
            '"datamesh-atn-covid-domain/covid-us",'
            '"datamesh-atn-bike-domain"]'
            '}'
        )
    else:
        params = json.loads(sys.argv[2])

    lakeFormationController = LakeFormationController(params)

    if create_or_destroy == 'create':
        LakeFormationController.create_lake_formation(lakeFormationController)
    elif create_or_destroy == 'destroy':
        LakeFormationController.destroy_lake_formation(lakeFormationController)
    # elif create_or_destroy == 'nuke':
    #     LakeFormationController.clear_administrators(lakeFormationController)
    else:
        print('please pass either destroy or create as first variable')


from django.db.models import Q
from typing import Union

from core.models import User, Match

def react_to_user(sender_user: User, recipient_user: User, liked: bool) -> Union[Match, None]:
    try:
        reverse_match = Match.objects.get(sender_user=recipient_user, recipient_user=sender_user)
    except Match.DoesNotExist:
        reverse_match = None

    if reverse_match:
        if liked:
            reverse_match.acquaintance_state = '2'
        else:
            reverse_match.acquaintance_state = '1'
        reverse_match.save()
        return reverse_match

    if liked:
        return Match.objects.get_or_create(sender_user=sender_user, recipient_user=recipient_user)[0]
    else:
        sender_user.disliked_users.add(recipient_user)

    return None

def get_match(sender_user: User, recipient_user: User) -> Union[Match, None]:
    match = Match.objects.filter(sender_user=sender_user).filter(recipient_user=recipient_user).first()
    return match

def get_unvisited_user(current_user: User) -> Union[User, None]:
    user_to_match = User.objects.exclude(pk=current_user.pk) \
        .exclude(pk__in=current_user.disliked_users.all()) \
        .exclude(received_match_requests__sender_user=current_user) \
        .exclude(Q(sent_match_requests__recipient_user=current_user) &
                 ~Q(sent_match_requests__acquaintance_state='0')).first()

    return user_to_match

def get_familiar_users(current_user: User) -> Union[User, None]:
    familiar_users = User.objects.filter((Q(sent_match_requests__recipient_user=current_user) &
                         Q(sent_match_requests__acquaintance_state='2')) |
                        (Q(received_match_requests__sender_user=current_user) &
                         Q(received_match_requests__acquaintance_state='2')))

    return familiar_users


from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn import svm
import pandas
import logging
import sys

logging.basicConfig(
    level=logging.DEBUG,
    format=(
        '%(asctime)s (%(relativeCreated)d) %(levelname)s %(name)s'
        ' [%(funcName)s:%(lineno)d] %(message)s'),
    stream=sys.stdout)
LOGGER = logging.getLogger(__name__)

def main():
    table = pandas.read_csv('modified_training.csv')
    clf = svm.SVC()
    X_train, X_holdout, y_train, y_holdout = train_test_split(
        table[['qgram', 'cosine', 'smith_waterman', 'lcs', 'len_a', 'len_b']],
        table['category'], test_size=0.2, random_state=42)

    reg = LinearRegression().fit(X_train, y_train)
    clf.fit(X_train, y_train)
    for x_set, y_set in [(X_train, y_train), (X_holdout, y_holdout)]:
        y_pred = clf.predict(x_set)
        svm_accuracy = accuracy_score(y_set, y_pred)
        LOGGER.info(f"SVM Accuracy: {svm_accuracy}")
        y_pred = reg.predict(x_set)
        reg_accuracy = reg.score(x_set, y_pred)
        LOGGER.info(f"REG Accuracy: {reg_accuracy}")
        LOGGER.info('\n'.join(str(x) for x in sorted(zip(y_pred, y_set))))

if __name__ == '__main__':
    main()


import pygame
from pygame.sprite import Sprite

class Ship(Sprite):
    """ A simple attempt to model a ship"""
    def __init__(self,ai_settings,screen):
        super(Ship,self).__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # load the ship image from the directory """
        self.image = pygame.image.load('images/ship.bmp')
        # treat the image to as rectangle
        self.rect = self.image.get_rect()
        # treat the screen as rectangle
        self.screen_rect = screen.get_rect()

        # define the x axis position of the ship in center of screen
        self.rect.centerx = self.screen_rect.centerx
        # define the y position of the ship in the bottom
        self.rect.bottom = self.screen_rect.bottom
        # convert the speed into float to modify the speed as per needs
        self.center = float(self.rect.centerx)

        # define a flag set the speed to false when the key is not pressed
        self.moving_right = False
        self.moving_left = False

    def center_ship(self):
        self.center = self.rect.centerx

    def update(self):
        """ update the speed of the ship when key is pressed"""
        if self.moving_right and self.rect.right < self.screen_rect.right:
           self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
           self.center -= self.ai_settings.ship_speed_factor

        # retriving the value of speed
        self.rect.centerx = self.center

    def blitme(self):
        """ Draw the contents on the screen """
        self.screen.blit(self.image,self.rect )


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Author  :xiaoyu
# time    :2021/1/26 17:26

import os

def dir_rename(file_save):
    '''
    文件夹下多个文件重命名
    :param file_save: 文件夹位置
                文件格式：img_root
    :return:
    '''
    dirs = os.listdir(file_save)  # 文件夹赋值
    i = 100  # 赋值
    num = 0
    for dir1 in dirs:  # for循环逻辑是每次执行for下文件

        s = dir1.split(".")  # s是文件夹格式

        print(s)

        if len(s) > 1:  # 判断s的长度文件夹长度为0

            new_name = file_save + os.sep + str(i) + "." + s[-1]  # 文件重命名

            file_name = file_save + os.sep + dir1  # 旧文件名
            os.rename(file_name, new_name)  # 执行重命名
            print(s)
            i += 2
        else:
            new_name = file_save + os.sep + str(num + 5)
            file_name = file_save + os.sep + dir1
            print(file_name)
            print(new_name)
            os.rename(file_name, new_name)
            num += 3

dir_rename("D:/lianxi/JPGImages")


from typing import Optional

from anytree import RenderTree

from nndt.space2.abstracts import AbstractBBoxNode, AbstractTreeElement
from nndt.space2.filesource import FileSource
from nndt.space2.implicit_representation import ImpRepr
from nndt.space2.method_set import MethodSetNode
from nndt.space2.transformation import AbstractTransformation

def _construct_filter(child_classes, not_parent_classes):
    def filter_(children):
        ret = [
            v
            for v in children
            if isinstance(v, child_classes)
            and not isinstance(v.parent, not_parent_classes)
        ]
        return ret

    return filter_

class PrintContainer:
    def __init__(self, text):
        self.text = text

    def __repr__(self):
        return self.text

    def __str__(self):
        return self.text

def _pretty_print(node: AbstractTreeElement, mode: Optional[str] = "default"):
    if mode is None or (mode == "default"):
        ret = RenderTree(
            node,
            childiter=_construct_filter(
                (AbstractTreeElement,),
                (MethodSetNode, AbstractTransformation, FileSource, ImpRepr),
            ),
        ).__str__()
    elif mode == "source" or mode == "sources":
        ret = RenderTree(
            node, childiter=_construct_filter((AbstractBBoxNode,), ())
        ).__str__()
    elif mode == "full":
        ret = RenderTree(node).__str__()
    else:
        raise NotImplementedError(f"{mode} is not implemented for the explore method. ")
    return PrintContainer(ret)


"""
    sample components
"""

import decimal

import zoom
import zoom.html as h
import zoom.components as c

def use_common_package(message):
    zoom.requires('common_package_test')
    return zoom.Component(
        h.tag('div', message, id='common_package_test')
    )

def view():

    hr = '<hr>\n'

    data = [
        ('String', 'Integer', 'Decimal'),
        ('One', 1, decimal.Decimal(1234)),
        ('Two', 2, decimal.Decimal(2345))
    ]

    content = zoom.Component(

        'zoom.browse',
        zoom.browse(
            data,
            title='Sample Header',
            footer='sample footer'
        ),
        hr,

        'zoom.components.HeaderBar',
        c.HeaderBar(
            left=h.h2('HeaderBar Left'),
            right='HeaderBar right'
        ),
        hr,

        'zoom.components.spinner',
        h.div(c.spinner(), classed="clearfix", style="margin: 40px auto; width: 0;"),
        hr,

        'zoom.components.dropzone',
        c.dropzone('/sample/components'),
        hr,

        use_common_package('not updated yet')
    )

    return zoom.page(content, title='Components')


import itertools

import plotly.colors as plotly_colors
import plotly.graph_objects as go

def plottable_events(events):
    epoch = None
    for e in events:
        if epoch is None:
            epoch = e['timestamp']
        assert e['timestamp'] >= epoch
        wait_for = []
        if e['event'] == 'await results':
            wait_for = sorted(e['jobs'])
        details = ', '.join(wait_for) if wait_for else ''
        if 'job' not in e:
            continue
        yield dict(
            event=e['event'],
            task=e['job'],
            time=e['timestamp'] - epoch,
            done=e['event'] == 'finish',
            label=e['event'] + (f' ({details})' if details else ''),
            wait_for=wait_for,
        )

def plot_schedule(
    title,
    events,
    colors=None,
    bar_width=0.45,
    showgrid_x=True,
    showgrid_y=True,
    **kwargs,
):
    fig = go.Figure(
        layout=dict(
            title=title,
            showlegend=False,
            hovermode='closest',
            xaxis=dict(
                title='Time [seconds]',
                autorange=True,
                showgrid=showgrid_x,
                zeroline=False,
            ),
            yaxis=dict(
                title='Jobs',
                showgrid=showgrid_y,
                ticktext=[],  # rows.keys()
                tickvals=[],  # rows.values()
                range=[-1, 1],  # use rows.values() to update
                autorange=False,
                zeroline=False,
            ),
            **kwargs,
        ),
    )

    # Events are grouped into rows by their 'task'. The tasks are ordered
    # vertically by the appearance of its first event. Rows are drawn top-down,
    # i.e. in the _negative_ y-direction.
    rows = {}  # map task name -> y-coordinate from 0 and down

    def get_row(task):
        if task not in rows:
            rows[task] = -len(rows)
            fig.update_layout(
                dict(
                    yaxis=dict(
                        ticktext=list(rows.keys()),
                        tickvals=list(rows.values()),
                        range=[min(rows.values()) - 1, max(rows.values()) + 1],
                    )
                )
            )
        return rows[task]

    if colors is None:
        colors = {}  # map task name -> color
    # colors not already in colors are fetched from the list of default colors:
    palette = itertools.cycle(plotly_colors.DEFAULT_PLOTLY_COLORS)

    def get_color(task):
        if task not in colors:
            colors[task] = next(palette)
        return colors[task]

    def marker(event, y, color):
        """Draw a marker for the given event."""
        symbol = {
            'add': 'star',
            'start': 'diamond-wide-open',
            'await results': 'diamond-tall-open',
            'awaited results': 'diamond-wide-open',
            'await worker slot': 'diamond-tall-open',
            'awaited worker slot': 'diamond-wide-open',
            'start work in thread': 'triangle-right',
            'finish work in thread': 'triangle-left',
            'start work in subprocess': 'triangle-right',
            'finish work in subprocess': 'triangle-left',
            'finish': 'x',
        }
        return dict(
            name='',  # event['task'],
            legendgroup=event['task'],
            mode='markers',
            # ids=[...]
            x=[event['time']],
            y=[y],
            text=[event['label']],
            marker=dict(
                symbol=symbol.get(event['event'], 'square'),
                size=10,
                color=color,
            ),
        )

    def rect(a, b, y, color):
        """Draw a rectangle between the two given events.

        The label/metadata of the rectangle are taken from the first event.
        """
        assert a['task'] == b['task']
        x0, x1 = a['time'], b['time']
        y0, y1 = y - bar_width, y + bar_width
        opacity = {
            'add': 0.2,
            'start': 0.6,
            'await results': 0.2,
            'awaited results': 0.6,
            'await worker slot': 0.2,
            'awaited worker slot': 0.6,
            'start work in thread': 0.8,
            'finish work in thread': 0.6,
            'start work in subprocess': 0.8,
            'finish work in subprocess': 0.6,
        }
        return dict(
            name=a['task'],
            legendgroup=a['task'],
            opacity=opacity.get(a['event'], 1),
            mode='none',
            # ids=[...]
            # 4 corners, clockwise from top-left
            x=[x0, x1, x1, x0],
            y=[y1, y1, y0, y0],
            fill='toself',  # fill area enclosed by above points
            fillcolor=color,
            hoverinfo='text',
            text=a['label'],
        )

    def line(a, ay, b, by, color):
        """Draw a line from event a at y == ay to event b at y == by."""
        return dict(
            name='',
            opacity=0.75,
            mode='lines',
            x=[b['time'], a['time']],
            y=[by, ay],
            text=f"{a['task']} -> {b['task']}",
            line=dict(color=color, width=2, shape='hv', dash='dot'),
        )

    last_event_by_task = {}  # map task name -> last event seen for that task
    for e in plottable_events(events):
        task = e['task']
        y = get_row(task)
        color = get_color(task)
        fig.add_trace(marker(e, y, color))
        if task in last_event_by_task:
            last = last_event_by_task[task]
            fig.add_trace(rect(last, e, y, color))
            for t in last['wait_for']:
                other = last_event_by_task[t]
                assert other['done']
                fig.add_trace(line(other, get_row(t), e, y, color))
        last_event_by_task[task] = e

    return fig


#!/usr/bin/env python3
'''
Automatically buy and sell stocks.

Part of naps (neopets automation program suite)
'''

import bs4
import re
import sqlite3
import time
from NeoSession import NeoSession

class TradeStocks(NeoSession):
    stock_list = []
    portfolio_list = []
    buy_volume = '1000'

    def __init__(self):
        self.parse()
        self.lowest_stock = self.determine_lowest()
        self.save_data()
        self.buy()
        self.sell()

    def save_data(self):
        stock_data = sqlite3.connect('stockdata.db')
        cur = stock_data.cursor()
        try:
            cur.execute('''CREATE TABLE stocks
                                               (ticker TEXT, volume INTEGER,
                                                open INTEGER, curr INTEGER,
                                                 change TEXT, time FLOAT)''')
            cur.execute('''CREATE TABLE portfolio
                                               (ticker TEXT, volume INTEGER,
                                                price INTEGER, time FLOAT)''')
        except sqlite3.OperationalError:
            for stocks in self.stock_list:
                cur.execute('''INSERT INTO stocks (ticker, volume, open, curr,
                               change, time) VALUES (?, ?, ?, ?, ?, ?)''',
                            (stocks['ticker'], stocks['volume'], stocks['open'],
                             stocks['curr'], stocks['change'], stocks['time']))
            stock_data.commit()
            cur.close()
            print('{}: StockTrade - Stock data written to DB.'.format(
                self.time))

    def buy(self):
        url = 'http://www.neopets.com/stockmarket.phtml?type=buy&ticker={}' \
            .format(self.lowest_stock['ticker'])
        resp = self.get(url)
        ref_ck = re.search(r"'&_ref_ck=(\w*)';", resp.text).group(1)
        url = 'http://www.neopets.com/process_stockmarket.phtml'
        resp = self.post(url, data={'type': 'buy',
                                    'ticker_symbol': self.lowest_stock['ticker'],
                                    'amount_shares': self.buy_volume,
                                    '_ref_ck': ref_ck}, login_check=False)

        if 'Error: Sorry, that would' in resp.text:
            print('{}: StockTrade - Purchase exceeds daily 1000 share limit.'.
                  format(self.time))
            pass
        else:
            self.get('http://www.neopets.com/stockmarket.phtml?type=portfolio')
            print('{}: StockTrade - Bought {} shares of {}.'.format(
                self.time, self.buy_volume,
                self.lowest_stock['ticker']))

            stock_data = sqlite3.connect('stockdata.db')
            cur = stock_data.cursor()
            cur.execute('''INSERT INTO portfolio (ticker, volume, price,
                                      time) VALUES (?, ?, ?, ?)''',
                        (self.lowest_stock['ticker'], self.buy_volume, self.lowest_stock['curr'],
                         self.lowest_stock['time']))
            stock_data.commit()
            cur.close()

    def sell(self):
        stock_data = sqlite3.connect('stockdata.db')
        cur = stock_data.cursor()
        for row in cur.execute('SELECT * FROM portfolio'):
            print(row)
        print('{}: StockTrade - Stocks sold.'.format(self.time))

    def parse(self):
        url = 'http://www.neopets.com/stockmarket.phtml?type=list&full=true'
        resp = self.get(url)
        soup = bs4.BeautifulSoup(resp.text, 'lxml')
        table = soup.findAll('table')[7]
        for row in table.find_all('tr')[1:]:
            cells = row.find_all('td')
            self.stock_list.append({'ticker': cells[1].string.strip(),
                                    'link': cells[1].string.strip(),
                                    'volume': cells[3].string.strip(),
                                    'open': cells[4].string.strip(),
                                    'curr': cells[5].string.strip(),
                                    'change': cells[6].string.strip(),
                                    'time': time.time()})
        return self.stock_list

    def determine_lowest(self):
        negative_stocks = []
        for stocks in self.stock_list:
            if '-' in stocks['change']:
                if int(stocks['volume']) >= 1000:
                    if int(stocks['change']) >= 30:
                        negative_stocks.append(stocks)
            if len(negative_stocks) == 0:
                 pass
            else:
                self.lowest_stock = negative_stocks[0]
                print('{}: Stock Trade - Lowest stock found "{}"'.format(
                    self.time, self.lowest_stock))
                return self.lowest_stock

            if len(negative_stocks) > 1:
                lowest_stock = negative_stocks[0][1]
                if float(negative_stocks[1]) > float(lowest_stock[1]):
                    self.lowest_stock = stocks
                    print('{}: Stock Trade - Lowest stock found "{}"'.format(
                        self.time, self.lowest_stock))
                return self.lowest_stock

def main():
    NeoSession()
    TradeStocks()

if __name__ == '__main__':
    main()


# 2017110292 김지완
list1 = open("number1to10.txt", "r")
list2 = open("numberby10.txt", "r")
list_merge = open("merge.txt", "w")

line_num = list1.readline().rstrip()
num = list2.readline().rstrip()

while line_num and num:
    list_merge.write(f"{line_num} : {num}\n")

    line_num = list1.readline().rstrip()
    num = list2.readline().rstrip()

list1.close()
list2.close()
list_merge.close()


from django.urls import path,include
from .views import *

urlpatterns = [
    path('list/',EventListView,name="eventList"),
    path('create/',EventCreateView,name="eventCreate"),
    path('update/<int:id>/',EventUpdateView,name="eventUpdate"),
    path('booking/',EventBookingView,name="eventBooking"),
    path('booking/list/',EventBookingList,name="eventBookingList"),

]


def binary_search(array, value, left, right) -> int:
    if left > right:
        return left

    mid = (left + right) // 2

    if value == array[mid]:
        return mid
    elif value > array[mid]:
        return binary_search(array, value, mid + 1, right)
    elif value < array[mid]:
        return binary_search(array, value, left, mid - 1)

def insertion_sort(array):
    for index in range(1, len(array)):
        value = array[index]
        pos = binary_search(array, value, 0, index - 1)
        array = array[:pos] + [value] + array[pos + 1:index] + array[index + 1:]
    return array

def merge(left, right):
    if not left:
        return right

    if not right:
        return left

    if left[0] < right[0]:
        return [left[0]] + merge(left[1:], right)
    else:
        return [right[0]] + merge(left, right[1:])

def tim_sort(array):
    runs, sorted_runs = [], []
    new_run = [array[0]]

    # for every i in the range of 1 to length of array
    for i in range(1, len(array)):
        # if i is at the end of the list
        if i == len(array) - 1:
            new_run.append(array[i])
            runs.append(new_run)
            break
        # if the i'th element of the array is less than the one before it
        if array[i] < array[i-1]:
            # if new_run is set to None (NULL)
            if not new_run:
                runs.append([array[i]])
                new_run.append(array[i])
            else:
                runs.append(new_run)
                new_run = []
        # else if its equal to or more than
        else:
            new_run.append(array[i])

    # for every item in runs, append it using insertion sort
    for item in runs:
        sorted_runs.append(insertion_sort(item))

    # for every run in sorted_runs, merge them
    sorted_array = []
    for run in sorted_runs:
        sorted_array = merge(sorted_array, run)

    return sorted_array

print(tim_sort([2, 3, 5, 6, 7, 4, 8, 9]))


# -*- coding: UTF-8 -*-
# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/two-sum

# Given an array of integers, return indices of the two numbers such that they add up to a specific target.

# You may assume that each input would have exactly one solution, and you may not use the same element twice.

# -----------------
# Example:

# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
# -----------------

class Solution:
    def twoSum1(self, nums: List[int], target: int) -> List[int]: # 二分法
        orig = {}
        for idx, item in enumerate(nums) :
            if item in orig : orig[item].append(idx)
            else :
                orig[item] = idx
        nums = sorted(nums)
        for i in range(0, len(nums) - 1) :
            if nums[i] + nums[-1] < target : continue
            t2 = target - nums[i]
            a  = i
            b  = len(nums)
            while a + 1 < b :
                m = (a + b) // 2
                if   nums[m] < t2 : a = m
                elif nums[m] > t2 : b = m
                else :
                    num1 = nums[i]
                    num2 = nums[m]
                    break
        if num1 == num2 :
            return(orig[num1])
        else :
            return([orig[num1], orig[num2]])

    def twoSum2(self, nums: List[int], target: int) -> List[int]: # hash搜索
        d = {}
        for idx, item in enumerate(nums) :
            if target - item in d : return [d[target - item], idx]
            d[item] = idx

print(Solution().twoSum1([3,2,4],6))
print(Solution().twoSum2([7,2,7],14))
# print(Solution().twoSum([7,8,9,10,14],18))


import csv
from utils import is_substring
import spacy

class NasariReader :

    def __init__(self, filepath, language):
        self.filepath = filepath
        self.language = language
        self.dictionnary = self.readNasariUnified(filepath)
        if self.language == 'en' or self.language =='english' :
            self.nlp = spacy.load('en_core_web_sm')
        elif self.language == 'fr' or self.language == 'french' :
            self.nlp = spacy.load('fr_core_news_sm')

    def readNasariUnified(self, source):
        dictionnary_id_title = {}
        with open(source, encoding="utf8") as src:
                for line in csv.reader(src, delimiter='\t', quoting=csv.QUOTE_NONE):
                    dictionnary_id_title[line[0]] = line[1]
                    # nasari_id_vector[line[0]] = {}
                    # dim_split = [dim.split("_") for dim in line[2:]]
                    # nasari_id_vector[line[0]] = {dim: float(score) for [dim, score] in dim_split}
        return dictionnary_id_title

    def getBNForString(self, string):
        if len(string.split()) == 1 :
            return [id for id,title in self.dictionnary.items() if is_substring(string,title)]
        else :
            processed_string = str(string)
            doc = self.nlp(processed_string)
            subject = [tok.text for tok in doc if tok.dep_ == 'ROOT'][0] # nominal sentences and take only one root
            return [id for id, title in self.dictionnary.items() if is_substring(subject,title)]


from __future__ import print_function
from builtins import range
from builtins import object
from libedwa import *

def profile(filename):
    """
    Transparently add profiling to a particular function call.

    @profile("profile_output.prof")
    def my_function(arg1, arg2):
        pass

    Then from ipython:
        import pstats
        p = pstats.Stats("profile_output.prof")
        p.sort_stats("cumu").print_stats(50)
        p.sort_stats("time").print_stats(50)
    """
    import functools
    try: import cProfile as profile
    except ImportError: import profile
    def curried_decorator(f):
        def decorated_f(*args, **kwargs):
            g = f # so that it becomes locally visible
            l = locals() # to capture the return value
            profile.runctx("retval = g(*args, **kwargs)", globals(), l, filename)
            return l['retval']
        functools.update_wrapper(decorated_f, f)
        return decorated_f
    return curried_decorator

class ExerciseApi(object):
    """Simple demonstration of the API, without real HTTP requests."""
    def run3(self):
        import sqlalchemy as sa
        db = sa.create_engine("sqlite:///tmp-edwa.db")
        #db = sa.create_engine("sqlite:///:memory:")
        #self.run(DatabaseEDWA, db, None)
        conn = db.connect()
        trans = conn.begin()
        try:
            self.run(DatabaseEDWA, conn, None)
        finally:
            trans.commit()
            conn.close()
    def run2(self):
        self.run(KeyczarEDWA, "/home/ian.davis/tmp-pycrypto/crypt_keys")
    def run1(self):
        self.run(EDWA, 'my-secret-key')
    @profile("edwa.prof")
    def run(self, EdwaClass, *args):
        def show(action_id):
            print(("    Action ID length:", len(action_id)))
            return action_id
        edwa = EdwaClass(*args)
        edwa.start("<FAKE_REQUEST>", self.page1)
        edwa.run("<FAKE_REQUEST>", show(edwa.make_noop()), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_action(self.action3)), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_call(self.page2, return_handler=self.onreturn1)), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_action(self.action1)), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_goto(self.page3)), edwa.make_page_data())
        for i in range(100): edwa.make_goto(self.page4)
        edwa.run("<FAKE_REQUEST>", show(edwa.make_action(self.action1)), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_action(self.action2)), edwa.make_page_data()) # this does a call()
        edwa.run("<FAKE_REQUEST>", show(edwa.make_return()), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_return("HIMOM!")), edwa.make_page_data())
        edwa.run("<FAKE_REQUEST>", show(edwa.make_action(self.action1)), edwa.make_page_data())
        print("Suspending...")
        action_id = edwa.make_noop() # save current state
        page_data = edwa.make_page_data()
        print("Re-animating...")
        edwa = EdwaClass(*args) # clean object
        edwa.run("<FAKE_REQUEST>", action_id, page_data) # restore state (current view, etc)
        ## This makes encoding expensive (~ 1 sec), b/c it adds 100 large Action objects to be interned.
        for i in range(100): edwa.make_goto(self.page4)
        return edwa
    def page1(self, request, edwa):
        print("On page 1.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def page2(self, request, edwa):
        print("On page 2.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def page3(self, request, edwa):
        print("On page 3.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def page4(self, request, edwa):
        print("On page 4.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def action1(self, request, edwa):
        print("  Entering action 1.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
        edwa.context['foo'] = 'bar'
        edwa.context['big'] = list(range(10000))
        print("  Exiting action 1.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def action2(self, request, edwa):
        print("  Entering action 2.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
        edwa.do_call(self.page4, {"fizz":"buzz"}, self.onreturn1, "EXTRA-STUFF")
        print("  Exiting action 2.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def action3(self, request, edwa):
        print("  Entering action 3.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
        edwa.context['name'] = 'John Q. Public'
        edwa.context['address'] = '123 Main St, Ste 456'
        edwa.context['city'] = 'Couldabeenanywhere'
        edwa.context['state'] = 'Alaska'
        edwa.context['zip'] = '12345-6789'
        edwa.context['phone_home'] = '555-987-6543'
        print("  Exiting action 3.  Request=%s.  Context=%s." % (request, list(edwa.context.keys())))
    def onreturn1(self, edwa, return_value, return_context):
        print("Return value %s in context %s" % (return_value, return_context))


from tkinter import *
def reduce(c):
	global outList
	outList = [0,0,0]
	outList[0] = c[0]//3
	outList[1] = c[1]//3
	outList[2] = c[2]//3
	return outList
broke = 1
try:
	c0 = int(input("Please give me a value: "))
	c1 = int(input("Now give me another: "))
	c2 = int(input("And another: "))
	col1 = (c0,c1,c2)
	reduce(col1)
	print(outList)
	broke <= 1
except ValueError:
	print("pls I said a value or integer")
	broke = 1
root = Tk()
root.mainloop()


import cv2
import numpy as np

# 매칭을 위한 이미지 읽기
target = cv2.imread('../img/4star.jpg') # 매칭 대상
shapes = cv2.imread('../img/shapestomatch.jpg') # 여러 도형
# 그레이 스케일 변환
targetGray = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
shapesGray = cv2.cvtColor(shapes, cv2.COLOR_BGR2GRAY)
# 바이너리 스케일 변환
ret, targetTh = cv2.threshold(targetGray, 127, 255, cv2.THRESH_BINARY_INV)
ret, shapesTh = cv2.threshold(shapesGray, 127, 255, cv2.THRESH_BINARY_INV)
# 컨투어 찾기
cntrs_target, _ = cv2.findContours(targetTh, cv2.RETR_EXTERNAL, \
                                            cv2.CHAIN_APPROX_SIMPLE)[-2:]
cntrs_shapes, _ = cv2.findContours(shapesTh, cv2.RETR_EXTERNAL, \
                                            cv2.CHAIN_APPROX_SIMPLE)[-2:]

# 각 도형과 매칭을 위한 반복문
matchs = [] # 컨투어와 매칭 점수를 보관할 리스트
for contr in cntrs_shapes:
    # 대상 도형과 여러 도형 중 하나와 매칭 실행 ---①
    match = cv2.matchShapes(cntrs_target[0], contr, cv2.CONTOURS_MATCH_I2, 0.0)
    # 해당 도형의 매칭 점수와 컨투어를 쌍으로 저장 ---②
    matchs.append( (match, contr) )
    # 해당 도형의 컨투어 시작지점에 매칭 점수 표시 ---③
    cv2.putText(shapes, '%.2f'%match, tuple(contr[0][0]),\
                    cv2.FONT_HERSHEY_PLAIN, 1,(0,0,255),1 )
# 매칭 점수로 정렬 ---④
matchs.sort(key=lambda x : x[0])
# 가장 적은 매칭 점수를 얻는 도형의 컨투어에 선 그리기 ---⑤
cv2.drawContours(shapes, [matchs[0][1]], -1, (0,255,0), 3)
cv2.imshow('target', target)
cv2.imshow('Match Shape', shapes)
cv2.waitKey()
cv2.destroyAllWindows()


import json
import socket
import requests
import datetime
import time

ip_address = ''
port = 38899
url = 'https://api.spot-hinta.fi/Justnow'
off_hour = 0
on_hour = 7

while True:
    current_time = datetime.datetime.now().time()

    if current_time.minute == 2:
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()

            price_with_tax = data['PriceWithTax']
            price_with_tax *= 100
            print(f"Price with tax: {price_with_tax}")

            # Determine the color based on the price range
            if price_with_tax < 7:
                command = {
                    'id': 1,
                    'method': 'setPilot',
                    'params': {
                        'r': 0,
                        'g': 255,
                        'b': 0,
                        'dimming': 100
                    }
                }
            elif 7 <= price_with_tax <= 15:
                command = {
                    'id': 1,
                    'method': 'setPilot',
                    'params': {
                        'r': 255,
                        'g': 255,
                        'b': 0,
                        'dimming': 100
                    }
                }
            else:
                command = {
                    'id': 1,
                    'method': 'setPilot',
                    'params': {
                        'r': 255,
                        'g': 0,
                        'b': 0,
                        'dimming': 100
                    }
                }

            if off_hour >= current_time.hour <= on_hour:
                command = {
                    'id': 1,
                    'method': 'setPilot',
                    'params': {
                        'state': 'false'
                    }
                }

            print(command)
            command_string = json.dumps(command)
            message = command_string.encode()

            client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            client_socket.sendto(message, (ip_address, port))
            client_socket.close()
        else:
            print(f'Failed to fetch data. Status code: {response.status_code}')

    # Delay until the next target time
    next_hour = (datetime.datetime.now() + datetime.timedelta(hours=1)).replace(minute=2, second=0, microsecond=0)
    time.sleep((next_hour - datetime.datetime.now()).total_seconds())


import json
from django import http
from django.shortcuts import render
from django.views import View
from goods.models import SKU
from django_redis import get_redis_connection
from meiduo_mall.utils.response_code import RET
import pickle
import base64

class CartView(View):
    def post(self,request):
        #1,获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")
        count = dict_data.get("count")
        selected = dict_data.get("selected",True)
        user = request.user

        #2,校验参数
        #2.1为空校验
        if not all([sku_id,count]):
            return http.HttpResponseForbidden("参数不全")

        #2.2判断count是否是整数
        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden("购买的数量错误")

        #2,2校验商品对象是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden("商品不存在")

        #2,3校验库存是否充足
        if count > sku.stock:
            return http.HttpResponseForbidden("库存不足")

        #3,判断用户状态
        if user.is_authenticated:
            #3,1获取redis对象
            redis_conn = get_redis_connection("cart")

            #3,2添加数据到redis
            redis_conn.hincrby("cart_%s"%user.id,sku_id,count)

            if selected:
                redis_conn.sadd("cart_selected_%s"%user.id,sku_id)

            #3,返回响应
            return http.JsonResponse({"code":RET.OK})
        else:
            #4,1获取cookie中的购物车数据
            cookie_cart = request.COOKIES.get("cart")

            #4,2判断,转换成字典
            cookie_dict = {}
            if cookie_cart:
                cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

            #4,3累加count
            if sku_id in cookie_dict:
                count += cookie_dict[sku_id].get("count",0)

            #4,4设置新的数据
            cookie_dict[sku_id] = {
                "count":count,
                "selected":selected
            }

            #4,5设置cookie,返回响应
            response = http.JsonResponse({"code": RET.OK})
            cookie_cart = base64.b64encode(pickle.dumps(cookie_dict)).decode()
            response.set_cookie("cart",cookie_cart)

            return response

    def get(self,request):

        #1,判断用户登陆状态
        user = request.user
        if user.is_authenticated:
            #1,获取redis数据
            redis_conn = get_redis_connection("cart")
            cart_dict = redis_conn.hgetall("cart_%s"%user.id)
            cart_selected_list = redis_conn.smembers("cart_selected_%s"%user.id)

            #2,拼接数据
            sku_list = []
            for sku_id,count in cart_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_dict = {
                    "default_image_url":sku.default_image_url.url,
                    "name":sku.name,
                    "price":str(sku.price),
                    "amount":str(sku.price * int(count)),
                    "selected": str(sku_id in cart_selected_list),
                    "count":int(count)
                }
                sku_list.append(sku_dict)

            context = {
                "sku_carts":sku_list
            }
            #3,返回响应
            return render(request,'cart.html',context=context)
        else:
            #4,获取cookie中的数据
            cookie_cart = request.COOKIES.get("cart")

            if not cookie_cart:
                return render(request,'detail.html')

            #5,数据转换
            cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            sku_list = []

            for sku_id,count_selected in cookie_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_dict = {
                    "default_image_url": sku.default_image_url.url,
                    "name": sku.name,
                    "price": str(sku.price),
                    "amount": str(sku.price * int(count_selected["count"])),
                    "selected": str(count_selected["selected"]),
                    "count": int(count_selected["count"])
                }
                sku_list.append(sku_dict)

            #6,返回响应
            context = {
                "sku_carts": sku_list
            }
            # 3,返回响应
            return render(request, 'cart.html', context=context)


import pandas as pd
import streamlit as st

@st.cache()
def get_crash_data_df():

    try:

        df = pd.read_csv("datasets/Allegheny County Crash Data Clean.csv")

    except FileNotFoundError:

        url  ='https://drive.google.com/file/d/1qKICn7Jtw9b9RDv4ACgZVypAamAAFpFE/view?usp=sharing'
        path ='https://drive.google.com/uc?id=' + url.split('/')[-2]

        df = pd.read_csv(path)

        #Data set is trated

        # bool features

        df['SCH_BUS_IND'] = df['SCH_BUS_IND'].replace({
                        'N':0, '0':0, '0.0':0, 0:0, 0.0:0,
                        'Y':1, '1':1, '1.0':1, 1.0:1, 1:1
                    })
        bool_features=['AGGRESSIVE_DRIVING',
        'ALCOHOL_RELATED',
        'BICYCLE',
        'CELL_PHONE',
        'COMM_VEHICLE',
        'CROSS_MEDIAN',
        'CURVE_DVR_ERROR',
        'CURVED_ROAD',
        'DEER_RELATED',
        'DISTRACTED',
        'DRINKING_DRIVER',
        'DRIVER_16YR',
        'DRIVER_17YR',
        'DRIVER_65_74YR',
        'DRIVER_75PLUS',
        'FATAL',
        'FATIGUE_ASLEEP',
        'FIRE_IN_VEHICLE',
        'HAZARDOUS_TRUCK',
        'HIT_BARRIER',
        'HIT_BRIDGE',
        'HIT_DEER',
        'HIT_EMBANKMENT',
        'HIT_FIXED_OBJECT',
        'HIT_GDRAIL',
        'HIT_GDRAIL_END',
        'HIT_POLE',
        'HIT_TREE_SHRUB',
        'HO_OPPDIR_SDSWP',
        'HVY_TRUCK_RELATED',
        'ICY_ROAD',
        'ILLEGAL_DRUG_RELATED',
        'ILLUMINATION_DARK',
        'IMPAIRED_DRIVER',
        'INJURY',
        'INJURY_OR_FATAL',
        'INTERSECTION',
        'INTERSTATE',
        'LANE_CLOSED',
        'LIMIT_65MPH',
        'LOCAL_ROAD',
        'LOCAL_ROAD_ONLY',
        'MOTORCYCLE',
        'NHTSA_AGG_DRIVING',
        'NO_CLEARANCE',
        'NON_INTERSECTION',
        'NTFY_HIWY_MAINT',
        'OVERTURNED',
        'PEDESTRIAN',
        'PHANTOM_VEHICLE',
        'PROPERTY_DAMAGE_ONLY',
        'PSP_REPORTED',
        'REAR_END',
        'SCHOOL_ZONE',
        'SCH_BUS_IND',
        'SIGNALIZED_INT',
        'SNOW_SLUSH_ROAD',
        'SPEEDING',
        'SPEEDING_RELATED',
        'STATE_ROAD',
        'STOP_CONTROLLED_INT',
        'SV_RUN_OFF_RD',
        'TAILGATING',
        'TRAIN',
        'TRAIN_TROLLEY',
        'TROLLEY',
        'TURNPIKE',
        'UNBELTED',
        'UNDERAGE_DRNK_DRV',
        'UNLICENSED',
        'UNSIGNALIZED_INT',
        'VEHICLE_FAILURE',
        'VEHICLE_TOWED',
        'WET_ROAD',
        'WORK_ZONE',
        'WORKERS_PRES',
        'WZ_CLOSE_DETOUR',
        'WZ_FLAGGER',
        'WZ_LAW_OFFCR_IND',
        'WZ_LN_CLOSURE',
        'WZ_MOVING',
        'WZ_OTHER',
        'WZ_SHLDER_MDN',
        ]

        for col in bool_features:
            df[col]=df[col].astype(bool)

        # Int features
        int_features=[
        'AUTOMOBILE_COUNT',
        'BELTED_DEATH_COUNT',
        'BICYCLE_COUNT',
        'BICYCLE_DEATH_COUNT',
        'BUS_COUNT',
        'COMM_VEH_COUNT',
        'CRASH_MONTH',
        'CRASH_YEAR',
        'DAY_OF_WEEK',
        'DRIVER_COUNT_16YR',
        'DRIVER_COUNT_17YR',
        'DRIVER_COUNT_65_74YR',
        'DRIVER_COUNT_75PLUS',
        'FATAL_COUNT',
        'HEAVY_TRUCK_COUNT',
        'HOUR_OF_DAY',
        'INJURY_COUNT',
        'MCYCLE_DEATH_COUNT',
        'MOTORCYCLE_COUNT',
        'OFFSET',
        'PED_COUNT',
        'PED_DEATH_COUNT',
        'PERSON_COUNT',
        'SUV_COUNT',
        'UNB_DEATH_COUNT',
        'UNK_INJ_DEG_COUNT',
        'UNK_INJ_PER_COUNT',
        'VAN_COUNT',
        'VEHICLE_COUNT',
                ]
        for col in int_features:
            print(col)
            df[col]=df[col].astype(int, errors='ignore')

        # Categorical fetures
        categorical_feature_dicts = {
            "COLLISION_TYPE":{  0 : 'Non collision',
                                1 : 'Rear-end',
                                2 : 'Head-on',
                                3 : 'Rear-to-rear (Backing)',
                                4 : 'Angle',
                                5 : 'Sideswipe (same dir.)',
                                6 : 'Sideswipe (Opposite dir.)',
                                7 : 'Hit fixed object',
                                8 : 'Hit pedestrian',
                                9 : 'Other or Unknown',
                                98 : 'Other',
                                99 : 'Unknown'},
            "DAY_OF_WEEK": {
                1 : 'Sunday',
                2 : 'Monday',
                3 : 'Tuesday',
                4 : 'Wednesday',
                5 : 'Thursday',
                6 : 'Friday',
                7 : 'Saturday',
                    },
            "ILLUMINATION":{
                1 : "Daylight",
                2 : "Dark - no street lights",
                3 : "Dark - street lights",
                4 : "Dusk",
                5 : "Dawn",
                6 : "Dark - unknown roadway lighting",
                8 : "Other",
                9 : "Unknown (expired)",
            },
            "INTERSECT_TYPE":{  0 : 'Mid-block',
                                1 : 'Four way intersection',
                                2 : '"T" intersection',
                                3 : '"Y" intersection',
                                4 : 'Traffic circle or Round About',
                                5 : 'Multi-leg intersection',
                                6 : 'On ramp',
                                7 : 'Off ramp',
                                8 : 'Crossover',
                                9 : 'Railroad crossing',
                                10 : 'Other',
                                99 : 'Unknown (expired)',
                                11: 'Unknown (expired)',
                                12: 'Unknown (expired)',
                            },
            "LN_CLOSE_DIR":{1 : "North",
                            2 : "South",
                            3 : "East",
                            4 : "West",
                            5 : "North and South",
                            6 : "East and West",
                            7 : "All",
            },
            "LOCATION_TYPE":{
                0 : 'Not applicable',
                1 : 'Underpass',
                2 : 'Ramp',
                3 : 'Bridge',
                4 : 'Tunnel',
                5 : 'Toll Booth',
                6 : 'Cross over related',
                7 : 'Driveway or Parking Lot',
                8 : 'Ramp and bridge',
                9 : 'Unknown',
            },

            'MAX_SEVERITY_LEVEL' :{
                                0 : 'Not injured',
                                1 : 'Killed',
                                2 : 'Major injury',
                                3 : 'Moderate injury',
                                4 : 'Minor injury',
                                8 : 'Injury/ Unknown Severity',
                                9 : 'Unknown'
                                },
            'RDWY_SURF_TYPE_CD':{
                1 : 'Concrete',
                2 : 'Blacktop',
                3 : 'Brick or Block',
                4 : 'Slag, Gravel, or Stone',
                5 : 'Dirt',
                8 : 'Other',
                9 : 'Unknown',
            },
            'RELATION_TO_ROAD':{
                1 : 'On roadway',
                2 : 'Shoulder',
                3 : 'Median',
                4 : 'Roadside (off trafficway; on vehicle area)',
                5 : 'Outside trafficway (in area not meant for vehicles)',
                6 : 'In parking lane',
                7 : 'Gore (intersection of ramp and highway)',
                9 : 'Unknown'
            },
            'ROAD_CONDITION':{
                0 : 'Dry',
                1 : 'Wet',
                2 : 'Sand/ mud/ dirt/ oil/ or gravel',
                3 : 'Snow covered',
                4 : 'Slush',
                5 : 'Ice',
                6 : 'Ice Patches',
                7 : 'Water - standing or moving',
                8 : 'Other',
                9 : 'Unknown (expired)',
                98 : 'Other',
                99 : 'Unknown'
            },
            'ROAD_OWNER':{
                1 : 'Interstate - non turnpike',
                2 : 'State highway',
                3 : 'County road',
                4 : 'Local road or street',
                5 : 'East-West portion of turnpike',
                6 : 'Turnpike spur (extension)',
                7 : 'Private Road',
                9 : 'Other or Unknown'
            },
            'SPEC_JURIS_CD':{
                0 : 'No Special Jurisdiction',
                1 : 'National Park',
                2 : 'Military',
                3 : 'Indian Reservation',
                4 : 'College/University Campus',
                5 : 'Other Federal Sites',
                8 : 'Other',
                9 : 'Unknown'
                },
            'TCD_FUNC_CD':{
                0 : 'No Controls',
                1 : 'Device not Functioning',
                2 : 'Device Functioning improperly',
                3 : 'Device Functioning properly',
                4 : 'Emergency Preemptive Signal',
                9 : 'Unknown'
            },
            'TCD_TYPE':{
                0 : 'Not applicable',
                1 : 'Flashing traffic signal',
                2 : 'Traffic signal',
                3 : 'Stop sign',
                4 : 'Yield sign',
                5 : 'Active RR crossing controls',
                6 : 'Passive RR crossing controls',
                7 : 'Police officer or flagman',
                8 : 'Other Type TCD',
                9 : 'Unknown',
            },
        'WEATHER' :{1 : 'Blowing Sand, Soil, Dirt',
            2 : 'Blowing Snow',
            3 : 'Clear',
            4 : 'Cloudy',
            5 : 'Fog, Smog, Smoke',
            6 : 'Freezing Rain or Freezing Drizzle',
            7 : 'Rain',
            8 : 'Severe Crosswinds',
            9 : 'Sleet or Hail',
            10 : 'Snow',
            98 : 'Other',
            99 : 'Unknown'},

            'WORK_ZONE_LOC':{
                1 : 'Before the 1st work zone warning sign',
                2 : 'Advance warning area',
                3 : 'Transition area',
                4 : 'Activity area',
                5 : 'Termination area',
                8 : 'Other'
            },

            'WORK_ZONE_TYPE':{  1 : 'Construction',
                                2 : 'Maintenance',
                                3 : 'Utility company',
                                8 : 'Other'}
        }

        for key in categorical_feature_dicts.keys():
            df[key] = df[key].replace(categorical_feature_dicts[key])
            df[key]=df[key].astype('category', errors='ignore')

        float_features = [
                    'SPEED_LIMIT',
                    'CONS_ZONE_SPD_LIM',
        ]

        for key in float_features:
            df[key]=df[key].astype(float)

        str_features = ['ADJ_RDWY_SEQ',
                    "ACCESS_CTRL",

        ]

        for key in str_features:
            df[key]=df[key].astype(str)

        df.to_csv("datasets/Allegheny County Crash Data Clean.csv")

    finally:

        return df

@st.cache()
def get_gridwise_data_df():
    try:

        df = pd.read_csv("datasets/gridwise_df.csv")

    except FileNotFoundError:

        url  ='https://drive.google.com/file/d/1iiJ4N3H1ZcBSmxPbi1wNn9B-QZudQiaP/view?usp=sharing'
        path ='https://drive.google.com/uc?id=' + url.split('/')[-2]

        df = pd.read_csv(path)

        df.to_csv("datasets/gridwise_df.csv")

    finally:

        return df

@st.cache()
def get_intersections_clust_data_df():
    try:

        df = pd.read_csv("datasets/intersections_cluster_df.csv")

    except FileNotFoundError:

        url  ='https://drive.google.com/file/d/1c42lpKgqX8ofAwcm2Zh5yy0lGu43rqrH/view?usp=sharing'
        path ='https://drive.google.com/uc?id=' + url.split('/')[-2]

        df = pd.read_csv(path)

        df.to_csv("datasets/intersections_cluster_df.csv")

    finally:

        return df

@st.cache()
def get_bikes_clust_data_df():
    try:

        df = pd.read_csv("datasets/bikes_cluster_df.csv")

    except FileNotFoundError:

        url  ='https://drive.google.com/file/d/1-0xCBSypYJvb_fNcbAjvg2bT_A8DA-yZ/view?usp=sharing'
        path ='https://drive.google.com/uc?id=' + url.split('/')[-2]

        df = pd.read_csv(path)

        df.to_csv("datasets/bikes_cluster_df.csv")

    finally:

        return df


# medium

'''
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.

The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.

For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
'''

# https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/

# Two pointer
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:

        left = right = head
        count = 1

        if left.next == None:
            return None

        while right.next:
            right = right.next
            count += 1

        step = count // 2

        for _ in range(step-1):
            left = left.next

        left.next = left.next.next

        return head

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:

        if head.next == None:
            return None

        slow = head
        fast = head.next.next

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        slow.next = slow.next.next

        return head

# Time complexity = O(n)
# Space complexity = O(1)

Medium/2095. Delete the Middle Node of a Linked List.py


__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"

from typing import Dict, Iterable, Optional

import numpy as np
import paddlehub as hub
from jina import DocumentArray, Executor, requests
from jina_commons.batching import get_docs_batch_generator

class TextPaddleEncoder(Executor):
    """
    Encode an array of string in size `B` into an ndarray in size `B x D`

    The ndarray potentially is BatchSize x (Channel x Height x Width)

    Internally, :class:`TextPaddlehubEncoder` wraps the Ernie module from paddlehub.
    https://github.com/PaddlePaddle/PaddleHub
    For models' details refer to
        https://www.paddlepaddle.org.cn/hublist?filter=en_category&value=SemanticModel
    """

    def __init__(
        self,
        model_name: Optional[str] = 'ernie_tiny',
        traversal_paths: Iterable[str] = ('r',),
        batch_size: int = 32,
        device: str = 'cpu',
        *args,
        **kwargs,
    ):
        """
        :param model_name: the name of the model. Supported models include
            ``ernie``, ``ernie_tiny``, ``ernie_v2_eng_base``, ``ernie_v2_eng_large``,
            ``bert_chinese_L-12_H-768_A-12``, ``bert_multi_cased_L-12_H-768_A-12``,
            ``bert_multi_uncased_L-12_H-768_A-12``, ``bert_uncased_L-12_H-768_A-12``,
            ``bert_uncased_L-24_H-1024_A-16``, ``chinese-bert-wwm``,
            ``chinese-bert-wwm-ext``, ``chinese-electra-base``,
            ``chinese-electra-small``, ``chinese-roberta-wwm-ext``,
            ``chinese-roberta-wwm-ext-large``, ``rbt3``, ``rbtl3``
        :param traversal_paths: fallback traversal path in case there is not traversal path sent in the request
        :param batch_size: fallback batch size in case there is not batch size sent in the request
        :param device: Device to be used. Use 'gpu' for GPU or use 'cpu' for CPU.
        """
        super().__init__(*args, **kwargs)
        self.device = device
        self.model = hub.Module(name=model_name)
        self.batch_size = batch_size
        self.traversal_paths = traversal_paths

    @requests
    def encode(
        self, docs: Optional[DocumentArray] = None, parameters: Dict = {}, **kwargs
    ):
        """Encode doc content into vector representation.

        :param docs: documents sent to the encoder. The docs must have the
            ``text`` attribute.
        :param parameters: dictionary to define the `traversal_paths` and the `batch_size`. For example,
            `parameters={'traversal_paths': ['r'], 'batch_size': 10}`.
        :param kwargs: Additional key value arguments.
        """
        if docs:
            document_batches_generator = get_docs_batch_generator(
                docs,
                traversal_path=parameters.get('traversal_paths', self.traversal_paths),
                batch_size=parameters.get('batch_size', self.batch_size),
                needs_attr='text',
            )
            for batch_of_docs in document_batches_generator:
                pooled_features = []
                contents = [[doc.content] for doc in batch_of_docs]
                results = self.model.get_embedding(
                    contents, use_gpu=self.device == 'gpu'
                )
                for pooled_feature, _ in results:
                    pooled_features.append(pooled_feature)
                for doc, feature in zip(batch_of_docs, pooled_features):
                    doc.embedding = np.asarray(feature)


import click
import uvicorn

import torch as th
import torch.multiprocessing as tmp

from loguru import logger
from typing import List, Tuple, Dict, Optional

from os import path
from glob import glob
from time import perf_counter, sleep

import multiprocessing as mp

from server import start_server
from vectorizer import start_vectorizer

@click.group(chain=False, invoke_without_command=True)
@click.option('--transformers_cache', envvar='TRANSFORMERS_CACHE', required=True)
@click.option('--gpu_index', help='index of the target gpu card, if cuda not availble, model will be on cpu. this value can be on of [0..7] for 8 gpu card', type=click.IntRange(min=0, max=8), default=0)
@click.pass_context
def command_line_interface(ctx:click.core.Context, transformers_cache:str, gpu_index:int):
    ctx.ensure_object(dict)
    ctx.obj['cache_folder'] = transformers_cache
    ctx.obj['gpu_index'] = gpu_index
    crr_command = ctx.invoked_subcommand
    if crr_command is not None:
        logger.debug(f'{crr_command} was called')

@command_line_interface.command()
@click.option('--port', type=int)
@click.option('--hostname', type=str)
@click.option('--transformer_model_name', type=str, default='Sahajtomar/french_semantic')
@click.option('--language_model_name', type=str, default='fr_core_news_md')
@click.option('--router_address', type=str, default='ipc://router.ipc')
@click.option('--publisher_address', type=str, default='ipc://publisher.ipc')
@click.option('--mounting_path', type=str, default='/')
@click.pass_context
def start_services(ctx:click.core.Context, port:int, hostname:str, transformer_model_name:str, language_model_name:str, router_address:str, publisher_address:str, mounting_path:str):
    assert mounting_path.startswith('/')
    cache_folder = ctx.obj['cache_folder']

    workers_barrier = mp.Barrier(parties=2)

    server_process = mp.Process(
        target=start_server,
        kwargs={
            'port': port,
            'hostname': hostname,
            'mounting_path': mounting_path,
            'router_address': router_address,
            'publisher_address': publisher_address,
            'workers_barrier': workers_barrier
        }
    )

    vectorizer_process = mp.Process(
        target=start_vectorizer,
        kwargs={
            'transformer_model_name': transformer_model_name,
            'language_model_name': language_model_name,
            'cache_folder': cache_folder,
            'router_address': router_address,
            'publisher_address': publisher_address,
            'workers_barrier': workers_barrier,
            'gpu_index': ctx.obj['gpu_index']
        }
    )

    try:
        vectorizer_process.start()
        server_process.start()

        keep_loop = True
        while keep_loop:
            sleep(1)
            if not vectorizer_process.is_alive() or not server_process.is_alive():
                keep_loop = False
        # ...!
        logger.warning('some problems to start all workrs')
        workers_barrier.abort()
    except KeyboardInterrupt:
        logger.debug('ctl+c ...!')
        vectorizer_process.join()
        server_process.join()
    except Exception as e:
        logger.error(e)
    finally:
        vectorizer_process.terminate()
        server_process.terminate()
        vectorizer_process.join()
        server_process.join()

if __name__ == '__main__':
    if th.cuda.is_available():
        tmp.set_start_method('spawn')
    command_line_interface()


from test_Common import Log
from test_Common import Email
from test_Config import Config
from test_Common.Report import run_case_main

if __name__ == '__main__':
    # 读取Config 配置信息
    conf = Config.Config()
    log = Log.MyLog()
    log.info('初始化配置文件, path=' + conf.conf_path)

# 运行 测试用例，生成报告
try:
    run_case_main()
except Exception:
    log.error('执行用例失败，请检查环境配置')
    raise

# 发送测试报告邮件
try:
    mail = Email.SendMail()
    mail.sendMail()
except Exception as e:
    log.error('发送邮件失败，请检查邮件配置')
    raise


#!/user/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 这两句代码输出一个5阶单位矩阵
A = np.eye(5)
print(A)

# 从文件读取数据保存为 dataFrame
path = './ex1data1.txt'
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])

# 这两句代码将数据在平面坐标系中画出来，x轴表示人口，y轴表示利润
# data.plot(kind='scatter', x='Population', y='Profit')
# plt.show()

# 定义代价函数
def compute_cost(X, y, theta):
    inner = X @ theta.T - y
    square_sum = inner.T @ inner
    return square_sum / (2*X.shape[0])

# 构造 X 矩阵
def get_X(df):
    ones = pd.DataFrame({'ones': np.ones(len(df))})
    data_new = pd.concat([ones, df], axis=1)
    return data_new.iloc[:, :-1].values

# 构造 y
def get_y(df):
    return np.array(df.iloc[:, -1:])

# 特征缩放 mean 函数求均值，std 函数求标准差
def normalize_feature(df):
    return df.apply(lambda column : (column - column.mean()) / column.std())

X = get_X(data)
y = get_y(data)
# X = np.asmatrix(get_X(data))
# y = np.asmatrix(get_y(data))
theta = np.zeros((1, X.shape[1]))

# print(compute_cost(X, y, theta))
# print(theta.ravel().shape[1])

# 梯度递减函数，迭代实现
def gradient_descent(X, y, theta, alpha, iters):
    temp = theta.copy()
    cost = [compute_cost(X, y, theta)[0]]
    m = X.shape[0]

    for i in range(iters):
        error = X.T @ (X @ temp.T - y) / m
        temp = temp - alpha * error.T
        cost.append(compute_cost(X, y, temp)[0])
    return temp, cost

alpha = 0.01
iters = 500
theta_, cost = gradient_descent(X, y, theta, alpha, iters)

print(np.array(cost))
# print(cost)
# x = np.linspace(data.Population.min(), data.Population.max(), 100)
# f = theta_[0] + (theta_[1] * x)

# plt.plot(x, f, 'r', label='Prediction')
# plt.scatter(data.Population, data.Profit, label='Traning Data')
# plt.legend(loc=2)
# plt.xlabel('Population')
# plt.ylabel('Profit')
# plt.title('Predicted Profit vs. Population Size')
# plt.show()

# fig, ax = plt.subplots()
# ax.plot(x, f, 'r', label='Prediction')
# ax.scatter(data.Population, data.Profit, label='Traning Data')
# ax.legend(loc=2)
# ax.set_xlabel('Population')
# ax.set_ylabel('Profit')
# ax.set_title('Predicted Profit vs. Population Size')
# plt.show()

# x = range(0,501)
# plt.plot(x, cost)
# plt.xlabel('iterations')
# plt.ylabel('cost')
# plt.show()


import random
import webbrowser
import time
from unittest import result

Chiffres = "0123456789"
Lettres = "abcdefghijklmnopqrstuvwxyz"
Lettres1 = "ABCDEFGHIJKLMNOP"
Lien =  "https://discord.gift/"

Tout = Chiffres + Lettres + Lettres1
longeur = 18

time.sleep(10)
##############
x = 40
###############
for i in range(x):

    Séquence = "".join(random.sample(Tout, longeur))

    result = Lien + Séquence

    webbrowser.open(result)
    print(result)


from jsonschema._validators import required
from rest_framework import serializers

from onepageapi.stats.models import TgUser, UserForcing

class TgUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = TgUser
        fields = "__all__"

class UserForcingSerializer(serializers.ModelSerializer):
    tg_user_id = serializers.CharField(required=True, write_only=True)

    class Meta:
        model = UserForcing
        exclude = "tg_user",


from datetime import datetime

import logging as log
import os.path
import re
import threading

try:
    import queue as Queue
except ImportError:
    import Queue

from avocado.utils import process

from virttest import utils_libvirtd
from virttest import utils_misc
from virttest import utils_package
from virttest import virsh

from virttest.libvirt_xml import network_xml
from virttest.utils_test import libvirt

msg_queue = Queue.Queue()

# Using as lower capital is not the best way to do, but this is just a
# workaround to avoid changing the entire file.
logging = log.getLogger('avocado.' + __name__)

def start_journal():
    """
    Track system journal
    """

    ret = process.run("journalctl -f", shell=True, verbose=True, ignore_status=True)
    msg_queue.put(ret.stdout_text)

def test_check_journal(params, test):
    """
    Test restart libvirtd with running guest.
    1) Start a guest;
    2) Start journal;
    3) Restart libvirtd;
    4) Check the output of `journalctl -f`;
    5) Check libvirtd log

    :param params: dict, test parameters
    :param test: test object
    """
    libvirtd_debug_file = params.get("libvirtd_debug_file")
    error_msg_in_journal = params.get("error_msg_in_journal")
    error_msg_in_log = params.get("error_msg_in_log")
    ignore_log_err_msg = params.get("ignore_log_err_msg", "")

    utils_libvirtd.Libvirtd("libvirtd-tls.socket").stop()
    utils_libvirtd.Libvirtd("libvirtd-tcp.socket").stop()

    # Start journal
    monitor_journal = threading.Thread(target=start_journal, args=())
    monitor_journal.start()

    # Restart libvirtd
    libvirtd = utils_libvirtd.Libvirtd()
    libvirtd.restart()

    monitor_journal.join(2)

    # Stop journalctl command
    utils_misc.kill_process_by_pattern("journalctl")
    output = msg_queue.get()
    # Check error message in journal
    if re.search(error_msg_in_journal, output):
        test.fail("Found error message during libvirtd restarting: %s" % output)
    else:
        logging.info("Not found error message during libvirtd restarting.")

    # Check error messages in libvirtd log
    libvirt.check_logfile(error_msg_in_log, libvirtd_debug_file,
                          False, ignore_str=ignore_log_err_msg)

def get_installable_old_libvirt(installed_version, test):
    """
    Get old version of libvirt package available to be installed

    :param installed_version: str, version info
    :param test: test object

    :return: str, version installable
    """
    cmd = 'dnf list libvirt --showduplicates --available'
    cmd_ret = process.run(cmd,
                          shell=True,
                          ignore_status=False,
                          verbose=True)
    versions = re.findall(r"\s+(\d+.*\d+)\s+\w+", cmd_ret.stdout_text.strip())
    versions = versions[::-1]
    old_version = None
    for one_version in versions:
        if one_version < installed_version:
            old_version = one_version
            break
    if not old_version:
        test.cancel("There are no older libvirt packages "
                    "available in the repos")
    return old_version

def downgrade_libvirt(test):
    """
    Install older version of libvirt packages

    :param test: test object
    """
    cmd = 'yum list libvirt --showduplicates --installed'
    cmd_ret = process.run(cmd, shell=True, ignore_status=False,
                          verbose=True)
    installed_version = re.findall(r"libvirt.*\s+(\d.*\d)\s", cmd_ret.stdout_text.strip())
    if not installed_version:
        test.cancel("libvirt packages are not installed")
    else:
        test.log.debug("Step: Current installed libvirt version %s", installed_version)
    if not utils_package.package_remove('libvirt'):
        test.error("Fail to uninstall current libvirt packages")
    else:
        test.log.debug("Step: Installed libvirt packages are removed")
    old_version = get_installable_old_libvirt(installed_version[0], test)
    if not utils_package.package_install('libvirt-%s' % old_version):
        test.error("Fail to install libvirt package %s" % ('libvirt-%s' % old_version))
    else:
        test.log.debug("Step: Libvirt %s is installed", old_version)

def update_conf_files(params, test):
    """
    Update configuration files

    :param params: dict, test parameters
    :param test: test object
    """
    def _customize_conf(conf_dict, config_type):
        if config_type == 'sysconfig':
            sysconfig_conf_path = params.get('sysconfig_conf_path')
            if not os.path.exists(sysconfig_conf_path):
                process.run('touch %s' % sysconfig_conf_path)
                params['delete_file'] = sysconfig_conf_path
        is_force = True if config_type == 'libvirtd' else False
        conf_obj = libvirt.customize_libvirt_config(conf_dict,
                                                    config_type=config_type,
                                                    restart_libvirt=False,
                                                    force=is_force)
        test.log.debug("%s is updated", conf_obj.conf_path)
        return conf_obj

    libvirt_conf_dict = eval(params.get("libvirt_conf_dict"))
    sysconfig_conf_dict = eval(params.get("sysconfig_conf_dict"))
    libvirtd_conf_dict = eval(params.get("libvirtd_conf_dict"))
    config_dict = {}
    config_dict.update({'libvirt': _customize_conf(libvirt_conf_dict, 'libvirt')})
    config_dict.update({'sysconfig': _customize_conf(sysconfig_conf_dict, 'sysconfig')})
    config_dict.update({'libvirtd': _customize_conf(libvirtd_conf_dict, 'libvirtd')})
    params['config_dict'] = config_dict

def setup_default(params, test):
    pass

def setup_upgrade_with_legacy_mode(params, test):
    """
    Setup for libvirt package upgrade test with non-socket activation mode

    :param params: dict, test parameters
    :param test: test object
    """
    downgrade_libvirt(test)
    update_conf_files(params, test)
    daemons_masked = params.get('daemons_masked')
    process.run("systemctl mask %s" % daemons_masked, shell=True, ignore_status=False, verbose=True)
    test.log.debug("Step: The socket files were masked")
    process.run("systemctl restart libvirtd", shell=True, ignore_status=False)
    test.log.debug("Step: The libvirtd daemon is restarted")
    # In 'systemctl status libvirtd output, there might be below error:
    #   -- libvirtd[xxx]: operation failed: network 'default' already exists with uuid xxx
    # The error might impact on following cases because it exists in journal file.
    # Below two steps are to eliminate the bad impact.
    net_obj = network_xml.NetworkXML()
    if net_obj.get_active():
        virsh.net_destroy('default', ignore_status=False, debug=True)
        test.log.debug("Step: The default network is destroyed "
                       "in order to avoid the systemd error")
    process.run("systemctl restart libvirtd", shell=True, ignore_status=False)

def get_libvirtd_pid(test):
    """
    Get the PID of libvirtd process

    :param test: test object
    :return： tuple, (pid, stdout)
    """
    ret = process.run("systemctl status libvirtd", shell=True, verbose=True)
    pat = r"Main PID:\s+(\d+)\s+\(libvirtd\)"
    match_obj = re.findall(pat, ret.stdout_text.strip())
    if not match_obj:
        test.error("libvirtd daemon is not started correctly and no PID is found")
    return match_obj[0], ret.stdout_text.strip()

def test_upgrade_with_legacy_mode(params, test):
    """
    Test for upgrading libvirt package in non-socket activation mode

    :param params: dict, test parameters
    :param test: test object
    """
    old_dt = datetime.now()
    old_timestamp = int(round(old_dt.timestamp()))
    old_libvirtd_pid, status_output = get_libvirtd_pid(test)
    pat = r"%s\s+/usr/sbin/libvirtd\s+--listen" % old_libvirtd_pid
    if not re.search(pat, status_output):
        test.error("libvirtd daemon is not started "
                   "correctly as the pattern '%s' is not found" % pat)
    else:
        test.log.debug("Step: The libvirt daemon is started in "
                       "traditional mode(non-socket activation mode)")
    if not utils_package.package_upgrade('libvirt'):
        test.error("Fail to upgrade libvirt packages")
    else:
        test.log.debug("Step: The libvirt packages were upgraded")
    new_libvirtd_pid, status_output = get_libvirtd_pid(test)
    if old_libvirtd_pid == new_libvirtd_pid:
        test.fail("libvirtd pid '%s' is expected to change after "
                  "libvirt packages are upgraded")
    else:
        test.log.debug("Step: libvirtd PID changes as expected")
    pat = r"active\s+\(running\).*(\d{4}.*\d{2})\s+"
    matches = re.findall(pat, status_output)
    if not matches:
        test.error("The pattern '%s' did not match anything" % pat)
    dt_output = datetime.strptime(matches[0], "%Y-%m-%d %H:%M:%S")
    if int(round(dt_output.timestamp())) < old_timestamp:
        test.fail("The libvirtd's started time should be after %s" % old_dt)
    else:
        test.log.debug("The libvirtd's started time is new as expected")

def teardown_upgrade_with_legacy_mode(params, test):
    """
    Teardown for test with upgrading libvirt packages in
    non-socket activation mode

    :param params: dict, test parameters
    :param test: test object
    """
    net_obj = network_xml.NetworkXML()
    if not net_obj.get_active():
        virsh.net_start('default', ignore_status=False, debug=True)
        test.log.debug("Step: default network is restarted")
    daemons_masked = params.get('daemons_masked')
    process.run("systemctl unmask %s" % daemons_masked,
                shell=True, ignore_status=False, verbose=True)
    test.log.debug("Step: Socket files were unmasked")
    config_dict = params.get('config_dict', {})
    for config_type, config_obj in config_dict.items():
        is_force = True if config_type == 'libvirtd' else False
        libvirt.customize_libvirt_config(None,
                                         config_type=config_type,
                                         config_object=config_obj,
                                         is_recover=True,
                                         restart_libvirt=False,
                                         force=is_force)
    test.log.debug("Step: Config files were recovered")
    utils_libvirtd.Libvirtd().restart()
    delete_file = params['delete_file']
    if delete_file and os.path.exists(delete_file):
        os.remove(delete_file)
        test.log.debug("Step: Files were deleted")

def teardown_default(params, test):
    """
    Default teardown

    :param params: dict, test parameters
    :param test: test object
    """
    pass

def run(test, params, env):
    """
    libvirtd daemon related tests.
    """
    case = params.get('case', '')
    run_test = eval("test_%s" % case)
    setup_test = eval("setup_%s" % case) if "setup_%s" % case \
                                            in globals() else setup_default
    teardown_test = eval("teardown_%s" % case) if "teardown_%s" % case \
                                                  in globals() else teardown_default

    try:
        setup_test(params, test)
        run_test(params, test)
    finally:
        teardown_test(params, test)


class MyStack:
    def __init__(self, size):
        if size <= 0:
            raise Exception("size must be positive")
        self.count = 0
        self.top = -1
        self.array = [0] * size

    def is_full(self):
        return self.count >= len(self.array)

    def is_empty(self):
        return self.count == 0

    def push(self, item):
        if self.is_full():
            raise Exception("stack is full")
        self.top += 1
        self.array[self.top] = item
        self.count += 1

    def pop(self):
        if self.is_empty():
            raise Exception("stack is empty")
        tobereturn = self.array[self.top]
        self.top -= 1
        self.count -= 1
        return tobereturn

    def __len__(self):
        return self.count

mystack = MyStack(6)
mystack.push(4)
mystack.push(2)
mystack.push(1)
mystack.push(6)
mystack.push(7)
mystack.push(7)

print(mystack.pop())
print(mystack.pop())

name = "fermi"
mystack2 = MyStack(len(name))
for i in range(len(name)):
    mystack2.push(name[i])
ret = ""

while not mystack2.is_empty():
    ret = ret + mystack2.pop()

print(ret)

class MyQueue:
    def __init__(self, size):
        if size <= 0:
            raise Exception("size must be positive")
        self.count = 0
        self.front = 0
        self.rear = 0
        self.array = [0] * size

    def is_full(self):
        return self.rear >= len(self.array)

    def is_empty(self):
        return self.count == 0

    def append(self, item):
        if self.is_full():
            raise Exception("queue is full")
        self.array[self.rear] = item
        self.rear += 1
        self.count += 1

    def serve(self):
        if self.is_empty():
            raise Exception("queue is empty")
        tobereturn = self.array[self.front]
        self.front += 1
        self.count -= 1
        return tobereturn

myqueue = MyQueue(5)
myqueue.append(5)
myqueue.append(1)
myqueue.append(3)
print(myqueue.serve())
print(myqueue.serve())
print(myqueue.rear,myqueue.front, myqueue.count)
print(myqueue.array)


import os
import socket
import sys
import tempfile
import threading

import pymonetdb

try:
    from MonetDBtesting import process
except ImportError:
    import process

# Find a free network port
def freeport():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 0))
    port = sock.getsockname()[1]
    sock.close()
    return port

def query(conn, sql):
    print(sql)
    cur = conn.cursor()
    cur.execute(sql)
    r = cur.fetchall()
    cur.close()
    return r

with tempfile.TemporaryDirectory() as farm_dir:
    os.mkdir(os.path.join(farm_dir, 'node1'))
    os.mkdir(os.path.join(farm_dir, 'node2'))

    # node1 is the worker
    prt1 = freeport()
    with process.server(mapiport=prt1, dbname='node1',
                        dbfarm=os.path.join(farm_dir, 'node1'),
                        stdin=process.PIPE, stdout=process.PIPE,
                        stderr=process.PIPE) as prc1:
        conn1 = pymonetdb.connect(database='node1', port=prt1, autocommit=True)

        q = "create table t1 (i int, v varchar(10))"
        print(q); conn1.execute(q)
        q = "insert into t1 values (48, 'foo'), (29, 'bar'), (63, 'abc')"
        print(q); conn1.execute(q)

        # node2 is the master
        prt2 = freeport()
        with process.server(mapiport=prt2, dbname='node2',
                            dbfarm=os.path.join(farm_dir, 'node2'),
                            stdin=process.PIPE, stdout=process.PIPE,
                            stderr=process.PIPE) as prc2:
            conn2 = pymonetdb.connect(database='node2', port=prt2,
                                      autocommit=True)

            q = "create remote table t1 (i int, v varchar(10)) on 'mapi:monetdb://localhost:{}/node1';".format(prt1)
            print("#{}".format(q)); conn2.execute(q)

            print(query(conn2, "select * from t1"))
            print(query(conn2, "select * from t1 where i < 50"))
            print(query(conn2, "select * from t1 where i > 50"))
            print(query(conn2, "select * from t1 where i <> 50"))    # WRONG
            print(query(conn2, "select * from t1 where v = 'foo'"))
            print(query(conn2, "select * from t1 where v <> 'foo'")) # WRONG
            print(query(conn2, "select * from t1 where v <> 'bla'")) # WRONG

            # cleanup: shutdown the monetdb servers and remove tempdir
            out, err = prc1.communicate()
            sys.stdout.write(out)
            sys.stderr.write(err)

            out, err = prc2.communicate()
            sys.stdout.write(out)
            sys.stderr.write(err)


from PIL import ImageFilter, Image
import os
spisok = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]
os.mkdir("for_new_pic")
for i in spisok:
    img = Image.open(i)
    img = img.filter(ImageFilter.EMBOSS)
    os.startfile(i)
    #print(os.path.getsize(i))
    name = "for_new_pic/new" + i
    img.save(name)
'''os.replace("new1.jpg", "for_new_pic/new1.jpg")
os.replace("new2.jpg", "for_new_pic/new2.jpg")
os.replace("new3.jpg", "for_new_pic/new3.jpg")
os.replace("new4.jpg", "for_new_pic/new4.jpg")
os.replace("new5.jpg", "for_new_pic/new5.jpg")'''

def z2():
    for i in os.listdir(r"F:\алгоритмизация\laba99"): #содержимое папок
        if i[-4:] == ".jpg" or i[-4:] == ".png":
            img = Image.open(i)
            img = img.filter(ImageFilter.EMBOSS)
            img.show()

def z3():
    import csv
    with open('data.csv', newline='') as f:
        faylik = csv.reader(f)
        all = 0
        for i in faylik:
            print((i[0]) + " " + i[1] + "шт." + " " + "за" + " " + i[2] + "руб")
            summa = int(i[1]) * int(i[2])
            #print(summa)
            all += summa
        print("Итоговая сумма:" + " " + str(all))
z2()
z3()


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

from time import sleep
from google.cloud import translate
from IPython.display import clear_output

SOURCE_LANG = 'en'

class Translate:
    def __init__(self,target_lang):
        self.translate_client = translate.Client()
        self.target_lang = target_lang

    def get_translation(self, text, nmt=True):
        text = text.replace("\n", " ")
        text = text.replace("\\", "")
        #Call translation api with NMT
        model = translate.NMT if nmt else translate.BASE
        result = self.translate_client.translate(
            text
            , source_language=SOURCE_LANG
            , target_language=self.target_lang
            , model=model
        )
        #Return the translated result
        return result['translatedText'], text

    def check_arxiv(self, bulk, nmt=True):
        N = len(bulk)
        lc = 0
        breaker = None

        while not breaker:
            title = bulk[lc]['title']
            pdf_url = bulk[lc]['pdf_url']
            abst = bulk[lc]['summary']

            translation, org = self.get_translation(abst, nmt)

            print()
            print("{} / {}(Total number)".format(lc+1,N))
            print()
            print(title)
            print()
            print(pdf_url)
            print()
            print(org)
            print()
            print(translation)

            sleep(0.3)
            breaker = input(
                    "Just enter to proceed or enter any key to quit:"
            )
            clear_output()
            lc +=1
            if lc == N:
                print("All papers were translated.")
                break


import argparse
import os

def add_to_dict(line, dictionary):
    line = line.split("\t")
    analysis_id = line[1]
    time = line[2]
    if analysis_id not in dictionary:
        dictionary[analysis_id] = 0
    dictionary[analysis_id] += float(time)
    return dictionary

def write_to_file(f_ptr, dictionary):
    for analysis_id in dictionary:
        f_ptr.write("%s\t%s\n" %(analysis_id, dictionary[analysis_id]))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog='collect_metrics.py', description='Collect Metrics from node')
    required = parser.add_argument_group("Required Input Parameters")
    required.add_argument('--target_dir', default='/home/ubuntu/SCRATCH', help='target directory')
    required.add_argument('--node_name', default=None, help='Name of node')
    args = parser.parse_args()

    target_dir = args.target_dir
    output_dir = "/home/ubuntu/logs"

    t_out = open(os.path.join("%s" %(output_dir), "tophat_%s" %(args.node_name)), "w")
    s_out = open(os.path.join("%s" %(output_dir), "samtools_%s" %(args.node_name)), "w")

    tophat = dict()
    samtools = dict()

    for dirname in os.listdir(target_dir):
        subdir = os.path.join(target_dir, dirname)
        if os.path.isdir(subdir):
            for filename in os.listdir(subdir):
                if filename.endswith(".log"):
                    filename = os.path.join(subdir, filename)
                    #print filename
                    f = open(filename, "r")
                    for line in f:
                        if "TOPHAT_TIME" in line:
                            tophat = add_to_dict(line, tophat)
                        if "SAMTOOLS_TIME" in line:
                            samtools = add_to_dict(line, samtools)
                            #outfile.write(line)
    write_to_file(t_out, tophat)
    write_to_file(s_out, samtools)
    t_out.close()
    s_out.close()


import pygame
from config import *

class Tile(pygame.sprite.Sprite):
	def __init__(self,pos,groups):
		super().__init__(groups)
		self.image = pygame.image.load('assets\img\cobble brick wall.png').convert_alpha()
		self.image = pygame.transform.scale(self.image, (TILESIZE, TILESIZE))
		self.rect = self.image.get_rect(topleft = pos)
		self.hitbox = self.rect.inflate(0,-10)