from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Diary

# Create your views here.

@login_required(login_url='login-page')
def diary_index(request):
    context ={
        'index' : True
    }
    return render(request,"mydiary/diary_home.html",context)

@login_required(login_url='login-page')
def view_all_content(request):

    data = Diary.objects.filter(user=request.user)
    context = {
        'view_list': True,
        'data':data,
    }
    return render(request, "mydiary/view_content.html", context)

@login_required(login_url='login-page')
def add_new_content(request):
    context = {
        'add_new': True
    }
    if request.method == 'POST':
        user_title = request.POST['title']
        user_content = request.POST['content']
        print(user_title,user_content)
        obj = Diary(user=request.user,title=user_title,content=user_content)
        obj.save()
        messages.success(request,'Saved Successfully')
        return redirect('diary-add')
    else:
        return render(request, "mydiary/add_new.html", context)

@login_required(login_url='login-page')
def delete_content(request,id):
    obj = Diary.objects.filter(user=request.user, id=id)
    if not obj:
        messages.error(request, 'Not found')
        return redirect('diary-view')
    obj.delete()
    messages.success(request, 'Delete Successfully')
    return redirect('diary-view')


from keras import models
from keras import layers
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import pandas as pd
import mlflow
mlflow.autolog()
mlflow.set_experiment("SAW approximate and predict new data FINAL")
def generatesaw():
    x = np.linspace(0, 50, 10000)
    sawx = x % 4.0
    y = x % 4.0

    return x, sawx, y

def build_model():
    model = models.Sequential()
    #model.add(layers.Dense(2))

    model.add(layers.Dense(100, activation='tanh'))
    model.add(layers.Dense(50, activation='tanh'))
    model.add(layers.Dense(25, activation='tanh'))
   # model.add(layers.Dense(32, activation='tanh'))

    # ok result
    # model.add(layers.Dense(256, activation='tanh'))
    # model.add(layers.Dense(256, activation='tanh'))
    # model.add(layers.Dense(128, activation='tanh'))
    # model.add(layers.Dense(32, activation='tanh'))
    #model.add(layers.Dense(4, activation='tanh'))
   # model.add(layers.Dropout(rate=0.1))
    #model.add(layers.Dense(2, activation='hard_sigmoid'))

    model.add(layers.Dense(1))
    model.compile(optimizer='adam', loss='mse', metrics=['mse'])
    return model

if __name__ == "__main__":
    with mlflow.start_run(run_name="good run"):
        x, sawx, y = generatesaw()
        # x = x.reshape(-1, 1)
        # sawx = sawx.reshape(-1, 1)
        # y = y.reshape(-1, 1)

        d = {'x' : x, 'sawx': sawx, 'y' :y}
        data = pd.DataFrame(d)
        print(data)
        X_train, x_test, Y_train, y_test = train_test_split(data[['x', 'sawx']], data['y'], test_size=0.25, shuffle=False)
        print(X_train)
        model = build_model()

        # x_test = np.linspace(6, 12, 1000)
        # y_test = 2*np.saw(10*x)+ np.random.randn(*x.shape) * 0.3

        model.fit(X_train, Y_train, epochs=100, batch_size=80, validation_data=(x_test, y_test))
        #predictedY = model.predict(y_test)

        # переопределяем xy с новыми данными
        x = np.linspace(0, 75, 12000)
        y = x % 4.0
        sawx = x % 4.0

        dd = {'x' : x, 'sawx': sawx, 'y' :y}
        expandedData = pd.DataFrame(dd)
        predictedY = model.predict(expandedData[['x', 'sawx']])

        plt.subplot(211)
        plt.plot(X_train['x'], Y_train, c = 'r', label = "train data")

        plt.plot(expandedData['x'], predictedY, c='b', linewidth = 1, label = "original data + new data")
        plt.legend(loc='upper left')
        plt.subplot(212)
        plt.plot(x, y, c = 'y', label = "original ALL data")
        plt.plot(expandedData['x'], predictedY, c ='m', label = "original + expanded data, predictedY")
        plt.legend(loc='upper left')
        mlflow.log_figure(plt.gcf(), "approximate + predict on new data.png")
        #plt.plot(x_test, predictedY)
        plt.show()

timeSeries mlflow Final/timeSeriesSin sawX feature predict All data.py


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

from abc import ABC, abstractmethod
import math

from interface.loggable import Loggable
from interface.transceiver import Transceiver

class Router(Loggable, ABC):
    """
    Responsible for forwarding messages received by publisher to other
    subscribers and routers

    Attributes:
        uid: identifier of object
        heartbeat_rate: interaction rate with other nodes (cycles per second)
        routing_table_size: max number of items router can store
        topic_preferences: list of topics in prefered order
    """

    def __init__(
        self,
        uid=None,
        routing_table_size=math.inf,
        topic_preferences=[],
        heartbeat_rate=0.0,
    ):
        super().__init__()
        if any(arg is None for arg in [uid]):
            raise TypeError("args cannot be none")
        self.uid = uid
        self.routing_table_size = routing_table_size
        self.heartbeat_rate = heartbeat_rate
        self.topic_preferences = topic_preferences
        self.trxs = []

    def __repr__(self):
        return str(self)

    def __str__(self):
        return f"{self.uid}"

    def use(self, trx: Transceiver):
        """
        Provide access to a transceiver that the subscriber can use to disperse
        and receive information about topics and routers

        Args:
            trx: transceiver used
        """
        trx.subscribe(self.on_recv)
        self.trxs.append(trx)

    @abstractmethod
    async def on_recv(self, trx, data):
        raise NotImplementedError


#!/usr/bin/env python
'''
:mod:`module.ecb`
'''

import re
import math
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
from scipy.interpolate import griddata
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

import numpy as np

from module import AbstractModule
from util import SizeUtils
from util import NumberUtils

class ECB(AbstractModule):
    '''
    ECB
    '''
    """Regexp pattern for logs generated by RawErasureCoderBenchmark."""
    PATTERN_ECB = r"Using (?P<buffer_size>\S+) buffer\.\n(?:.*?\n)*?(?P<coder>.*?) coder (?P<method>\S+?)\s(?P<total_data_size>\S+) data, with chunk size (?P<chunk_size>.*?)\nTotal time: (?P<total_time>.*?)\ss\.\nTotal throughput: (?P<total_throughput>.*?) MB/s\nThreads statistics:\s*(?P<threads_num>.*?) threads in total\.\nMin: (?P<time_min>.*?) s, Max: (?P<time_max>.*?) s, Avg: (?P<time_avg>.*?) s, 90th Percentile: (?P<time_90>.*?) s\."

    """Regexp terms for finding fields in ECB logs"""
    FIELDS_ECB = [
        'buffer_size', 'coder', 'method', 'total_data_size', 'chunk_size', 'total_time',
        'total_throughput', 'threads_num', 'time_min', 'time_max', 'time_avg', 'time_90'
    ]

    TYPES_ECB = [
        "TotalThroughput", "Throughput", "Latency"
    ]

    def __init__(self, sub_type):
        if sub_type not in self.TYPES_ECB:
            raise Exception("{} is not one of {}".format(sub_type, self.TYPES_ECB))
        self.sub_type = sub_type

    def delimeter(self):
        return "**********"
    def pattern(self):
        return re.compile(self.PATTERN_ECB)
    def split_info(self, parts):
        fields = self.FIELDS_ECB
        results = []

        for part in parts:
            result = {}
            for sectionname in fields:
                value = part[sectionname]
                if sectionname == 'buffer_size':
                    value = SizeUtils.convert_size(value)
                if sectionname == 'chunk_size':
                    value = SizeUtils.convert_size(value)
                if sectionname == 'total_data_size':
                    value = SizeUtils.convert_size(value)
                value = NumberUtils.as_number_otherwise_string(value)
                result[sectionname] = value
            results.append(result)
        return results
    def num_plots(self):
        return 1
    def xy_data(self, data):
        xdata = set()
        ydata = set()
        for cell in data:
            xdata.add(cell['chunk_size'])
            ydata.add(cell['threads_num'])
        self.xdata = sorted(xdata)
        self.ydata = sorted(ydata)
    def preprocess_data(self, data):
        results = {}
        for cell in data:
            coder = cell["coder"].replace("Java", "").strip()
            if coder == "Mellanox":
                coder = "Mellanox EC Offload"
            elif coder == "ISA-L":
                coder = "Intel ISA-L"

            method = cell["method"]
            chunk_size = cell["chunk_size"]
            buffer_size = cell["buffer_size"]
            threads_num = cell["threads_num"]
            factor = buffer_size * threads_num
            iteration = cell["total_data_size"] / factor

            if self.sub_type == "TotalThroughput":
                result = cell["total_throughput"]
            elif self.sub_type == "Throughput":
                result = cell["total_throughput"] / threads_num
            else:
                result = cell["time_avg"]

            if method not in results:
                results[method] = {}
            if iteration not in results[method]:
                results[method][iteration] = {}
            if chunk_size not in results[method][iteration]:
                results[method][iteration][chunk_size] = {}
            if threads_num in results[method][iteration][chunk_size] \
                    and results[method][iteration][chunk_size][threads_num]:
                results[method][iteration][chunk_size][threads_num].append(result)
            else:
                results[method][iteration][chunk_size][threads_num] = [result]

        for method in results:
            for iteration in results[method]:
                for chunk_size in results[method][iteration]:
                    for threads_num in results[method][iteration][chunk_size]:
                        results[method][iteration][chunk_size][threads_num] = \
                            np.mean(results[method][iteration][chunk_size][threads_num])
        self.coder = coder
        self.results = results

    def generate_ticks(self):
        xcount = len(self.xdata)
        xtick_label_stepsize = xcount / 15
        if xtick_label_stepsize == 0:
            xtick_label_stepsize = 1
        self.xticks = np.arange(0, xcount, xtick_label_stepsize)
        self.xtick_labels = [SizeUtils.number_to_size(self.xdata[i]) for i in self.xticks]

        ycount = len(self.ydata)
        ytick_label_stepsize = ycount / 15
        if ytick_label_stepsize == 0:
            ytick_label_stepsize = 1
        self.yticks = np.arange(0, ycount, ytick_label_stepsize)
        self.ytick_labels = [self.ydata[i] for i in self.yticks]

    def paint(self, fig):
        x_labels = 14
        y_labels = 7
        method = "encode"
        blocks = 1024

        ax = fig.gca(projection='3d')
        results = self.results[method][blocks]
        xticks, yticks = np.meshgrid(self.xticks, self.yticks)
        xdata, ydata = np.meshgrid(self.xdata, self.ydata)

        if self.sub_type != "Latency":
            unit, zticks = self.__throughput_array(results, xdata, ydata)
        else:
            unit = "sec"
            zticks = np.array([results[x][y] for x, y in zip(np.ravel(xdata), np.ravel(ydata))])

        zticks = zticks.reshape(xdata.shape)
        ax.plot_surface(xticks, yticks, zticks, alpha=0.6)
        xtick_labels = [self.xtick_labels[int(x)] for x in ax.get_xticks() if int(x) in range(len(self.xtick_labels))]
        ytick_labels = [self.ytick_labels[int(y)] for y in ax.get_yticks() if int(y) in range(len(self.ytick_labels))]
        x_plane = ax.contour(xticks, yticks, zticks, zdir='x', offset=0 - 0.230, cmap=cm.Dark2)
        y_plane = ax.contour(xticks, yticks, zticks, zdir='y', offset=y_labels - 1 + 0.130, cmap=cm.cool)
        x_legends = ["chunk size: {}".format(x) for x in xtick_labels]
        y_legends = ["#threads: {}".format(y) for y in ytick_labels]

        for i in range(len(xtick_labels)):
            if (i % 2) == 1:
                xtick_labels[i] = ""
        for i in range(len(ytick_labels)):
            if (i % 2) == 1:
                ytick_labels[i] = ""
        if self.sub_type == "TotalThroughput":
            title = "Total Throughput"
        else:
            title = self.sub_type

        ax.set_zlabel('{} ({})'.format(title, unit))
        plt.title('{} - {}'.format(title, self.coder))
        ax.set_xlabel('Chunk Size')
        ax.set_ylabel('#Threads')
        ax.set_xlim(0, x_labels - 1)
        ax.set_ylim(0, y_labels - 1)
        ax.set_zlim(0)
        ax.set_xticklabels(xtick_labels)
        ax.set_yticklabels(ytick_labels)

        x_num = len(x_plane.collections)
        y_num = len(y_plane.collections)
        lg = plt.legend(x_plane.collections + y_plane.collections,
                        x_legends[(len(x_legends) - x_num):] + y_legends[(len(y_legends) - y_num):],
                        ncol = int(math.ceil(x_num + y_num) / 4), bbox_to_anchor=(0.95, 0), frameon=False)
        if lg is not None:
            lg.get_frame().set_alpha(0)
            lg_txts = lg.get_texts()
            plt.setp(lg_txts, fontsize=6)
        box = ax.get_position()
        ax.set_position([box.x0 - box.width * 0.1, box.y0 + box.height * 0.14, box.width, box.height])

    def __throughput_array(self, source, xdata, ydata):
        temp_array = [source[x][y] for x, y in zip(np.ravel(xdata), np.ravel(ydata))]
        unit = "MB/sec"
        if np.mean(temp_array) > 5 * 1024:
            temp_array = [x / 1024 for x in temp_array]
            unit = "GB/sec"
        return (unit, np.array(temp_array))


