#
# This code is adapted from code presented in:
# programarcadegames.com/index.php?chapter=introduction_to_graphics&lang=en#section_5
#

import pygame
import random

pygame.init()

# Define some colors
# (red, green, blue) triplets, each one in range 0-255.
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

PI = 3.1416

global rectColour
global m_x, m_y  # Mouse x and y positions

global circ1_x, circ1_y  # x and y positions for circle 1

global circ2_x, circ2_y
global circ2_colour
circ2_colour = WHITE  # same as background initially, to make the circle invisible

global follower_x, follower_y  # x and y position offsets for "follower" rectangle

global displayImage
displayImage = False  # No image stuff unless user presses I key.
#theImage = pygame.image.load("Lina.jpg")

rectColour = RED
m_x = 0
m_y = 0

size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
keepgoing = True

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Set initial position for circle 1
circ1_x = 200
circ1_y = 100

# Set initial position of "surprise" circle 2 to that of circle 1
circ2_x = circ1_x
circ2_y = circ1_y

# Set an initial offset for "follower" rectangle
follower_x = 0
follower_y = 0

# -------- Main Program Loop -----------

# In an infinite processing loop until done gets set to true.

while keepgoing:

    # --- Main event loop

    # Check whether an event has occurred.
    for event in pygame.event.get():  # User did something

        # The stuff at this indentation level only gets executed when pygame has received and event via its get() function.

        if event.type == pygame.QUIT:  # If user clicked close
            keepgoing = False  # We are done so we exit the main processing loop.

        elif event.type == pygame.KEYDOWN:
            print("User pressed a key.")
            if (event.key == pygame.K_UP):
                circ1_y -= 10  # move circle 1 up 10 units
            if (event.key == pygame.K_DOWN):
                circ1_y += 10
            if (event.key == pygame.K_LEFT):
                circ1_x -= 10
            if (event.key == pygame.K_RIGHT):
                circ1_x += 10

            if (event.key == pygame.K_o):
                # Set initial position of "surprise" circle (O key pressed)
                # and make it appear other than background colour.
                circ2_x = circ1_x + 50
                circ2_y = circ1_y + 100
                circ2_colour = BLACK
            if (event.key == pygame.K_p):
                # Make "surprise" circle disappear (same as background colour)
                # when P key is pressed
                circ2_colour = WHITE

            if (event.key == pygame.K_i):
                # User wants to display the image
                displayImage = True
            if (event.key == pygame.K_u):
                # User wants to remove the image
                displayImage = False

        elif event.type == pygame.KEYUP:
            print("User let go of a key.")
        elif event.type == pygame.MOUSEBUTTONDOWN:
            print("User pressed mouse button down.")
        elif event.type == pygame.MOUSEBUTTONUP:
            print("User released the mouse button.")

        elif event.type == pygame.MOUSEMOTION:
            m_x, m_y = pygame.mouse.get_pos()
            print("x is ", m_x, " y is ", m_y)
            if (rectColour == RED):
                rectColour = BLUE
            else:
                rectColour = RED

            follower_x = m_x + random.randint(-50, 50)
            follower_y = m_y + random.randint(-50, 50)

    # --- Game logic should go here

    # --- Drawing code should go here

    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(WHITE)

    # Move the green circle slowly to the right continually
    # if the D key is held down!
    keys = pygame.key.get_pressed()
    if (keys[pygame.K_d] == True):
        circ1_x += 1

    # Move the green circle slowly to the left continually
    # if the A key is held down!
    keys = pygame.key.get_pressed()
    if (keys[pygame.K_a] == True):
        circ1_x -= 1

    # Draw a rectangle based on my current mouse cursor position!
    # Will end up making the rectangle move according to mouse movement!
    pygame.draw.rect(screen, rectColour, [m_x, m_y, 20, 40], 0)

    pygame.draw.rect(screen, BLACK, [follower_x, follower_y, 20, 25], 2)

    # Draw circle 1
    pygame.draw.circle(screen, GREEN, [circ1_x, circ1_y], 25, 3)

    # Draw/hide circle 2 "surprise circle" when user presses O/P key
    # Hiding it is done by drawing it in the same colour as the background.
    pygame.draw.circle(screen, circ2_colour, [circ2_x, circ2_y], 10, 0)

    # The stuff below here is stuff we want to always have on the screen
    # for whatever reason.

    # STATIC DRAWING STUFF

    # Draw on the screen a green line from (0, 0) to (100, 100)
    # that is 5 pixels wide.
    pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)

    # Draw on the screen several lines from (0, 10) to (100, 110)
    # 5 pixels wide using a while loop
    y_offset = 0
    while y_offset < 100:
        pygame.draw.line(screen, BLUE, [0, 10 + y_offset], [100, 110 + y_offset], 5)
        y_offset = y_offset + 10

    # Display the jpg image if the I key was pressed.
    if (displayImage == True):
        screen.blit(theImage, (100, 50))

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second

    # Wait a little bit.

    clock.tick(60)

pygame.quit()


#!/usr/bin/env python3

from random import randint
from words import words

lives = 5
class Hangman():

    def __init__(self):
        self.word = ""
        self.revealed = ""
        self.letters = ""
        self.lives = lives

    def ChooseWord(self):
        length = len(words) -1
        choice = randint(0,length)
        self.word = words[choice]
        self.revealed = [0] * len(self.word)

    def AttemptLetter(self,letter) -> int:
        if letter in self.letters:
            return 2

        self.letters += letter

        if letter not in self.word:
            return 1

        return 0

    def RevealLetter(self, letter):
        indexes = [i for i, v in enumerate(self.word) if letter == v]
        for _i in indexes:
            self.revealed[_i] = 1

    def PrintRevealed(self):
        for i,v in enumerate(self.revealed):
            if v == 1:
                print(self.word[i], sep="", end="")
            else:
                print('#', sep="", end="")
        print("")

    def run(self):
        self.ChooseWord()
        while self.lives > 0 and 0 in self.revealed:
            print(f"What you've got: ")
            self.PrintRevealed()
            _l = input("What will the letter be, stranger: ")[0]
            res = self.AttemptLetter(_l)
            if res == 0:
                print(f"Big succ, the letter {_l} is in the word.")
                self.RevealLetter(_l)
            if res == 1:
                print(f"No, this word does not contain {_l}.")
                self.lives -= 1
            if res == 2:
                print(f"You've already tried the letter {_l}, my dude.")

        if(0 not in self.revealed):
            print(f"Big day, my confederate. The word was indeed {self.word}!")
        if(self.lives <= 0):
            print(f"Little day, my dead man. The word was actually {self.word}...")

if __name__ == "__main__":
    Hangman().run()


"""
Unit test for scos_actions.signal_processing.calibration
"""
import numpy as np
from scipy.constants import Boltzmann

from scos_actions.signal_processing import calibration

def test_y_factor():
    """
    Test Y-factor calculation of noise figure and gain.
    The test generates arrays of samples at mean power values
    calculated for a set of input gain and noise figure values.
    """
    # Set desired results for a few test cases
    excess_noise_ratio__dB = 15.0
    noise_figure__dB = [5.0, 10.0]
    gain__dB = [30.0, 40.0]

    # Other parameters for generating power samples
    number_of_samples = 1000
    temperature__K = 300.0
    bandwidth__Hz = 10e6
    excess_noise_ratio = 10.0 ** (excess_noise_ratio__dB / 10.0)
    ones_arr = np.ones(number_of_samples)
    ktb = Boltzmann * temperature__K * bandwidth__Hz

    # Iterate and test
    for nf__dB, g__dB in zip(noise_figure__dB, gain__dB):
        noise_factor = 10.0 ** (nf__dB / 10.0)
        gain = 10.0 ** (g__dB / 10.0)
        # Generated arrays have identical values, all representing
        # the value of mean received power. The function under
        # test computes the mean of these arrays, which is needed for
        # real-world data, but redundant for this test.
        pwr_noise_off__W = ones_arr * ktb * noise_factor * gain
        pwr_noise_on__W = ones_arr * ktb * (excess_noise_ratio + noise_factor) * gain

        nf_test, g_test = calibration.y_factor(
            pwr_noise_on__W,
            pwr_noise_off__W,
            excess_noise_ratio,
            bandwidth__Hz,
            temperature__K,
        )
        assert isinstance(nf_test, float)
        assert isinstance(g_test, float)
        assert np.isclose(nf_test, nf__dB)
        assert np.isclose(g_test, g__dB)

# NOT IMPLEMENTED: Requires connected preselector
# def test_get_linear_enr():
#     pass

# NOT IMPLEMENTED: Requires connected preselector with temperature sensor.
# def test_get_temperature():
#     pass


from pydantic import BaseModel

class BarModel(BaseModel):
    whatever: int

class FooBarModel(BaseModel):
    banana: float
    foo: str
    bar: BarModel

m = FooBarModel(banana=3.14, foo="hello", bar={"whatever": 123})

print("m.dict: ", m.dict())

print("include: ", m.dict(include={"foo", "bar"}))

print("include: ", m.dict(exclude={"foo", "bar"}))

print("dict m: ", dict(m))


import cv2
from data import BaseTransform, VOC_CLASSES as labelmap
from ssd import build_ssd
import scipy.misc
from numpy import asarray
import torch
from torch.autograd import Variable
from PIL import Image
import numpy

def detect(frame, net, transform):
    height = frame.shape[0]
    width = frame.shape[1]
    frame_t = transform(frame)[0]
    x = torch.from_numpy(frame_t).permute(2,0,1)
    x = Variable(x.unsqueeze(0))
    y = net(x)
    detections = y.data

    scale = torch.Tensor([width, height, width, height])
    # detections = [batch, number of calsses, number of occurence, (score, x0, y0, x1, y1)]

    for i in range(detections.size(1)):
        j = 0
        while detections[0,i,j,0] > 0.7:
            pt = (detections[0,i,j,1:] * scale).numpy()
            cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), (255,0, 0), 2)
            cv2.putText(frame, labelmap[i-1] +" " +  str(round(detections[0,i,j,0],4)), (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,0),1, cv2.LINE_AA)
            j += 1

    return frame

def retImage(path= 'image.jpeg'):
    net = build_ssd('test')
    net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location = lambda storage, loc : storage))
    transform = BaseTransform(net.size, (104/256.0, 117/256.0, 123/256.0))

    #frame = cv2.imread(path)
    img = Image.open(path)
    frame = numpy.array(img)
    retval = detect(frame, net, transform)
    new_im = Image.fromarray(retval)
    new_im.save("numpy_altered_sample2.png")
    print('Done')

retImage('test3.jpg')


import numpy as np
import resonant

kmin=4
kmax=10

#-- all triangles with max vector shorter than kmax --

allT = resonant.Triangles(kmax, debug=False)

#-- remove triangles with any vector shorter than kman --

T = np.array(list(allT)).squeeze()
kk = (T[:,:,0]**2 + T[:,:,1]**2).squeeze()
kkmin = np.min(kk,1)

ind = np.argwhere(kkmin>kmin**2).squeeze()

T = T[ind]
kk = kk[ind]

#-- sort triangles by largest vector --

kkmax = np.max(kk,1).squeeze()
ind = np.argsort(kkmax)

