import os
import argparse
from getpass import getpass

import requests

def main():
    user = CommandLineParser().parse()
    API(user).parse()

class API:
    def __init__(self, user):
        self.target = "http://localhost:8080/"
        self.user = user
        self.header = self._create_header()

    def parse(self):
        projects = self._parse_projects()
        for project in projects:
            if project != "lifecycle":
                self._delete_project(project)
        users = self._parse_users()
        for user in users:
            if user != self.user:
                self._delete_user(user)

    def _parse_projects(self):
        projects = []
        localhost_project_dict = self._get_projects()
        for project in localhost_project_dict:
            projects.append(project["name"])
        return projects

    def _parse_users(self):
        users = []
        localhost_user_dict = self._get_users()
        for user in localhost_user_dict:
            users.append(user["email"])
        return users

    @staticmethod
    def _create_header():
        token = getpass("Token: ")
        return {"Authorization": "Bearer " + token}

    def _delete_project(self, project_name):
        response = requests.delete(f"{self.target}access/projects/{project_name}", headers=self.header)
        response.raise_for_status()

    def _delete_user(self, user_email):
        response = requests.delete(f"{self.target}access/users/{user_email}", headers=self.header)
        response.raise_for_status()

    def _get_projects(self):
        response = requests.get(f"{self.target}access/projects", headers=self.header).json()
        return response

    def _get_users(self):
        response = requests.get(f"{self.target}access/users", headers=self.header).json()
        return response

class CommandLineParser:
    def __init__(self):
        self.parser = CommandLineInterface()

    def parse(self):
        su = self._parse_su()
        return su

    def _parse_su(self):
        return self.parser.get_argument("user")

class CommandLineInterface:
    def __init__(self):
        parser = self._create_argument_parser()
        self.arguments = parser.parse_args()

    @staticmethod
    def _create_argument_parser():
        """
        Creation of the Command Line Arguments, and whenever they should be displayed as
        "required" or not.
        """
        parser = argparse.ArgumentParser(
            prog="Reset localhost projects and users",
            description="Utilitarian script for developers that want to reset their localhost instance to just Project "
                        "'Lifecycle' and a singular user if they supply -u. Does not affect Profiles."
        )
        required = parser.add_argument_group("Required arguments")
        required.add_argument(
            "-u",
            "--user",
            type=str,
            required=True,
            help="The single user that is registered on the localhost that needs to remain."
        )
        return parser

    def get_argument(self, argument_key):
        """
        Small getter function for CLI, including some error handling.
        """
        if argument_key in self.arguments:
            return getattr(self.arguments, argument_key)
        else:
            raise KeyError(f"Argument {argument_key} invalid, not found in CLI arguments.")

if __name__ == "__main__":
    main()


import imaplib
import email
import email.header
import datetime
import base64
from bs4 import BeautifulSoup

class Email(object):
    def __init__(self):
        self.connected = False
        self.mids = []
        self.mails = []

    def connect(self, username, password, host):
        self._mail = imaplib.IMAP4_SSL(host)
        self._mail.login(username, password)
        self._mail.select('inbox')
        result, data = self._mail.search(None, 'ALL')
        self.mids = data[0].split()
        self.connected = True

    def get_mail(self):
        n = 1
        while(n < 11):
            rv, data = self._mail.fetch(self.mids[len(self.mids) - n], '(RFC822)')
            n+=1
            msg = email.message_from_bytes(data[0][1])
            hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
            subject = str(hdr)
            date_tuple = email.utils.parsedate_tz(msg['Date'])
            date = datetime.datetime.fromtimestamp(
                email.utils.mktime_tz(date_tuple))
            body_str = ''
            if msg.is_multipart():
                for part in msg.get_payload():
                    body = self._process_body(part)

                    if isinstance(body,str):
                        body_str += body

            else:
                body_str = self._process_body(msg)
                if isinstance(body, str):
                    body_str += body

            self.mails.append({'Date':date, 'Subject':subject, 'Body':body_str})

    def _process_body(self, part):
        body = part.get_payload()

        if 'base64' in part['Content-Transfer-Encoding']:
            body = base64.b64decode(body)
        if 'text/html' in part['Content-Type']:
            soup = BeautifulSoup(body, "html.parser")
            body = soup.get_text()

        return body


import torch
from torch import nn
from .operation import Operation, OP_COV_KRON, OP_GRAM_HADAMARD
from .operation import BASIC_OPS, OP_COV_UNIT_WISE, OP_COV_UNIT_WISE_INV, OP_COV_DIAG, OP_COV_DIAG_INV, OP_GRAM_DIRECT, OP_BATCH_GRADS

class LayerNorm(Operation):
    """
    module.weight: normalized_shape
    module.bias: normalized_shape

    Argument shapes
    in_data: n x normalized_shape
    out_grads: n x normalized_shape

    normalized_shape: f[0] x f[1] x ... x f[-1]
    """
    supported_operations = set(
        BASIC_OPS + [OP_COV_UNIT_WISE, OP_COV_UNIT_WISE_INV, OP_COV_DIAG, OP_COV_DIAG_INV, OP_GRAM_DIRECT, OP_BATCH_GRADS])

    @staticmethod
    def preprocess_in_data(module, in_data, out_data):
        # restore normalized input
        in_data_norm = (out_data - module.bias).div(module.weight)
        in_data = in_data_norm
        # n x * x norm_shape -> n x norm_shape
        norm_shape_len = len(module.weight.shape)
        in_data_shape_len = len(in_data.shape)
        if norm_shape_len < in_data_shape_len - 1:
            in_data = in_data.flatten(end_dim=-norm_shape_len - 1)
        return in_data

    @staticmethod
    def preprocess_out_grads(module, out_grads):
        # n x * x norm_shape -> n x norm_shape
        norm_shape_len = len(module.weight.shape)
        out_grads_shape_len = len(out_grads.shape)
        if norm_shape_len < out_grads_shape_len - 1:
            out_grads = out_grads.flatten(end_dim=-norm_shape_len - 1)
        return out_grads

    @staticmethod
    def batch_grads_weight(
        module: nn.Module, in_data: torch.Tensor, out_grads: torch.Tensor
    ):
        return in_data.mul(out_grads)  # n x normalized_shape

    @staticmethod
    def batch_grads_bias(module, out_grads):
        return out_grads

    @staticmethod
    def grad_weight(module: nn.Module, in_data: torch.Tensor, out_grads: torch.Tensor):
        return in_data.mul(out_grads).sum(dim=0)

    @staticmethod
    def grad_bias(module: nn.Module, out_grads: torch.Tensor):
        return out_grads.sum(dim=0)

    @staticmethod
    def cov_diag_weight(module, in_data, out_grads):
        grads = in_data.mul(out_grads)
        return grads.mul(grads).sum(dim=0)  # normalized_shape

    @staticmethod
    def cov_diag_bias(module, out_grads):
        return out_grads.mul(out_grads).sum(dim=0)  # normalized_shape

    @staticmethod
    def cov_unit_wise(module, in_data, out_grads):
        n_features = in_data.flatten(start_dim=1).shape[1]  # (f[0] x f[1] x ... x f[-1])
        grads_w = in_data.mul(out_grads)  # n x normalized_shape
        grads_b = out_grads  # n x normalized_shape
        cov_ww = (grads_w ** 2).sum(0).flatten()  # n_features x 1
        cov_bb = (grads_b ** 2).sum(0).flatten()  # n_features x 1
        cov_wb = (grads_w * grads_b).sum(0).flatten()  # n_features x 1
        blocks = torch.vstack([cov_ww, cov_wb, cov_wb, cov_bb]).reshape(2, 2, n_features).transpose(0, 2)
        return blocks  # n_features x 2 x 2

    @staticmethod
    def cov_kron_A(module, in_data):
        raise ValueError(
            f'{OP_COV_KRON} operation is not supported in LayerNorm.'
        )

    @staticmethod
    def cov_kron_B(module, out_grads):
        raise ValueError(
            f'{OP_COV_KRON} operation is not supported in LayerNorm.'
        )

    @staticmethod
    def gram_A(module, in_data1, in_data2):
        raise ValueError(
            f'{OP_GRAM_HADAMARD} operation is not supported in LayerNorm.'
        )

    @staticmethod
    def gram_B(module, out_grads1, out_grads2):
        raise ValueError(
            f'{OP_GRAM_HADAMARD} operation is not supported in LayerNorm.'
        )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar  2 23:43:12 2018