import json
from django.apps import apps
from django.core import serializers
from django.urls import reverse, reverse_lazy
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from django.views.generic import DetailView, ListView, TemplateView, View
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin

from directory.utils import get_model, get_linked_obj, get_detail_fields_mapping, get_child_list
from directory.views.routers import DIRECTORY_ITEMS
from utils.choices import get_choices, filters_choices

class ModelDetail(LoginRequiredMixin, DetailView):
    template_name = 'model_detail.jinja2'

    def dispatch(self, request, *args, **kwargs):
        self.model = get_model(kwargs.get('model_name', None))
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context.update({
            'url': self.request.path,
            'title': self.model._meta.verbose_name,
            'model_name': self.model.__name__.lower(),
            'menu_items': DIRECTORY_ITEMS,
            'detail_list': get_detail_fields_mapping(context['object']),
            'child_list': get_child_list(self.object),
            'bread_crumbs': self.object.get_bread_crumbs()
        })
        obj = get_object_or_404(self.model, pk=self.kwargs.get('pk'))
        return context

class ModelList(LoginRequiredMixin, ListView):
    parent_model = None
    object = None
    related_name = None
    list_display = None
    count = 0
    permissions = []
    paging = dict()
    filters = {}

    def dispatch(self, request, *args, **kwargs):
        self.paging = dict(
            range=9,
            page=1,
            page_items=100,
            pages=1
        )
        # try:
        #     self.model = apps.get_model(request.GET.get('meta_label'))
        # except (ValueError, LookupError):
        self.model = get_model(kwargs.get('model_name') or request.GET.get('model_name'))
        self.permissions = self.model.get_permissions(request)
        parent_model_name = request.GET.get('parent_model_name', kwargs.get('parent_model_name'))
        if parent_model_name:
            self.parent_model = get_model(parent_model_name)
            pk = request.GET.get('parent_pk', kwargs.get('parent_pk'))
            self.object = self.parent_model.objects.get(pk=pk)
            self.related_name = request.GET.get('related_name', kwargs.get('related_name'))
            self.model = getattr(self.object, self.related_name).model
        self.list_display = ['id'] + getattr(self.model, 'list_display', [])

        self.paging['page'] = int(request.GET.get('page', 1))
        filters = self.model.get_filters(request)
        self.filters = filters_choices(request, filters, self.model)
        return super().dispatch(request, *args, **kwargs)

    def get_queryset(self):
        list_related = getattr(self.model, 'list_related', [])
        queryset = self.model.objects.all()
        if self.object and self.related_name:
            queryset = getattr(self.object, self.related_name).all()
        queryset = queryset.filter(self.model.get_filters_q(self.request)).select_related(*list_related)
        return queryset.distinct()

    def get_item_actions(self, pk):
        return [
            dict(
                name='edit', label='Редактировать'
            ),
            dict(
                name='detail', label='Детализация',
                url=reverse_lazy('directory:model_detail', kwargs={
                    'model_name': self.model.__name__.lower(), 'pk': pk
                }),
            )
        ]

    def get_items(self):
        items = []
        _queryset = self.get_queryset()

        # TODO: отфильтровать по группам доступа
        if self.model.__name__.lower() == 'servicetimetable':
            _queryset = _queryset.filter(service__in=get_choices(self.request, 'deal.Service', get_list=True))

        elif self.model.__name__.lower() == 'client':
            if (self.request.GET.get('phones') and len(self.request.GET.get('phones')) > 5) or \
                    (self.request.GET.get('full_name') and len(self.request.GET.get('full_name')) > 3):
                pass
            else:
                _queryset = _queryset.filter(
                    Q(rel_deals__deal__branch__in=get_choices(self.request, 'company.Branch', get_list=True)) |
                    Q(rel_deals=None)
                )

        begin = 1
        self.count = _queryset.count()
        if self.count:
            self.paging['pages'] = round(self.count / self.paging['page_items'] + 0.5)
            self.paging['page'] = \
                self.paging['page'] if self.paging['page'] <= self.paging['pages'] else self.paging['pages']
            begin = (self.paging['page'] - 1) * self.paging['page_items']
        for q_item in _queryset[begin:begin + self.paging['page_items']]:
            item = dict()  # {'actions': self.get_item_actions(q_item.pk)}
            for field_name in self.list_display:
                _q_item = q_item
                for field in field_name.split('__'):
                    try:
                        _q_item = getattr(q_item, 'get_%s_display' % field)()
                    except AttributeError:
                        if hasattr(_q_item, field):
                            _q_item = getattr(_q_item, field)
                item[field_name] = _q_item.__str__() if _q_item else ''
            items.append(item)

        return items

    def get(self, request, *args, **kwargs):
        if 'view' not in self.permissions:
            return JsonResponse(dict(answer='No permissions'), safe=False)
        if not request.GET:
            return render(request, 'app_vue.jinja2')

        context = dict(
            title=self.model._meta.verbose_name_plural,
            meta_label=self.model._meta.label,
            parent_model_name=self.parent_model.__name__.lower() if self.parent_model else '',
            model_name=self.model.__name__.lower(),
            url=self.request.path,
            actions=self.model.base_actions,
            bread_crumbs=self.object.get_bread_crumbs() if self.object else None,
            child_list=get_child_list(self.object),
            pk=self.object.pk if self.object else '',
            related_name=self.related_name,
            headers=self.model.get_headers(),
            items=self.get_items(),
            count=self.count,
            paging=self.paging,
            permissions=self.permissions,
            filters=self.filters,
        )

        if request.GET.get('debug'):
            from django.shortcuts import render_to_response
            return render_to_response('debug.jinja2', locals())

        return JsonResponse(context)


from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import Student, Course

def get_students(request):
    students = Student.objects.all().values()
    output = [entry for entry in students]
    return JsonResponse(output, safe=False)

def create_student(request):
    if request.method == "POST":
        data = request.POST
        name = data.get("name")
        surname = data.get("surname")
        course_id = data.get("course")

        #course = Course.objects.get(id=course_id)

        student = Student.objects.create(
            name=name,
            surname=surname,
            course_id=course_id
        )

        student.save()
        return HttpResponse(status=200)

def delete_student(request):
    if request.method == "POST":
        data = request.POST
        student_id = data.get("student_id")
        student = Student.objects.get(id=student_id)
        student.delete()
        student.save()
        return HttpResponse(status=200)


from argparse import ArgumentParser
from os import mkdir
from os.path import join, exists
import h5py
import sys

def write_mesh_as_obj(fname, verts, faces):
    with open(fname, 'w') as fp:
        for v in verts:
            fp.write('v %f %f %f\n' % (v[0], v[1], v[2]))
        for f in faces + 1:  # Faces are 1-based, not 0-based in obj files
            fp.write('f %d %d %d\n' % (f[0], f[1], f[2]))

if __name__ == '__main__':

    # Subject ids
    sids = ['50002', '50004', '50007', '50009', '50020',
            '50021', '50022', '50025', '50026', '50027']
    # Sequences available for each subject id are listed in scripts/subjects_and_sequences.txt

    parser = ArgumentParser(description='Save sequence registrations as obj')
    parser.add_argument('--path', type=str, default='../registrations_f.hdf5',
                        help='dataset path in hdf5 format')
    parser.add_argument('--seq', type=str, default='jiggle_on_toes',
                        help='sequence name')
    parser.add_argument('--sid', type=str, default='50004', choices=sids,
                        help='subject id')
    parser.add_argument('--tdir', type=str, default='./',
                        help='target directory')
    args = parser.parse_args()

    sidseq = args.sid + '_' + args.seq
    with h5py.File(args.path, 'r') as f:
        if sidseq not in f:
            print('Sequence %s from subject %s not in %s' % (args.seq, args.sid, args.path))
            f.close()
            sys.exit(1)
        verts = f[sidseq][...].transpose([2, 0, 1])
        faces = f['faces'][...]

    tdir = join(args.tdir, sidseq)
    if not exists(tdir):
        mkdir(tdir)

    # Write to an obj file
    for iv, v in enumerate(verts):
        fname = join(tdir, '%05d.obj' % iv)
        print('Saving mesh %s' % fname)
        write_mesh_as_obj(fname, v, faces)


import numpy as np
from astropy.io.fits import file

def sign(x):
    """
    Return 1 if x is positive, -1 if it's negative, and 0 if it's zero.
    """
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

def vertex_sign(P, O):
    """
    Sign of the vertex P with respect to O, as defined above.
    """
    #print("0   ", sign(P[0] - O[0]))
    #print("1   ", sign(P[1] - O[1]))
    #print("2   ", sign(P[2] - O[2]))
    result = sign(P[0] - O[0]) or sign(P[1] - O[1]) or sign(P[2] - O[2])
    print(result)

    if not result:
       raise ValueError("vertex coincides with origin")
    return result