T = T[ind]
kk = kk[ind]

#-- in each trianble, sort vectors by amplitude ---

for i in np.arange(len(kk)):
    t = T[i]
    ind = np.argsort(kk[i])
    T[i] = t[ind]

#-- output --
print("above kmin={}:  {}".format(kmin, len(T)) )
for i in np.arange(len(kk)):
    t = T[i]
    kk = (t[:,0]**2 + t[:,1]**2)
    print("[{:3d} {:3d}]  [{:3d} {:3d}]  [{:3d} {:3d}]    [{:3d} {:3d}  {:3d}] ".
          format(t[0][0], t[0][1],  t[1][0], t[1][1],  t[2][0], t[2][1],  kk[0], kk[1], kk[2]) )


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#CRITICAL=50> ERROR=40> WARNING=30> INFO=20> DEBUG=10> NOTSET=0

import logging
from logging.handlers import RotatingFileHandler, SMTPHandler, SysLogHandler
from netmon_env import envi

#------------logging for python-script
logger = logging.getLogger('netmon')
logger.setLevel(envi['log_lvl'])
File1 = '/var/www/html/netmon/log/netmon.log'
FM = '%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s'
DF = '%Y-%m-%d %H:%M:%S'
#定义RotatingFileHandler，最多备份5个日志文件，每个日志文件5M
RH = RotatingFileHandler(File1, 'a', 5*1024*1024, 5)
RH.setLevel(logging.DEBUG)
RH.setFormatter(logging.Formatter(FM,DF))
logger.addHandler(RH)
#定义StreamHandler，输出到屏幕
SH = logging.StreamHandler()
SH.setLevel(logging.DEBUG)
SH.setFormatter(logging.Formatter(FM,DF))
logger.addHandler(SH)

#------------logging for link status
link_logger = logging.getLogger('link-status-local')
link_logger.setLevel(logging.DEBUG)
File2 = '/var/www/html/netmon/log/link.log'
FM = '%(asctime)s %(message)s'
RH = RotatingFileHandler(File2, 'a', 2*1024*1024, 3)
RH.setLevel(logging.DEBUG)
RH.setFormatter(logging.Formatter(FM,DF))
link_logger.addHandler(RH)
#
#定义SysLogHandler
syslog = logging.getLogger('link-status-syslog')
#slogH = SysLogHandler('/dev/log', 1)
slogH = SysLogHandler((envi['slog_server'],514))
slogH.setLevel(logging.DEBUG)
slogH.setFormatter(logging.Formatter(FM,DF))
syslog.addHandler(slogH)

if __name__ == '__main__':
   #link_logger.error('ZJ_ECN_R1 测试线路DX up->down')
   #link_logger.warn('ZJ_ECN_R2 测试线路 down->up')
   msg = 'ZJ_ECN_R2 测试线路 down->up'
   msg = msg.decode("UTF-8").encode('gbk')
   syslog.error(msg)


from django.conf import Settings
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.http.response import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string, get_template
from auth_email_verify.models import TeamMember

from auth_email_verify.tokens import account_activation_token
from django.conf import settings as _settings
from .models import Client, Company, Customer, ServiceItem, Supplier

# Create your views here.

# For Index page with View
from customers.forms import CreateContactForm, CreateNoteForm, CustomerForm, ServiceItemForm, SupplierForm
from .utilities import get_company

@login_required(login_url='signin')
def home(request):
    company = get_company(request)
    # if company is None:
    print(company)
    if company is None:
        return redirect('signin')
    return render(request, "home/index.html")

# @login_required
@login_required(login_url='signin')
def customers_list(request):
    # company = get_company(request)
    # if company is None:
    #     return redirect("signin")
    # customers = Customer.objects.filter(company=company)
    customers = request.user.get_customers
    return render(request, 'customers/index.html', {'customers': customers})

@login_required(login_url='signin')
def client_list(request):
    clients = request.user.get_clients
    clients = clients.order_by("-id")
    type = request.GET.get('type', None)
    if type:
        clients = clients.filter(customer_type=type)
    return render(request, 'customers/index.html', {'customers': clients})

@login_required(login_url='signin')
def client_detail(request, id):
    client = get_object_or_404(Client, id = id)
    if client not in request.user.get_clients:
        raise Http404()

    create_contact_form = CreateContactForm()
    create_note_form = CreateNoteForm()
    context = {
        'client': client,
        'create_contact_form': create_contact_form,
        'create_note_form': create_note_form,
        }
    return render(request, 'customers/client_detail.html', context)

@login_required(login_url='signin')
def contact_create(request):
    if request.method == "POST":
        client_id = request.POST.get('client_id', None)
        create_contact_form = CreateContactForm(request.POST)
        client = get_object_or_404(Client, id = client_id)
        if create_contact_form.is_valid():
            contact = create_contact_form.save(commit=False)
            contact.parent = client
            contact.save()
        return HttpResponseRedirect(reverse("customers:client_detail", kwargs={'id': client.id}))

@login_required(login_url='signin')
def note_create(request):
    if request.method == "POST":
        client_id = request.POST.get('client_id', None)
        create_note_form = CreateNoteForm(request.POST)
        client = get_object_or_404(Client, id = client_id)
        if create_note_form.is_valid():
            note = create_note_form.save(commit=False)
            note.parent = client
            note.save()
        return HttpResponseRedirect(reverse("customers:client_detail", kwargs={'id': client.id}))

@login_required(login_url='signin')
def services(request):
    if request.method == "GET":
        # services = ServiceItem.objects.all()
        services = request.user.get_service_items
        form = ServiceItemForm()
        context = {'services': services, 'form': form}
        return render(request, 'customers/services.html', context)
    elif request.method == "POST":
        form = ServiceItemForm(request.POST)
        services = request.user.get_service_items
        if form.is_valid():
            service_item = form.save(commit=False)
            service_item.company = get_company(request)
            service_item.save()
        context = {'services': services, 'form': form}
        return render(request, 'customers/services.html', context)

@login_required(login_url='signin')
def settings(request):
    return render(request, 'customers/settings.html')

@login_required(login_url='signin')
def team_members(request):
    if request.method == "GET":
        # team_members = TeamMember.objects.all()
        team_members = request.user.get_team_members
        context = {'team_members': team_members}
        return render(request, 'customers/team_members.html', context)
    if request.method == "POST":
        invite_email = request.POST.get('invite_email', None)
        if invite_email:
            current_site = get_current_site(request)
            company = get_company(request)
            mail_subject = 'Activate your account.'
            message = render_to_string('customers/invite_template.html', {
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(invite_email)),
                        'company': urlsafe_base64_encode(force_bytes(company.id)),
                        'token': account_activation_token.make_token(None, invite_email),
                    })
            to_email = invite_email
            from_email = _settings.EMAIL_HOST_USER
            send_mail(mail_subject, message, from_email, [to_email])
        return redirect("customers:team_members")

# @login_required
# @login_required(login_url='signin')
# def suppliers_list(request):
#     company = get_company(request)
#     # if company is None:
#     if company is not None:
#         return redirect("signin")
#     suppliers = Supplier.objects.filter(company=company)
#     return render(request, 'suppliers/index.html', {'suppliers': suppliers})
@login_required(login_url='signin')
def suppliers_list(request):
    suppliers = request.user.get_suppliers
    # suppliers = Supplier.objects.all()
    return render(request, 'suppliers/index.html', {'suppliers': suppliers})

# @login_required
@login_required(login_url='signin')
def customers_create(request):
    company = get_company(request)
    if company is None:
        return redirect("signin")
    if request.method == "POST":
        print(request.POST)
        form = CustomerForm(request.POST)
        if form.is_valid():
            try:
                customer = form.save(commit=False)
                customer.company = company
                customer.save()
                return redirect('/customers')
            except:
                pass
    else:
        form = CustomerForm()
    return render(request, 'customers/new.html', {'form': form, 'company': company.id})

# @login_required
@login_required(login_url='signin')
def suppliers_create(request):
    # company = get_company(request)
    company = request.user.company
    # company = Company.objects.all().last()
    # if company is None:
    #     return redirect("signin")
    if request.method == "POST":
        form = SupplierForm(request.POST)
        # print(form.is_valid())
        # print(form.errors)
        if form.is_valid():
            try:
                supplier = form.save(commit=False)
                supplier.company = company
                supplier.save()
                return redirect('/suppliers')
            except:
                pass
    else:
        form = SupplierForm()
    return render(request, 'suppliers/new.html', {'form': form, 'company': company.id})

# @login_required
@login_required(login_url='signin')
def client_create(request):
    if request.method == "POST":
        # print(request.POST)
        contact_name = request.POST.get('contact_name', None)
        account_type = request.POST.get('account_type', None)
        customer_type = request.POST.get('customer_type', None)
        entity = request.POST.get('entity', None)
        company_name = request.POST.get('company_name', None)
        trading_name = request.POST.get('trading_name', None)
        work_email = request.POST.get('work_email', None)
        landline_number = request.POST.get('landline_number', None)
        mobile_number = request.POST.get('mobile_number', None)
        note_field = request.POST.get('note_field', None)
        financial_year_end = request.POST.get('financial_year_end', None)
        registration_number = request.POST.get('registration_number', None)
        registration_date = request.POST.get('registration_date', None)
        income_tax = request.POST.get('income_tax', None)
        vat_number = request.POST.get('vat_number', None)
        vat_month = request.POST.get('vat_month', None)
        payee_number = request.POST.get('payee_number', None)
        uif_number = request.POST.get('uif_number', None)
        coida_number = request.POST.get('coida_number', None)
        efiling_profile = request.POST.get('efiling_profile', None)
        last_financials = request.POST.get('last_financials', None)
        billing_address = request.POST.get('billing_address', None)
        billing_city = request.POST.get('billing_city', None)
        billing_state = request.POST.get('billing_state', None)
        billing_zip = request.POST.get('billing_zip', None)
        billing_country = request.POST.get('billing_country', None)
        address = request.POST.get('address', None)
        address_city = request.POST.get('address_city', None)
        address_state = request.POST.get('address_state', None)
        address_zip = request.POST.get('address_zip', None)
        address_country = request.POST.get('address_country', None)

        client_date = request.POST.get('client_date', None)
        employer = request.POST.get('employer', None)
        date_birth = request.POST.get('date_birth', None)
        marital_status = request.POST.get('marital_status', None)
        id_number = request.POST.get('id_number', None)
        occupation = request.POST.get('occupation', None)

        if not client_date:
            client_date = None

        client = Client.objects.create(
            name = contact_name,
            account_type = account_type,
            customer_type = customer_type,
            company = get_company(request),
            entity = entity,
            company_name = company_name,
            trading_name = trading_name,
            work_email = work_email,
            landline_number = landline_number,
            mobile_number = mobile_number,
            note_field = note_field,
            financial_year_end = financial_year_end,
            registration_number = registration_number,
            registration_date = registration_date,
            income_tax = income_tax,
            vat_number = vat_number,
            vat_month = vat_month,
            payee_number = payee_number,
            uif_number = uif_number,
            coida_number = coida_number,
            efiling_profile = efiling_profile,
            last_financials = last_financials,
            billing_address = billing_address,
            billing_city = billing_city,
            billing_state = billing_state,
            billing_zip = billing_zip,
            billing_country = billing_country,
            address = address,
            address_city = address_city,
            address_state = address_state,
            address_zip = address_zip,
            address_country = address_country,

            client_date=client_date,
            employer=employer,
            date_birth=date_birth,
            marital_status=marital_status,
            id_number=id_number,
            occupation=occupation
        )
        client.save()

        return HttpResponseRedirect(reverse('customers:clients_list'))