@author: Chandra Sekhar Ravuri
"""

import numpy as np
import matplotlib.pyplot as plt
from time import time
from datetime import datetime, timedelta
import pandas as pd

duration = 5 # in minutes
strt_time = 000000 # HHmmSS
############ Load the data file #######################
#data1 = np.genfromtxt('/home/hadoop1/Documents/prml/project/data/UK_DALE/DATA/house_1/channel_1.dat')
data = pd.read_table('/home/hadoop1/Documents/prml/project/data/UK_DALE/DATA/house_2/channel_8.dat',sep=' ')
data = np.array(data)

# for making(not required)
#data = data1[:10000]

st_time = time()

############# Convert Time stamp to YYYYMMDDHHmmss format #######
data[:,0] = [datetime.utcfromtimestamp(i).strftime("%Y%m%d%H%M%S") for i in data[:,0]]

#for i in range(len(data[:,0])):
#    data[i,0] = datetime.utcfromtimestamp(data[i,0]).strftime("%Y%m%d%H%M%S")

#print(time() - st_time)

############ Collecting dates YYYYMMDD format ###############
lst = np.unique(data[:,0]//1000000) # list of all dates

print('Total '+str(len(lst))+' days')

########### listing day wise ###########################
day_data = []

for i in lst:
    a = data[data[:,0]//1000000==i]
    day_data.append(a)

########## Time generation day wise ######################
min_inter = np.arange(strt_time,5959,500)
hr_inter = np.arange(000000,235959,10000)

time_axis = np.array([min_inter+i for i in hr_inter]).flatten()

# save days list also ( lst )
########### matrix with day data ############################
# DeviceOn=1 ; DeviceOff=0 ; MissingData=-1
day_mat = - np.ones((len(lst), int(1440/duration)))

for i1 in range(len(day_data)):

    day_wise = day_data[i1]
    for i2 in range(len(time_axis)-1):

        aa = []
        for i in range(len(day_wise[:,0])):
            if (day_wise[i,0]%1000000 >= time_axis[i2] and day_wise[i,0]%1000000 < time_axis[i2+1]):
                aa.append(day_wise[i,1])

        aa = np.array(aa)

        if (len(aa) == 0):
            day_mat[i1,i2] = 0

        elif (aa.max() > 10):
            day_mat[i1,i2] = 1

print(time() - st_time)
print('Done!')

#ax = data[data[:,0]%1000000 < time_axis[1],0]

#aa = day_wise[1 <= day_wise[:,0]%1000000 < 10]

#aa = [day_wise[i,1] for i in day_wise[:,0]%1000000 if(i>=1 and i<20)]

#plt.figure()
#plt.plot(data[:50000,0],data[:50000,1])
#plt.show()

#data[:,0] = data[:,0]//1000000

#a = data[data[:,0]//1000000==data[0,0]//1000000]

'''
print(a.shape)
plt.figure()
plt.plot(a[:,0],a[:,1])
plt.show()
'''

#print(time.strftime("%Y %m %d %H %M %S","15465465"))
#print(time.ctime())
#print(time.clock())

#print(datetime.fromtimestamp(1175412949).strftime("%Y%m%d%H%M%S")) ## YYYYMMDDHHmmss


from django.shortcuts import render, get_object_or_404
from django.views.generic import View, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.http import FileResponse
from django.urls import reverse_lazy
import os

from .models import Book
from .forms import UploadBookForm

class BookList(LoginRequiredMixin, View):
    def get(self, request):

        return render(request, 'books/list.html')

class UploadBook(LoginRequiredMixin, View):
    init_form = UploadBookForm()
    def post(self, request):
        form = UploadBookForm(request.POST, request.FILES)
        if form.is_valid():
            book_name = form.cleaned_data.get('book')
            if str(book_name).lower().endswith('pdf'):
                obj = form.save(commit=False)
                obj.owner = request.user
                obj.save()
                messages.success(
                    request, "Your file has been uploaded successfully!!!")
            else:
                messages.error(
                    request, "You should select pdf file (e.g: exampl.pdf).")
            books = Book.objects.filter(owner=request.user)
        else:
            messages.error(
                request, "Sorry!! you didn't select anything.")
        return render(request, 'books/list.html', {
            'form': self.init_form,
            'books': books
        })

def download_book(request, pk):
    book = get_object_or_404(Book, pk=pk)
    return FileResponse(book.book.open(), content_type='application/pdf')

def read_book(request, pk, file_=None):
    book = get_object_or_404(Book, pk=pk)
    cred_id = os.environ.get('CRED_ID')     # credentail_id for adobe reader
    return render(request, 'books/pdf_viewer.html', {'book': book})

def view_book(request):
    return render(request, 'books/viewer.html')

class DeleteBook(DeleteView):
    model = Book
    template_name = 'books/confirm_delete.html'
    context_object_name = 'book'
    success_url = reverse_lazy('books:list')


'''Lv.2 [1차] 뉴스 클러스터링'''

# 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/17677

# 풀이 1
def solution(str1, str2):
    # 1. s1 전처리
    s1 = []
    for i in range(len(str1)-1):
        element = str1[i:i+2]
        if element.isalpha():
            s1.append(element.lower())
    #print(s1)

    # 2. s2 전처리
    s2 = []
    for i in range(len(str2)-1):
        element = str2[i:i+2]
        if element.isalpha():
            s2.append(element.lower())
    #print(s2)

    # 3. 교집합원소개수, 합집합원소개수 계산
    cnt_gyo = 0
    for element in s1:
        if element in s2:
            cnt_gyo += 1
            s2[s2.index(element)] = ''
    cnt_hap = len(s1) + len(s2) - cnt_gyo

    # 4. J 구하기
    if cnt_hap == 0:
        return 65536
    else:
        return int(cnt_gyo / cnt_hap * 65536)

# 풀이 2
def solution(str1, str2):
    # 1. s1 전처리
    s1 = [str1[i:i+2].lower() for i in range(len(str1)-1) if str1[i:i+2].isalpha()]
    s2 = [str2[i:i+2].lower() for i in range(len(str2)-1) if str2[i:i+2].isalpha()]

    # 2. 교집합원소개수, 합집합원소개수 계산
    gyo = set(str1) & set(str2)
    cnt_gyo = sum([min(str1.count(gg), str2.count(gg)) for gg in gyo])
    cnt_hap = len(s1) + len(s2) - cnt_gyo

    # 4. J 구하기
    if cnt_hap == 0:
        return 65536
    else:
        return int(cnt_gyo / cnt_hap * 65536)

# 풀이 3
import re
import math
def solution(str1, str2):
    str1 = [str1[i:i+2].lower() for i in range(0, len(str1)-1) if not re.findall('[^a-zA-Z]+', str1[i:i+2])]
    str2 = [str2[i:i+2].lower() for i in range(0, len(str2)-1) if not re.findall('[^a-zA-Z]+', str2[i:i+2])]

    gyo = set(str1) & set(str2)
    hap = set(str1) | set(str2)

    if len(hap) == 0 :
        return 65536

    cnt_gyo = sum([min(str1.count(gg), str2.count(gg)) for gg in gyo])
    cnt_hap = sum([max(str1.count(hh), str2.count(hh)) for hh in hap])

    return math.floor((cnt_gyo/cnt_hap)*65536)

# 풀이 4
from collections import Counter
def solution(str1, str2):
    s1 = [str1[i:i+2].lower() for i in range(len(str1)-1) if str1[i:i+2].isalpha()]
    s2 = [str2[i:i+2].lower() for i in range(len(str2)-1) if str2[i:i+2].isalpha()]

    if not s1 and not s2:
        return 65536

    c1 = Counter(s1)
    c2 = Counter(s2)
    gyo = c1&c2
    hap = c1|c2
    cnt_gyo = sum(gyo.values())
    cnt_hap = sum(hap.values())

    answer = int(cnt_gyo / cnt_hap * 65536)

    return answer

# 풀이 5
from collections import Counter
def solution(str1, str2):
    s1 = [str1[i:i+2].lower() for i in range(len(str1)-1) if str1[i:i+2].isalpha()]
    s2 = [str2[i:i+2].lower() for i in range(len(str2)-1) if str2[i:i+2].isalpha()]
    if not s1 and not s2: return 65536
    return int(float(sum((Counter(s1)&Counter(s2)).values()))/float(sum((Counter(s1)|Counter(s2)).values())) * 65536)

[1차] 뉴스 클러스터링.py


# Collect the name from your player
# Check whether it meets the length requirements for the API call
# Ping the Uzby API to create a new random name for your player,
#   using the length of their given name as input
# Inform the player about their in-game name

import requests
player_name_good = False

while player_name_good == False:
    player_name = input("Please tell us us your first name ")
    length = len(player_name)
    if length >= 40:
        print("your name is too long. please type a name that has 2-40 chars")
    elif length <2:
        print("your name is too short. please type a name that has 2-40 chars")
    else:
        url = f"https://uzby.com/api.php?min={2}&max={length}"

        response = requests.get(url)
        print(f'Your player name is {response.text}')
        player_name_good = True
        break


import json
import subprocess
from json import JSONDecodeError

from vosk import Model, KaldiRecognizer, SetLogLevel
import os
import wave
import soundfile as sf
from bot.config import BASE_DIR
import requests

# model_path = BASE_DIR / 'model'
model_path = "/home/mark/PycharmProjects/atom/vosk_test/model"

def convert_ogg2wav(path_ogg, path_wav=None):
    data, samplerate = sf.read(path_ogg)
    if not path_wav:
        path_wav = path_ogg + '.wav'
    sf.write(path_wav, data, samplerate)
    return path_wav

def get_text(path_wav):
    SetLogLevel(0)

    if not os.path.exists(model_path):
        print("Идиот, забыл модель скачать блять. https://alphacephei.com/vosk/models/vosk-model-ru-0.10.zip")
        exit(1)

    wf = wave.open(path_wav, "rb")
    if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
        print("Audio file must be WAV format mono PCM.")
        exit(1)

    model = Model(model_path)
    rec = KaldiRecognizer(model, wf.getframerate())
    rec.SetWords(True)

    # all_text = ""
    while True:
        data = wf.readframes(4000)
        if len(data) == 0:
            break
        if rec.AcceptWaveform(data):
            partial_res = json.loads(rec.Result())
            # if 'text' in partial_res.keys():
            #     all_text += partial_res['text']
            # print(partial_res)
        else:
            json.loads(rec.PartialResult())
    final_result = json.loads(rec.FinalResult())
    # is_final = all_text + final_result['text']
    return final_result['text']

def ogg_to_wav(ogg_full_path, wav_full_path):
    print('start converting ogg to wav')
    command = ['ffmpeg', '-i', ogg_full_path, '-ac', '1', '-f', 'wav', wav_full_path]
    subprocess.run(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    print('conversion finished')

def convert_and_get_text(file_ogg) -> str:
    # file_wav = convert_ogg2wav(file_ogg)
    file_wav = file_ogg + ".wav"
    ogg_to_wav(file_ogg, file_wav)
    text = get_text(path_wav=file_wav)
    return text

def send_request(text):
    api_host = "http://10.91.54.226:8000"
    endpoint = "/api/task/"
    res = requests.post(api_host + endpoint, data={"description": text})
    try:
        data = res.json()
    except JSONDecodeError:
        return "Внутренняя ошибка 😢 в сообщении от сервера"
    if not 'description' in data.keys() and not 'user_id' in data.keys():
        print("че происходит. пришел стремный ответ от сервера")
        print(data)
        return "Внутренняя ошибка 😢"
    if data['description'].startswith("Choosing department model cannot confidently define department to choose for"):
        return "Не смогли найти подходящий департамент. Мы перенаправили запрос человеку на рассмотрение"
    enpdpoint = f"/api/user/{data['user_id']}/"
    res_new = requests.get(api_host + enpdpoint)
    try:
        data_new = res_new.json()
    except JSONDecodeError:
        return "Внутренняя ошибка 😢 в сообщении от сервера"
    print(data_new)
    return f"Задача назначилась на сотрудника #{data_new['pk']}.\nИмя: {data_new['user']['first_name']} {data_new['user']['last_name']}\n" \
           f"Из департамента: {data_new['department']['name']}"


import pygame

#배경그림 설정값
screen = pygame.display.set_mode((700, 700))
bg_image1 = pygame.image.load("images/bg.jpg")
bg_image1 = pygame.transform.scale(bg_image1, (700,700))
bg_image2 = pygame.transform.flip(bg_image1, True, False)
bg_image3 = pygame.transform.flip(bg_image1, False, True) #처음그림 대칭시킨 그림
bg_image4 = pygame.transform.flip(bg_image1, True, True)

class Background:
    def __init__(self,screen):
        width, height = screen.get_size()
        self.image1 = bg_image1
        self.image2 = bg_image2
        self.image3 = bg_image3
        self.image4 = bg_image4

        self.pos1 = [0, 0]
        self.pos2 = [width, 0]
        self.pos3 = [0, height]
        self.pos4 = [width, height]
        self.pos5 = [-width, 0]
        self.pos6 = [0, -height]
        self.pos7 = [-width, -height]
        self.pos8 = [width, -height]
        self.pos9 = [-width, height]

        self.to = [0,0]
    #배경 이동
    def goto(self, x, y):
        self.to[0] += x
        self.to[1] += y

    #배경 이동속도 제어
    def update(self, dt, screen):
        width, height = screen.get_size()
        self.pos1[0] = (self.pos1[0] + dt * self.to[0] * 0.05)
        self.pos1[1] = (self.pos1[1] + dt * self.to[1] * 0.05)

        self.pos2[0] = (self.pos2[0] + dt * self.to[0] * 0.05)
        self.pos2[1] = (self.pos2[1] + dt * self.to[1] * 0.05)

        self.pos3[0] = (self.pos3[0] + dt * self.to[0] * 0.05)
        self.pos3[1] = (self.pos3[1] + dt * self.to[1] * 0.05)

        self.pos4[0] = (self.pos4[0] + dt * self.to[0] * 0.05)
        self.pos4[1] = (self.pos4[1] + dt * self.to[1] * 0.05)

        self.pos5[0] = (self.pos5[0] + dt * self.to[0] * 0.05)
        self.pos5[1] = (self.pos5[1] + dt * self.to[1] * 0.05)

        self.pos6[0] = (self.pos6[0] + dt * self.to[0] * 0.05)
        self.pos6[1] = (self.pos6[1] + dt * self.to[1] * 0.05)

        self.pos7[0] = (self.pos7[0] + dt * self.to[0] * 0.05)
        self.pos7[1] = (self.pos7[1] + dt * self.to[1] * 0.05)

        self.pos8[0] = (self.pos8[0] + dt * self.to[0] * 0.05)
        self.pos8[1] = (self.pos8[1] + dt * self.to[1] * 0.05)

        self.pos9[0] = (self.pos9[0] + dt * self.to[0] * 0.05)
        self.pos9[1] = (self.pos9[1] + dt * self.to[1] * 0.05)

Python Learning/[프로젝트] 총알 피하기 게임 Upgrade!/code/background.py


# LeetCode. Yandex Task List. 1493. Longest Subarray of 1's After Deleting One Element

'''

1493. Longest Subarray of 1's After Deleting One Element
Medium

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.

Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].

Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.

Example 4:

Input: nums = [1,1,0,0,1,1,1,0,1]
Output: 4

Example 5:

Input: nums = [0,0,0]
Output: 0

Constraints:

    1 <= nums.length <= 105
    nums[i] is either 0 or 1.

Accepted
30,851
Submissions
51,601

Related Topics
Math, Dynamic Programming, Sliding Window

Similar Questions
-

Hide Hint 1
Maintain a sliding window where there is at most one zero on it.

Intuition
There are only 3 cases that we need to take care of:
(1) only zeros in nums
(2) only ones in nums
(3) others

Complexity
Time O(N)
Space O(N)

Solution

def longestSubarray(self, nums: List[int]) -> int:
	# We get the group's key and length first, e.g. [0,1,1,1,0,1,1,0,1] -> [[0 , 1], [1, 3], [0, 1], [1, 2], [0, 1], [1, 1]]
	groupby = [ [k, len(list(i))] for k, i in itertools.groupby(nums)]

	if len(groupby) == 1:
		# case(1) only zeros in nums
		if groupby[0][0] == 0:
			return 0
		# case(2) only ones in nums
		elif groupby[0][0] == 1:
			return groupby[0][1] - 1
	else:
		# case(3) others
		res = max([times for i,times in groupby if i==1])
		for i in range(1, len(groupby)-1):
			# if both sides have ones and are separated by only 1 zero
			if groupby[i][0] == 0 and groupby[i][1] == 1:
				res = max(res, groupby[i-1][1] + groupby[i+1][1])
		return res

Similar Sliding Window Problems
1156. Swap For Longest Repeated Character Substring

'''

import math
import time
import collections
from typing import List
import numpy as np
import random as rnd
import itertools as it
from collections import defaultdict, Counter
import re
from functools import reduce
from functools import lru_cache
from bisect import bisect, bisect_left

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        subArrSizesList = list()
        firstSubArrSize = 0
        secondSubArrSize = 0
        n = len(nums)
        if nums.count(0) == 0:
            return n-1
        for i in range(0, n):
            if nums[i] != 0:
                firstSubArrSize += 1
            elif nums[i] == 0:
                for j in range(i+1, n):
                    if nums[j] != 0:
                        secondSubArrSize += 1
                    else:
                        break
                subArrSizesList.append(firstSubArrSize + secondSubArrSize)
                firstSubArrSize = 0
                secondSubArrSize = 0
        return max(subArrSizesList)

if __name__ == "__main__":
    #
    start = time.perf_counter()
    solution = Solution()
    print(solution.twoSum(nums = [2 ,7 ,11 ,15], target = 9))
    end = time.perf_counter()
    print(f"test 1: {end - start:10.6f} sec")
    #
    start2 = time.perf_counter()
    print(solution.twoSum(nums = [3 ,2 ,4], target = 6))
    end2 = time.perf_counter()
    print(f"test 2: {end2 - start2:10.6f} sec")
    #
    start3 = time.perf_counter()
    print(solution.twoSum(nums = [3 ,3], target = 6))
    end3 = time.perf_counter()
    print(f"test 3: {end3 - start3:10.6f} sec")
    #
    start4 = time.perf_counter()
    print(solution.isIsomorphic("badc", "baba"))
    end4 = time.perf_counter()
    print(f"test 4: {end4 - start4:10.6f} sec")
    #
    start5 = time.perf_counter()
    print(solution.isIsomorphic("abab", "baba"))
    end5 = time.perf_counter()
    print(f"test 5: {end5 - start5:10.6f} sec")
    #
    start6 = time.perf_counter()
    print(solution.firstMissingPositive([1, 1]))
    end6 = time.perf_counter()
    print(f"test 6: {end6 - start6:10.6f} sec")


import sys
input = sys.stdin.readline

N = int(input())
data = [int(input()) for _ in range(N)]
answer = 0
'''
a, b 포인트
전체 길이의 합에 절반이 bast **
부분집합으로 best와 근사하는 값 찾기
'''
sumd = sum(data)
best = sum(data) / 2
s, e = 0, 1
stack = data[0]

while e <= len(data):
    if stack <= best:
        e += 1
        if e > len(data):
            break
        stack += data[e-1]
    else:
        answer = max(min(stack, sumd-stack), answer)
        stack -= data[e-1]
        answer = max(min(stack, sumd-stack), answer)
        s += 1
        stack += data[e-1] - data[s-1]
        #answer = max(min(stack, sumd-stack), answer)

print(answer)


from __future__ import unicode_literals

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models

from django_changeset.models.mixins import RevisionModelMixin

def forwards_func(apps, schema_editor):
    RevisionModelMixin.set_enabled(False)
    db_alias = schema_editor.connection.alias

    User = apps.get_model('auth', 'User')
    Task = apps.get_model('projects', 'Task')
    TaskAssignedUser = apps.get_model('projects', 'TaskAssignedUser')

    # iterate over all tasks
    for task in Task.objects.using(db_alias).all():
        TaskAssignedUser.objects.using(db_alias).create(
            task=task,
            assigned_user=task.assigned_user
        )

    RevisionModelMixin.set_enabled(True)

def reverse_func(apps, schema_editor):
    db_alias = schema_editor.connection.alias

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('projects', '0056_task_assigned_users'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]


#Asal Sayı: kendinden ve 1'den başka sayıya kalansız bölünemiyorsa sayı asaldır.
#Girilen sayının asal olupup olmadığını bulan uygulama
#sayıyı al
#Bölen sayi, girilen sayının bir küçüğü olana kadar
#girilen sayı bölen sayıya kalansız bölmeye bakılır

print('Bir sayı giriniz')
girilen_sayi=int(input())
bolen_sayi=2
asal_mi=True

while bolen_sayi<girilen_sayi:
    if girilen_sayi % bolen_sayi == 0:
        asal_mi = False
        break
    bolen_sayi +=1
if asal_mi==True:
    print(girilen_sayi, 'asaldır.')
else:
    print(girilen_sayi,'asal değildir.')


from fractions import Fraction as fract

def solution(pegs):
    print("solution_final -> pegs: ", pegs)
    lenPegs = len(pegs)
    if (lenPegs < 2):
        return [-1, -1]

    isEven = True if (lenPegs % 2 == 0) else False
    x = (- pegs[0] + pegs[lenPegs -1]) if isEven else (- pegs[0] - pegs[lenPegs - 1])

    if (lenPegs > 2):
        for i in range(1, lenPegs - 1):
            x += 2 * (-1)**(i+1) * pegs[i]

    G = []
    G.append(fract(2 * (float(x)/3 if isEven else x)).limit_denominator())
    radius = G[0]

    if ((radius / 2 > (pegs[-1] - pegs[-2])) or (radius < 2)):
        return [-1, -1]

    for index in range(0, lenPegs - 1):
            dist = pegs[index + 1] - pegs[index]
            nextRadius = fract(dist - radius).limit_denominator()
            if (radius < 1 or nextRadius < 1):
                return [-1, -1]
            else:
                radius = nextRadius
                G.append(radius)

    return [G[0].numerator, G[0].denominator]

def solution2(pegs):
    print("solution2 -> pegs: ", pegs)
    lenPegs = len(pegs)
    if (lenPegs < 2):
        return [-1, -1]

    isEven = True if (lenPegs % 2 == 0) else False
    x = (- pegs[0] + pegs[lenPegs -1]) if isEven else (- pegs[0] - pegs[lenPegs - 1])

    if (lenPegs > 2):
        for i in range(1, lenPegs - 1):
            x += 2 * (-1)**(i+1) * pegs[i]

    G = []
    G.append(fract(2 * (float(x)/3 if isEven else x)).limit_denominator())

    radius = G[0]
    for index in range(0, lenPegs - 2):
            dist = pegs[index + 1] - pegs[index]
            nextRadius = dist - radius
            if (radius < 1 or nextRadius < 1):
                return [-1, -1]
            else:
                radius = nextRadius

    return [G[0].numerator, G[0].denominator]

def solution1(pegs):
    print("solution1 -> pegs: ", pegs)
    lenP = len(pegs)

    if ((not pegs) or lenP == 1):
        return [-1, -1]

    a = pegs[0]
    gradient = -1
    for peg in pegs:
        a += 2 * peg * gradient
        gradient *= -1
    a += pegs[lenP - 1] * gradient
    a *= 2
    b = 3 if (lenP % 2 == 0) else 1

    if ((b == 3) and (a % b == 0)):
        a /= b
        b = 1

    prevRadius = float(float(a) / float(b))
    for i in range(0, lenP - 2):
        w = int(pegs[i+1] - pegs[i])
        if ((prevRadius < 1) or (prevRadius > (w - 1))):
            return [-1, -1]

    return [int(a), int(b)]

from random import sample

assert((solution([4, 30, 50])) == [12, 1])
print(solution([1, 11]))
print(solution([4.5, 30.5, 50.5]))
print(solution([10, 50.77, 70, 90.5, 115, 150]))
print(solution([4, 9, 17, 31, 40]))
print(solution([4, 30, 50]))
assert((solution1([4, 30, 50])) == [12, 1])
print(solution1([1, 11]))
print(solution1([4.5, 30.5, 50.5]))
print(solution1([10, 50.77, 70, 90.5, 115, 150]))
print(solution1([4, 9, 17, 31, 40]))
print(solution1([4, 30, 50]))
assert((solution2([4, 30, 50])) == [12, 1])
print(solution2([1, 11]))
print(solution2([4.5, 30.5, 50.5]))
print(solution2([10, 50.77, 70, 90.5, 115, 150]))
print(solution2([4, 9, 17, 31, 40]))
print(solution2([4, 30, 50]))

for i in range(1, 150):
    a = sample([x for x in range(1, 10000)], k=(sample([x for x in range(2, 21)], k=1)[0]))
    a.sort()
    print(solution(a))
    print(solution1(a))
    print(solution2(a))

gearing up for destruction/test-solution5.py


#1.	По двум заданным числам проверить является ли одно квадратом второго
a =int(input( 'Введите a = '   ))
b =int(input( 'Введите b = '   ))
c=a**2

if b==c:
    print('число a является квадратом b')
else:
    print('число a не  является квадратом b')
c=b**2

if c==a:
    print('число b является квадратом a')
else:
    print('число b не  является квадратом a')


import re

location = "./data/Sanskrit-English/en-sa.en.bped"
req = open(location, 'r', encoding="utf-8").read()

#req = [re.sub(r'\(.*\)', '', line.rstrip()) for line in file]

text = re.sub('<[^<]+>', "", req)
text1=text.split('\n')[:-1]
non_empty_lines = text1#[line for line in text1 if line.strip() != ""]
print(len(text1))
#text1=""
article=""
list1=text1
#for i in range(len(non_empty_lines)):
#    ans=non_empty_lines[i]
#    article = re.sub(r'\([^)]*\)', r'', ans)
#    article = re.sub(r'\[[^\]]*\]', r'', article)
#    article = re.sub(r'<[^>]*>', r'', article)
#    article = re.sub(r'^https?:\/\/.*[\r\n]*', '', article)
#    article = article.replace(u'\ufeff','')
#    article = article.replace(u'\xa0', u' ')
#    article = article.replace('  ', ' ')
#    article = article.replace(' , ', ', ')
#
#    text1+=article+'\n'
#    article = re.sub('[0-9]', '', article)
#    list1.append(article.lstrip())

#print(data[:100])

train = list1[:int(0.85*len(list1))]
valid = list1[int(0.85*len(list1)) + 1: int(0.9*len(list1))]
test = list1[int(0.9*len(list1)) + 1:]

print(len(train), len(valid), len(test))

def write(file, data):
    with open(file, 'w', encoding="utf-8") as f:
        for item in data:
            f.write("%s\n" % item)

write("data/en-sa.en.train", train)
write("data/en-sa.en.valid", valid)
write("data/en-sa.en.test", test)
#write("en-sa.en.all", list1)


from rest_framework.permissions import BasePermission, SAFE_METHODS
from core.utils import response_payload

class IsAdmin(BasePermission):
    message = response_payload(
        success=False,
        message="Only admins can perform this action",
    )

    def has_permission(self, request, view):
        return request.user.is_superuser

class IsTeacher(BasePermission):
    message = response_payload(
        success=False,
        message="Only teachers can perform this action",
    )

    def has_permission(self, request, view):
        return request.user.role == 'teacher'

class IsTeacherOfThisClassroom(BasePermission):
    message = response_payload(
        success=False,
        message="Only teachers of this classroom can perform this action",
    )

    def has_permission(self, request, view):
        classroom_id = view.kwargs['classroom_id']
        # This works because of the related_name='classrooms' in Classroom model.
        # Only teacher has 'classrooms' attribute, not the students.
        return request.user.classrooms.filter(classroom_id=classroom_id).exists()

class IsStudent(BasePermission):
    message = response_payload(
        success=False,
        message="Only students can perform this action",
    )

    def has_permission(self, request, view):
        return request.user.role == 'student'

class IsStudentOfThisClassroom(BasePermission):
    message = response_payload(
        success=False,
        message="Only students of this classroom can perform this action",
    )

    def has_permission(self, request, view):
        classroom_id = view.kwargs['classroom_id']
        # This works because of the related_name='enrollments' in Enrollment model.
        # Only student has 'enrollments' attribute, not the teachers.
        return request.user.enrollments.filter(classroom_id=classroom_id).exists()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.urls import re_path as url
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import response
from django.test import RequestFactory
from django.test.utils import override_settings
import six
from six.moves.urllib.parse import parse_qsl, urlparse

from ..models import WeChatUser
from ..oauth import (WeChatAuthenticated, wechat_auth, WeChatSNSScope,
                     WeChatOAuthClient, WeChatOAuthView)
from .base import mock, WeChatTestCase
from .interceptors import common_interceptor

def oauth_api(openid, callback=None):
    kwargs = dict(
        netloc=r"(.*\.)?api\.weixin\.qq\.com$",
        path="/sns/oauth2/access_token"
    )

    def mock(url, request):
        headers = {
            "Content-Type": "application/json"
        }
        data = dict(
            access_token="123",
            refresh_token="123",
            expires_in=7200,
            openid=openid
        )
        from httmock import response
        resp = response(200, data, headers)
        if callback:
            callback(url, request, resp)
        return resp

    return common_interceptor(mock, **kwargs)

def snsinfo_api(openid, callback=None, **data):
    kwargs = dict(
        netloc=r"(.*\.)?api\.weixin\.qq\.com$",
        path="/sns/userinfo"
    )

    def mock(url, request):
        headers = {
            "Content-Type": "application/json"
        }
        from httmock import response
        resp = response(200, data, headers)
        if callback:
            callback(url, request, resp)
        return resp

    return common_interceptor(mock, **kwargs)

@wechat_auth("test", state="state")
def test_oauth_view(request, *args):
    user = request.wechat.user
    return dict(
        openid=user.openid,
        id=user.id,
        args=args
    )

urlpatterns = [
    url(r"^test/(.+)$", test_oauth_view)
]

@override_settings(ROOT_URLCONF=__name__)
class OAuthTestCase(WeChatTestCase):
    def test_oauth_api(self):
        """测试oauth接口请求"""
        pass

    def test_redirect_uri(self):
        """测试redirect_uri生成"""
        host = "example.com"
        rf = self.rf(HTTP_HOST=host)
        api = "/app"
        absolute_uri = lambda uri: "http://" + host + uri

        # 测试写入redirect_uri时
        redirect_uri = "https://mp.weixin.qq.com/wiki"
        view_cls = WeChatOAuthView(
            appname=self.app.name, redirect_uri=redirect_uri)
        request = rf.get(api)
        SessionMiddleware().process_request(request)
        view_cls.setup(request)
        request = view_cls.initialize_request(request)
        self.assertEqual(request.wechat.redirect_uri, redirect_uri)

        redirect_uri = "/app"
        view_cls = WeChatOAuthView(
            appname=self.app.name, redirect_uri=redirect_uri)
        request = rf.get(api)
        SessionMiddleware().process_request(request)
        view_cls.setup(request)
        request = view_cls.initialize_request(request)
        self.assertEqual(request.wechat.redirect_uri,
                         absolute_uri(redirect_uri))

        # 测试模板请求redirect_uri
        view_cls = WeChatOAuthView(appname=self.app.name)
        request = rf.get(redirect_uri)
        SessionMiddleware().process_request(request)
        view_cls.setup(request)
        request = view_cls.initialize_request(request)
        self.assertEqual(request.wechat.redirect_uri,
                         absolute_uri(redirect_uri))

        # 测试ajax请求redirect_uri
        view_cls = WeChatOAuthView(appname=self.app.name)
        request = rf.post(api, dict(a=1),
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
            HTTP_REFERRER=absolute_uri(redirect_uri))
        SessionMiddleware().process_request(request)
        view_cls.setup(request)
        request = view_cls.initialize_request(request)
        self.assertEqual(request.wechat.redirect_uri,
                         absolute_uri(redirect_uri))

        # 测试callable redirect_uri
        callable_redirect = lambda request, *args, **kwargs: redirect_uri
        view_cls = WeChatOAuthView(appname=self.app.name,
                                   redirect_uri=callable_redirect)
        request = rf.get(redirect_uri)
        SessionMiddleware().process_request(request)
        view_cls.setup(request)
        request = view_cls.initialize_request(request)
        self.assertEqual(request.wechat.redirect_uri,
                         absolute_uri(redirect_uri))

    def test_unauthorization(self):
        rf = RequestFactory()
        path = "/test"
        redirect_uri = "https://mp.weixin.qq.com/wiki"

        # 默认response
        state = "abc"
        request = rf.get(path)
        handler = self._make_handler(
            request, redirect_uri=redirect_uri,
            scope=WeChatSNSScope.USERINFO, state=state)
        request = handler.initialize_request(request)
        resp = handler.unauthorization_response(request)
        self.assertIsInstance(resp, response.HttpResponseRedirect)
        client = WeChatOAuthClient(self.app)
        self.assertEqual(resp.url, client.authorize_url(
            redirect_uri, WeChatSNSScope.USERINFO, state))

        # 传入callable state
        state = lambda request: request.path
        request = rf.get(path)
        handler = self._make_handler(
            request, redirect_uri=redirect_uri,
            scope=WeChatSNSScope.USERINFO, state=state)
        request = handler.initialize_request(request)
        resp = handler.unauthorization_response(request)
        self.assertIsInstance(resp, response.HttpResponseRedirect)
        client = WeChatOAuthClient(self.app)
        self.assertEqual(resp.url, client.authorize_url(
            redirect_uri, WeChatSNSScope.USERINFO, path))

        # 传入callback response
        resp = response.HttpResponseForbidden()
        request = rf.get(path)
        handler = self._make_handler(request, response=resp)
        request = handler.initialize_request(request)
        self.assertIs(
            resp,
            handler.unauthorization_response(request)
        )

        # 传入普通response
        resp_func = lambda request: response.HttpResponseForbidden(request.path)
        request = rf.get(path)
        handler = self._make_handler(request, response=resp_func)
        request = handler.initialize_request(request)
        resp = handler.unauthorization_response(request)
        self.assertIsInstance(resp, response.HttpResponseForbidden)
        self.assertEqual(resp.content, path.encode())

    def test_user_update(self):
        "测试更新授权数据"
        pass

    def test_request(self):
        "测试请求"
        redirect_uri = "https://mp.weixin.qq.com/wiki"
        url = "/test"
        request = self._create_request(url)

        # 设置了response
        resp = response.HttpResponseForbidden()
        handler = self._make_handler(
            request, redirect_uri=redirect_uri, response=resp)
        self.assertIs(handler.dispatch(request), resp)

        # 未授权
        handler = self._make_handler(request, redirect_uri=redirect_uri)
        resp = handler.dispatch(request)
        self.assertIsInstance(resp, response.HttpResponseRedirect)
        self.assertEqual(resp.url, request.wechat.oauth_uri)

        # 授权
        request = self._create_request(url + "?code=123")
        openid = "456"
        view = lambda request, *args, **kwargs: request.wechat.openid
        handler = self._make_handler(request, view=view)
        with oauth_api(openid):
            resp = handler.dispatch(request)
            self.assertEqual(resp.content, openid.encode())

        # 已授权
        session_key = "sessionid"
        resp = SessionMiddleware().process_response(request, resp)
        request = self._create_request(url + "?code=123")
        request.COOKIES[session_key] = resp.cookies[session_key].value
        resp = handler.dispatch(request)
        self.assertEqual(resp.content, openid.encode())

    def test_decorator(self):
        """测试class based view与decorator是否一致"""
        openid = "test_decorator"
        user = WeChatUser.objects.upsert_by_dict(
            dict(openid=openid), app=self.app)
        session_key = "wechat_{0}_user".format(self.app.name)

        view = lambda request: request
        # 测试appname
        wrapped_view = wechat_auth(self.app.name)(view)
        request = self._create_request("/")
        request.session[session_key] = openid
        self.assertEqual(wrapped_view(request).wechat.appname, self.app.name)

        # 测试scope
        wrapped_view = wechat_auth(
            self.app.name, scope=WeChatSNSScope.USERINFO)(view)
        request = self._create_request("/")
        request.session[session_key] = openid
        self.assertIn(WeChatSNSScope.USERINFO, wrapped_view(request).wechat.scope)

        # 测试redirect_uri
        redirect_uri = "https://www.baidu.com/"
        wrapped_view = wechat_auth(
            self.app.name, redirect_uri=redirect_uri)(view)
        request = self._create_request("/")
        request.session[session_key] = openid
        self.assertEqual(wrapped_view(request).wechat.redirect_uri, redirect_uri)

        # 测试required
        wrapped_view = wechat_auth(self.app.name, required=False)(view)
        request = self._create_request("/")
        self.assertEqual(wrapped_view(request), request)

        # 测试默认required及response
        resp = response.HttpResponse()
        wrapped_view = wechat_auth(self.app.name, response=resp)(view)
        request = self._create_request("/")
        self.assertEqual(wrapped_view(request), resp)

        # 测试state
        state = "abc"
        wrapped_view = wechat_auth(
            self.app.name, state=state)(view)
        request = self._create_request("/")
        request.session[session_key] = openid
        self.assertEqual(wrapped_view(request).wechat.state, state)

        # 测试methods
        request_get = self._create_request("/")
        request_get.session[session_key] = openid
        request_post = self._create_request("/", "post")
        request_post.session[session_key] = openid

        # 测试仅get
        view = lambda request: resp
        wrapped_view = wechat_auth(self.app.name)(view)
        self.assertEqual(wrapped_view(request_get), resp)
        self.assertIsInstance(wrapped_view(request_post),
                              response.HttpResponseNotAllowed)

        # 测试仅post
        wrapped_view = wechat_auth(self.app.name, methods=["POST"])(view)
        self.assertIsInstance(wrapped_view(request_get),
                              response.HttpResponseNotAllowed)
        self.assertEqual(wrapped_view(request_post), resp)

    def test_view(self):
        """测试view是否正常"""
        args = "t"
        openid = "666"
        host = "example.com"
        path = "/test/" + args

        resp = self.client.get(path, HTTP_HOST="example.com")
        self.assertEqual(resp.status_code, 302)
        parsed_url = urlparse(resp.url)
        self.assertEqual(parsed_url.netloc, "open.weixin.qq.com")
        query = dict(parse_qsl(parsed_url.query))
        self.assertEqual(query["appid"], self.app.appid)
        self.assertEqual(query["response_type"], "code")
        self.assertEqual(query["scope"], WeChatSNSScope.BASE)
        self.assertEqual(query["state"], "state")
        self.assertEqual(parsed_url.fragment, "wechat_redirect")
        self.assertEqual(query["redirect_uri"], "http://" + host + path)

        with oauth_api(openid):
            resp = self.client.get(path + "?code=123", follow=True,
                HTTP_HOST=host)
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content.decode())
        self.assertEqual(data["openid"], openid)
        self.assertEqual(data["args"], [args])
        id = data["id"]
        user = WeChatUser.objects.get(id=id)
        self.assertEqual(user.openid, openid)

    def test_custom_oauth_url(self):
        """测试设置了OAUTH_URL url后 不再向微信请求授权,转向第三方请求授权"""
        with mock.patch.object(WeChatOAuthClient, "authorize_url"):
            new_url = "new_url"
            self.app.configurations["OAUTH_URL"] = new_url
            hasattr(self.app, "_oauth") and delattr(self.app, "_oauth")
            url = self.app.oauth.authorize_url("redirect_url")
            self.assertTrue(url.startswith(new_url))
            delattr(self.app, "_oauth")
            del self.app.configurations["OAUTH_URL"]

    def _make_handler(self, request, appname="", **kwargs):
        view = kwargs.pop("view", lambda request, *args, **kwargs: "")
        appname = appname or self.app.name
        scope = kwargs.get("scope")
        if scope and isinstance(scope, six.text_type):
            kwargs["scope"] = (scope,)
        cls = type(str("WeChatOAuthView"), (WeChatOAuthView,), dict())
        kwargs = cls.prepare_init_kwargs(appname=appname, **kwargs)
        rv = cls(**kwargs)
        rv.setup(request)
        rv.get = view
        return rv

    def _create_request(self, path, method="get"):
        request = getattr(self.rf(), method)(path)
        SessionMiddleware().process_request(request)
        return request


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

# ## Data Exploration

# In[ ]:

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

# In[ ]:

rawData = pd.read_csv("../../../input/aljarah_xAPI-Edu-Data/xAPI-Edu-Data.csv")

# In[ ]:

rawData.tail().T

# In[ ]:

rawData.columns

# In[ ]:

rawData.info()

# In[ ]:

import numpy as np

np.where(pd.isnull(rawData))

# In[ ]:

rawData.describe()

# ###  Catagorical variables

# In[ ]:

cat_Vars = ['gender', 'NationalITy', 'PlaceofBirth', 'StageID','Relation', 'GradeID', 'Topic', 'Semester', 'StudentAbsenceDays']

# In[ ]:

fig = plt.figure(figsize=(20, 30))
fig.subplots_adjust(hspace=.3, wspace=0.2)

for i in range(1,len(cat_Vars)+1,1):
    ax = fig.add_subplot(5, 2, i,)
    sns.countplot(rawData[cat_Vars[i-1]])
    ax.xaxis.label.set_size(20)
    plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    total = float(len(rawData))
    for p in ax.patches:
        height = p.get_height()
        ax.text(p.get_x()+p.get_width()/2.,height + 5,'{:1.1f}%'.format(100 * height/total),ha="center")

# #### Based on the the above plots several observations can be made:
#     -Majority of students are male
#     -Most of the students are from either Kuwait or Jordan
#     -Majority of students are middleschool or lower

# ### Numerical Variables

# In[ ]:

num_Vars = [ 'raisedhands','VisITedResources', 'AnnouncementsView', 'Discussion', 'Class']

# fig = plt.figure(figsize=(10, 10))
# for i in range(1,len(num_Vars)+1,1):
#     ax = fig.add_subplot(2, 2, i)
#     sns.distplot(rawData[num_Vars[i-1]],kde= None)

# In[ ]:

# In general these features represent the level of student particapation in their respective courses.
# Cleary the students with low grades tend to have lower level of class particapation.

# ## Lets try to figure out which feauters are most important (if any) for predicting students' academic perfomance.

# Lets predict student perfomance using scikit random forest classifier

# In[ ]:

target = rawData.pop('Class') # target

# Drop the features not relevant to the student perfomance
rawData.drop(rawData[['ParentAnsweringSurvey', 'ParentschoolSatisfaction']], axis=1, inplace=True)

X = pd.get_dummies(rawData) # get numeric dummy variables for categorical data

# In[ ]:

from sklearn import preprocessing

le = preprocessing.LabelEncoder()
y = le.fit_transform(target) # encode target labels with a value

# In[ ]:

from sklearn.cross_validation import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.40) # split data set into train and set
X_train.shape, X_test.shape

# ### Cross-Validation to determine the best model parameter values

# In[ ]:

from sklearn.grid_search import GridSearchCV
from sklearn.ensemble import RandomForestClassifier

rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=50, oob_score = True)

param_grid ={'n_estimators': [50, 100, 200],'max_features': ['auto', 'sqrt', 'log2'],'min_samples_leaf' : [1, 5,10, 50],}

CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5, refit=True)
CV_rfc.fit(X_train, y_train)
CV_rfc.best_params_

# In[ ]:

#CV_rfc.grid_scores_

# ### Use best fit model parameters to make predictions on test set

# In[ ]:

from sklearn.metrics import accuracy_score

rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=100, oob_score = True)
rfc.fit(X_train, y_train)
pred = rfc.predict(X_test)
accuracy_score(y_test, pred)

# ### Plot feature importance

# In[ ]:

feature_importance = pd.DataFrame(rfc.feature_importances_, index=X_train.columns, columns=["Importance"])
feature_importance.head(8)

# In[ ]:

feature_importance.sort('Importance', ascending=False, inplace=True)

# In[ ]:

fig = plt.figure(figsize=(25, 10))
ax = sns.barplot(feature_importance.index, feature_importance['Importance'])
fig.add_axes(ax)
plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')[1]

# ### Quick test with xgboost classifier

# In[ ]:

import xgboost as xgb

xg_train = xgb.DMatrix(X_train, label=y_train)
xg_test = xgb.DMatrix(X_test, label=y_test)

# In[ ]:

param = {}

# use softmax multi-class classification
param['objective'] = 'multi:softmax'

# set xgboost parameter values
param['eta'] = 0.1
param['max_depth'] = 9
param['silent'] = 1
param['nthread'] = 3
param['num_class'] = 3

num_round = 100
bst = xgb.train(param, xg_train, num_round)

# get prediction
pred = bst.predict( xg_test ).astype(int)
accuracy_score(y_test, pred)

# In[ ]:

xgb.plot_importance(bst, height=0.5)

# The features related to the student participation in the class are important in accurate prediction of the student
# performance in any given course. (This is specific to the data set and the model we are using in this analysis.)
# This can be further tested by studying the variation in acuracy obtained by removing the important featues one by one from the model.

# In[ ]:


import numpy as np
import time
import sys
from pathlib import Path
import logging
import os

class Logger(object):
    def __init__(self, outfile):
        self.terminal = sys.stdout
        self.log = open(outfile, "w")
        sys.stdout = self

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        self.terminal.flush()

class AverageMeter:
    def __init__(self, *keys):
        self.__data = dict()
        for k in keys:
            self.__data[k] = [0.0, 0]

    def add(self, dict):
        for k, v in dict.items():
            if k not in self.__data:
                self.__data[k] = [0.0, 0]
            self.__data[k][0] += v
            self.__data[k][1] += 1

    def get(self, *keys):
        if len(keys) == 1:
            return self.__data[keys[0]][0] / self.__data[keys[0]][1]
        else:
            v_list = [self.__data[k][0] / self.__data[k][1] for k in keys]
            return tuple(v_list)

    def pop(self, key=None):
        if key is None:
            for k in self.__data.keys():
                self.__data[k] = [0.0, 0]
        else:
            v = self.get(key)
            self.__data[key] = [0.0, 0]
            return v

class Timer:
    def __init__(self, starting_msg = None):
        self.start = time.time()
        self.stage_start = self.start

        if starting_msg is not None:
            print(starting_msg, time.ctime(time.time()))

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return

    def update_progress(self, progress):
        self.elapsed = time.time() - self.start
        self.est_total = self.elapsed / progress
        self.est_remaining = self.est_total - self.elapsed
        self.est_finish = int(self.start + self.est_total)

    def str_estimated_complete(self):
        return str(time.ctime(self.est_finish))

    def get_stage_elapsed(self):
        return time.time() - self.stage_start

    def reset_stage(self):
        self.stage_start = time.time()

    def lapse(self):
        out = time.time() - self.stage_start
        self.stage_start = time.time()
        return out

def to_one_hot(sparse_integers, maximum_val=None, dtype=np.bool):

    if maximum_val is None:
        maximum_val = np.max(sparse_integers) + 1

    src_shape = sparse_integers.shape

    flat_src = np.reshape(sparse_integers, [-1])
    src_size = flat_src.shape[0]

    one_hot = np.zeros((maximum_val, src_size), dtype)
    one_hot[flat_src, np.arange(src_size)] = 1

    one_hot = np.reshape(one_hot, [maximum_val] + list(src_shape))

    return one_hot

def create_logger(args, root_output_dir='outputs', log_output_dir='logs'):
    root_output_dir = Path(root_output_dir)
    # set up logger
    if not root_output_dir.exists():
        print('=> creating {}'.format(root_output_dir))
        root_output_dir.mkdir()

    final_output_dir = root_output_dir /\
                       '{}_{}'.format(args.cam_network.split('.')[-1], args.irn_network.split('.')[-1])

    print('=> creating {}'.format(final_output_dir))
    final_output_dir.mkdir(parents=True, exist_ok=True)

    time_str = time.strftime('%Y-%m-%d-%H-%M')

    tensorboard_log_dir = Path(log_output_dir) / \
                          '{}_{}'.format(args.cam_network.split('.')[-1], args.irn_network.split('.')[-1]) / \
                          time_str
    print('=> creating {}'.format(tensorboard_log_dir))
    tensorboard_log_dir.mkdir(parents=True, exist_ok=True)

    args.log_name = str(tensorboard_log_dir)

    cam_weight_path = final_output_dir / Path('cam_weight.pth')
    args.cam_weights_name = str(cam_weight_path)
    aff_weight_path = final_output_dir / Path('aff_weight.pth')
    args.irn_weights_name = str(aff_weight_path)
    args.cam_out_dir = str(final_output_dir / Path('cam'))
    args.ir_label_out_dir = str(final_output_dir / Path('aff_label'))
    args.sem_seg_out_dir = str(final_output_dir / Path('sem_seg'))
    args.ins_seg_out_dir = str(final_output_dir / Path('ins_seg'))
    os.makedirs(args.cam_out_dir, exist_ok=True)
    os.makedirs(args.ir_label_out_dir, exist_ok=True)
    os.makedirs(args.sem_seg_out_dir, exist_ok=True)
    os.makedirs(args.ins_seg_out_dir, exist_ok=True)


# -*- coding:utf -8 -*-

from termcolor import colored
import socket

def fanc1():
    color_a = colored("[+] ", 'green')
    print("~"*50)
    host = input(color_a + "Host --> ")
    port = int(input(color_a + "Port --> "))
    print("~"*50)

    scan = socket.socket()

    color_b = colored("[!] ", 'red')
    color_c = colored("[!] ", 'yellow')

    try:
        scan.connect((host, port))
    except socket.error:
        print(color_b + "Port -- ", port, " -- [CLOSED]")
    else:
        print(color_c + "Port -- ", port, " -- [OPEN]")

def fanc2():
    color_a = colored("[+] ", 'green')
    color_b = colored("[!] ", 'red')
    color_c = colored("[!] ", 'yellow')

    host = input(color_a + "Host --> ")
    print("\n")
    port = []

    for i in port:
        try:
            scan = socket.socket()
            scan.settimeout(0.5)
            scan.connect((host, i))
        except socket.error:
            print(color_b + "Port -- ", i, " -- [CLOSED]")
        else:
            print(color_c + "Port -- ", i, " -- [OPEN]")

print("~"*50)

print("\t[1] --- сканировать отделный порт")
print("\t[2] --- сканировать список")

print("~"*50, "\n")
text_a = input("[scan]--> ")

if text_a == "1":
    fanc1()
elif text_a == "2":
    fanc2()
else:
    print(colored("Параметр введен не правильно!", 'red'))


import cv2
import numpy as np

cap = cv2.VideoCapture(0)
screen = np.zeros((800, 800, 3), np.uint8)

while True:
    re, frame = cap.read()
    frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
    screen[0:480, 0:640] = frame

    cv2.imshow('screen', screen)
    cv2.imshow('frame', frame)
    print(type(frame[0, 0][0]))
    print(cv2.getWindowProperty('screen', cv2.WND_PROP_VISIBLE))
    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cv2.destroyAllWindows()
cap.release()


import os
from app.environment import load_environment
mode = os.getenv('MODE','staging')
load_environment(mode)

from fastapi import FastAPI, Depends
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.responses import HTMLResponse, JSONResponse

from typing import Optional , List
from enum import Enum
import datetime
import boto3
import json
from sqlalchemy.exc import IntegrityError

from app.controllers.scrapping import return_sites_from_db, get_listings_and_save_results, scrape_listings_and_save_results, get_sites_by_state
from app.controllers.scrapping import scrape_listings_and_save_results_concurrent, scrape_listings_and_save_results_concurrentV2
from app.scraping.craigslist import return_sites_for_state, return_results_for

from app.constants import SupportedStates

#db set up
# Dependency
from . import crud, models, schemas
from .database import SessionLocal, engine
from sqlalchemy.orm import Session

#doubt this should be here
#models.Base.metadata.create_all(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

from app.authentication import authenticate_user

app = FastAPI(docs_url=None, redoc_url=None, openapi_url = None, dependencies=[Depends(authenticate_user)])

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.get('/health_check')
async def health_check():
    return {'status': 'ok'}

@app.get('/sites/{state}')
async def return_sites(state: SupportedStates, db: Session = Depends(get_db)):
    sites = return_sites_from_db(state, models, db)
    return sites

@app.post('/sites/{state}')
async def get_sites(state: SupportedStates, all_states: bool = False, save: bool = False, db: Session = Depends(get_db)):
    if all_states:
        print('getting and saving all states')
        results = []
        for state in SupportedStates:
            result = get_sites_by_state(state, True, models, db)
            results.append(result)
        return results
    results = get_sites_by_state(state, save, models, db)
    return results

@app.get('/results_cars_and_trucks/')
async def get_results_for( site:str,search_term: Optional[str]=None, limit: int = 10):
    print('in get results for')
    results = return_results_for(search_term, site)
    return { 'total': len(results) , 'results': results[:limit]}

@app.post('/save_results/results_cars_and_trucks/')
async def save_results_for(site:str,search_term: Optional[str] = None,
                            get_all_states = Optional[bool], states: Optional[str] = None,
                            db: Session = Depends(get_db)):
    if get_all_states:
        results = []
        if states:
            states = states.split(',')
        else:
            print('getting all states')
            states = SupportedStates
        for state in states:
            print('getting results for state', state)
            sites = return_sites_from_db(state, models, db)
            sites = [site[1][8:] if site[1].startswith('https://') else site[1] for site in sites]
            for site in sites:
                result = get_listings_and_save_results(search_term, site, models, db)
                results.append(result)
        return results
    return get_listings_and_save_results(search_term, site, models, db)

@app.get('/process_listings')
async def process_listings(limit: int, db: Session = Depends(get_db)):
    return scrape_listings_and_save_results(limit, models, db)

@app.get('/process_listings_concurrent')
async def process_listings_concurrent(limit: int, db: Session = Depends(get_db)):
    return scrape_listings_and_save_results_concurrent(limit, models, db)

@app.get('/process_listings_concurrentV2')
async def process_listings_concurrent(limit: int, db: Session = Depends(get_db)):
    return scrape_listings_and_save_results_concurrentV2(limit, models, db)

@app.get("/docs", include_in_schema=False)
async def overridden_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url="/openapi.json", title="Customized docs"
    )

@app.get("/openapi.json", include_in_schema=False)
async def overridden_openapi():
    openapi_schema = get_openapi(
        title="Custom API",
        version="1.0.0",
        description="This is a custom OpenAPI schema",
        routes=app.routes,
    )
    return JSONResponse(openapi_schema)


import socket
import json
import rsa
from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")

UDP_IP = "127.0.0.1"
UDP_PORT = 5005

pesan = input("Masukkan Pesan Anda \t: ")

print(f"Target IP \t\t: {UDP_IP}")
print(f"Target Port \t\t: {UDP_PORT}")
# print(f"Pesan \t\t\t: {pesan}")

# Membuat Socket UDP
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
msg = {
    "user" : "Josua",
    "pesan" : pesan,
    "waktu"  : current_time
    }

x = "Halooo"

publicKey, privateKey = rsa.newkeys(512)

encMsg = rsa.encrypt(x.encode(), publicKey)
print(f"Pesan \t\t\t: {encMsg}")
# Mengirim pesan ke server
sock.sendto(encMsg, (UDP_IP, UDP_PORT))


# -*- coding: utf-8 -*-

# lineare_regression
#
# Routinen zur Berechnung der multivariaten linearen Regression mit Modell-
# funktion
#
# h_theta(x) = theta_0 + theta_1 * x_1 + ... + theta_n * x_n
#
# und Kostenfunktion
#
#   J(theta) = 1/(2m) sum_i=1^m ( h_theta(x^(i)) - y^(i) )^2
#
# Der Vektor theta wird als
#
#   (theta_0, theta_1, ... , theta_n)
#
# gespeichert. Die Feature-Matrix mit m Daten und n Features als
#
#        [ - x^(1) - ]
#   X = [    .      ]    (m Zeilen und n Spalten)
#       [ - x^(m) - ]
#

import numpy as np

# %% extend_matrix

# Erweitert eine Matrix um eine erste Spalte mit Einsen
#
# X_ext = extend_matrix(X)
#
# Eingabe:
#   X      Matrix m x n (numpy.ndarray)
#
# Ausgabe
#   X_ext  Matrix m x (n+1) der Form [1 X] (numpy.ndarray)
#
def extend_matrix(X):
    # TODO: setze X_ext
    vek_one = np.ones((X.shape[0], 1))
    X_ext = np.concatenate((vek_one, X), axis=1)
    return X_ext

# %% LR_fit

# Berechnung der optimalen Parameter der multivariaten linearen Regression
# mithilfe der Normalengleichung.
#
# theta = LR_fit(X, y)
#
# Eingabe:
#   X      Matrix m x n mit m Datenpunkten und n Features (numpy.ndarray)
#   y      Vektor der Länge m der Zielwerte (numpy.ndarray)
#
# Ausgabe
#   theta  Vektor der  Länge n+1 der optimalen Parameter (numpy.ndarray)
#
# Hinweis: Benutzen Sie extend_matrix und np.linalg.solve zur Lösung des
#   linearen Gleichungssystems
#
def LR_fit(X, y):
    # TODO: berechne theta
    Xn = extend_matrix(X)
    Xt = Xn.T
    a = Xt.dot(Xn)
    b = Xt.dot(y)
    theta = np.linalg.solve(a, b)
    return theta

# %% LR_predict

# Berechnung der Vorhersage der der multivariaten linearen Regression.
#
# y = LR_predict(X,theta)
#
# Eingabe:
#   X      Matrix m x n mit m Datenpunkten und n Features (numpy.ndarray)
#   theta  Vektor der  Länge n+1 der Parameter (numpy.ndarray)
#
# Ausgabe
#   y      Vektor der Länge m der Vorhersagewerte (numpy.ndarray)
#
# Hinweis: Benutzen Sie extend_matrix.
#
def LR_predict(X, theta):
    # TODO: berechne y
    y = extend_matrix(X).dot(theta)
    return y

# %% r2_score

# Berechnung des Bestimmtheitsmaßes R2
#
# y = r2_score(X, y, theta)
#
# Eingabe:
#   X      Matrix m x n mit m Datenpunkten und n Features (numpy.ndarray)
#   y      Vektor der Länge m der Zielwerte (numpy.ndarray)
#   theta  Vektor der  Länge n+1 der Parameter (numpy.ndarray)
#
# Ausgabe
#   r2     Bestimmtheitsmaß R2 (Skalar)
#
# Hinweis: Benutzen Sie LR_predict
#
def r2_score(X, y, theta):
    # TODO: berechne r2
    r1 = extend_matrix(X).dot(theta)
    c = (r1 - y) ** 2
    r2 = np.sum(c) / 2 * X.shape[0]
    return r2


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 10:39:41 2016

@author: RJovelin
"""