def edge_sign(P, Q, O):
    """
    Sign of the edge PQ with respect to O, as defined above.
    """
    result = (
        sign((P[1] - O[1]) * (Q[0] - O[0]) - (P[0] - O[0]) * (Q[1] - O[1])) or
        sign((P[2] - O[2]) * (Q[0] - O[0]) - (P[0] - O[0]) * (Q[2] - O[2])) or
        sign((P[2] - O[2]) * (Q[1] - O[1]) - (P[1] - O[1]) * (Q[2] - O[2]))
    )
    #if not result:
        # with origin")
    return result

def triangle_sign(P, Q, R, O):
    """
    Sign of the triangle PQR with respect to O, as defined above.
    """
    m1_0 = P[0] - O[0]
    m1_1 = P[1] - O[1]
    m2_0 = Q[0] - O[0]
    m2_1 = Q[1] - O[1]
    m3_0 = R[0] - O[0]
    m3_1 = R[1] - O[1]
    result = sign(
        (m1_0 * m2_1 - m1_1 * m2_0) * (R[2] - O[2]) +
        (m2_0 * m3_1 - m2_1 * m3_0) * (P[2] - O[2]) +
        (m3_0 * m1_1 - m3_1 * m1_0) * (Q[2] - O[2]))
    if not result:
        raise ValueError("vertices coplanar with origin")
    return result

def triangle_chain(v1, v2, v3, origin):
    """
    Return the contribution of this triangle to the winding number.
    Raise ValueError if the face contains the origin.
    """
    v1sign = vertex_sign(v1, origin)
    v2sign = vertex_sign(v2, origin)
    v3sign = vertex_sign(v3, origin)

    face_boundary = 0
    if v1sign != v2sign:
        face_boundary += edge_sign(v1, v2, origin)
    if v2sign != v3sign:
        face_boundary += edge_sign(v2, v3, origin)
    if v3sign != v1sign:
        face_boundary += edge_sign(v3, v1, origin)
    if not face_boundary:
        return 0

    return triangle_sign(v1, v2, v3, origin)

def winding_number(point):
            x, y, z = point
            if -1 < x < 1 and -1 < y < 1 and -1 < z < 1:
                return "inside"
            if -1 <= x <= 1 and -1 <= y <= 1 and -1 <= z <= 1:
                return "boundary"
            return "outside"

class Polyhedron(object):
    def __init__(self, triangles, vertex_positions):
        """
        Initialize from list of triangles and vertex positions.
        """
        # Validate: check the combinatorial data.
        edges = set()
        vertices = set()
        for triangle in triangles:
            vertices.update(triangle)
            P, Q, R = triangle
            for edge in ((P, Q), (Q, R), (R, P)):
                if edge[0] == edge[1]:
                    raise ValueError("Self edge: {!r}".format(edge))
                if edge in edges:
                    raise ValueError("Duplicate edge: {!r}".format(edge))
                edges.add(edge)

        # For each edge that appears, the reverse edge should also appear.
        for P, Q in edges:
            if not (Q, P) in edges:
                raise ValueError("Unmatched edge: {!r}".format((P, Q)))

        # Vertex set should match indices in vertex_positions.
        if vertices != set(range(len(vertex_positions))):
            raise ValueError("Vertex set doesn't match position indices.")

        # Vertex positions in R^3.
        self.vertex_positions = vertex_positions
        # Indices making up each triangle, counterclockwise
        # around the outside of the face.
        self.triangles = triangles

    def triangle_positions(self):
        """
        Triples of vertex positions.
        """
        for triangle in self.triangles:
            yield tuple(self.vertex_positions[vx] for vx in triangle)

    def volume(self):
        """
        Return the volume of this polyhedron.
        """
        acc = 0
        for p1, p2, p3 in self.triangle_positions():
            # Twice the area of the projection onto the x-y plane.
            det = ((p2[1] - p3[1]) * (p1[0] - p3[0]) -
                   (p2[0] - p3[0]) * (p1[1] - p3[1]))
            # Three times the average height.
            height = p1[2] + p2[2] + p3[2]
            acc += det * height
        return acc / 6.0

    def winding_number(self, point):
        """Determine the winding number of *self* around the given point.
        """
        return sum(
            triangle_chain(v1, v2, v3, point)
            for v1, v2, v3 in self.triangle_positions()) // 2
"""
def read_off(file):
    #if 'OFF' != file.readline().strip():
     #   raise('Not a valid OFF header')
    n_verts, n_faces, n_dontknow = tuple([int(s) for s in file.readline().strip().split(' ')])
    verts = [[float(s) for s in file.readline().strip().split(' ')] for i_vert in range(n_verts)]
    faces = [[int(s) for s in file.readline().strip().split(' ')][1:] for i_face in range(n_faces)]
    return verts, faces
"""

import os
import sys

def read_off(file):
    """
    Reads vertices and faces from an off file.

    :param file: path to file to read
    :type file: str
    :return: vertices and faces as lists of tuples
    :rtype: [(float)], [(int)]
    """

    assert os.path.exists(file)

    with open(file, 'r') as fp:

        lines = fp.readlines()
        lines = [line.strip() for line in lines]
        assert lines[0] == 'OFF'

        parts = lines[1].split(' ')
        assert len(parts) == 3

        num_vertices = int(parts[0])
        assert num_vertices > 0

        num_faces = int(parts[1])
        assert num_faces > 0

        vertices = []
        for i in range(num_vertices):

            vertex = lines[2 + i+1].split(' ')

            vertex = [float(point) for point in vertex]
            assert len(vertex) == 3

            vertices.append(vertex)

        faces = []
        for i in range(num_faces):

            face = lines[2 + num_vertices + i + 1].split(' ')
            face = [int(index) for index in face]

            #print(face[0], "  " , len(face) - 1)
            #assert face[0] == len(face) - 1
            for index in face:
                assert index >= 0 and index < num_vertices

            assert len(face) > 1

            faces.append(face)

        return vertices, faces
if __name__ == "__main__":
    file = '0.off'
    vertices, faces = read_off(file)
    point = [0,0,0.25]
    print(Polyhedron(faces,vertices).winding_number(point))
    #return verts, faces


import time
import sys
import pygame
import pygame_gui
import re
import pygame_gui

pygame.init()
font = pygame.font.Font('arial.ttf', 24)
screen = pygame.display.set_mode([800, 500])
timer = pygame.time.Clock()
message = "chukdsa"
color = 'white'
snip = font.render(message, True, pygame.Color(color))
counter = 0
speed = 10
done = False
run = True
ms=''
pygame.display.set_caption('Your Pygame Window')
pygame.mixer.init()
pygame.mixer.music.load('beat.mp3')
pygame.mixer.music.set_volume(1)
pygame.mixer.music.play(-1)

# Đọc nội dung từ tệp beat.txt
with open('beat.txt', 'r', encoding="utf-8") as file:
    beat_data = file.read()

# Sử dụng biểu thức chính quy để tìm và trích xuất các giá trị từ dữ liệu XML
param_pattern = re.compile(r'<param\s+s="b">([\s\S]*?)<\/param>')
item_pattern = re.compile(r'<i\s+va="([\d.]+)">([^<]+)<\/i>')

# Tìm tất cả các phần param trong dữ liệu
param_matches = param_pattern.findall(beat_data)

# Tạo danh sách các từ điển từ các phần param
list_of_dicts = []
for param in param_matches:
    param_items = item_pattern.findall(param)
    a=float(param_items[0][0])-0.44

    # Khởi tạo một từ điển mới với key '1' và giá trị '-'
    param_dict = {f"{a}": ' '}

    for value, key in param_items:
        param_dict[value] = key

    list_of_dicts.append(param_dict)

defaut=0
defaut3=0
k=0
kx=0
last_height = 0
last_height3 = 0
scroll_speed = 1.0
clock = pygame.time.Clock()
ui_manager = pygame_gui.UIManager((800, 500))
playing=True
scroll_bar = pygame_gui.elements.UIHorizontalSlider(
    relative_rect=pygame.Rect((10, 60), (400, 20)),
    start_value=0.0,
    value_range=(0.0, 1.0),
    manager=ui_manager
)
play_pause_button = pygame_gui.elements.UIButton(
    relative_rect=pygame.Rect((10, 10), (100, 50)),
    text='Pause',
    manager=ui_manager
)
running = True
current_seconds = 0
total_seconds = 120
y=0
while running:
    for dictionary in list_of_dicts:
        k2 = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            time_delta = clock.tick(60) / 1000.0  # Thời gian giữa các khung hình

            # Tính giá trị mới cho thanh trượt dựa trên thời gian đã trôi qua
            current_seconds += time_delta
        # Clear the screen
            if current_seconds <= total_seconds:
                new_value = current_seconds / total_seconds
                scroll_bar.set_current_value(new_value)

            if event.type == pygame.USEREVENT:
                if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                    if event.ui_element == play_pause_button:
                        if playing:
                            pygame.mixer.music.pause()
                            play_pause_button.set_text('Play')
                        else:
                            pygame.mixer.music.unpause()
                            play_pause_button.set_text('Pause')
                        playing = not playing
            ui_manager.process_events(event)

        k3 =0
        for key, value in dictionary.items():
            vl = float(key)  # -3 youtube nhanh hơn beat.mp3 3s

            if defaut3 != vl:
                vl = vl - defaut3

            seconds = vl

            for i in range(len(value)):
                snip = font.render(value[i], True, pygame.Color('white'))
                screen.blit(snip, ((i + 1) * 15 + k3, (100 + kx)))
                pygame.display.flip()

            last_height3 = (len(value)+1) * 15  # 24 là chiều cao của mỗi ký tự, có thể thay đổi
            k3 += last_height3

            defaut3 = float(key)
        kx+=40
        print()
        for key, value in dictionary.items():
            vl = float(key)

            if defaut != vl:
                vl = vl - defaut

            seconds = vl * scroll_speed  # Apply the scroll speed
            i=0
            while (i < (len(value))):

                time.sleep(seconds / len(value))
                snip = font.render(value[i], True, pygame.Color('red'))
                screen.blit(snip, ((i + 1) * 15 + k2, (100 + k)))
                pygame.display.flip()
                if playing==True:
                    i +=1
                elif playing==False:
                    pass
            last_height = (len(value) + 1) * 15
            k2 += last_height

            defaut = float(key)

        k += 40
        y+=1

        ui_manager.update(time_delta)
        ui_manager.draw_ui(screen)
    # Update and draw the UI manager

    pygame.display.flip()

pygame.quit()


# Oytun Demirbilek
# 150150032

import moviepy.video.io.VideoFileClip as mpy
import moviepy.editor as edit
import cv2
import numpy as np
from sklearn.svm import SVR
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt

def MSE(y_pred, y_true):
    return np.sqrt(np.square(y_pred - y_true)).mean()

def get_nfold_split(X, number_of_folds, current_fold_id):
    kf = KFold(n_splits=number_of_folds)
    split_indices = kf.split(range(X.shape[0]))
    train_indices, test_indices = [(list(train), list(test)) for train, test in split_indices][current_fold_id]
    #Split train and test
    X_train = X[train_indices]
    X_test = X[test_indices]
    return X_train, X_test