import logging
import sys
from roflan_bot.common import DataStorage
from roflan_bot.bot import BotClient

if __name__ == "__main__":
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S",
                        format="%(asctime)s %(name)s [%(levelname)s]: %(message)s")

    success = True
    success &= DataStorage.set_actions_data(path="../../data/actions.json")
    success &= DataStorage.set_configuration_data(path="../../data/config.json")
    success &= DataStorage.set_phrases_data(path="../../data/phrases.json")
    success &= DataStorage.set_conversation_settings_data(path="../../data/conversation_settings.json")

    if success:
        client = BotClient()
        client.run(DataStorage.get("config")["credentials"]["token"], log_handler=None)


#!/usr/bin/env python3

import time

class SimplePlay:
    ui = None
    seek = None

    def __init__(self, config):
        pass

    def wire(self, *, ui, seek=None, **kwargs):
        self.ui = ui
        self.seek = seek

    def __call__(self, stdscr, status):
        self.stdscr = stdscr
        y = self.stdscr.getmaxyx()[0]
        line = status()
        while line is not None:
            ch = self.ui.get_key(timeout=0.1)
            if ch is not None:
                if self.seek is None:
                    break
                if ch == 'q' or ch == 'Q' or ch == "^]":
                    break
                elif ch == '[' or ch == '{':
                    self.seek(-60)
                elif ch == ']' or ch == '}':
                    self.seek(60)
                elif ch == ',' or ch == '<':
                    self.seek(-1)
                elif ch == '.' or ch == '>':
                    self.seek(1)
            self.stdscr.addstr(y - 1, 0, str(line))
            self.stdscr.clrtoeol()
            self.stdscr.refresh()
            line = status()
            time.sleep(0.1)


import numpy as np
import matplotlib.pyplot as plt

import binclassifier

binclassifier_names = {
    "Adaline":            binclassifier.AdalineSGD,
    "LogisticRegression": binclassifier.LogisticRegression
}

class OVRClassifier(object):
    def __init__(self, classifier, eta=0.01, n_iter=1000, random_state=None):
        self.eta = eta                    # learning rate
        self.n_iter = n_iter              # the number of iteration
        self.random_state = random_state  # random seed
        self.submodels = None             # sub models
        self.label_names = None           # label names

        if isinstance(classifier, str):
            if classifier.upper() not in [name.upper() for name in binclassifier_names.keys()]:
                raise TypeError(f"Binary classifier {classifier} not found")

            self.classifier = binclassifier_names[classifier]
        else:
            self.classifier = classifier

    def fit(self, data, label, shuffle=True):
        self.submodels = []
        self.label_names = np.unique(label)

        for idx, name in enumerate(self.label_names):
            processed_label = np.zeros(shape=label.shape)
            processed_label[np.where(label == name)] = 1

            self.submodels.append(self.classifier(eta=self.eta, n_iter=self.n_iter, random_state=self.random_state))
            self.submodels[-1].fit(data, processed_label, shuffle=shuffle)

        return self

    def partial_fit(self, data, label):
        pass

    def sigmoid(self, x):
        return 1. / (1. + np.exp(-np.clip(x, -250, 250)))

    def predict(self, data, one_hot=False):
        if data.ndim > 1:
            prob = np.zeros(shape=(data.shape[0], len(self.submodels)))

            for midx, model in enumerate(self.submodels):
                prob[:, midx] = self.sigmoid(model.output(data))

            if one_hot:
                oh_res = np.zeros(prob.shape)
                for didx in range(data.shape[0]):
                    oh_res[prob[didx, :].argmax()] = 1
                return oh_res

            res = np.array([prob[idx, :].argmax() for idx in range(data.shape[0])])
            return res
        else:
            prob = np.zeros(shape=len(self.submodels))

            for midx, model in enumerate(self.submodels):
                prob[midx] = model.output(data)

            if one_hot:
                oh_res = np.zeros(prob.shape)
                oh_res[prob.argmax()] = 1
                return oh_res

            res = np.where(prob == max(prob))[0][0]
            return res

    def plot_costs(self, resolution=1, ax=plt):
        if self.submodels is None: return
        markers = ('s', 'x', 'o', '^', 'v', '+', 'x')
        for midx, md in enumerate(self.submodels):
            md.plot_costs(label=f"{self.label_names[midx]}", marker=markers[midx], resolution=resolution, ax=ax)


import pandas as pd
from bs4 import BeautifulSoup

from utils import get_request

def get_sonny_moore_rating(year):
    """
    Scrape Sonny Moore's computer power index of a certain year
    :param year: string or int
    :return: pandas.DataFrame containing Sonny Moore’s ratings for a given year
    """
    # only the last two digits of the year are used in the url
    if len(str(year)) > 2:
        year = str(year)[-2:]

    url = 'http://sonnymoorepowerratings.com/cb' + str(year) + '.htm'

    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A"}

    r = get_request(url, headers=headers)

    if r is None:
        return None

    soup = BeautifulSoup(r.text, 'lxml')

    header = soup.find_all('font')[1].text.split('\n')[1]
    columns = header.split()

    table = soup.find_all('b')[0]
    table = str(table.string)

    table = table.split('\n')
    data = []

    n = len(columns) - 1

    for i in table:
        row = i.split()
        if row:
            el = []
            name = ' '.join(row[1:-n])
            el.append(name)
            el.extend(row[-n:])
            data.append(el)

    df = pd.DataFrame(data=data, columns=columns)

    return df


import os
import tkinter as tk
import pandas as pd
import Markov
import matplotlib
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

matplotlib.rcParams["lines.linewidth"] = 0.5

def text_plot(txt, fs):
    plt.figure(figsize=fs)
    font = {'family': 'monospace',
            'weight': 'normal',
            'size': 'larger'}
    plt.text(0, -0.05, txt, fontdict=font)
    for it in plt.gca().spines.keys():
        plt.gca().spines[it].set_visible(False)
    plt.tick_params(which='both', bottom=False, left=False, labelbottom=False, labelleft=False)
    plt.show()

def plot_summary(ts, order, name):
    model = ARIMA(ts, order=order)
    fit = model.fit()
    text_plot(
        name + "------------------------------------------------------------------------------\n" + str(fit.summary()),
        (10, 7))

def arima_insample(ts, g, order, name):
    plt.figure()
    model = ARIMA(ts, order=order)
    fit = model.fit()
    p = pd.Series(dtype=float)
    print(type(fit))
    if g == 1:
        p = fit.predict()
    else:
        i = int(0.1 * len(ts))
        while i < ts.index[-1]:
            p = p.append(fit.predict(start=i, end=i + g - 1, dynamic=True))
            i += g
    plt.plot(ts)
    plt.plot(p)
    plt.title(name + " | [p,d,q] : " + str(order) + " | gap=" + str(g))
    plt.legend(["actual", "predicted"])
    plt.show()

def arima_man_forecast(ts, f, order, name):
    plt.figure()
    train = ts[:int(len(ts) * f)]
    test = ts[int(len(ts) * f):]
    model = ARIMA(train, order=order)
    fit = model.fit()
    plt.plot(train)
    plt.plot(test)

    forecast = fit.get_forecast(len(test))
    plt.plot(forecast.predicted_mean)

    ci = forecast.conf_int()
    plt.fill_between(x=test.index, y1=ci["lower Close Price"], y2=ci["upper Close Price"], color=(0.5, 0.5, 0.5, 0.2))

    plt.title(name + " | [p,d,q] : " + str(order))
    plt.legend(["train", "test", "forecast", "95% confidence"])
    plt.show()

def acf(ts, name):
    plt.figure()
    plot_acf(ts, ax=plt.gca())
    plt.title(name + " - ACF")
    plt.show()

def pacf(ts, name):
    plt.figure()
    plot_pacf(ts, ax=plt.gca())
    plt.title(name + " - PACF")
    plt.show()

def diagnostics(ts, order, name):
    # plt.figure()
    ARIMA(ts, order=order).fit().plot_diagnostics(figsize=(10, 10))
    plt.suptitle(name + " | [p,d,q] : " + str(order))
    plt.show()