# use this function to find the pattern of lenght k given its index in the
# list of all possible kmers ordered lexicographically
def FastNumberToPattern(index, k):
    '''
    (str) -> int
    Take the index kmer in the list of all possible kmers of length k
    ordered lexicographically and the length k and return the corresponding kmer
    '''

    # use the following relationship
    # PatternToNumber(Pattern) = 4 · PatternToNumber(Prefix(Pattern)) + SymbolToNumber(LastSymbol(Pattern))
    # where Prefix(Pattern) = Pattern minus last symbol
    # and SymBolToNumber of last symol of Pattern is defined by A = 0, C = 1, G = 2, T =3

    NumberToSymbol = {0:'A', 1: 'C', 2: 'G', 3: 'T'}

    if k == 1:
        return NumberToSymbol[index]
    prefixIndex = index // 4
    remainder = index % 4
    symbol = NumberToSymbol[remainder]
    PrefixPattern = FastNumberToPattern(prefixIndex, k - 1)
    return PrefixPattern + symbol


# @time 2022/6/16 10:46
# @Author howell
# @File test_auto_ui.PY
import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.webdriver import WebDriver
import uiautomator2 as u2

# from hamcrest import *

capabilities = {}
# Android平台测试
capabilities['platformName'] = 'Android'
# 测试手机版本为5.0
capabilities['platformVersion'] = '7.1.2'
capabilities['deviceName'] = '127.0.0.1:21503'
# 系统手机中的联系人app的包名   adb shell "dumpsys window | grep mCurrentFocus"
capabilities['appPackage'] = 'com.smjcs.app'
# 系统手机中的联系人app的主入口activity
capabilities['appActivity'] = 'io.dcloud.PandoraEntryActivity'
capabilities['unicodeKeyboard'] = True
capabilities['resetKeyboard'] = False
capabilities['noReset'] = True
capabilities['automationName'] = 'uiautomator2'
driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', capabilities)
driver.implicitly_wait(10)