def fix_camera(samples, truths, axis, n_folds=5):
    np.random.seed(1)

    # In part 3, we need to find a learned function that maps the OF with camera motion to the fixed one.
    max_err = 9999999
    best_model = None
    for f in range(n_folds):
        predictor = SVR(C=1.0, epsilon=0.2)
        X_train, X_test = get_nfold_split(samples,n_folds,f)
        Y_train, Y_test = get_nfold_split(truths,n_folds,f)
        predictor.fit(X_train,Y_train[:,axis])
        y_pred = predictor.predict(X_test)
        error = MSE(y_pred,Y_test[:,axis])
        if error < max_err: best_model = predictor
        print(f"MSE Fold {f}:",error)

    return best_model

def lucas_canade(frame0,frame1, x,y, window_size=5,camera_model=None):
    # Get index range of window.
    window_start= window_size // 2
    window_end= window_size // 2 + 1

    # Take derivatives.
    Ix = cv2.filter2D(frame0,-1,np.array([[-1,1],[-1,1]]))[ x-window_start : x+window_end, y-window_start : y+window_end]
    Iy = cv2.filter2D(frame0,-1,np.array([[-1,-1],[1,1]]))[ x-window_start : x+window_end, y-window_start : y+window_end]
    It = (cv2.filter2D(frame0,-1,np.ones((2,2))) + cv2.filter2D(frame1,-1,np.ones((2,2))*-1))[ x-window_start : x+window_end, y-window_start : y+window_end]

    # Find image structure tensor.
    A_T = np.array([Ix.flatten(),Iy.flatten()])
    A = np.array([Ix.flatten(),Iy.flatten()]).transpose()
    b = np.array([It.flatten()]).transpose()
    # Build equation: (u,v) = -(A_T.A)^-1.A_T.b
    motion_vector = np.matmul(np.matmul( -1*(np.linalg.pinv(np.matmul(A_T,A)) ),A_T),b)
    if camera_model is not None:
        x = camera_model[0].predict(motion_vector.T)[0]
        y = camera_model[1].predict(motion_vector.T)[0]
        return np.array([x,y])
    return motion_vector.squeeze()

def optical_flow(video, points=None, background_motion=None, next_images=1, update_pos=True, mark_region=False, camera_model=None):
    frame_count = video.reader.nframes
    video_fps = video.fps
    image_list = []
    frame_displacements = []
    if points is None: find_points = True
    else: find_points = False
    for i in range(frame_count-next_images):
        # Get video frames.
        walker_frame0 = video.get_frame(i*1.0/video_fps)
        if mark_region:
            # In part 2, region is marked as a red rectangle.
            walker_frame0 = cv2.rectangle(walker_frame0, tuple(points[0]), tuple(points[3]), color=(255,0,0), thickness=2)
        # Reduce noise and take the grayscale.
        im0 = cv2.medianBlur(walker_frame0,5)
        im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY).astype(np.float32)
        if find_points:
            points = find_hand(walker_frame0)
            print("HAND LOC:",points)
        corner_displacements = []
        motion_list = []
        for p in points:
            x = p[0]
            y = p[1]
            # Calculate vectors for the next N frame sequence.
            for j in range(1,next_images+1):
                # j will be delta-t
                walker_frame1 = video.get_frame((i+j)*1.0/video_fps)
                # Reduce noise and take the grayscale.
                im1 = cv2.medianBlur(walker_frame1,5)
                im1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY).astype(np.float32)
                # Find optical flow of a given point between 2 images.
                motion = lucas_canade(im0,im1,y,x,window_size=5,camera_model=camera_model)
                print("OF:",motion)

                if background_motion is not None:
                    # In part 2, we subtract the background motion from calculated hand motion to reduce error.
                    # Background motion is the average/absmax of the calculated motion of the selected region on the wall.
                    fix = background_motion.mean(axis=(0,1))
                    # fix = absmaxND(fix,axis=0) # Take absolute max of the OF vectors of corners.
                    print("BACKGROUND:",fix)
                    motion = motion - fix
                # Normalize calculated velocity vector and find displacement by multiplying with delta-t
                if np.linalg.norm(motion) != 0: motion_list.append(motion*j)# / np.linalg.norm(motion))
                else: motion_list.append(np.zeros(2))
                #motion_list.append(motion)

            # Average displacement in the next N frame sequence.
            avg_displacement = np.round(np.array(motion_list).mean(axis=0)).astype(np.int32)
            displacement_x, displacement_y = avg_displacement[0], avg_displacement[1]
            corner_displacements.append(avg_displacement)
            #print("DISPLACEMENT:",avg_displacement)
            print(f"MOVES FROM: {x},{y} TO: {x-displacement_x},{y-displacement_y}")

            # Draw arrow. Exaggerated for better visualization.
            cv2.arrowedLine(walker_frame0,(x,y),(x+displacement_x*10, y+displacement_y*10),(255,255,255))

            if update_pos:
                # In order to track the hand, we will need to update its position.
                p[0] = x - displacement_x
                p[1] = y - displacement_y
        frame_displacements.append(np.array(corner_displacements))
        image_list.append(walker_frame0)
    return image_list, np.array(frame_displacements)

def part1():
    biped_vid = mpy.VideoFileClip("biped_1.avi")

    # (x,y) Corner of the green hand: (401,336) at first frame.
    x, y = 401, 334
    image_list,frame_displacements = optical_flow(biped_vid,[[x,y]],next_images=1,update_pos=True)

    clip = edit.ImageSequenceClip(image_list,fps=25)
    clip.write_videofile("test_hand_corners_part1_video.mp4",codec="libx264")
    np.save("truth_biped_1_hand.npy",np.array(frame_displacements))

def part2():
    biped_vid = mpy.VideoFileClip("biped_2.avi")

    # Region motion.
    corners = [[210,183],[308,183],[210,315],[308,315]]
    image_list,region_displacements = optical_flow(biped_vid,corners,next_images=1, update_pos=False, mark_region=True)

    clip = edit.ImageSequenceClip(image_list,fps=25)
    clip.write_videofile("test_part2_video_region.mp4",codec="libx264")
    np.save("truth_biped_2_region.npy",np.array(region_displacements))

    # Hand motion.
    x, y = 401, 334
    region_displacements = np.load("truth_biped_2_region.npy")
    image_list,frame_displacements = optical_flow(biped_vid,[[x,y]],next_images=1, background_motion=None) # Considering background motion did not give better results.

    clip = edit.ImageSequenceClip(image_list,fps=25)
    clip.write_videofile("test_part2_video_hand_wallignored.mp4",codec="libx264")
    np.save("truth_biped_2_hand_wallignored.npy",np.array(frame_displacements))

def part3():
    biped_vid = mpy.VideoFileClip("biped_3.avi")

    hand_truth = np.load("truth_biped_1_hand.npy")
    region_truth = np.load("truth_biped_2_region.npy")

    # Region motion.
    corners = [[210,183],[308,183],[210,315],[308,315]]
    image_list,region_displacements = optical_flow(biped_vid,corners,next_images=1,update_pos=False, mark_region=True)

    clip = edit.ImageSequenceClip(image_list,fps=25)
    clip.write_videofile("test_part3_video_region.mp4",codec="libx264")
    np.save("truth_biped_3_region.npy",np.array(region_displacements))

    region_displacements= np.load("truth_biped_3_region.npy")
    print("Mean Squared Error (REGION): ",MSE(region_displacements,region_truth))
    region_shape = region_truth.shape
    print("-------------------------------------------------------------------")
    print("Model X Axis")
    model_x = fix_camera(region_displacements.reshape((region_shape[0]*region_shape[1],region_shape[2])),region_truth.reshape((region_shape[0]*region_shape[1],region_shape[2])), axis=0)
    print("-------------------------------------------------------------------")
    print("Model Y Axis")
    model_y = fix_camera(region_displacements.reshape((region_shape[0]*region_shape[1],region_shape[2])),region_truth.reshape((region_shape[0]*region_shape[1],region_shape[2])), axis=1)
    print("-------------------------------------------------------------------")

    # Hand motion.
    x, y = 401, 334
    image_list,frame_displacements = optical_flow(biped_vid,[[x,y]],next_images=1,camera_model=(model_x,model_y))

    clip = edit.ImageSequenceClip(image_list,fps=25)
    clip.write_videofile("test_part3_video_hand.mp4",codec="libx264")
    np.save("truth_biped_3_hand.npy",np.array(frame_displacements))

    hand_displacements= np.load("truth_biped_3_hand.npy")
    print("Mean Squared Error (HAND): ",MSE(hand_displacements,hand_truth))


import re
from functools import partial

from pyramid.config import Configurator
from clldutils.path import Path

from clld.interfaces import IParameter, IMapMarker, IDomainElement, IValue
from clld.web.adapters.base import adapter_factory
from clld.web.app import menu_item
from clld_glottologfamily_plugin.util import LanguageByFamilyMapMarker

# we must make sure custom models are known at database initialization!
from nts import models

class NtsMapMarker(LanguageByFamilyMapMarker):
    def get_icon(self, ctx, req):
        """to allow for user-selectable markers, we have to look up a possible custom
        selection from the url params.
        """
        icon = None
        if IValue.providedBy(ctx):
            icon = ctx.domainelement.jsondata['icon']
        elif IDomainElement.providedBy(ctx):
            icon = ctx.jsondata['icon']
        if icon:
            return icon
        return super(NtsMapMarker, self).get_icon(ctx, req)

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    convert = lambda spec: ''.join(c if i == 0 else c + c for i, c in enumerate(spec))
    filename_pattern = re.compile('(?P<spec>(c|d|s|f|t)[0-9a-f]{3})\.png')
    icons = {}
    for fname in sorted(Path(__file__).parent.joinpath('static', 'icons').iterdir()):
        m = filename_pattern.match(fname.name)
        if m:
            icons[m.group('spec')] = convert(m.group('spec'))
    settings['icons'] = icons

    config = Configurator(settings=settings)
    config.include('clldmpg')
    config.include('clld_glottologfamily_plugin')
    config.registry.registerUtility(NtsMapMarker(), IMapMarker)
    config.register_menu(
        ('dataset', partial(menu_item, 'dataset', label='Home')),
        ('parameters', partial(menu_item, 'parameters', label='Features')),
        ('languages', partial(menu_item, 'languages')),
        ('sources', partial(menu_item, 'sources')),
        ('designers', partial(menu_item, 'contributions', label="Contributors")),
    )
    config.register_adapter(adapter_factory(
        'parameter/detail_tab.mako',
        mimetype='application/vnd.clld.tab',
        send_mimetype="text/plain",
        extension='tab',
        name='tab-separated values'), IParameter)
    return config.make_wsgi_app()


#!/usr/bin/env python
from pathlib import Path
import subprocess
from versions import get_versions_data, write_versions_json

INDEX_HTML = r'''<!DOCTYPE html>

    <meta http-equiv="Refresh" content="0; url={default_branch}" />

Got to default documentation.

'''

def write_index_html(default_branch):
    """Write an index.html that redirects to the DEFAULT_BRANCH."""
    with open("index.html", "w") as out_fh:
        out_fh.write(INDEX_HTML.format(default_branch=default_branch))
    subprocess.run(['git', 'add', 'index.html'], check=True)

def find_downloads(folder):
    """Find files in the 'download' subfolder of the given `folder`."""
    downloads = []
    for filename in Path(folder).glob(r'download/*'):
        label = "".join(filename.suffixes).replace('.', '').lower()
        if len(label) > 0:
            downloads.append((label, str(filename)))
    return downloads