class StockGUI:
    def __init__(self, name):
        if not os.path.exists("appdata"):
            os.mkdir("appdata")

        if not os.path.exists("appdata/" + name + ".csv"):
            file = open("appdata/" + name + ".csv", "w+")
            file.writelines(["key,value\n", "p,1\n", "d,1\n", "q,1\n", "f,0.5\n", "g,1\n"])
            file.close()
        self.app_data = pd.read_csv("appdata/" + name + ".csv", index_col=0).value
        self.p = int(self.app_data["p"])
        self.d = int(self.app_data["d"])
        self.q = int(self.app_data["q"])
        self.f = float(self.app_data["f"])
        self.g = int(self.app_data["g"])

        self.ts = pd.read_csv("stkdata/" + name + ".csv")["Close Price"]

        # window config ###############################################################

        self.win = tk.Tk()
        self.screen_height = self.win.winfo_screenheight()
        self.screen_width = self.win.winfo_screenwidth()
        self.name = name
        self.win.title(self.name)
        self.win.minsize(int(self.screen_width / 5), int(self.screen_height / 7))

        # ---------------------------------

        def plf():
            self.pldt()

        plt_btn = tk.Button(self.win, text="plot", command=plf)
        plt_btn.pack()

        # --------------------------------

        lbl_arima_start = tk.Label(self.win, text="------------ ARIMA ------------")
        lbl_arima_start.pack(pady=15)
        self.arima_params = ["p", "d", "q", "f", "g"]

        pdq_frame = tk.Frame(self.win)
        pdq_frame.pack()

        pdq = tk.Entry(pdq_frame)
        pdq.configure(justify=tk.CENTER)
        pdq.insert(0, "(p,d,q) : " + str(int(self.p)) + "," + str(int(self.d)) + "," + str(int(self.q)))

        pdq.pack(side=tk.LEFT)

        def get_pdq():
            tp = [1, 1, 1]
            i = 0
            for x in str(pdq.get().split(":")[1]).strip().split(","):
                tp[i] = int(x)
                i += 1
            return tp

        # --------------------------------

        def call_arima_forecast():
            tp = [1, 1, 1]
            i = 0
            for x in str(pdq.get().split(":")[1]).strip().split(","):
                tp[i] = int(x)
                i += 1
            arima_man_forecast(self.ts, float(fraction.get().split(":")[1].strip()), tp, self.name)

        forecast_tab = tk.Frame(self.win)
        forecast_tab.pack(pady=(10, 0))

        fraction = tk.Entry(forecast_tab)
        fraction.insert(0, "(train%) : " + str(self.f))
        fraction.pack(side=tk.LEFT)

        forecast_btn = tk.Button(forecast_tab, text="forecast ", command=call_arima_forecast)
        forecast_btn.pack(side=tk.LEFT, padx=20)

        # --------------------------------

        def call_arima_insample():
            tp = [1, 1, 1]
            i = 0
            for x in str(pdq.get().split(":")[1]).strip().split(","):
                tp[i] = int(x)
                i += 1
            arima_insample(self.ts, int(gap.get().split(":")[1].strip()), tp, self.name)

        insample_tab = tk.Frame(self.win)
        insample_tab.pack(pady=10)

        gap = tk.Entry(insample_tab)
        gap.insert(0, "(gap) : " + str(int(self.g)))
        gap.pack(side=tk.LEFT)

        insample_btn = tk.Button(insample_tab, text="insample", command=call_arima_insample)
        insample_btn.pack(side=tk.LEFT, padx=20)

        # --------------------------------

        acpc_tab = tk.Frame(self.win)
        acpc_tab.pack(pady=10)

        acf_btn = tk.Button(acpc_tab, text="Plot ACF", command=lambda: acf(self.ts, self.name))
        acf_btn.pack(side=tk.LEFT)

        pacf_btn = tk.Button(acpc_tab, text="Plot PACF", command=lambda: pacf(self.ts, self.name))
        pacf_btn.pack(side=tk.LEFT)

        # --------------------------------

        def call_diagnostics():
            tp = [1, 1, 1]
            i = 0
            for x in str(pdq.get().split(":")[1]).strip().split(","):
                tp[i] = int(x)
                i += 1
            diagnostics(self.ts, tp, self.name)

        diagnostic_tab = tk.Frame(self.win)
        diagnostic_tab.pack(pady=(0, 10))

        summary_btn = tk.Button(diagnostic_tab, text="Summary",
                                command=lambda: plot_summary(self.ts, get_pdq(), self.name))
        summary_btn.pack(side=tk.LEFT)

        diag_btn = tk.Button(diagnostic_tab, text="Diagnostics", command=call_diagnostics)
        diag_btn.pack(side=tk.LEFT)

        # --------------------------------

        def iter_params():
            for x in self.app_data.keys():
                setattr(self, x, self.app_data[x])

        def update_params():
            tp = str(pdq.get().split(":")[1]).strip().split(",")
            if len(tp) == 3:
                self.app_data["p"] = tp[0]
                self.app_data["d"] = tp[1]
                self.app_data["q"] = tp[2]
                print(tp)
            self.app_data["f"] = fraction.get().split(":")[1].strip()
            self.app_data["g"] = gap.get().split(":")[1].strip()
            iter_params()
            self.app_data.to_csv("appdata/" + name + ".csv")

        def reset_params():
            pdq.delete(0, 'end')
            pdq.insert(0, "(p,d,q) : " + str(int(self.p)) + "," + str(int(self.d)) + "," + str(int(self.q)))
            fraction.delete(0, 'end')
            fraction.insert(0, "(train%) : " + str(self.f))
            gap.delete(0, 'end')
            gap.insert(0, "(gap) : " + str(int(self.g)))

        reset_save = tk.Frame(self.win)
        reset = tk.Button(reset_save, text="Reset", command=reset_params)
        update = tk.Button(reset_save, text="Update", command=update_params)
        reset.pack(side=tk.LEFT)
        update.pack(side=tk.LEFT)
        reset_save.pack()

        # lbl_arima_end = tk.Label(self.win, text="-------------------------------")
        # lbl_arima_end.pack(pady=15)

        # --------------------------------

        def density_plots():
            diff, hl = mk_p.get().split(":")[1].strip().split(",")
            diff = int(diff)
            hl = int(hl)
            br_d, br_u = Markov.get_brackets(self.ts,diff,hl)
            fig, ax = plt.subplots(2,2,figsize=(10,10))
            ax[0,0].plot(self.ts)
            ax[0,0].fill_between(range(0, len(self.ts)), br_d, br_u, color=(0.5, 0.5, 0.5, 0.2))
            uda = Markov.ud_array(self.ts, br_d, br_u)
            u,d,m = Markov.udm_lengths(uda)
            ax[0,1].hist(u,bins=range(0,max(u)))
            ax[1,0].hist(d,bins=range(0,max(d)))
            ax[1,1].hist(m,bins=range(0,max(u)))

            ax[0,0].set_title("bins")
            ax[0,1].set_title("U")
            ax[1,0].set_title("D")
            ax[1,1].set_title("M")

            plt.show()

        lbl_arima_start = tk.Label(self.win, text="------------ MARKOV ------------")
        lbl_arima_start.pack(pady=15)

        mk_slab = tk.Frame(self.win)
        mk_slab.pack(pady=10)

        mk_p = tk.Entry(mk_slab)
        mk_p.insert(0, "(diff,hl) : 10,10 ")
        mk_p.pack(side=tk.LEFT)

        mk_plt = tk.Button(mk_slab, text="Density Plots", command=density_plots)
        mk_plt.pack(side=tk.LEFT, padx=20)

        ################################################################################

        self.df = pd.read_csv("stkdata/" + self.name + ".csv").dropna()
        self.ts = self.df["Close Price"]
        print(self.df.head)

    def pldt(self):
        plt.figure()
        plt.plot(self.ts)
        plt.title(self.name)
        plt.xlabel("Index")
        plt.ylabel("Price")
        plt.show()

    def launch(self):
        self.win.mainloop()


class UserSequence:
    def __init__(self, order):
        self.order = order

    def __getitem__(self, item):
        if isinstance(item, int):
            if item < len(self.order):
                return self.order[item]
            else:
                raise IndexError
        if isinstance(item, slice):
            res = []
            start = item.start or 0
            stop = item.stop or len(self.order)
            step = item.step or 1
            for i in range(start, stop, step):
                res.append(self.order[i])
            return res
        raise TypeError


import csv
import itertools
import random

guessedNumber = None
counter = 1

# Daten werden aus der data.csv gelesen und in Data gespeichert.
with open('data.csv', newline='', encoding='utf-8-sig') as csvfile:
    data = list(csv.reader(csvfile))
numbersList = list(itertools.chain.from_iterable(data))

# Die NumbersList wird in Int gecastet, um den maximalen und minimale Wert der gesamten Nummern zu ermitteln.
numbersListMaxMinValues = list(map(int, numbersList))
maxValue = max(numbersListMaxMinValues)
minValue = min(numbersListMaxMinValues)

# Wahl einer willkürlichen Zahl aus der eingelesen Liste.
randomNumber = random.choice(numbersList)

# Iteriert bis guessedNumber und randomNumber gleich sind.
while guessedNumber != randomNumber:
    # Aufforderung eine Nummer von dem mindesten Wert bis zum höchsten Wert der Daten zu liefern.
    guessedNumber = input(f"Give me a number between {minValue} and {maxValue}: ")

    # Abfrage, ob guessedNumber groeßer oder kleiner als die Random Number ist. Wenn eins der beiden zutrifft, wird ein Counter hochgesetzt und der Nutzende wird darauf hingewiesen, dass die Nummer darüber bzw. darunter liegt.
    if guessedNumber > randomNumber:
        counter += 1
        print("The Random Number is under your guessed Number.")

    else:
        counter += 1
        print("The Random Number is over your guessed Number.")

    # Abfrage, ob die guessedNumber mit der randomNumber übereinstimmt UND ob der zuvor angelegte Counter auf dem initialen Wert 1 (Anzahl der Versuche) liegt. Wenn dem so ist, wird dem Nutzenden zum Lucky guess gratuliert und die While-Schleife unterbrochen.
    if guessedNumber == randomNumber and counter == 1:
        print("Lucky guess! You won on the first try")
        break
    # Abfrage, ob die guessedNumber mit der randomNumber übereinstimmt. Wenn dem so ist, wird dem Nutzenden gratuliert, eine Anzahl der Versuche ausgegeben und die While-Schleife unterbrochen.
    if guessedNumber == randomNumber:
        print("Congrats. You won!")
        print("You needed " + str(counter) + " tries.")
        break


import pygame
import random
from Scripts.constants import *