def test_click():
    x = driver.get_window_size()['width']
    y = driver.get_window_size()['height']
    time.sleep(2)
    click_y = int(y / 5 * 3 - 30 - 3)
    driver.tap([(x * 0.09, click_y)], 500)
    for i in range(50):
        # 选择分类
        el = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                                 'new UiSelector().className(\"android.view.View\").textContains(\"测试标签\")')
        el.click()
        # 选择规格
        el = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                                 'new UiSelector().className(\"android.view.View\").textContains(\"选规格\")')
        el.click()
        time.sleep(1)
        driver.tap([(x * 0.5, y - 30)], 500)
        # 结算
        driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                            'new UiSelector().className(\"android.view.View\").textContains(\"结算\")').click()
        try:
            # 提交订单
            driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                                'new UiSelector().className(\"android.view.View\").textContains(\"提交订单\")').click()
        except Exception as e:
            print(e)
            # name = str(i) + "error.png"
            # driver.save_screenshot(name)
            # 结算
            driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                                'new UiSelector().className(\"android.view.View\").textContains(\"结算\")').click()
            # 提交订单
            el2 = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                                      'new UiSelector().className(\"android.view.View\").textContains(\"提交订单\")')
            el2.click()

        # driver.find_element_by_android_uiautomator(
        #     'new UiSelector().className(\"android.view.View\").textContains(\"结算\")').click()
        # 支付
        driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                            'new UiSelector().className(\"android.view.View\").textContains(\"确认支付\")').click()
        # 返回首页
        driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                            'new UiSelector().className(\"android.view.View\").textContains(\"返回首页\")').click()