def main():
    """Main function."""
    print("Post-processing documentation on gh-pages")
    print("Gather versions info")
    versions_data = get_versions_data(find_downloads=find_downloads)
    latest_release = versions_data['latest_release']
    if latest_release is None:
        latest_release = 'master'
    print("Write index.html")
    write_index_html(latest_release)
    print("Write versions.json")
    write_versions_json(versions_data, outfile='versions.json')
    print("DONE post-processing")

if __name__ == "__main__":
    main()


import math
import numpy as np
import matplotlib.pyplot as plt

def A(a1, a2):
    """Створення матриці А з заданими параметрами а1 та а2"""
    A = np.zeros((3, 3))
    A[0][1] = 1
    A[1][2] = 1
    A[2][0] = -1
    A[2][1] = -a1
    A[2][2] = -a2
    return A

def B(b):
    """Створення матриці B з заданим параметром b"""
    B = np.zeros((3, 1))
    B[0][0] = 0
    B[1][0] = 0
    B[2][0] = b
    return B

def C():
    """Створення матриці C"""
    C = []
    for i in range(3):
        value = np.zeros((1, 3))
        if i != 0:
            value[0][i] = 0
        else:
            value[0][i] = 1
        C.append(value)
    return C

def F(x, t, q):
    """Обрахуємо F = e^(A*T0)"""
    I = np.eye(3)  # одинична матриця n*n
    for i in range(1, q + 1):
        I += np.linalg.matrix_power(x.dot(t), i) / math.factorial(i)
    return I

def G(x, q, t, b):
    """Обрахуємо G = I*B*(T0 + (A*T0^2)/2! + ... + (A^q-1*T0^q)/q!)"""
    b1 = B(b)
    I = np.eye(3)
    tmp = b1*I
    for j in range(2, q):
        tmp += (np.linalg.matrix_power(x, j - 1).dot(I) * (t ** j)) / math.factorial(j)
    return tmp.dot(b1)

def formulaX(f, x, u, g):
    """Обрахуємо Xk+1 = F*Xk + G*Uk"""
    res = f.dot(x) + g * u
    return res

def X():
    x = np.zeros((3, 1))
    x[0][0] = 0
    x[1][0] = 0
    x[2][0] = 0
    return x

def formulaY(x, c, y):
    """Обрахуємо y = C*x"""
    y.append(c.dot(x))
    return y

def variables():
    """Задаємо параметри"""
    a1 = float(input('Введіть a1 для матриці A: '))
    a2 = float(input('Введіть a2 для матриці A: '))
    b = float(input('Введіть b для матриці B: '))
    t0 = float(input('Введіть T0:'))
    q = int(input('Введіть q:'))
    var = [a1, a2, t0, q, b]

    return var

def main():
    vars = variables()
    vec = X()
    t = list(np.arange(0, 200 + vars[2], vars[2]))
    a = A(vars[0], vars[1])
    f = F(a, vars[2], vars[3])
    g = G(a, vars[3], vars[2], vars[4])
    x = []
    x.append(vec)
    option = int(input('Виберіть один варіант з трьох: '))
    if option == 1:
        u = 1
        for i in range(len(t)):
            vec = formulaX(f, vec, u, g)
            x.append(vec)
    elif option == 2:
        k0 = 15//vars[2]
        u = 1
        for i in range(len(t)):
            vec = formulaX(f, vec, u, g)
            x.append(vec)
            if t[i] == k0:
                u = -1
    elif option == 3:
        k0 = 15//vars[2]
        u = 1
        k = 0
        for i in range(len(t)):
            vec = formulaX(f, vec, u, g)
            x.append(vec)
            if k == k0:
                u = -1
            elif k == 2 * k0:
                u = -1
            elif k == 3 * k0:
                u = 1
            k += 1
    else:
        print("Немає такого варіанту")
        return 0

    y = []
    for i in x:
        y = formulaY(i, C()[0], y)
    list_x = []
    for i in y:
        a = i.tolist()
        list_x.append(a[0])
    list_y = []
    for i in range(len(list_x) - 1):
        list_y.append(list_x[i][0])

    """Графік"""
    plt.xlabel('t')
    plt.ylabel('y(t)')
    plt.grid()
    plt.xticks(np.arange(t[0], t[-1] + 1, 20))
    plt.plot(t, list_y, color='red')
    plt.show()

main()

"""Параметри для дослідження"""
# 1) a1 = 1, a2 = 10, b = 1, t0 = 0.0001, q = 10
# 2) a1 = 1, a2 = 1, b = 1, t0 = 0.0001, q = 10
# 3) a1 = 10, a2 = 1, b = 1, t0 = 0.0001, q = 10


from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db.utils import IntegrityError
from django.core.files import File
import os

class Command(BaseCommand):
    help = 'Creates demo users'

    def handle(self, *args, **options):

        User = get_user_model()

        avatars = ["avatar01.png", "avatar02.png", "avatar03.png", "avatar04.png"]

        demo_users = [
            {
                "name": "rebecca",
                "email": "rebecca@company.com",
                "avatar": avatars[0],
                "is_active": True,
            },
            {
                "name": "williams",
                "email": "williams@company.com",
                "avatar": avatars[1],
                "is_active": True,
            },
            {
                "name": "leo",
                "email": "leo@company.com",
                "avatar": avatars[2],
                "is_active": True,
            },
            {
                "name": "katherine",
                "email": "katherine@company.com",
                "avatar": avatars[3],
                "is_active": True,
            }
        ]

        for demo_user in demo_users:
            try:
                user = User.objects.create_user(
                    demo_user['email'],
                    demo_user['name'],
                    os.getenv('VUE_APP_DEMO_PASSWORD', 'demopwd123'),
                )

                avatar = open(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'img', demo_user['avatar'])), "rb")  # noqa: E501

                django_file = File(avatar)

                user.avatar.save(demo_user['avatar'], django_file, save=True)

                user.save()
                print(f"Created demo user {user.email}.")

            except IntegrityError:
                print(f"Demo user {demo_user['email']} already exists")


import pytest

# jax imports
import jax
import jax.numpy as jnp

# crs imports
import cr.nimble as cnb
from cr.nimble.dsp import *

atol = 1e-6
rtol = 1e-6

def test_dct1():
    for n in [4,8,16]:
        for i in range(n):
            print(n, i)
            y = cnb.vec_unit(n, i)
            a = dct(y)
            x = idct(a)
            assert jnp.allclose(x, y, rtol=rtol, atol=atol)

def test_orthonormal_dct1():
    for n in [4,8,16]:
        for i in range(n):
            print(n, i)
            y = cnb.vec_unit(n, i)
            a = orthonormal_dct(y)
            x = orthonormal_idct(a)
            assert jnp.allclose(x, y, rtol=rtol, atol=atol)


# Your code goes here.
# You can delete these comments, but do not change the name of this file
# Write your code to expect a terminal of 80 characters wide and 24 rows high
import gspread
from google.oauth2.service_account import Credentials

SCOPE = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/drive"
    ]

CREDS = Credentials.from_service_account_file('creds.json')
SCOPED_CREDS = CREDS.with_scopes(SCOPE)
GSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS)
SHEET = GSPREAD_CLIENT.open('love_sandwiches')

def get_sales_data():
    """
    Get the sales figures from the input
    """
    while True:
        print("Please enter some data")
        print("Should be 6 numbers")
        print("e.g 10,20,30,40,50,60\n")

        data_str = input("Enter your data here:\n")

        sales_data = data_str.split(",")

        if validate_data(sales_data):
            print("Data is valid!")
            break

    return sales_data

def validate_data(values):
    """
    Tries to convert all the strings vlaues into ints.
    Raise an error if they cant be converted or if
    there are not exatly 6 values entered.
    """
    try:
        [int(v) for v in values]
        if len(values) != 6:
            raise ValueError(f"Exactly 6 values required, you entered {len(values)}")
    except ValueError as e:
        print(f"Invalid data: {e}, please try again\n")
        return False

    return True

def update_worksheet(data, worksheet):
    """ New function """
    print(f"Updating {worksheet}...\n")

    worksheet_to_update = SHEET.worksheet(worksheet)
    worksheet_to_update.append_row(data)
    print(f"{worksheet} has been updated")

def calculate_surplus_data(sales_row):
    """
    Works out stock shortages / extra food made for customers
    """
    print("Calculating suplus / excess\n")
    stock = SHEET.worksheet("stock").get_all_values()
    stock_row = stock[-1]

    new_surplus_data = []
    for stock, sales in zip(stock_row, sales_row):
        surplus = int(stock) - sales
        new_surplus_data.append(surplus)

    return new_surplus_data

def get_last_5_entries_sales():
    """works out the average"""
    sales = SHEET.worksheet("sales")

    columns = []
    for c in range(1, 7):
        col_val = sales.col_values(c)
        columns.append(col_val[-5:])

    return columns

def calculate_stock_data(data):
    """ works out avg stock changes """
    print("Calcualting stock stats")
    new_stock_data = []

    for col in data:
        int_column = [int(num) for num in col]
        average = sum(int_column) / len(int_column)
        stock_num = average * 1.1
        new_stock_data.append(round(stock_num))

    return new_stock_data

def main():
    """
    Run all program functions
    """
    data = get_sales_data()
    sales_data = [int(num) for num in data]
    update_worksheet(sales_data, "sales")
    new_surplus_data = calculate_surplus_data(sales_data)
    update_worksheet(new_surplus_data, "surplus")
    sales_columns = get_last_5_entries_sales()
    stock_data = calculate_stock_data(sales_columns)
    print(stock_data)
    update_worksheet(stock_data, "stock")

print("Welcome to Love sandiwches automation tool")
main()


from json import load
import os
import argparse
import random
from copy import deepcopy
import torchvision
import torchvision.transforms as transforms
from torch import nn
from torch.nn import functional as F
import sys
import torch
import numpy as np

# sys.path.append("../../")
torch.manual_seed(0)

from fedlab.core.client.scale.trainer import SubsetSerialTrainer, SubsetSerialTrainerWithDifferentialUpdate
from fedlab.utils.aggregator import Aggregators
from fedlab.utils.serialization import SerializationTool
from fedlab.utils.dataset.partition import CIFAR10Partitioner
from fedlab.utils.functional import evaluate
from fedlab.utils.functional import get_best_gpu, load_dict

# configuration
parser = argparse.ArgumentParser(description="Standalone training example")
parser.add_argument("--total_client", type=int, default=100)
parser.add_argument("--com_round", type=int, default=10)

parser.add_argument("--sample_ratio", type=float)
parser.add_argument("--batch_size", type=int)
parser.add_argument("--epochs", type=int)
parser.add_argument("--lr", type=float, default=0.1)
parser.add_argument("--cuda", type=bool, default=False)

args = parser.parse_args()