class Ghost(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__()
        self.image = pygame.Surface((20, 20))
        self.image.fill(color)  # Set the color of the ghost
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = GHOST_SPEED
        self.direction = "left"

    def change_direction(self):
        directions = ["left", "right", "up", "down"]
        if self.rect.x % 16 == 0 and self.rect.y % 16 == 0:
            self.direction = random.choice(directions)

    def collide_with_walls(self, walls):
        for wall in walls:
            if self.rect.colliderect(wall.rect):
                if self.direction == "right":
                    self.rect.right = wall.rect.left
                elif self.direction == "left":
                    self.rect.left = wall.rect.right
                elif self.direction == "up":
                    self.rect.top = wall.rect.bottom
                elif self.direction == "down":
                    self.rect.bottom = wall.rect.top

    def update(self, walls, pacman):
        if self.direction == "left":
            self.rect.x -= self.speed
        elif self.direction == "right":
            self.rect.x += self.speed
        elif self.direction == "up":
            self.rect.y -= self.speed
        elif self.direction == "down":
            self.rect.y += self.speed

        self.collide_with_walls(walls)
        self.change_direction()


# coding: utf-8
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import requests

from config import API_KEY, API_SECRET, DETECT_PATH
from example.common import get_input_file_path

return_landmark = 0
return_attributes = None
calculate_all = 0
face_rectangle = ''
beauty_score_min = 0
beauty_score_max = 100

def call_api():
    data = {
        'api_key': API_KEY,
        'api_secret': API_SECRET,
        'return_gesture': return_landmark,
        'return_attributes': return_attributes,
        'calculate_all': calculate_all,
        'beauty_score_min': beauty_score_min,
        'beauty_score_max': beauty_score_max
    }
    if face_rectangle:
        data.update({'face_rectangle': face_rectangle})
    input_file = get_input_file_path(os.path.abspath(os.path.dirname(__file__)), 'input')
    if not input_file:
        print('请将input.png/input.jpg文件放在detect目录下')
        return
    files = {
        'image_file': open(input_file, 'rb').read()
    }
    resp = requests.post(DETECT_PATH, data=data, files=files).json()
    print(resp)

if __name__ == "__main__":
    call_api()


import random
import time
import os

def value_assign():

    assign = " "

    while assign != "y" and assign != "n":
        assign = input("Would you like to assign values to the coin? [y,n]: ").lower()

    option1 = " "
    option2 = " "

    if assign == "y":
        while option1 == " ":
            option1 = input("Heads: ")
        while option2 == " ":
            option2 = input("Tails: ")
    return option1, option2

def end_menu():

    menu = " "

    time.sleep(1)

    while menu != "1" and menu != "3":
        print(" ")
        print("Would you like to...")
        menu = input("[1] Flip again [3] Close the app: ")

    if menu == "1":
        coin_flip()
    else:
        print(" ")
        time.sleep(1)
        print("Good Bye")
        quit()

def coin_flip():

    option1, option2 = value_assign()

    flip = random.randint(0,1)

    print("---Flipping Coin---")
    time.sleep(0.75)
    print(" ")
    time.sleep(0.75)
    print(" ")
    time.sleep(0.75)

    if flip == 0:
        print(f"Heads {option1}")
    else:
        print(f"Tails {option2}")

    end_menu()

coin_flip()


a = input()
length = len(a)
white = 0
lower = 0
upper = 0
other = 0
for char in a:
    if char == '_':
        white += 1
    elif char.isupper():
        upper+=1
    elif char.islower():
        lower+=1
    else:
        other+=1

print(white/length)
print(lower/length)
print(upper/length)
print(other/length)


class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        dp = [[False for j in range(len(p)+1)] for i in range(len(s)+1)]
        dp[0][0] = True
        for j in range(1,len(p)+1):
            dp[0][j] = (p[j-1] == "*" and dp[0][j-1])
        for i in range(1,len(s)+1):
            for j in range(1,len(p)+1):
                if p[j-1] == "?" or p[j-1] == s[i-1]:
                    dp[i][j] = dp[i-1][j-1]
                elif p[j-1] == "*":
                    dp[i][j] = dp[i-1][j] or dp[i][j-1]
                    # *represents character  or * represents 0 character
                #print(str(i)+", "+str(j)+"  " + str(dp[i][j]))
        return dp[-1][-1]

        # i = 0
        # j = 0
        # start = -1
        # match = 0
        # while i < len(s):
        #     # 一对一匹配,匹配成功一起移
        #     if j < len(p) and (s[i] == p[j] or p[j] == "?"):
        #         i += 1
        #         j += 1
        #     # 记录p的"*"的位置,还有s的位置
        #     elif j < len(p) and p[j] == "*":
        #         start = j
        #         match = i
        #         j += 1
        #     # j 回到 记录的下一个位置
        #     # match 更新下一个位置
        #     # 这不代表用*匹配一个字符
        #     elif start != -1:
        #         j = start + 1
        #         match += 1
        #         i = match
        #     else:
        #         return False
        #  # 将多余的 * 直接匹配空串
        # return all(x == "*" for x in p[j:])

solution = Solution()
solution.isMatch("abceb","*a*b")


from time import time

from django.conf import settings
from django.db import connection
from django.template.loader import render_to_string

def test_middleware(get_response):
    def middleware(request):
        if not settings.DEBUG:
            return get_response(request)

        # Get beginning stats
        start_queries = len(connection.queries)
        start_time = time()

        # Process the request
        response = get_response(request)

        # Calculate stats
        total_time = time() - start_time
        queries = len(connection.queries) - start_queries
        db_time = 0
        if queries:
            for query in connection.queries[start_queries:]:
                db_time += float(query['time'])
        py_time = total_time - db_time

        # Render the result
        stats = render_to_string("stats_fragment.html", {
            'total_time': total_time,
            'py_time': py_time,
            'db_time': db_time,
            'queries': queries,
        })

        response.content = response.content.replace(b"<!-- STATS -->", response.make_bytes(stats))
        return response
    return middleware


"""Provides the repository macro to import Gloo."""

load("//third_party:repo.bzl", "tf_http_archive", "tf_mirror_urls")

def repo():
    """Imports Gloo."""

    GLOO_COMMIT = "5354032ea08eadd7fc4456477f7f7c6308818509"
    GLOO_SHA256 = "5759a06e6c8863c58e8ceadeb56f7c701fec89b2559ba33a103a447207bf69c7"

    tf_http_archive(
        name = "gloo",
        sha256 = GLOO_SHA256,
        strip_prefix = "gloo-{commit}".format(commit = GLOO_COMMIT),
        urls = tf_mirror_urls("https://github.com/facebookincubator/gloo/archive/{commit}.tar.gz".format(commit = GLOO_COMMIT)),
        build_file = "//third_party/gloo:gloo.BUILD",
    )


from __future__ import print_function
import argparse
import logging
import math
import mido
import numpy as np
import sys
import time

from rotate3D import *

ports = mido.get_output_names()

parser = argparse.ArgumentParser(description="Use markers in the Vicon DataStream as a realtime MIDI controller.")
parser.add_argument('host', nargs='?', help="Host name, in the format of server:port", default = "172.32.3.195:801")
parser.add_argument('-o', '--origin', help="Marker name to use as the origin of the point cloud.", default="rbA", required=False)
parser.add_argument('-x', '--xPos', help="Marker name to place at +1 on the X axis when normalizing the point cloud.", default="rbB", required=False)
parser.add_argument('-n', '--noVicon', help="Run without connecting to Vicon DataStream. Will generate smulated data for setting up without requiring the Vicon software to be present.", action="store_true", required=False)
parser.add_argument('-l', '--listPorts', help="List available MIDI ports.", action='store_true', required=False)
parser.add_argument('-p', '--port', help="Specify MIDI port to use.", default=ports[0], required=False)
args = parser.parse_args()

if args.listPorts:
	ports = mido.get_output_names()
	sys.exit("Available output ports: " + ', '.join(ports))

if not args.noVicon:
	from vicon_dssdk import ViconDataStream

	logging.info("Found ViconDataStream. Setting up.")

	client = ViconDataStream.Client()
	client.Connect( args.host )

	# Check the version
	logging.debug( 'Version', client.GetVersion() )

	# Check setting the buffer size works
	client.SetBufferSize( 1 )

	#Enable all the data types
	client.EnableSegmentData()
	client.DisableMarkerData()
	client.DisableUnlabeledMarkerData()
	client.DisableMarkerRayData()
	client.DisableDeviceData()
	client.DisableCentroidData()

	# Report whether the data types have been enabled
	logging.debug( 'Segments', client.IsSegmentDataEnabled() )
	logging.debug( 'Markers', client.IsMarkerDataEnabled() )
	logging.debug( 'Unlabeled Markers', client.IsUnlabeledMarkerDataEnabled() )
	logging.debug( 'Marker Rays', client.IsMarkerRayDataEnabled() )
	logging.debug( 'Devices', client.IsDeviceDataEnabled() )
	logging.debug( 'Centroids', client.IsCentroidDataEnabled() )

	client.SetStreamMode( ViconDataStream.Client.StreamMode.EServerPush )

	try:
		client.ConfigureWireless()
	except ViconDataStream.DataStreamException as e:
		logging.info( 'Failed to configure wireless', e )

	logging.info("Finished setting up.")

def getMarkerLocations():
	"""Connect to the Vicon system and get the locations of all the
	subjects (a.k.a. markers) that the system knows about.

	Return the frame number and a dictionary of marker names (as String)
	and locations (as Numpy arrays.)
	"""

	try:

		HasFrame = False
		while not HasFrame:
			try:
				client.GetFrame()
				HasFrame = True
			except ViconDataStream.DataStreamException as e:
				client.GetFrame()

		frame = client.GetFrameNumber()

		locators = {}

		subjectNames = client.GetSubjectNames()
		print("subject names:", subjectNames)

		for subjectName in subjectNames:
			#print("subject name:", subjectName )

			rootSegmentName = client.GetSubjectRootSegmentName(subjectName)
			#print("root segment name:", rootSegmentName)
			globalTranslation = client.GetSegmentGlobalTranslation(subjectName, rootSegmentName)
			#print("global translation:", globalTranslation)
			globalTranslation = globalTranslation[0]
			xpos, ypos, zpos = globalTranslation
			#xpos = round(xpos)
			#ypos = round(ypos)
			#zpos = round(zpos)

			locators[subjectName] = np.array([xpos, ypos, zpos])
			print('frame', client.GetFrameNumber(), subjectName, rootSegmentName, xpos, ypos, zpos)

		#print( 'frame', client.GetFrameNumber(), locators)
		return frame, locators

	except ViconDataStream.DataStreamException as e:
		print( 'Handled data stream error', e )

def simulateMarkerLocations():

	markers = {args.origin: np.array([0, 0, 0]),
			   args.xPos: np.array([1, 0, 0])}

	# The first other marker switches on and off.
	if (time.time() % 10) > 1:
		markers['rbC'] = np.array([(math.sin(time.time())+1)/2, (math.cos(time.time())+1)/2, 0])

	markers['rbD'] = np.array([(math.sin(time.time() / 3) + 1) / 2,
							   (math.cos(time.time() / 3) + 1) / 2,
							   time.time() - math.floor(time.time())])
	markers['rbE'] = np.array([(math.sin(time.time() / 5) + 1) / 2,
							   (math.cos(time.time() / 5) + 1) / 2,
							   (time.time() / 1000) - math.floor((time.time() / 1000))])
	frame = math.floor(time.time()*24) % 10000

	return frame, markers

if __name__ == "__main__":

	print(args)

	lastFrame = 0

	"""
	Marker-to-MIDI-channel mapping:
	other1	on/off: 0
			x:		1
			y:		2
			z:		3
	other2	on/off: 4
			x:		5
			y:		6
			z:		7
	other3	on/off: 8
			x:		9
			y:		10
			z:		11

	"""

	subjectMarkers = ['rbC', 'rbD', 'rbE']

	print("Using ", args.port,  '. ', sep='', end='')
	with mido.open_output(args.port) as outport:
		print("Open.")

		while True:

			if args.noVicon:
				frame, markers = simulateMarkerLocations()
			else:
				frame, markers = getMarkerLocations()

			if frame != lastFrame:
				lastFrame = frame

				markers = normalize(markers, args.origin, args.xPos)

				#print('Frame:', frame, 'Markers:', markers)

				controller = 0
				for name in subjectMarkers:
					# First controller: marker on/off (gets sent at the end)
					value = 0
					if name in markers.keys():
						value = 127
						# Second controller: X
						msg2 = mido.Message('control_change', channel = 0,
								control = controller + 1,
								value = int( max(min(markers[name][0] * 127, 127), 0) ),
								time=0)
						outport.send(msg2)
						# Third controller: Y
						msg3 = mido.Message('control_change', channel = 0,
								control = controller + 2,
								value = int( max(min(markers[name][1] * 127, 127), 0) ),
								time=0)
						outport.send(msg3)
						# Fourth controller: Z
						msg4 = mido.Message('control_change', channel = 0,
								control = controller + 3,
								value = int( max(min(markers[name][2] * 127, 127), 0) ),
								time=0)
						outport.send(msg4)
					msg1 = mido.Message('control_change', channel = 0, control = controller, value = value, time=0)
					outport.send(msg1)
					controller += 4 # 4 controllers per marker (exists, x, y, z)

		# logging.info("frame:", frame, "markers:", markers)

		# markers = normalize(markers, originName, xPosName)

		# logging.info("frame:", frame, "markers:", markers)


import unittest
import lsst.utils.tests

import os
import pytest
import sys
import numpy as np
try:
    import matplotlib.pyplot as plt
except ImportError as e:
    print("Initialising testValidate.py:", e)
    plt = None

from lsst.cwfs.instrument import Instrument
from lsst.cwfs.algorithm import Algorithm
from lsst.cwfs.image import Image, readFile

class MatlabValidationTestCase(lsst.utils.tests.TestCase):
    """Demo test case."""

    @classmethod
    def setUpClass(cls):
        """ setup any state specific to the execution of the given class (which
        usually contains tests).
        """
        cls.rootdir = os.path.dirname(__file__)

        cls.myinst = 'lsst'
        cls.validationDir = os.path.join(str(cls.rootdir), 'validation')

        cls.tests = [
            ('testImages/F1.23_1mm_v61', 'z7_0.25_%s.txt', (0, 0),          ('fft',),       'paraxial'),
            ('testImages/LSST_C_SN26',   'z7_0.25_%s.txt', (0, 0),          ('fft', 'exp'), 'onAxis'),
            ('testImages/LSST_NE_SN25',  'z11_0.25_%s.txt', (1.185, 1.185), ('fft', 'exp'), 'offAxis'),
            ]
        # filenames with matlab results and tolerance on absolute discrepancy (in nm)
        #
        # N.b. these tolerances are set at 10nm because centering algorithm has changed.
        #      difference in the wavefront on the ~10nm is well below noise level.
        #
        cls.matlabZFile_Tol = [('F1.23_1mm_v61_z7_0.25_fft.txt', 10),#
                               ('LSST_C_SN26_z7_0.25_fft.txt',   10),
                               ('LSST_C_SN26_z7_0.25_exp.txt',   10),
                               ('LSST_NE_SN25_z11_0.25_fft.txt', 10),
                               ('LSST_NE_SN25_z11_0.25_exp.txt', 10),
        ]
        #
        # Check that we have the right number of matlab files.  Not really a unit test, just consistency
        #
        cls.nTest = 0
        for inDir, filenameFmt, fldxy, algorithms, model in cls.tests:
            cls.nTest += len(algorithms)
        assert cls.nTest == len(cls.matlabZFile_Tol)

        cls.Zernike0 = 4                # first Zernike to fit
        znmax = 22                      # last Zernike to fit
        cls.x = range(cls.Zernike0, znmax + 1)

    def testMatlab(self):
        global doPlot
        if doPlot:
            fig = plt.figure(figsize=(10, 10))

        j = 0                           # counter for matlab outputs, self.matlabZFile_Tol
        for imgDir, filenameFmt, fldxy, algorithms, model in self.tests:
            imgDir = os.path.join(str(self.rootdir), imgDir)
            intraFile = os.path.join(imgDir, filenameFmt % "intra")
            I1 = Image(readFile(intraFile), fldxy, Image.INTRA)

            extraFile = os.path.join(imgDir, filenameFmt % "extra")
            I2 = Image(readFile(extraFile), fldxy, Image.EXTRA)

            inst = Instrument(self.myinst, I1.sizeinPix)

            for algorithm in algorithms:
                matlabZFile, tol = self.matlabZFile_Tol[j]; j += 1

                algo = Algorithm(algorithm, inst, 1)
                algo.runIt(inst, I1, I2, model)

                zer = algo.zer4UpNm
                matZ = np.loadtxt(os.path.join(self.validationDir, matlabZFile))

                aerr = np.abs(matZ - zer)
                print("%-31s max(abs(err)) = %8.3g median(abs(err)) = %8.3g [Z_%d], tol=%.0f nm" %
                      (matlabZFile, np.max(aerr), np.median(aerr), self.Zernike0 + np.argmax(aerr), tol))

                if doPlot:
                    ax = plt.subplot(self.nTest, 1, j)
                    plt.plot(self.x, matZ, label='Matlab', marker='o', color='r', markersize=10)
                    plt.plot(self.x, zer, label='Python',  marker='.', color='b', markersize=10)
                    plt.axvline(self.Zernike0 + np.argmax(aerr), ls=':', color='black')
                    plt.legend(loc="best", shadow=True, title=matlabZFile, fancybox=True)
                    ax.get_legend().get_title().set_color("red")
                    plt.xlim(self.x[0] - 0.5, self.x[-1] + 0.5)

                assert np.max(aerr) < tol

        if doPlot:
            plt.show()

if False:                               # used for C++, and triggers a file descriptor leak from matplotlib
    class MemoryTester(lsst.utils.tests.MemoryTestCase):
        pass

def setup_module(module):
    lsst.utils.tests.init()

try:
    doPlot                              # should I plot things?
except NameError:
    doPlot = False

if __name__ == "__main__":
    doPlot = sys.stdout.isatty()        # enable matplotlib when run from a terminal

    lsst.utils.tests.init()
    unittest.main()


from datetime import datetime
import pandas as pd

from utils import *

csv_file = "notes.csv"

#
def create_note(title, text):
    id_note = get_id()
    df = pd.read_csv(csv_file)
    new_row = pd.Series([id_note, title, text, datetime.now()],
                        index=["Id", "Title", "Text", "Date"])
    df.loc[len(df.index)] = new_row
    df.to_csv(csv_file, index=False)
    increment_id(int(id_note))

def delete_note(id_note):
    df = pd.read_csv(csv_file)
    df = df[df["Id"] != int(id_note)]
    df.to_csv(csv_file, index=False)

def edit_note(id_note, title, text):
    df = pd.read_csv(csv_file)
    if title != "":
        df.loc[df["Id"] == int(id_note), "Title"] = title
        df.loc[df["Id"] == int(id_note), "Date"] = datetime.now()
        df.to_csv(csv_file, index=False)
    if text != "":
        df.loc[df["Id"] == int(id_note), "Text"] = text
        df.loc[df["Id"] == int(id_note), "Date"] = datetime.now()
        df.to_csv(csv_file, index=False)

def get_note(id_note):
    df = pd.read_csv(csv_file)
    if (df["Id"] == int(id_note)).any():
        note = df[(df["Id"] == int(id_note))]
        return note.to_string(index=False)
    else:
        return None

def get_list_of_notes():
    df = pd.read_csv(csv_file)
    df.sort_values(by="Date", inplace=True)
    return df.to_string(index=False)


a=input("Enter a preflix string")
b=a[::-1]
stack=[]
for i,j in enumerate(b):  # i=index and j=string char
     if j in ['+','-','*','/']:
         l=f"{stack.pop()}{j}{stack.pop()}"
         stack.append(l)
     else:
         stack.append(j)
L=[]
for i in stack:
    L.append(i)
print("\n")
for i in L[::-1]:
    print(i,end="")

Data Structue/# Write a program to convert prefix expression to infix expression..py


import socket
import pickle
import threading

class Messenger:

    def __init__(self, host, hosts):
        self.send_address = (host['ip_address'], host['udp_start_port'])
        self.recv_address = (host['ip_address'], host['udp_end_port'])

        self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.recv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.send_sock.bind(self.send_address)
        self.recv_sock.bind(self.recv_address)

        self.listeners = list()
        self.hosts = hosts

        threading.Thread(target = self.listen).start()

    def add_listener(self, listener):
        self.listeners.append(listener)

    def send(self, host, message=b"Hello, world"):
        ''' Send a message to another host '''
        self.send_sock.sendto(message, host)

    def listen(self):
        while True:
            data, server = self.recv_sock.recvfrom(1024)
            message = pickle.loads(data)
            #print(message.message)
            pID = self.hosts[message.siteID]['id']

            #for listener in self.listeners:
            self.listeners[0].receive(message.clock, pID, message.np)
            self.listeners[1].receive(message.clock, pID, message.np)

            users, myID, userPlanes = self.listeners[0].getUsers(message.np)
            self.listeners[2].receiveAdd(users, myID, len(self.hosts), userPlanes)
            self.listeners[2].receive(pID, self.listeners[0])


from turtle import Screen
from snake import Snake
from scores import ScoreBoard
from limits import Limits
from food import Food
from start_over import StartOver
import time
from math import sqrt

BOARD_LIMIT = 281

def collision(tail, head):
    """ A function to check for collisions between head and tail """

    y_tail = tail.ycor()
    x_tail = tail.xcor()
    y_head = head.ycor()
    x_head = head.xcor()

    distance = round(sqrt((x_head - x_tail) ** 2 + (y_head - y_tail) ** 2), 2)

    if distance < 10:
        return True
    else:
        return False

def game(event):

    global screen
    global canvas
    global limit
    global start_over
    global score

    # Initialise snake, limits, food and score
    snake = Snake()
    start_over.clear()
    food = Food()
    score.score = 0
    score.clear()
    score.write_score()

    # Key binding
    canvas.bind('<Up>', snake.go_up)
    canvas.bind('<Down>', snake.go_down)
    canvas.bind('<Left>', snake.go_left)
    canvas.bind('<Right>', snake.go_right)

    game_is_on = True

    # Set initial speed (time between to snake moves)
    speed = 0.15

    while game_is_on:

        snake.move()

        # Set time to wait before next move
        time.sleep(speed)

        snake.set_direction(snake.head.heading())

        # Check for collision between snake head and food
        if snake.head.distance(food) < 1:
            snake.grow_up()
            food.refresh()
            food_on_snake = True

            # This while loop ensures that the new generated food
            # does not fall on snake's body
            while food_on_snake:
                count = 0
                for segment in snake.segments:
                    if abs(food.xcor() - segment.xcor()) < 11 and \
                        abs(food.ycor() - segment.ycor()) < 11:

                        food.refresh()
                        count += 1
                if count == 0:
                    food_on_snake = False

            # Increase speed and score
            speed *= 0.97
            score.score += 1
            score.clear()
            score.write_score()

        # Check if snake collide with board limits
        if snake.head.xcor() > BOARD_LIMIT or \
            snake.head.xcor() < BOARD_LIMIT * -1 or \
                snake.head.ycor() > BOARD_LIMIT or \
                    snake.head.ycor() < BOARD_LIMIT * -1:

            game_is_on = False

        # Check if snake collide with himself
        for segment in snake.segments[1:]:
            if collision(segment, snake.head):

                game_is_on = False

        # Show game over screen
        if not game_is_on:
            snake.hide_snake()
            food.hideturtle()
            start_over.game_over()

        screen.update()

if __name__ == '__main__':

    screen = Screen()
    screen.setup(width=700, height=720)
    screen.bgcolor('#EEEEEE')
    screen.title("Snake")

    # Prevent the screen from refreshing unless said explicitly with update()
    screen.tracer(0)
    screen.update()

    start_over = StartOver()
    limit = Limits()
    limit.create_limits()
    score = ScoreBoard()
    start_over.start_game()

    screen.listen()
    canvas = screen.getcanvas()

    # Execute "game" function when the user press Enter
    canvas.bind('<Return>', game)

    screen.update()
    screen.exitonclick()


from tkinter import (
    Tk, Text, INSERT, END
)

from tkinter.messagebox import showinfo

layar = Tk()
layar.title("Text")

text = Text(master=layar)
text.insert( INSERT, "Hello......")
text.insert( END, "Bye Bye......")
text.pack()

text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")

text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")

showinfo("isi text", text.get("1.0", END))

layar.mainloop()


from kernels import *
from numpy import array, sqrt, dot, sign, around
import hashing

# Smoothed density
def Density(current,neighbor,r,h,r_vector=[],beta=[],correction=False,kernel_name='Poly_6'):
    # Initialization
    kernel_name = globals()['%s' % kernel_name]

    if correction == True:
        W = (beta[0]+beta[1]*r_vector[0]+beta[2]*r_vector[1]+beta[3]*r_vector[2])*kernel_name(r,h).Kernel()
    else:
        W = kernel_name(r,h).Kernel()

        return neighbor['Mass']*W

# Smoothed pressure force
def Pressure(current,neighbor,r,h,t,r_vector,kernel_name,alpha=0,beta=0,c=0):
    # Initialization
    #R = 0.006 # Tensile instability term
    kernel_name = globals()['%s' % kernel_name]

    Grad_W = kernel_name(r,h).Gradient(r_vector)
    # PI = Artificial_Viscosity(current,neighbor,alpha,beta,h,c,r_vector)
    # return -neighbor['Mass']*current['Density']* \
    # ((current['Pressure']/current['Density']**2)+(neighbor['Pressure']/neighbor['Density']**2))*Grad_W
    # return array(-current['Mass']/current['Density']*(current['Pressure']+neighbor['Pressure'])/2*Grad_W)

    return array(-current['Mass']/current['Density']*neighbor['Mass']/neighbor['Density']*(current['Pressure']+neighbor['Pressure'])/2*Grad_W) # Force -> must be divided by mass
    # return array(-current['Mass']*neighbor['Mass']*(current['Pressure']/current['Density']**2+neighbor['Pressure']/neighbor['Density']**2)*Grad_W)

# Smoothed Viscosity

def Viscosity(current,neighbor,r,h,t,kernel_name,mu):
    #Initialization
    kernel_name = globals()['%s' % kernel_name]

    Laplacian_W = kernel_name(r,h).Laplacian()
    dv = array([neighbor['X Velocity']-current['X Velocity'],neighbor['Y Velocity']-current['Y Velocity'],neighbor['Z Velocity']-current['Z Velocity']])

    # return array(mu*dv*neighbor['Mass']/neighbor['Density']*Laplacian_W)

    return array(current['Mass']/current['Density']*mu*neighbor['Mass']/neighbor['Density']*dv*Laplacian_W) # Force -> must be divided by mass

# Smoothed Surface Tension Force
def Surface_Tension(current,neighbor,r,h,r_vector,kernel_name,delta,rho_0):
    # Initialization
    kernel_name = globals()['%s' % kernel_name]
    W = kernel_name(r,h).Kernel()

    # Cohesion force
    cohesion = -delta*current['Mass']*neighbor['Mass']*W*r_vector/r

    # Surface area minimization
    curvature = -delta*current['Mass']*(current['Normal']-neighbor['Normal'])

    # correction factor
    K = 2*rho_0/(current['Density']+neighbor['Density'])

    # Surface tension force
    return K*(cohesion+curvature)
    # if sqrt(dot(current['Normal'],current['Normal'])) > threshold:
    #     kappa = current['Color Map Laplacian']/sqrt(dot(current['Normal'],current['Normal']))
    #     return array(-delta*kappa*neighbor['Mass']*r_vector*W) # Force -> must be divided by mass
    # else:
    #     return array([0.,0.,0.])

    # return array(-delta * n/sqrt(dot(n,n))*neighbor['Mass']/neighbor['Density'] * Laplacian_W)

# def Artificial_Viscosity(current,neighbor,alpha,beta,h,c,r_vector):
#     v_ab = array([-neighbor['X Velocity']+current['X Velocity'],-neighbor['Y Velocity']+current['Y Velocity'],-neighbor['Z Velocity']+current['Z Velocity']])
#     if dot(v_ab,r_vector) < 0:

#         c_ab = (c[current['Type']]+c[neighbor['Type']])/2
#         rho_ab = (current['Density']+neighbor['Density'])/2

#         mu_ab = h*dot(v_ab,r_vector)/(dot(r_vector,r_vector)+0.01*h**2)

#         return -alpha*c_ab*mu_ab + beta*mu_ab**2/rho_ab

#     else:

#         return 0

# Boundary-Fluid Pressure Force
def Boundary_Fluid_Pressure(current,neighbor,r,h,r_vector,kernel_name):
    kernel_name = globals()['%s' % kernel_name]
    Grad_W = kernel_name(r,h).Gradient(r_vector)
    #array(Grad_W * -neighbor['psi']*current['Pressure']/current['Density']**2)
    return array(-current['Density']*(current['Pressure']/(current['Density'])**2)*neighbor['Mass']*Grad_W)
    # return array(-Grad_W * neighbor['psi']*current['Pressure']/current['Density']**2)

# Boundary-Fluid Friction Force
def Boundary_Fluid_Friction(current,neighbor,r,h,r_vector,kernel_name,delta,c):
    kernel_name = globals()['%s' % kernel_name]

    v_ab = array([current['X Velocity']-neighbor['X Velocity'],current['Y Velocity']-neighbor['Y Velocity'],current['Z Velocity']-neighbor['Z Velocity']])

    Grad_W = kernel_name(r,h).Gradient(r_vector)

    c_ab = (c[current['Type']]+c[neighbor['Type']])/2

    ni_ab = delta*h*c_ab/(2*current['Density'])

    PI = -ni_ab*max(0,dot(v_ab,r_vector))/(r**2+0.01*h**2)

    return array(-current['Density']*current['Mass']*neighbor['Mass']*PI*Grad_W)


from Abstract.Expresion import *
from Abstract.Return import *
from Symbol.Entorno import *
from Symbol.Generador import *

class While(Expresion):
    def __init__(self, condicion, instrucciones, linea, columna):
        Expresion.__init__(self, linea, columna)
        self.condicion = condicion
        self.instrucciones = instrucciones

    def compilar(self, entorno):
        genAux = Generador()
        generador = genAux.getInstancia()

        continuel = generador.agregarLabel()
        generador.printLabel(continuel)

        condicion = self.condicion.compilar(entorno)
        newEnv = Entorno(entorno, "WHILE")

        newEnv.breakl = condicion.falsel
        newEnv.continuel = continuel

        generador.printLabel(condicion.truel)

        self.instrucciones.compilar(newEnv)
        generador.printGoto(continuel)

        generador.printLabel(condicion.falsel)


def groupIsomorphic(strs):
    def encode(s):
        d = {}
        encoded = []
        for c in s:
            if c not in d:
                d[c] = len(d)
            encoded.append(d[c])
        print('encoded: ' + s)
        print(encoded)
        return str(encoded)

    groups = {}
    for s in strs:
        encoded = encode(s)
        if encoded not in groups:
            groups[encoded] = []
        groups[encoded].append(s)
        print(groups)

    return list(groups.values())

print(groupIsomorphic(['aab', 'xxy', 'xyz', 'abc', 'def', 'xyx']))


import string

def felhasznalo(n):
    if "@" in n:
        k=n.find("@")
        fh=n[:k]
        a=string.ascii_letters + string.digits

        if len(fh)>1:
            if (fh[0] in a) and (fh[-1] in a):
                a+="-"+"_"+"."
                for i in range(len(fh)):
                    if (fh[i]=="." and (fh[i+1]=="." or fh[i-1]==".")) or (fh[i] not in a):
                        return False
                return True
    return False

def kiszolgalo(n):
    if "@" in n and "." in n:
        k=n.find("@")
        sz=n[:-3].rfind(".")
        ksz=n[k+1:sz]

        a=string.ascii_letters + string.digits
        if len(ksz)>1:
            if (ksz[0] in a) and (ksz[-1] in a):
                a+="-"+"."
                for i in range(len(ksz)):
                    if (ksz[i]=="." and (ksz[i+1]=="." or ksz[i-1]==".")) or (ksz[i] not in a):
                        return False
            return True
    return False

def tld(n):
    if "." in n:
        l=n[:-3].rfind(".")
        t=n[l+1:]

        a=string.ascii_letters+"."
        for i in range(len(t)):
            if (t[i] not in a) or (t[len(t)-1])==".":
                return False
            elif t[i]==".":
                a=string.ascii_letters
        return True
    return False

def email(n):
    if felhasznalo(n) and kiszolgalo(n) and tld(n):
        return "Helyes"
    return "Hibás"

n=input("Adja meg az e-mail címet: ")
while n != "0":
    print(email(n))
    n=input("Adja meg az e-mail címet: ")


#  6. Expand your soluation to the previous problem to allow the calcualtion of a complete name such as "John Marvin Zelle" or
#     "John Jacob Jingleheimer Smith." The total value is just the sum of the numberic values of all the names.
#

# create a string of alphabet
# take as an input from the user a complete name and make it lower case
# create a loop for the name
#   which will return index of the letter from the string alphabet
#   sum the index
# print the sum

def main():
    alpha = "abcdefghijklmnopqrstuvwxyz"
    name = input("Enter the name: ")
    name2 = name.lower().split()
    sum = 0
    for i in name2:
        for j in i:
            sum = sum + alpha.find(j) + 1

    print("The final sum of your {0} is {1}".format(name, sum))

main()


import httplib2
import json

from plugins.text_plugin import TextPlugin

def to_celsius(kelvin_temperature):
    return kelvin_temperature - 273.15

class WeatherAnnouncer(TextPlugin):

    def __init__(self, api_key, location_query):
        super(WeatherAnnouncer, self).__init__()

        self.api_key = api_key
        self.location_query = location_query

    def fetch_weather(self):
        url = 'http://api.openweathermap.org/data/2.5/forecast?q={}&APPID={}'.format(self.location_query, self.api_key)

        http = httplib2.Http()
        resp, content = http.request(url)

        assert resp.status == 200

        return json.loads(content)

    def generate_string(self):
        try:
            weather = self.fetch_weather()
            next_12_hours_data = weather['list'][:4] # chunks of 3 hours
        except:
            return 'Error fetching weather'

        min_temp = int(round(min(to_celsius(chunk['main']['temp_min']) for chunk in next_12_hours_data)))
        max_temp = int(round(max(to_celsius(chunk['main']['temp_max']) for chunk in next_12_hours_data)))

        weather_types = list(set([chunk['weather'][0]['description'] for chunk in next_12_hours_data]))

        return u'. '.join([
            'Here is the forecast for the day:'
            'Weather should be {}'.format(', '.join(weather_types)),
            'Temperatures should be between {} and {} degrees celsius'.format(min_temp, max_temp)
        ])


#count the number of emails send on days of the week
with open("mbox-short.txt",'r')as file: #read the file
    count = {} #def data as a dict()
    for line in file:
        if line.startswith('From ') == True: #only lines with From at the start
            line = line.split()
            day = line[2] # only take the day info
            count[day]=count.get(day,0) +1 #add or increment the value of the day count

print(count)


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 17 17:54:23 2022

@author: user
"""

import random as r   #匯入亂數模組

while True :  #以while迴圈擲骰子
    inkey = input("按任意鍵再按[Enter]鍵擲骰子，直接按[Enter]鍵結束：")
    if len(inkey) > 0 :
        num = r.randint(1, 6)
        print("你擲的骰子點數為：" + str(num))
    else :
        print("遊戲結束！")
        break


# This problem was asked by Amazon.
#
# Given an integer k and a string s, find the length of the longest substring
# that contains at most k distinct characters.
#
# For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".

def subString(s, k):
    longestSubString = ''
    for i in range(len(s)):
        for l in range( i +1 , len(s) +1):
            if k == len((set(s[i:l]))) and len(longestSubString) < len(s[i:l]):
                longestSubString = s[i:l]
    return longestSubString

if __name__ == "__main__":
    print(subString("abcba", 2))


import argparse
import os.path
import sys

from .LogConsole import LogConsole

class CliBase(object):
    """Base class for all cli programs
    Overridden in subclasses that add stuff for the specific programs."""

    # also used by setup.py
    VERSION = "3.2-beta2"
    HEADER = "{} v{} - (c)2022 E.H.Eefting (edwin@datux.nl)".format(os.path.basename(sys.argv[0]), VERSION)

    def __init__(self, argv, print_arguments=True):

        self.parser=self.get_parser()
        self.args = self.parse_args(argv)

        # helps with investigating failed regression tests:
        if print_arguments:
            print("ARGUMENTS: " + " ".join(argv))

    def parse_args(self, argv):
        """parses the arguments and does additional checks, might print warnings or notes
        Overridden in subclasses with extra checks.
        """

        args = self.parser.parse_args(argv)

        if args.help:
            self.parser.print_help()
            sys.exit(255)

        if args.version:
            print(self.HEADER)
            sys.exit(255)

        # auto enable progress?
        if sys.stderr.isatty() and not args.no_progress:
            args.progress = True

        if args.debug_output:
            args.debug = True

        if args.test:
            args.verbose = True

        if args.debug:
            args.verbose = True

        self.log = LogConsole(show_debug=args.debug, show_verbose=args.verbose, color=sys.stdout.isatty())

        self.verbose(self.HEADER)
        self.verbose("")

        return args

    def get_parser(self):
        """build up the argument parser
        Overridden in subclasses that add extra arguments
        """

        parser = argparse.ArgumentParser(description=self.HEADER, add_help=False,
                                         epilog='Full manual at: https://github.com/psy0rz/zfs_autobackup')

        # Basic options
        group=parser.add_argument_group("Common options")
        group.add_argument('--help', '-h', action='store_true', help='show help')
        group.add_argument('--test', '--dry-run', '-n', action='store_true',
                            help='Dry run, dont change anything, just show what would be done (still does all read-only '
                                 'operations)')
        group.add_argument('--verbose', '-v', action='store_true', help='verbose output')
        group.add_argument('--debug', '-d', action='store_true',
                            help='Show zfs commands that are executed, stops after an exception.')
        group.add_argument('--debug-output', action='store_true',
                            help='Show zfs commands and their output/exit codes. (noisy)')
        group.add_argument('--progress', action='store_true',
                            help='show zfs progress output. Enabled automaticly on ttys. (use --no-progress to disable)')
        group.add_argument('--no-progress', action='store_true',
                            help=argparse.SUPPRESS)  # needed to workaround a zfs recv -v bug
        group.add_argument('--utc', action='store_true',
                            help='Use UTC instead of local time when dealing with timestamps for both formatting and parsing. To snapshot in an ISO 8601 compliant time format you may for example specify --snapshot-format "{}-%%Y-%%m-%%dT%%H:%%M:%%SZ". Changing this parameter after-the-fact (existing snapshots) will cause their timestamps to be interpreted as a different time than before.')
        group.add_argument('--version', action='store_true',
                            help='Show version.')

        return parser

    def verbose(self, txt):
        self.log.verbose(txt)

    def warning(self, txt):
        self.log.warning(txt)

    def error(self, txt):
        self.log.error(txt)

    def debug(self, txt):
        self.log.debug(txt)

    def progress(self, txt):
        self.log.progress(txt)

    def clear_progress(self):
        self.log.clear_progress()

    def set_title(self, title):
        self.log.verbose("")
        self.log.verbose("#### " + title)


def bfs(r, c, location_num):
    [r, c, location_num,]

N = int(input())  # 체스판 크기
arr = [list(map(int, input().split())) for _ in range(N)]
location_num = 1  # 1부터 시작

# 나이트, 비숍, 룩 델타 이동 (시계방향)
k_dr = [-2, -1, 1, 2, 2, 1, -1, -2]
k_dc = [1, 2, 2, 1, -1, -2, -2, -1]
b_dr = [-1, 1, 1, -1]
b_dc = [1, 1, -1, -1]
r_dr = [-1, 0, 1, 0]
r_dc = [0, 1, 0, -1]

for i in range(N):
    for j in range(N):
        if arr[i][j] == 1:
            row = i
            col = j
            break

bfs(row, col, location_num)


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

class Regression(object):
    pass

class PolynomialFeature(object):
    def __init__(self, degree=2):
        assert isinstance(degree, int)
        self.degree = degree # degree : int - degree of polynomial

    def transform(self, x):
        if x.ndim == 1: x = x[:, None]
        x_t = x.transpose()
        features = [np.ones(len(x))]
        for degree in range(1, self.degree + 1):
            for items in itertools.combinations_with_replacement(x_t, degree):
                features.append(functools.reduce(lambda x, y: x * y, items))
        return np.asarray(features).transpose()

class LinearRegression(Regression):
    def fit(self, X:np.ndarray, t:np.ndarray):
        self.w = np.linalg.pinv(X) @ t
        self.var = np.mean(np.square(X @ self.w - t))

    def predict(self, X:np.ndarray, return_std:bool=False):
        y = X @ self.w
        if return_std:
            y_std = np.sqrt(self.var) + np.zeros_like(y)
            return y, y_std
        return y

class RidgeRegression(Regression):
    def __init__(self, lambd:float=1.):
        self.lambd = lambd # lambd = PRML alpha

    def fit(self, X:np.ndarray, t:np.ndarray):
        eye = np.eye(np.size(X, 1))
        self.w = np.linalg.solve(self.lambd * eye + X.T @ X, X.T @ t)

    def predict(self, X:np.ndarray):
        return X @ self.w

if __name__ == "__init__":

    x_train = np.array([0.1387, 0.2691, 0.3077, 0.3625, 0.4756, 0.5039, 0.5607, 0.6468, 0.7490, 0.7881 ])
    t_train = np.array([0.8260, 1.0469, 0.7904, 0.6638, 0.1731, -0.0592, -0.2433, -0.6630, -1.0581, -0.8839 ])

    x_correct = np.linspace(0, 1, 100)
    t_correct = np.sin(2 * np.pi * x_correct)

    x_test = np.linspace(0.01,0.99,1000, endpoint=False)
    noise = np.random.randn(len(x_test))
    # noise = np.random.normal(scale=0.3, size=x_train.shape) #scale=desvio padrão
    t_test = np.sin(2*np.pi*x_test) + 0.1 * noise

    M = [0, 1, 3, 9]

    for i, degree in enumerate(M):
        plt.subplot(2, 2, i + 1)
        feature = PolynomialFeature(degree)
        A_train = feature.transform(x_train)
        A_test = feature.transform(x_test)

        w1 = np.linalg.inv( A_train.T.dot(A_train)).dot(A_train.T.dot(t_train) )
        w2 = np.linalg.pinv(A_train) @ t_train

        model = LinearRegression()
        model.fit(A_train, t_train)
        y_test = model.predict(A_test)

        plt.scatter(x_train, t_train, facecolor="none", edgecolor="b", s=50, label="training data")
        plt.plot(x_correct, t_correct, c="g", label="$\sin(2\pi x)$")
        plt.plot(x_test, y_test, c="r", label="fitting")
        plt.ylim(-1.5, 1.5)
        plt.annotate("M={}".format(degree), xy=(-0.15, 1))
    plt.legend(bbox_to_anchor=(1.05, 0.64), loc=2, borderaxespad=0.)
    plt.show()

    ## Erro MSE
    training_errors = []
    test_errors = []

    # Erms = []
    # ErmsV = []

    for i in range(10):
        feature = PolynomialFeature(i)
        A_train = feature.transform(x_train)
        A_test = feature.transform(x_test)

        model = LinearRegression()
        model.fit(A_train, t_train)
        y_test = model.predict(A_test)
        y_train = model.predict(A_train)

        training_errors.append(np.sqrt(np.mean(np.square(y_train - t_train))))
        test_errors.append(np.sqrt(np.mean(np.square( y_test - t_test ))))

        # Erms.append( math.sqrt( (y_train-t_train).T.dot(y_train-t_train)/len(x_train) ) )
        # ErmsV.append( math.sqrt( (y_test - t_test).T.dot(y_test - t_test)/len(x_test) ) )

    plt.plot(training_errors, 'o-', mfc="none", mec="b", ms=10, c="b", label="Training")
    plt.plot(test_errors, 'o-', mfc="none", mec="r", ms=10, c="r", label="Test")
    plt.legend()
    plt.xlabel("degree")
    plt.ylabel("RMSE")
    plt.show()

    ## Regularization (quanto maior o expoente, maior a regularizacao)

    l = np.exp(-18) # np.exp(-18) == 1e-8
    l = np.exp(-6.9) # 1e-3 == 0.001 ~ np.exp(-6.9)#

    feature = PolynomialFeature(9)
    A_train = feature.transform(x_train)
    A_test = feature.transform(x_test)

    model = RidgeRegression(lambd=l)
    model.fit(A_train, t_train)
    y_test = model.predict(A_test)

    plt.scatter(x_train, t_train, facecolor="none", edgecolor="b", s=50, label="training data")
    plt.plot(x_correct, t_correct, c="g", label="$\sin(2\pi x)$")
    plt.plot(x_test, y_test, c="r", label="fitting")
    plt.ylim(-1.5, 1.5)
    plt.legend()
    plt.annotate("M=9", xy=(-0.15, 1))
    plt.show()

# =============================================================================
#     M = 3
#     lambd = -18
#
#     A_train = np.asarray([x_train**i for i in range(M+1)]).T
#     w = np.linalg.inv( A_train.T.dot(A_train) + np.exp(lambd) * np.identity(M+1) ).dot(
#             A_train.T.dot(t_train) )
#     y_train = np.dot(A_train,w)
#
#     A_test = np.asarray([x_test**i for i in range(M+1)]).T
#     y_test = np.dot(A_test,w)
#
#     plt.figure(figsize=(13,5))
#     plt.scatter(x_train, t_train, facecolor="none", edgecolor="b", s=50, label="target train")
#     #plt.scatter(x_train, y_train, facecolor="none", edgecolor="r", s=50, label="predicted train $y(x,w)$")
#     plt.plot(x_test, y_test, c="r", label="$y(x,w)$") #curve of predicted test data
#     plt.plot(x_correct, t_correct, c="g", alpha=0.6, label="$\sin(2\pi x)$")
#
#     plt.ylabel('$t$', fontsize=13, rotation = 360)
#     plt.xlabel('$\mathit{x}$', fontsize=13,labelpad=-15)
#     plt.xticks([0,1])
#     plt.yticks([-1,0,1])
#     plt.ylim(-1.5,1.5)
#     plt.annotate(('ln $\lambda$ = {}'.format(lambd)), xy=(0.8, 1))
#     plt.legend(loc='lower left')
#     #plt.savefig('figures/Fig2.1.png', format='png', dpi=300, transparent=True, bbox_inches='tight')
#
#     E_train = (y_train-t_train).T.dot(y_train-t_train) + np.exp(lambd)/2 * w.T.dot(w)
#     Erms_train = math.sqrt(E_train/len(x_train))
#
#     E_test = (y_test-t_test).T.dot(y_test-t_test) + np.exp(lambd)/2 * w.T.dot(w)
#     Erms_test = math.sqrt(E_test/len(x_test))
# =============================================================================