if __name__ == '__main__':
    test_click(5)


import cv2
import numpy as np
from scipy.spatial import distance
from supervision.detection.annotate import BoxAnnotator
from supervision.detection.core import Detections
from ultralytics import YOLO

class DetectorTracker:
    def __init__(self):
        self.model = YOLO('yolov8n.pt')
        self.class_names_dict = self.model.model.names
        self.box_annotator = BoxAnnotator()
        self.point = ()
        self.tracking = False
        self.track_id = None

    def __clickEvent(self, event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            self.point = (x, y)

    def __select_box(self, bboxes):
        if len(bboxes) != 0:
            x, y = self.point
            min_distance = None
            bbox_track = []

            for bbox in bboxes:
                x1, y1, x2, y2 = bbox
                if (x1 <= x <= x2) and (y1 <= y <= y2):
                    center = ((x2 + x1) / 2, (y2 + y1) / 2)
                    dist = distance.euclidean(center, self.point)
                    if min_distance:
                        if dist < min_distance:
                            min_distance = dist
                            bbox_track = bbox
                    else:
                        min_distance = dist
                        bbox_track = bbox
            return bbox_track
        else:
            return []

    def run(self):
        cap = cv2.VideoCapture(0)
        cv2.namedWindow('frame')
        cv2.setMouseCallback('frame', self.__clickEvent)
        tracker_id = None
        while True:
            ret, frame = cap.read()
            if ret is False:
                break

            results = self.model.track(frame, tracker="botsort.yaml", persist=True)[0]

            xyxy = results.boxes.xyxy.cpu().numpy()
            confidence = results.boxes.conf.cpu().numpy()
            class_id = results.boxes.cls.cpu().numpy().astype(int)

            if results.boxes.id is not None:
                tracker_id = results.boxes.id.cpu().numpy().astype(int)
            else:
                tracker_id = None

            if self.point != ():
                box_track = self.__select_box(bboxes=detections.xyxy)
                idx = np.where(detections.xyxy == box_track)[0][0]

                self.track_id = tracker_id[idx]
                self.tracking = True
                self.point = ()

            if self.tracking:
                idx = np.where(tracker_id == self.track_id)
                if len(idx[0]) != 0:
                    idx = idx[0][0]
                    xyxy = np.array([xyxy[idx]])
                    confidence = np.array([confidence[idx]])
                    tracker_id = np.array([tracker_id[idx]])
                    class_id = np.array([class_id[idx]])
                else:
                    xyxy = np.empty((0, 4), 'float64')
                    confidence = np.array([], 'float64')
                    tracker_id = np.array([], 'int')
                    class_id = np.array([], 'int')

            detections = Detections(xyxy=xyxy,
                                    confidence=confidence,
                                    class_id=class_id,
                                    tracker_id=tracker_id)

            labels = [
                f"{tracker_id}: {self.class_names_dict[class_id]} {confidence:0.2f}"
                for _, _, confidence, class_id, tracker_id
                in detections
            ]

            frame = self.box_annotator.annotate(scene=frame,
                                                detections=detections,
                                                labels=labels)

            cv2.imshow('frame', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    det_track = DetectorTracker()
    det_track.run()


import labrad
from matplotlib import pyplot
#get access to servers
cxn = labrad.connect()
dv = cxn.data_vault

'This is phase oscillation due to AC Stark shift for local detection experiment'

dv.cd(['','Experiments','RamseyDephaseScanDuration','2013Apr05','1545_16'])
dv.open(1)
data = dv.get().asarray
x = data[:,0]
y = data[:,1]
figure = pyplot.figure()
figure.clf()
pyplot.plot(x, y,'o-')

pyplot.title('AC Stark Shift', fontsize = 40)
pyplot.ylim([0,1])
pyplot.xlabel(r'Interaction Time ( $\mu s$ )', fontsize = 32)
pyplot.ylabel('Excitation percentage', fontsize = 32)
pyplot.tick_params('both', labelsize = 20)
pyplot.show()


g = lambda: map(int, input().split())
n, *nums = g()
while n:
    res = [''] * 20
    num = ord('A')
    for i in range(20):
        if not res[i]:
            res[i] = chr(num)
            num += 1
        Next = i + nums[i % n]
        if Next < 20:
            if res[Next]:
                res = 'CRASH'
                break
            else:
                res[Next] = res[i]
    print(*res, sep='')
    n, *nums = g()


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

import sys

h = list(map(int, input().strip().split(' ')))
word = input().strip()

highest = 0
for i in word:
    index  = ord(i)-97
    if h[index] > highest:
        highest = h[index]

print(len(word)*highest)


x,y = [ int(i) for i in input().split(" ") ]

start = 2

a, b = x, y
while a != b:
  temp = abs(a - b)
  a = min(a, b)
  b = temp

ans = x * y / a

print(int(ans))


import csv
import io
import pandas as pd
from tqdm import tqdm

filename = 'data/merge1.csv'
df = pd.read_csv(filename)
data = []
for index, row in tqdm(df.iterrows(), total=df.shape[0]):
    count = row[5]
    if count != 0:
        data.append([row[0], row[1], row[2], row[3], row[4], row[5]])

with io.open("data/filter_properties_count.csv", mode='w', encoding='UTF8', newline='') as toWrite:
    writer = csv.writer(toWrite)
    writer.writerow(["Name", "Label", "Domain", "Range", "URI", "Count"])
    writer.writerows(data)

2018 - Neural QA model/filter_properties_count.py


import sys, os
import logging, traceback
import pandas as pd
import re
import collections

logging.basicConfig(
    filename=snakemake.log[0],
    level=logging.INFO,
    format="%(asctime)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error(
        "".join(
            [
                "Uncaught exception: ",
                *traceback.format_exception(exc_type, exc_value, exc_traceback),
            ]
        )
    )

# Install exception handler
sys.excepthook = handle_exception

sectors_common_aggreg = {
    sheet_name: pd.read_excel(
        snakemake.config["sectors_common_aggreg"], sheet_name=sheet_name, index_col=0
    )
    for sheet_name in [
        "eora26_without_reexport_to_common_aggreg",
        "euregio_to_common_aggreg",
        "exiobase_full_to_common_aggreg",
        "icio2021_reworked_to_common_aggreg",
    ]
}

regions_common_aggreg = {
    sheet_name: pd.read_excel(
        snakemake.config["regions_common_aggreg"], sheet_name=sheet_name, index_col=0
    )
    for sheet_name in [
        "eora26_without_reexport_to_common_aggreg",
        "euregio_to_common_aggreg",
        "exiobase_full_to_common_aggreg",
        "icio2021_reworked_to_common_aggreg",
    ]
}

def load_regions_aggreg(mrio_name):
    if "eora26" in mrio_name:
        return regions_common_aggreg["eora26_without_reexport_to_common_aggreg"]
    elif "euregio" in mrio_name:
        return regions_common_aggreg["euregio_to_common_aggreg"]
    elif "exiobase" in mrio_name:
        return regions_common_aggreg["exiobase_full_to_common_aggreg"]
    elif "oecd" in mrio_name:
        return regions_common_aggreg["icio2021_reworked_to_common_aggreg"]
    else:
        raise ValueError(f"Invalid MRIO name: {mrio_name}")

def load_sectors_aggreg(mrio_name):
    if "eora26" in mrio_name:
        return sectors_common_aggreg["eora26_without_reexport_to_common_aggreg"]
    elif "euregio" in mrio_name:
        return sectors_common_aggreg["euregio_to_common_aggreg"]
    elif "exiobase" in mrio_name:
        return sectors_common_aggreg["exiobase_full_to_common_aggreg"]
    elif "oecd" in mrio_name:
        return sectors_common_aggreg["icio2021_reworked_to_common_aggreg"]
    else:
        raise ValueError(f"Invalid MRIO name: {mrio_name}")

def aggreg_df(df, mrio_name):
    regions_aggreg = load_regions_aggreg(mrio_name)
    _df = df.copy()
    regions_aggreg = load_regions_aggreg(mrio_name)
    _df.rename(regions_aggreg["new region"].to_dict(), axis=1, level=0, inplace=True)
    _df = _df.groupby(["region", "sector"], axis=1).sum()
    sectors_aggreg = load_sectors_aggreg(mrio_name)
    _df.rename(sectors_aggreg["new sector"].to_dict(), axis=1, level=1, inplace=True)
    _df = _df.groupby(["region", "sector"], axis=1).sum()
    return _df

def common_monetary_factor(df, mrio_basename):
    _df = df.copy()
    _df = _df * (snakemake.config["monetary_factor"][mrio_basename] / 10**6)
    return _df

def create_result_dict(inputs):
    xp_regex = re.compile(
        r"results/simulations/mrio~(?P<mrio_basename>[\w]+)_(?P<year>\d\d\d\d)(?:_ixi)?/sectors_scenario~(?P<sectors_scenario>[^/]+)/recovery_scenario~(?P<recovery_scenario>[^/]+)/flood_scenario~(?P<flood_scenario>[^/]+)/order~(?P<order>[^/]+)_psi~(?P<psi>[^/]+)_base_alpha~(?P<base_alpha>[^/_]+)_max_alpha~(?P<max_alpha>[^/_]+)_tau_alpha~(?P<tau_alpha>[^/]+)"
    )
    res_dict = {}
    for key, val in inputs.items():
        for xp_file in val:
            match = xp_regex.match(xp_file)
            if match:
                df = pd.read_parquet(xp_file)
                df = aggreg_df(df, match.group("mrio_basename"))
                df = common_monetary_factor(df, match.group("mrio_basename"))
                res_dict[
                    (
                        key,
                        match.group("mrio_basename"),
                        match.group("year"),
                        match.group("sectors_scenario"),
                        match.group("recovery_scenario"),
                        match.group("flood_scenario"),
                        match.group("order"),
                        match.group("psi"),
                        match.group("base_alpha"),
                        match.group("max_alpha"),
                        match.group("tau_alpha"),
                    )
                ] = df
            else:
                ValueError(
                    f"Unmatched file, verify regex ?\n {val} to match with {xp_regex}"
                )

    return res_dict

logger.info(f"Starting creation of all results dictionary.")
res = create_result_dict(snakemake.input)
logger.info(f"Saving to {snakemake.output[0]}")
pd.concat(
    res,
    keys=res.keys(),
    names=[
        "variable",
        "mrio",
        "mrio year",
        "sectors_sce",
        "recovery_sce",
        "flood_sce",
        "order type",
        "psi",
        "alpha_base",
        "alpha_max",
        "alpha_tau",
    ],
).to_parquet(snakemake.output[0])


from datetime import datetime
from typing import List, Optional, Tuple, cast

import pkg_resources
import structlog
from flask import Flask
from flask_restful import Resource
from gevent.pywsgi import WSGIServer
from prometheus_client import make_wsgi_app
from werkzeug.exceptions import NotFound
from werkzeug.middleware.dispatcher import DispatcherMiddleware

from monitoring_service import metrics
from monitoring_service.constants import API_PATH, DEFAULT_INFO_MESSAGE
from monitoring_service.service import MonitoringService
from raiden_libs.api import ApiWithErrorHandler
from raiden_libs.utils import to_checksum_address

log = structlog.get_logger(__name__)

class MSResource(Resource):
    def __init__(self, monitoring_service: MonitoringService, api: "MSApi"):
        self.monitoring_service = monitoring_service
        self.service_token_address = (
            self.monitoring_service.context.user_deposit_contract.functions.token().call()
        )
        self.api = api

class InfoResource(MSResource):
    version = pkg_resources.get_distribution("raiden-services").version
    contracts_version = pkg_resources.get_distribution("raiden-contracts").version

    def get(self) -> Tuple[dict, int]:
        info = {
            "price_info": self.api.monitoring_service.context.min_reward,
            "network_info": {
                "chain_id": self.monitoring_service.chain_id,
                "token_network_registry_address": to_checksum_address(
                    self.monitoring_service.context.ms_state.blockchain_state.token_network_registry_address  # noqa
                ),
                "user_deposit_address": to_checksum_address(
                    self.monitoring_service.context.user_deposit_contract.address
                ),
                "service_token_address": to_checksum_address(self.service_token_address),
                "confirmed_block": {
                    "number": self.monitoring_service.context.ms_state.blockchain_state.latest_committed_block  # noqa
                },
            },
            "version": self.version,
            "contracts_version": self.contracts_version,
            "operator": self.api.operator,
            "message": self.api.info_message,
            "UTC": datetime.utcnow().isoformat(),
        }
        return info, 200

class InfoResource2(MSResource):
    version = pkg_resources.get_distribution("raiden-services").version
    contracts_version = pkg_resources.get_distribution("raiden-contracts").version

    def get(self) -> Tuple[dict, int]:
        info = {
            "price_info": str(self.api.monitoring_service.context.min_reward),
            "network_info": {
                "chain_id": self.monitoring_service.chain_id,
                "token_network_registry_address": to_checksum_address(
                    self.monitoring_service.context.ms_state.blockchain_state.token_network_registry_address  # noqa
                ),
                "user_deposit_address": to_checksum_address(
                    self.monitoring_service.context.user_deposit_contract.address
                ),
                "service_token_address": to_checksum_address(self.service_token_address),
                "confirmed_block": {
                    "number": str(
                        self.monitoring_service.context.ms_state.blockchain_state.latest_committed_block  # noqa
                    )
                },
            },
            "version": self.version,
            "contracts_version": self.contracts_version,
            "operator": self.api.operator,
            "message": self.api.info_message,
            "UTC": datetime.utcnow().isoformat(),
        }
        return info, 200

class MSApi:
    def __init__(
        self,
        monitoring_service: MonitoringService,
        operator: str,
        info_message: str = DEFAULT_INFO_MESSAGE,
    ) -> None:
        flask_app = Flask(__name__)
        self.api = ApiWithErrorHandler(flask_app)

        # Add the metrics prometheus app
        self.flask_app = DispatcherMiddleware(
            NotFound(),
            {
                "/metrics": make_wsgi_app(registry=metrics.REGISTRY),
                API_PATH: flask_app.wsgi_app,
            },
        )

        self.rest_server: Optional[WSGIServer] = None

        self.monitoring_service = monitoring_service
        self.operator = operator
        self.info_message = info_message

        resources: List[Tuple[str, Resource, str]] = [
            ("/v1/info", cast(Resource, InfoResource), "info"),
            ("/v2/info", cast(Resource, InfoResource2), "info2"),
        ]

        for endpoint_url, resource, endpoint in resources:
            self.api.add_resource(
                resource,
                endpoint_url,
                resource_class_kwargs={"monitoring_service": monitoring_service, "api": self},
                endpoint=endpoint,
            )

    def run(self, host: str, port: int) -> None:
        self.rest_server = WSGIServer((host, port), self.flask_app)
        self.rest_server.start()

        log.info("Running endpoint", endpoint=f"http://{host}:{port}")

    def stop(self) -> None:
        if self.rest_server:
            self.rest_server.stop()


from django import forms
from django.core import validators

class FormArticle(forms.Form):
    title = forms.CharField(
        label="Titulo",
        max_length=20,
        required=True,
        widget=forms.TextInput(
            attrs={  # html attributes
                'placeholder': 'Mete el titulo',
                'class': 'title_form_article'
            }
        ),
        validators=[
            validators.MinLengthValidator(4, 'El titulo es demasiado corto'),
            validators.RegexValidator('^[A-Za-z0-9]*$', 'El titulo esta mal formado', 'invalid_title')
            # validation characters
        ]
    )

    content = forms.CharField(
        label="Contenido",
        widget=forms.Textarea,
        validators=[
            validators.MaxLengthValidator(50, 'Te has pasado, has puesto mucho texto')
        ]
    )
    content.widget.attrs.update({  # html attributes
        'placeholder': 'Mete el contenido',
        'class': 'content_form_article',
        'id': 'contenido_form'
    })

    public_options = [
        (1, 'si'), (0, 'no')
    ]
    public = forms.TypedChoiceField(
        choices=public_options,
        label='¿Publicado?'
    )


# -*- coding: utf-8 -*-
from typing import Any, Dict
from googleapiclient import discovery
from matos_gcp_provider.lib import factory
from matos_gcp_provider.lib.base_provider import BaseProvider

class serviceAccount(BaseProvider):
    """GCP service account class

    Args:
        BaseProvider (Class): Base provider class
    """

    def __init__(self, resource: Dict, **kwargs) -> None:
        """
        Construct service acounts service
        """
        self.resource = resource
        self.resource_type = "iam.googleapis.com/ServiceAccount"
        self.project_id = resource.pop("project_id")
        super().__init__(**kwargs)

    def get_inventory(self) -> Any:
        """
        Service discovery
        """
        service_accounts = []
        resources = self._get_assets(self.project_id, self.resource_type)
        service = discovery.build("iam", "v1", credentials=self.credentials)
        request = service.projects().serviceAccounts()
        for resource in resources:
            service_accounts.append(
                {
                    "type": "serviceAccount",
                    **resource.get("resource").get("data"),
                    "getPolicy": request.getIamPolicy(
                        resource=resource.get("resource").get("data").get("name")
                    ).execute(),
                    **request.keys()
                    .list(name=resource.get("resource").get("data").get("name"))
                    .execute(),
                }
            )
        return service_accounts

def register() -> Any:
    """Register plugins type"""
    factory.register("serviceAccount", serviceAccount)


"""
### Excercise 1.6 | Tickets (approx. 1 hour)
Assumptions:
    - 0-6   - kindergarten - ticket price: 0
    - 7-17  - school       - ticket price: 2.28
    - 18-64 - adult        - ticket price: 3.80
    - +65   - pensioner    - ticket price: 1.90
Write a program that will ask a user for his age and a number of tickets he'd like to buy.
Based on the assumptions above calculate the price he should pay for the tickets.
"""

age = int(input('Enter your age: '))
tickets = int(input('Enter the number of tickets: '))

if tickets > 0:
    if age <= 6:
        cost = 0
        print('Free ticket for you!')
    else:
        if age >= 7 and age <= 17:
            cost = 2.28
        elif age >= 18 and age <= 64:
            cost = 3.80
        else:
            cost = 1.90
        price = tickets * cost
        print(f'The total amount you have to pay is {price} $')
else:
    print("You didn't buy any ticket")


# implementation of card game - Memory
# Zhizheng Wang

import simplegui
import random

# helper function to initialize globals
def new_game():
    global list1, exposed, state, index, counter
    list1 = range(0,8)
    list2 = list1
    list1.extend(list2)
    random.shuffle(list1)
    exposed = [False] * 16
    state = 0
    index = [False, False]
    counter = 0

# define event handlers
def mouseclick(pos):
    global exposed, state, l1, l2, index, counter
    ind = pos[0]/50
    if exposed[ind] == False:
        if state == 0:
            state = 1
            exposed[ind] = True
            index[0] = ind
            l1 = list1[index[0]]
            exposed[index[0]] = True
        elif state == 1:
            state = 2
            counter += 1
            index[1] = ind
            l2 = list1[index[1]]
            exposed[index[1]] = True
        else:
            state = 1
            if l1 != l2:
                exposed[index[0]] = False
                exposed[index[1]] = False
            index[0] = ind
            index[1] = False
            l1 = list1[index[0]]
            exposed[index[0]] = True

# cards are logically 50x100 pixels in size
def draw(canvas):
    global exposed, counter
    for i in range(0, 16):
        if exposed[i]:
            rectangular_pos = [(50 * i, 0), (50 * (i+1) , 0), (50 * (i+1), 100), (50 * i, 100)]
            canvas.draw_polygon(rectangular_pos, 2, 'Grey', 'Black')
            text_pos = [15 + 50 * i,60]
            canvas.draw_text(str(list1[i]), text_pos, 40, 'White', 'monospace')
        else:
            rectangular_pos = [(50 * i, 0), (50 * (i+1) , 0), (50 * (i+1), 100), (50 * i, 100)]
            canvas.draw_polygon(rectangular_pos, 2, 'Grey', 'Green')
        i += 1
    label.set_text('Turns = ' + str(counter))

# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = 0")

# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)

# get things rolling
new_game()
frame.start()

# Always remember to review the grading rubric


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

import os
import time
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPRegressor
from toy_example import measure_time, load_from_csv, build_rating_matrix, make_submission
from learning_set_creation import create_learning_matrices2
import numpy as np
import random
from sklearn.metrics import mean_squared_error

def y_check(y):
    for i in range(len(y)):
        if y[i] > 5:
            y[i] = 5
        if y[i] < 0:
            y[i] = 0
    return y

add_noise = lambda x: x + random.uniform(-x/10, x/10)
v_noise = np.vectorize(add_noise)

if __name__ == '__main__':
    prefix = 'data/'

    # ------------------------------- Learning ------------------------------- #
    # Load training data
    training_user_movie_pairs = load_from_csv(os.path.join(prefix,
                                                           'data_train.csv'))
    training_labels = load_from_csv(os.path.join(prefix, 'output_train.csv'))
    user_movie_rating_triplets = np.hstack((training_user_movie_pairs,
                                            training_labels.reshape((-1, 1))))
    # Build the learning matrix
    rating_matrix = build_rating_matrix(user_movie_rating_triplets)
    X = create_learning_matrices2(rating_matrix, training_user_movie_pairs)

    # Build the model
    y = training_labels
    X_ls2, X_vs, y_ls2, y_vs = train_test_split(X, y, train_size=.8, random_state=20)
    # Creation of the learning and validation set.
    X_untouch = X_ls2.copy()
    scaler = StandardScaler()
    start = time.time()
    models = []
    n_estimator = 50
    y_pred = np.zeros((n_estimator,y_vs.shape[0]))
    with measure_time("Bagging training"):
        for i in range(n_estimator):
            # Training
            model = MLPRegressor(hidden_layer_sizes=(100, 50, 50), random_state=i)
            X_ls2 = v_noise(X_ls2)
            scaler.fit(X_ls2)
            X_ls2=scaler.transform(X_ls2)
            model.fit(X_ls2, y_ls2)
            models.append((model, scaler))
            X_t = scaler.transform(X_vs, copy=True)
            y_pred[i, :] = model.predict(X_t)
            print(model.predict(X_t))
            X_ls2 = X_untouch.copy()

    means = np.mean(y_pred, axis=0)
    print(mean_squared_error(y_vs, means))

    # ------------------------------ Prediction ------------------------------ #
    # Load test data
    test_user_movie_pairs = load_from_csv(os.path.join(prefix, 'data_test.csv'))

    # # Build the prediction matrix
    X_ts = create_learning_matrices2(rating_matrix, test_user_movie_pairs)
    X_ts = scaler.transform(X_ts)

    # Predict
    print(X_ts.shape)
    y_pred = np.zeros((n_estimator, X_ts.shape[0]))
    for i in range(n_estimator):
        y_pred[i, :] = models[i][0].predict(models[i][1].transform(X_ts))
    y_pred = np.mean(y_pred, axis=0)
    print(y_pred)

    y_pred = y_check(y_pred)
    # Making the submission file
    fname = make_submission(y_pred, test_user_movie_pairs, 'NLP_bagging' )
    print('Submission file "{}" successfully written'.format(fname))