# torch model
class CNN(nn.Module):

    def __init__(self, input_size=32, input_channel=3, output_size=10):
        super(CNN, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=input_channel, out_channels=32, kernel_size=5)
        self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        in_features = 64 * ((((input_size - 4) // 2) - 4) // 2) ** 2
        self.fc1 = nn.Linear(in_features, 512)
        self.fc2 = nn.Linear(512, output_size)

    def forward(self, x):
        x = F.relu(self.pool(self.conv1(x)))
        x = F.relu(self.pool(self.conv2(x)))
        x = x.view(x.size(0), -1)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# get mnist dataset
root = "../dataSet/cifar10/"
trainset = torchvision.datasets.CIFAR10(root=root,
                                      train=True,
                                      download=True,
                                      transform=transforms.Compose([
                                                transforms.RandomHorizontalFlip(0.5),
                                                transforms.RandomCrop(32, 4),
                                                transforms.ToTensor(),
                                                transforms.Normalize(mean=[0.491, 0.482, 0.447], std=[0.247, 0.243, 0.262])]))

testset = torchvision.datasets.CIFAR10(root=root,
                                     train=False,
                                     download=True,
                                     transform=transforms.Compose([transforms.ToTensor(),
                                                                   transforms.Normalize(mean=[0.491, 0.482, 0.447], std=[0.247, 0.243, 0.262])]))

test_loader = torch.utils.data.DataLoader(testset,
                                          batch_size=50,
                                          drop_last=False,
                                          shuffle=False)

# setup
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"

if args.cuda:
    gpu = get_best_gpu()
    print("using {}".format(gpu))
    model = CNN().cuda(gpu)
else:
    model = CNN()

# FL settings
num_per_round = int(args.total_client * args.sample_ratio)
aggregator = Aggregators.pca_aggregate
total_client_num = args.total_client  # client总数

data_indices = CIFAR10Partitioner(trainset.targets, args.total_client, True, "iid").client_dict

# fedlab setup
local_model = deepcopy(model)

trainer = SubsetSerialTrainerWithDifferentialUpdate(model=local_model,
                              dataset=trainset,
                              data_slices=data_indices,
                              aggregator=aggregator,
                              args={
                                  "batch_size": args.batch_size,
                                  "epochs": args.epochs,
                                  "max_norm":10,
                                  "optim":{"type":"SGD", "lr": args.lr, "weight_decay":1e-3}
                              })

# train procedure
to_select = [i for i in range(total_client_num)]
for round in range(args.com_round):
    model_parameters = SerializationTool.serialize_model(model)
    selection = random.sample(to_select, num_per_round)
    aggregated_parameters = trainer.train(model_parameters=model_parameters,
                                          id_list=selection,
                                          aggregate=True, n_components=5)

    SerializationTool.deserialize_model(model, aggregated_parameters + model_parameters)

    criterion = nn.CrossEntropyLoss()
    loss, acc = evaluate(model, criterion, test_loader)
    print("round {}, loss: {:.4f}, acc: {:.2f}".format(round + 1, loss, acc))


import pygame
import serial

(SCREEN_WIDTH, SCREEN_HEIGHT) = (300, 200)
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

BACKGROUND_COLOUR = (32, 32, 32)

pygame.display.set_caption('EOgmaDrive Controller')

pygame.font.init()
FONT = pygame.font.SysFont("Arial", 20)

def display_mode(string, colour):
    """ Display centered text """
    text = FONT.render(string, True, colour)
    text_rect = text.get_rect(center=(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
    SCREEN.blit(text, text_rect)

def main():
    """ Main function """
    port = serial.Serial(port="/dev/ttyACM0", baudrate=9600)
    if port._isOpen == False:
        print("Failed to open /dev/ttyACM0")
        pygame.quit()
        return

    training = True

    SCREEN.fill(BACKGROUND_COLOUR)
    display_mode(string="Mode: TRAINING", colour=(64, 64, 255))

    pygame.display.flip()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False

            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                SCREEN.fill(BACKGROUND_COLOUR)

                if training:
                    training = False
                    port.write(b'P')
                    display_mode(string="Mode: PREDICTING",
                                 colour=(255, 64, 64))
                else:
                    training = True
                    port.write(b'T')
                    display_mode(string="Mode: TRAINING",
                                 colour=(64, 64, 255))

                pygame.display.flip()

    port.close()
    pygame.quit()

if __name__ == '__main__':
    main()


from logging import getLogger

import httpx

from ddns_clienter_core.runtimes.config import TaskConfig

from .abs import DDNSProviderAbs, DDNSProviderException

logger = getLogger(__name__)

_update_api_url = "https://dynv6.com/api/update"
_rest_api_url = "https://dynv6.com/api/v2"

async def _call_update_api(
    domain: str,
    token: str,
    ipv4_address: str | None,
    ipv6_address: str | None,
    real_update: bool,
) -> (bool, str):
    # https://dynv6.com/docs/apis
    params = {
        "zone": domain,
        "token": token,
    }
    if ipv4_address:
        params.update({"ipv4": ipv4_address})
    if ipv6_address:
        params.update({"ipv6": ipv6_address})

    logger.debug(params)
    if not real_update:
        return True, ""

    try:
        async with httpx.AsyncClient() as client:
            r = await client.get(_update_api_url, params=params)
        logger.debug(f"{r.status_code} {r.content}")
    except (httpx.HTTPError, httpx.StreamError) as e:
        return False, str(e)

    if r.status_code == 200:
        return True, r.text
    else:
        return False, r.text

class CallRestApi:
    zone_id: int | None = None

    def __init__(
        self,
        config_task: TaskConfig,
        ipv4_address: str,
        ipv6_address: str,
        real_update: bool,
    ):
        self._c_task = config_task
        self.config_host, self.config_domain = config_task.domain.split(".", maxsplit=1)
        self.ipv4_address = ipv4_address
        self.ipv6_address = ipv6_address
        self.real_update = real_update

        self.headers = httpx.Headers()
        self.headers["Accept"] = "application/json"
        self.headers["Authorization"] = f"Bearer {self._c_task.provider_auth}"

    async def _call_rest_api_get(self, url) -> httpx.Response:
        async with httpx.AsyncClient() as client:
            r = await client.get(url, headers=self.headers)
        logger.debug(f"{r.status_code} {r.content}")

        if r.status_code != 200:
            raise DDNSProviderException(r)

        return r

    async def _call_rest_api_add_record(
        self, host: str, record_type: str, ip_address: str
    ) -> httpx.Response:
        j = {"name": host, "type": record_type, "data": ip_address}
        async with httpx.AsyncClient() as client:
            r = await client.post(
                f"{_rest_api_url}/zones/{self.zone_id}/records",
                headers=self.headers,
                json=j,
            )
        logger.debug(f"{r.status_code} {r.content}")

        if r.status_code != 200:
            raise DDNSProviderException(r)

        return r

    async def _call_rest_api_update_record(
        self, record_id: str, record_type: str, ip_address: str
    ) -> httpx.Response:
        j = {"type": record_type, "data": ip_address}
        async with httpx.AsyncClient() as client:
            r = await client.patch(
                f"{_rest_api_url}/zones/{self.zone_id}/records/{record_id}",
                headers=self.headers,
                json=j,
            )

        logger.debug(f"{r.status_code} {r.content}")

        if r.status_code != 200:
            raise DDNSProviderException(r)

        return r

    async def process(self) -> (bool, str):
        # https://dynv6.github.io/api-spec

        # get zone id
        r = await self._call_rest_api_get(f"{_rest_api_url}/zones")

        for item in r.json():
            if item.get("name") == self.config_domain:
                self.zone_id = item.get("id")
                continue

        if self.zone_id is None:
            raise DDNSProviderException(f"Can not match zone id:{r}")

        # get record id
        r = await self._call_rest_api_get(
            f"{_rest_api_url}/zones/{self.zone_id}/records"
        )

        ipv4_record_id = None
        ipv6_record_id = None
        for item in r.json():
            if item.get("name") != self.config_host:
                continue

            record_type = item.get("type")
            if record_type == "A":
                ipv4_record_id = item.get("id")
            elif record_type == "AAAA":
                ipv6_record_id = item.get("id")

        if self.ipv4_address:
            if ipv4_record_id is None:
                # add a new record
                await self._call_rest_api_add_record(
                    host=self.config_host,
                    record_type="A",
                    ip_address=self.ipv4_address,
                )
            else:
                # update a record
                await self._call_rest_api_update_record(
                    record_id=ipv4_record_id,
                    record_type="A",
                    ip_address=self.ipv4_address,
                )

        if self.ipv6_address:
            if ipv6_record_id is None:
                # add a new record
                await self._call_rest_api_add_record(
                    host=self.config_host,
                    record_type="AAAA",
                    ip_address=self.ipv6_address,
                )
            else:
                # update a record
                await self._call_rest_api_update_record(
                    record_id=ipv6_record_id,
                    record_type="AAAA",
                    ip_address=self.ipv6_address,
                )

        if 200 <= r.status_code <= 299:
            update_success = True
        else:
            update_success = False
        return update_success, f"{r.status_code} {r.text}"

class DDNSProviderDynv6(DDNSProviderAbs):
    name = "dynv6"

    async def _update_to_provider(self) -> None:
        logger.debug("update in Dynv6 UPDATE API")
        self.update_success, self.update_message = await _call_update_api(
            domain=self.task_config.domain,
            token=self.task_config.provider_auth,
            ipv4_address=self.address_info.ipv4_address_str,
            ipv6_address=self.address_info.ipv6_address_str_with_prefix,
            real_update=self.real_update,
        )

class DDNSProviderDynv6REST(DDNSProviderAbs):
    name = "dynv6.rest"

    async def _update_to_provider(self) -> None:
        logger.debug("update in Dynv6 REST API")
        call_rest_api = CallRestApi(
            config_task=self.task_config,
            ipv4_address=self.address_info.ipv4_address_str,
            ipv6_address=self.address_info.ipv6_address_str,  # REST API 似乎不支持 /xx 这种方式定义 prefix
            real_update=self.real_update,
        )

        self.update_success, self.update_message = call_rest_api.process()


import sqlalchemy as sa
from sqlalchemy import func

from flashcards.database import Base

class Card(Base):
    __tablename__ = 'cards'

    id = sa.Column(sa.Integer, primary_key=True)
    user_id = sa.Column(sa.Integer, sa.ForeignKey('users.id'), index=True)
    title = sa.Column('title', sa.String, nullable=False, index=True)
    content = sa.Column('content', sa.Text, nullable=True)
    created_at = sa.Column(sa.DateTime, nullable=False, server_default=func.now(), index=True)


"""fixture models

Revision ID: edf9d4b6cdea
Revises: bb02384217e4
Create Date: 2023-05-21 20:04:01.734393

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "edf9d4b6cdea"
down_revision = "bb02384217e4"
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column("categories", "archive", nullable=False, new_column_name="is_archived")
    op.add_column("tasks", sa.Column("title", sa.String(), nullable=False))
    op.add_column("tasks", sa.Column("name_organization", sa.String(), nullable=True))
    op.add_column("tasks", sa.Column("deadline", sa.Date(), nullable=True))
    op.add_column("tasks", sa.Column("description", sa.String(), nullable=False))
    op.alter_column("tasks", "archive", nullable=False, new_column_name="is_archived")
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column("tasks", "is_archived", nullable=False, new_column_name="archive")
    op.drop_column("tasks", "description")
    op.drop_column("tasks", "deadline")
    op.drop_column("tasks", "name_organization")
    op.drop_column("tasks", "title")
    op.alter_column("categories", "is_archived", nullable=False, new_column_name="archive")
    # ### end Alembic commands ###


#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
This file contains configuration for the locations of all the static file
libraries, such as JavaScript and CSS libraries. Packagers for individual
distributions can edit or replace this file, in order to change the paths
to match their distribution's standards.
"""

import os

import xstatic.main
import xstatic.pkg.angular
import xstatic.pkg.angular_bootstrap
import xstatic.pkg.angular_fileupload
import xstatic.pkg.angular_gettext
import xstatic.pkg.angular_lrdragndrop
import xstatic.pkg.angular_smart_table
import xstatic.pkg.bootstrap_datepicker
import xstatic.pkg.bootstrap_scss
import xstatic.pkg.bootswatch
import xstatic.pkg.d3
import xstatic.pkg.font_awesome
import xstatic.pkg.hogan
import xstatic.pkg.jasmine
import xstatic.pkg.jquery
import xstatic.pkg.jquery_migrate
import xstatic.pkg.jquery_quicksearch
import xstatic.pkg.jquery_tablesorter
import xstatic.pkg.jquery_ui
import xstatic.pkg.jsencrypt
import xstatic.pkg.mdi
import xstatic.pkg.rickshaw
import xstatic.pkg.roboto_fontface
import xstatic.pkg.spin
import xstatic.pkg.termjs

from horizon.utils import file_discovery

from openstack_dashboard import theme_settings

def get_staticfiles_dirs(webroot='/'):
    STATICFILES_DIRS = [
        ('horizon/lib/angular',
            xstatic.main.XStatic(xstatic.pkg.angular,
                                 root_url=webroot).base_dir),
        ('horizon/lib/angular',
            xstatic.main.XStatic(xstatic.pkg.angular_bootstrap,
                                 root_url=webroot).base_dir),
        ('horizon/lib/angular',
            xstatic.main.XStatic(xstatic.pkg.angular_fileupload,
                                 root_url=webroot).base_dir),
        ('horizon/lib/angular',
            xstatic.main.XStatic(xstatic.pkg.angular_gettext,
                                 root_url=webroot).base_dir),
        ('horizon/lib/angular',
            xstatic.main.XStatic(xstatic.pkg.angular_lrdragndrop,
                                 root_url=webroot).base_dir),
        ('horizon/lib/angular',
            xstatic.main.XStatic(xstatic.pkg.angular_smart_table,
                                 root_url=webroot).base_dir),
        ('horizon/lib/bootstrap_datepicker',
            xstatic.main.XStatic(xstatic.pkg.bootstrap_datepicker,
                                 root_url=webroot).base_dir),
        ('bootstrap',
            xstatic.main.XStatic(xstatic.pkg.bootstrap_scss,
                                 root_url=webroot).base_dir),
        ('horizon/lib/bootswatch',
         xstatic.main.XStatic(xstatic.pkg.bootswatch,
                              root_url=webroot).base_dir),
        ('horizon/lib',
            xstatic.main.XStatic(xstatic.pkg.d3,
                                 root_url=webroot).base_dir),
        ('horizon/lib',
            xstatic.main.XStatic(xstatic.pkg.hogan,
                                 root_url=webroot).base_dir),
        ('horizon/lib/font-awesome',
            xstatic.main.XStatic(xstatic.pkg.font_awesome,
                                 root_url=webroot).base_dir),
        ('horizon/lib/jasmine',
            xstatic.main.XStatic(xstatic.pkg.jasmine,
                                 root_url=webroot).base_dir),
        ('horizon/lib/jquery',
            xstatic.main.XStatic(xstatic.pkg.jquery,
                                 root_url=webroot).base_dir),
        ('horizon/lib/jquery',
            xstatic.main.XStatic(xstatic.pkg.jquery_migrate,
                                 root_url=webroot).base_dir),
        ('horizon/lib/jquery',
            xstatic.main.XStatic(xstatic.pkg.jquery_quicksearch,
                                 root_url=webroot).base_dir),
        ('horizon/lib/jquery',
            xstatic.main.XStatic(xstatic.pkg.jquery_tablesorter,
                                 root_url=webroot).base_dir),
        ('horizon/lib/jsencrypt',
            xstatic.main.XStatic(xstatic.pkg.jsencrypt,
                                 root_url=webroot).base_dir),
        ('horizon/lib/mdi',
         xstatic.main.XStatic(xstatic.pkg.mdi,
                              root_url=webroot).base_dir),
        ('horizon/lib',
            xstatic.main.XStatic(xstatic.pkg.rickshaw,
                                 root_url=webroot).base_dir),
        ('horizon/lib/roboto_fontface',
         xstatic.main.XStatic(xstatic.pkg.roboto_fontface,
                              root_url=webroot).base_dir),
        ('horizon/lib',
            xstatic.main.XStatic(xstatic.pkg.spin,
                                 root_url=webroot).base_dir),
        ('horizon/lib',
         xstatic.main.XStatic(xstatic.pkg.termjs,
                              root_url=webroot).base_dir),
    ]

    if xstatic.main.XStatic(xstatic.pkg.jquery_ui,
                            root_url=webroot).version.startswith('1.10.'):
        # The 1.10.x versions already contain the 'ui' directory.
        STATICFILES_DIRS.append(
            ('horizon/lib/jquery-ui',
             xstatic.main.XStatic(xstatic.pkg.jquery_ui,
                                  root_url=webroot).base_dir))
    else:
        # Newer versions dropped the directory, add it to keep the path the
        # same.
        STATICFILES_DIRS.append(
            ('horizon/lib/jquery-ui/ui',
             xstatic.main.XStatic(xstatic.pkg.jquery_ui,
                                  root_url=webroot).base_dir))

    return STATICFILES_DIRS

def find_static_files(
        HORIZON_CONFIG,
        AVAILABLE_THEMES,
        THEME_COLLECTION_DIR,
        ROOT_PATH):
    import horizon
    import openstack_dashboard
    os_dashboard_home_dir = openstack_dashboard.__path__[0]
    horizon_home_dir = horizon.__path__[0]

    # note the path must end in a '/' or the resultant file paths will have a
    # leading "/"
    file_discovery.populate_horizon_config(
        HORIZON_CONFIG,
        os.path.join(horizon_home_dir, 'static/')
    )

    # filter out non-angular javascript code and lib
    HORIZON_CONFIG['js_files'] = ([f for f in HORIZON_CONFIG['js_files']
                                   if not f.startswith('horizon/')])

    # note the path must end in a '/' or the resultant file paths will have a
    # leading "/"
    file_discovery.populate_horizon_config(
        HORIZON_CONFIG,
        os.path.join(os_dashboard_home_dir, 'static/'),
        sub_path='app/'
    )

    # Discover theme static resources, and in particular any
    # static HTML (client-side) that the theme overrides
    theme_static_files = {}
    theme_info = theme_settings.get_theme_static_dirs(
        AVAILABLE_THEMES,
        THEME_COLLECTION_DIR,
        ROOT_PATH)

    for url, path in theme_info:
        discovered_files = {}

        # discover static files provided by the theme
        file_discovery.populate_horizon_config(
            discovered_files,
            path
        )

        # Get the theme name from the theme url
        theme_name = url.split('/')[-1]

        # build a dictionary of this theme's static HTML templates.
        # For each overridden template, strip off the '/templates/' part of the
        # theme filename then use that name as the key, and the location in the
        # theme directory as the value. This allows the quick lookup of
        # theme path for any file overridden by a theme template
        template_overrides = {}
        for theme_file in discovered_files['external_templates']:
            # Example:
            #   external_templates_dict[
            #       'framework/widgets/help-panel/help-panel.html'
            #   ] = 'themes/material/templates/framework/widgets/\
            #        help-panel/help-panel.html'
            (templates_part, override_path) = theme_file.split('/templates/')
            template_overrides[override_path] = 'themes/' +\
                                                theme_name + theme_file

        discovered_files['template_overrides'] = template_overrides

        # Save all of the discovered file info for this theme in our
        # 'theme_files' object using the theme name as the key
        theme_static_files[theme_name] = discovered_files

    # Add the theme file info to the horizon config for use by template tags
    HORIZON_CONFIG['theme_static_files'] = theme_static_files


import matplotlib.pyplot as plt
import numpy as np
import cv2
import json
train_json = json.load(open('../../../SVHN-Data/mchar_train.json'))

# 数据标注处理
def parse_json(d):
    arr = np.array([
        d['top'], d['height'], d['left'],  d['width'], d['label']
    ])
    arr = arr.astype(int)
    return arr

img = cv2.imreasd('../../../SVHN-Data/mchar_train/000000.png')
arr = parse_json(train_json['000000.png'])

plt.figure(figsize=(10, 10))
plt.subplot(1, arr.shape[1]+1, 1)
plt.imshow(img)
plt.xticks([]); plt.yticks([])

for idx in range(arr.shape[1]):
    plt.subplot(1, arr.shape[1]+1, idx+2)
    plt.imshow(img[arr[0, idx]:arr[0, idx]+arr[1, idx],arr[2, idx]:arr[2, idx]+arr[3, idx]])
    plt.title(arr[4, idx])
    plt.xticks([]); plt.yticks([])


#!/usr/bin/env python3

import sys
from time import sleep
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from PIL import Image
from io import BytesIO
from xvfbwrapper import Xvfb

WEBCAMS = {
    "https://webcam.exdesign.ru/cds-polyustrovo-1": "webcam1.png",
    "https://webcam.exdesign.ru/cds-polyustrovo-2": "webcam2.png"}
VIDEO_CLASSNAME = "container"

def capture_photos():

    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options)

    for url, pic in WEBCAMS.items():
        print("%s: capturing..." % url)
        driver.get(url)
        sleep(5)
        element = driver.find_element_by_class_name(VIDEO_CLASSNAME)
        location = element.location
        size = element.size
        png = driver.get_screenshot_as_png()

        im = Image.open(BytesIO(png))

        left = location['x']
        top = location['y']
        right = location['x'] + size['width']
        if url == "https://webcam.exdesign.ru/cds-polyustrovo-1":
            # the site lies about element size (850px)
            bottom = 700
        else:
            bottom = location['y'] + size['height']

        im = im.crop((left, top, right, bottom))
        im.save(pic)
        print("%s: captured as %s" % (url, pic))
    driver.quit()

def main():
    with Xvfb(width=1920, height=1080) as xvfb:
        capture_photos()

if __name__ == "__main__":
    main()


"""Handle interactions with github."""
import logging
import os
import shutil

import requests
from github import Github
from provision.utils import chdir, run

LOG = logging.getLogger(__name__)

def git_clone(repo: str, dest_path: str = "", args: list = ["--recursive"]) -> None:
    """Clone git repo to dest path."""
    if not shutil.which("git"):
        LOG.error("Git not installed!")
        return
    if not repo[0:4] in ("git@", "http"):
        # Assume it's my repo
        repo = f"git@github.com:comfortablynick/{repo}.git"
    if dest_path is not None:
        args.append(os.path.expanduser(dest_path))
    cmd = ["git", "clone", repo, *args]
    LOG.debug("Cmd: %s", " ".join(cmd))
    with chdir(os.path.expanduser("~/git")):
        run(cmd)
    return

def github_token() -> str:
    """Retrieve secret access token from disk."""
    file = os.path.expanduser("~/.github_token")
    token = ""
    try:
        with open(file, "r") as f:
            token = f.read()
    except FileNotFoundError:
        LOG.error("GitHub token file not found: %s. Aborting!", file)
        return ""
    else:
        return token.strip("\n")

def clone_git_repos(args) -> None:
    """Clone repos from GitHub."""
    token = github_token()
    LOG.info("GitHub token found: %s", token)
    if token == "":
        return
    g = Github(token)
    for repo in g.get_user().get_repos():
        root_files = [content.name for content in repo.get_contents(".")]
        if ".provision_ignore" not in root_files:
            git_clone(repo.ssh_url)

def git_latest_tag() -> str:
    """Return first tag after reverse sort of available tags."""
    return run("git describe --tags --abbrev=0", capture_output=True).stdout.strip("\n")

def github_latest_release(args) -> int:
    """Get latest release binary."""
    token = github_token()
    if token == "":
        LOG.error("No GitHub token found!")
        return 1
    LOG.info("GitHub token found: %s", token)
    g = Github(token)
    r = g.get_repo(args.repo)
    name = r.name

    if shutil.which(name) and not args.force:
        LOG.warning("%s already exists. Skipping install!", name)
        return 1
    rel = r.get_releases()[0]  # latest
    assets = rel.get_assets()
    if assets.totalCount is None:
        LOG.error("Repo '%s' has no assets", args.repo)
        return 1
    print("Choose from the following packages:")
    for ctr, asset in enumerate(assets, 1):
        print(f"{str(ctr)}: {asset.name}")
    while True:
        choice = input("Enter number of choice: ")
        if choice == "":
            LOG.error("User input canceled!")
            return 1
        try:
            file = assets[int(choice) - 1]
        except IndexError:
            LOG.error("Choice '%s' out of range!", str(choice))
            continue
        except ValueError:
            LOG.error("Incorrect value: '%s'. Enter a number in range.", str(choice))
            continue
        else:
            break
    print(f"You chose to download {file.name}")
    r = requests.get(file.browser_download_url, stream=True)
    LOG.debug("Request response: %s", r.status_code)
    dest_path = os.path.join(os.path.expanduser(args.dest), file.name)
    print(f"Downloading to {dest_path}...")
    with open(dest_path, "wb") as f:
        for chunk in r.iter_content(chunk_size=128):
            f.write(chunk)
    return 0


import json
import os
from model.Puzzle import Puzzle
from PIL import Image, ImageDraw, ImageFont, ImageColor
from cryptography.fernet import Fernet
import base64
from controller.Context import Context
from controller.Strategy import plainSave, encryptSave
# from customExcept import OverwriteSave

# State class holding all save, load, and related methods

class SaveAndLoad:
    __SAVE_DIR = "saveFiles"

    # Display all save names held in json master save file
    @classmethod
    def allSaveNames(cls) -> list[str]:
        # list that is returned
        retNames = []
        # check if file exists, otherwise raise exception
        if os.path.exists(cls.__SAVE_DIR):
            tempList = os.listdir(cls.__SAVE_DIR)
            for i in tempList:
                retNames.append(os.path.splitext(i)[0])
        return retNames

    # isSaved checks the filename in the master save file to see if it is already an in use save name
    @classmethod
    def isSaved(cls, saveName: str) -> bool:
        return os.path.exists(saveName)

    # Save shell that allows for calling save data in 4 different ways scratch, current, overwrite scratch, and overwrite current
    # This is what is called for the user interface in the form state.save(state, "saveName", "saveType")
    @staticmethod
    def saveCurrent(puzzle: Puzzle, saveName: str, encrypt: bool = False):
        if encrypt:
            SaveAndLoad.saveData(saveName, puzzle.getPuzzleLetters(), puzzle.getWordList(),
                        puzzle.getGuessedWords(), puzzle.getCurrentPoints(), puzzle.getMaxPoints(), encrypt = True)
        else:
            SaveAndLoad.saveData(saveName, puzzle.getPuzzleLetters(), puzzle.getWordList(),
                        puzzle.getGuessedWords(), puzzle.getCurrentPoints(), puzzle.getMaxPoints(), encrypt = False)
        # Save shell that allows for calling save data in 4 different ways scratch, current, overwrite scratch, and overwrite current
        # This is what is called for the user interface in the form state.save(state, "saveName", "saveType")

    @staticmethod
    def saveScratch(puzzle: Puzzle, saveName: str, encrypt: bool = False):
        if encrypt:
            SaveAndLoad.saveData(saveName, puzzle.getPuzzleLetters(),
                        puzzle.getWordList(), [], 0, puzzle.getMaxPoints(), encrypt = True)
        else:
            SaveAndLoad.saveData(saveName, puzzle.getPuzzleLetters(),
                        puzzle.getWordList(), [], 0, puzzle.getMaxPoints(), encrypt = False)

    @classmethod
    def saveImg(cls, img: str, imgName: str):

        fnt = font = ImageFont.load_default()

        image = Image.new(mode = "RGB", size = (200,160), color = "black")
        draw = ImageDraw.Draw(image)

        draw.text((10,10), img, font=fnt, fill=(255,255,0))

        image = image.resize((900, 700), resample=Image.NEAREST)
        image.save(imgName)

    @classmethod
    def __checkJsonExt(cls, fileName:str):
        fileName = fileName.strip()
        if not fileName.endswith(".json"):
            fileName += ".json"

        return fileName

    # Main saving function that is only called within the state class
    # Originally two functions, was able to be condensed with the use of default parameters
    # Using default parameters we can do all 4 save routines
    # empty parameters with only cls, savename, wordPuzzle, will default the rest and save from the baseline
    # ^ but with type 1 will overwrite the savefile with scratch
    # full parameters without a type will save current
    # ^ but with type 1 will overwrite the savefile with current
    @classmethod
    def saveData(cls, saveName:str, puzzleLetters, wordList, foundWords=[], currentPoints=0, maxPoints=0, author = "Team SNEK", encrypt = False):

        saveName = cls.__checkJsonExt(saveName)
        # checking if the wordListSize is None, meaning a scratch or overwrite scratch
        save = Context()
        if encrypt:
            save.setStrategy(encryptSave())
        else:
            save.setStrategy(plainSave())

        retList = save.executeStrategy(puzzleLetters, wordList)
        puzzleLettersStr = retList[0]
        listType = retList[1]
        wordList = retList[2]
        requiredLetter = retList[3]
        data = cls.saveParse(puzzleLettersStr, listType, wordList,
                             foundWords, currentPoints, requiredLetter, maxPoints, author, encrypt)

        # dump new save data into master file and create if none is present
        dirs = os.path.dirname(saveName)

        os.makedirs(dirs, exist_ok=True)

        with open(saveName, "w") as f:
            json.dump(data, f, indent=2)

    # load the save data into the class variables into the puzzle class
    @ classmethod
    def load(cls, loadName: str) -> Puzzle:
        loadName = cls.__checkJsonExt(loadName)

        with open(loadName, "r") as loadFile:
            data = json.load(loadFile)

        puzzleLettersStr: str = data["PuzzleLetters"]
        requiredLetter = data["RequiredLetter"]
        puzzleLetters = []
        puzzleLetters.append(requiredLetter)
        # putting the req letter in front
        puzzleLetters = [requiredLetter] + list(puzzleLettersStr.replace(requiredLetter, ""))

        if list(data)[2] == "SecretWordList":
            decrypLis = []
            key = data["Author"]

            for i in range(0, 32-len(key)):
                key += "$"

            key = key.encode("utf-8")
            key = base64.b64encode(key)
            f = Fernet(key)

            temp = data["SecretWordList"].encode("utf-8")
            decrypLis = f.decrypt(temp).decode("utf-8").split(",")
            decrypLis.remove("")

            myPuzzle = Puzzle(puzzleLetters, decrypLis, data["GuessedWords"], data["MaxPoints"], data["CurrentPoints"])
        else:
            myPuzzle = Puzzle(puzzleLetters, data["WordList"], data["GuessedWords"], data["MaxPoints"], data["CurrentPoints"])

        return myPuzzle

    # Translate from variables into json format
    @ staticmethod
    def saveParse(puzzleLetters="", wordListType="WordList", wordList=[], guessedWords=[], currentPoints=0, requiredLetter="", maxPoints=0, author = "Team SNEK", crypBool: bool = False):
        # Translate to json format
        retData = {
            "Author": author,
            "GuessedWords": guessedWords,
            wordListType: wordList,
            "PuzzleLetters": puzzleLetters,
            "RequiredLetter": requiredLetter,
            "CurrentPoints": currentPoints,
            "MaxPoints": maxPoints
        }
        return retData


#
# Parse mapfile and dump all information collected.
# Requires https://github.com/pfalcon/pymapfile .
#
import sys
import logging
from pprint import pprint

from mapfile import GnuMapFile

logging.basicConfig(level=logging.DEBUG)

f = open(sys.argv[1])
m = GnuMapFile(f)
m.skip_till_memmap()
m.skip_while_lead_space()
m.parse_sections()
m.validate()

basename = sys.argv[1].replace("-", "_").replace(".", "_")

with open(basename + ".subareas", "w") as f:
    print("[subareas]", file=f)
    for k, addr, sz in m.section_order:
        #print("%08x %08x %s" % (addr, sz, k))
        for sec, addr, sz, obj, symbols in m.sections[k]["objects"]:
            if sec.endswith(".literal"):
                obj += ".literal"
            obj = obj.replace(" ", "_")
            print("%s 0x%08x(0x%08x)" % (obj, addr, sz), file=f)
        print(file=f)

with open(basename + "_script.py", "w") as f:
    print("""\
from idc import *

""", file=f)
    for k, addr, sz in m.section_order:
        #print("%08x %08x %s" % (addr, sz, k))
        for sec, addr, sz, obj, symbols in m.sections[k]["objects"]:
            if obj.endswith(".fill"):
                print("# %s 0x%08x(0x%08x)" % (obj, addr, sz), file=f)
                print("MakeAlign(0x%08x, 0x%08x, 0)" % (addr, sz), file=f)
        print(file=f)


import os, shutil, random
from glob import glob
from tqdm import tqdm

if __name__ == '__main__':
    in_bpath = '/data/datasets/godatasets/goboard_datasets/'
    train_bpath = in_bpath + 'train/yehu/'
    test_bpath = in_bpath +'test/yehu/'
    train_prop = 0.7
    label_file_postfix = '.schema'
    image_file_postfix = '.png'

    label_file_list = glob(train_bpath + '*/*' + label_file_postfix)
    # print(label_file_list[:3])
    random.shuffle(label_file_list)
    # print(label_file_list[:3])
    n = len(label_file_list)
    print(f"total instance: {n}")
    train_n = int(n * train_prop)
    for now_label_file in tqdm(label_file_list[train_n:]):
        now_image_file = now_label_file.replace(label_file_postfix, image_file_postfix)
        now_out_base_path = os.path.split(now_label_file)[0].replace(train_bpath, test_bpath) + '/'
        if not os.path.exists(now_out_base_path):
            os.makedirs(now_out_base_path)
        now_file_id  = os.path.split(now_label_file)[1].split('.')[0]
        shutil.move(now_label_file, now_out_base_path + now_file_id + label_file_postfix)
        shutil.move(now_image_file, now_out_base_path + now_file_id + image_file_postfix)