from django.utils.encoding import smart_unicode
import re
from htmlentitydefs import name2codepoint
import unicodedata
from uuid import uuid4
from random import choice
import string
import math
from web import models
import logging

log = logging.getLogger(__name__)

def slugify(s, entities=True, decimal=True, hexadecimal=True,
   instance=None, slug_field='slug', filter_dict=None):
    s = smart_unicode(s)

    #character entity reference
    if entities:
        s = re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: unichr(name2codepoint[m.group(1)]), s)

    #decimal character reference
    if decimal:
        try:
            s = re.sub('&#(\d+);', lambda m: unichr(int(m.group(1))), s)
        except:
            pass

    #hexadecimal character reference
    if hexadecimal:
        try:
            s = re.sub('&#x([\da-fA-F]+);', lambda m: unichr(int(m.group(1), 16)), s)
        except:
            pass

    #translate
    s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')

    #replace unwanted characters
    s = re.sub(r'[^-a-z0-9]+', '-', s.lower())

    #remove redundant -
    s = re.sub('-{2,}', '-', s).strip('-')

    slug = s
    if instance:
        def get_query():
            query = instance.__class__.objects.filter(**{slug_field: slug})
            if filter_dict:
                query = query.filter(**filter_dict)
            if instance.pk:
                query = query.exclude(pk=instance.pk)
            return query
        counter = 1
        while get_query():
            slug = "%s-%s" % (s, counter)
            counter += 1
    return slug

def generate_token():
    token = ''
    for c in str(uuid4())[:8]:
        if c.isalpha() and choice([True, False]):
            c = c.upper()
        token += c
    if choice([True, False]):
        return token[::-1]
    else:
        return token

def int2base(integer, base):
        if not integer: return '0'
        sign = 1 if integer > 0 else -1
        alphanum = string.digits + string.ascii_lowercase
        nums = alphanum[:base]
        res = ''
        integer *= sign
        while integer:
                integer, mod = divmod(integer, base)
                res += nums[mod]
        return ('' if sign == 1 else '-') + res[::-1]

def get_string_size(string):
    if len(string) <= 1024:
        return str(len(string) * 8) + ' b'
    else:
        return str(round(len(string) / 1024 * 8, 2)) + ' kb'

def get_age(seconds):
    minute = 60
    hour   = 60 * minute
    day    = 24 * hour
    year   = 365 * day

    age = ''
    if seconds == 1:
        age = '1 second'
    elif seconds < minute:
        age = str(int(seconds)) + ' seconds'
    elif seconds >= minute and seconds < hour and seconds < minute * 2:
        age = '1 minute'
    elif seconds >= minute and seconds < hour:
        age = str(int(math.ceil(seconds / minute))) + ' minutes'
    elif seconds >= hour and seconds < day and seconds < hour * 2:
        age = '1 hour'
    elif seconds >= hour and seconds < day:
        age = str(int(math.ceil(seconds / hour))) + ' hours'
    elif seconds >= day and seconds < year and seconds < day * 2:
        age = '1 day'
    elif seconds >= day and seconds < year:
        age = str(int(math.ceil(seconds / day))) + ' days'
    elif seconds >= year and seconds < year * 2:
        age = '1 year'
    elif seconds >= year:
        age = str(int(math.ceil(seconds / year))) + ' years'
    return age

def get_visitor(uuid):
    """Getting visitor by uuid."""
    log.debug('Getting visitor by uuid(%s)', uuid)
    try:
        visitor = models.Visitor.objects.get(uuid=uuid)
    except Exception:
        visitor      = models.Visitor()
        visitor.uuid = uuid
        visitor.save()
    return visitor


from protocol.src.com.teltonika.Codec.GPSElement import *
from protocol.src.com.teltonika.Codec.IOelement import*

class AVLData:
    #class which splits the AVLData

    def __init__(self, AVLData,datacount,IMEI):
            self.AVLData = AVLData
            self.datacount = datacount
            self.IMEI = IMEI

    def AVL_splitter(self):
        AVLData = self.AVLData
        datacount = self.datacount
        IMEI = self.IMEI
        sum1 = 0

        for i in range(1, datacount+1, +1):
            Timestamp = AVLData[sum1:sum1+16]
            Priority = AVLData[sum1+16:sum1+18]
            print("Timestamp", Timestamp)
            print("Priority", Priority)
            my_GPSElement = AVLData[sum1+18:sum1+48]
            print("GPS",my_GPSElement)
            myGPS = GPSElement(my_GPSElement,IMEI)
            myGPS.GPSElement_splitter()

            my_IOelement = AVLData[sum1+48:]
            myIO = IOelement(my_IOelement)
            sum = myIO.IOelement_splitter()
            #print("sum", sum)

            sum1 = i*len(Timestamp)+i*len(Priority)+i*len(my_GPSElement)+i*int(sum)+i*4


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import pickle
from joblib import dump

class OfflineStage :
    def __init__(self , tfidf_matrix_file_path, vectorizer_file_path,clustering_file_path):
        self._document_body_tfidf_matrix_file_path = tfidf_matrix_file_path
        self._document_body_tfidf_vectorizer_file_path = vectorizer_file_path
        self._document_body_tfidf_clustering_file_path = clustering_file_path

    # calculate and save tfidf of documents body , vectorizer and cluster
    def calculate_and_save_tfidf_of_documents_body(self, document):
        vectorizer = TfidfVectorizer()
        tfidf_matrix = vectorizer.fit_transform(document)
        # save the tfidfMatrix object to a file
        with open(self._document_body_tfidf_matrix_file_path, 'wb') as f:
            pickle.dump(tfidf_matrix, f)
        # save the TfidfVectorizer object to a file
        with open(self._document_body_tfidf_vectorizer_file_path, 'wb') as f:
            pickle.dump(vectorizer, f)
        # save the clustering object to a file
        kmeans = KMeans(n_clusters= 7, n_init=20 , random_state=30)
        kmeans.fit(tfidf_matrix)
        dump(kmeans, self._document_body_tfidf_clustering_file_path)


full2 = []
full = []
temp = []

itr = int(input())

cf2 = 0
for i in range(0, itr):
    full2.append([*map(int, input().split()[::-1])])

full2.sort()

full.append(full2[0])

cf2 = 1

topf = 0

while (True):
    if cf2 == itr: break
    if int(full[topf][0]) <= int(full2[cf2][1]):
        full.append(full2[cf2])
        topf += 1
    cf2 += 1

print(len(full))


class medallist:
    #注意int两边是要双划线不是单划线
    def __init__(self,country,gold,silver,bronze):
         self.country=country
         self.gold=gold
         self.silver=silver
         self.bronze=bronze

    def get_place(self,place):
        if place==1:
            self.gold+=1
        if place==2:
            self.silver+=1
        if place==3:
            self.bronze+=1

    @property
    # 装饰器 @property，将这个类方法转成只读的属性，称为属性函数。在调用时像属性一样，无需再加括号
    def medaloutput(self):
        return self.gold+self.silver+self.bronze

    # __str__ 是类的内容方法，用来生成一个可读性好的字符串，可供 print 函数调用
    def __str__(self):
        return '%s: gold:%d,silver:%d,bronze:%d'%(self.country, self.gold, self.silver, self.bronze)
    #字符串格式化，多个变量的时候需要加括号

if __name__ == '__main__':
    # 当.py文件被直接运行时，if __name__ == '__main__'之下的代码块将被运行；当.py文件以模块形式被导入时，if __name__ == '__main__'之下的代码块不被运行
    China=medallist('China',26,18,26)
    US=medallist('US',46,37,38)
    UK=medallist('UK',27,23,17)
    China.get_place(2)
    print(China)
    print(China.medaloutput)
    medalrank=[China,US,UK]
    #print(medalrank)
    print('goldrank')
    order_golden=sorted(medalrank,key=lambda x:x.gold,reverse=True)
    #print(order_golden)
    for i in order_golden:
        print(i)
    print('totalrank')
    order_total=sorted(medalrank,key=lambda x:x.gold+x.silver+x.bronze,reverse=True)
    #print(order_total)
    for j in order_total:
        print(j)


import unittest

import torch
from tqdm import tqdm

from fairseq import utils
from tests.speech import TestFairseqSpeech

class TestXMTransformer(TestFairseqSpeech):
    def setUp(self):
        self.set_up_sotasty_es_en()

    @torch.no_grad()
    def test_sotasty_es_en_600m_checkpoint(self):
        models, cfg, task, generator = self.download_and_load_checkpoint(
            "xm_transformer_600m_es_en_md.pt",
            arg_overrides={"config_yaml": "cfg_es_en.yaml"},
        )
        if not self.use_cuda:
            return

        batch_iterator = self.get_batch_iterator(
            task, "sotasty_es_en_test_ted", 3_000_000, (1_000_000, 1_024)
        )
        scorer = self.get_bleu_scorer()
        progress = tqdm(enumerate(batch_iterator), total=len(batch_iterator))
        for batch_idx, sample in progress:
            sample = utils.move_to_cuda(sample) if self.use_cuda else sample
            hypo = task.inference_step(generator, models, sample)
            for i, sample_id in enumerate(sample["id"].tolist()):
                tgt_tokens = (
                    utils.strip_pad(sample["target"][i, :], task.tgt_dict.pad())
                    .int()
                    .cpu()
                )
                tgt_str = task.tgt_dict.string(tgt_tokens, "sentencepiece")
                hypo_str = task.tgt_dict.string(
                    hypo[i][0]["tokens"].int().cpu(), "sentencepiece"
                )
                if batch_idx == 0 and i < 3:
                    print(f"T-{sample_id} {tgt_str}")
                    print(f"H-{sample_id} {hypo_str}")
                scorer.add_string(tgt_str, hypo_str)
        reference_bleu = 31.7
        print(f"{scorer.result_string()} (reference: {reference_bleu})")
        self.assertAlmostEqual(scorer.score(), reference_bleu, delta=0.2)

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


import matplotlib.pyplot as plt
import numpy as np

def _plot_spike_raster(
    aligned_spikes, trial_ids=None, vlines=[0], ax=None, title="", xlim=None
):
    if not ax:
        fig, ax = plt.subplots(1, 1)

    raster = np.concatenate(aligned_spikes)
    if trial_ids is None:
        trial_ids = range(len(aligned_spikes))

    trial_ids = np.concatenate(
        [[t] * len(s) for t, s in zip(trial_ids, aligned_spikes)]
    ).astype(int)

    assert len(raster) == len(trial_ids)

    ax.plot(raster, trial_ids, "ro", markersize=4)

    for x in vlines:
        ax.axvline(x=x, linestyle="--", color="k")

    ax.set_ylabel("Trial (#)")
    if xlim:
        ax.set_xlim(xlim)
    ax.set_title(title)

def _plot_psth(psth, psth_edges, bin_size, vlines=[0], ax=None, title="", xlim=None):
    if not ax:
        fig, ax = plt.subplots(1, 1)

    ax.bar(psth_edges, psth, width=bin_size, edgecolor="black", align="edge")

    for x in vlines:
        ax.axvline(x=x, linestyle="--", color="k")

    ax.set_ylabel("spikes/s")
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)

    if xlim:
        ax.set_xlim(xlim)
    ax.set_xlabel("Time (s)")
    ax.set_title(title)


from django.contrib import admin
from django.urls import path,include
from .api import RegisterApi
from . import views

from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="contact@snippets.local"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)

urlpatterns = [

    path('',views.home,name="home"),
    path('api/register', RegisterApi.as_view(),name="register"),

    path('api/addbook',views.AddBook.as_view(), name='AddBook'),
    path('api/updatebook',views.UpdateBook.as_view(), name='UpdateBook'),
    path('api/deletebook',views.DeleteBook.as_view(), name='DeleteBook'),
    path('api/viewbook',views.ViewBook.as_view(), name='ViewBook'),
    path('api/viewallbook',views.ViewAllBook.as_view(), name='ViewAllBook'),

    path('api/borrowbook',views.BorrowBook.as_view(), name='BorrowBook'),
    path('api/returnbook',views.ReturnBook.as_view(), name='ReturnBook'),

    path('api/addmember', views.AddMember.as_view(), name='AddMember'),
    path('api/updatemember', views.UpdateMember.as_view(), name='UpdateMember'),
    path('api/deletemember', views.DeleteMember.as_view(), name='DeleteMember'),
    path('api/viewmember', views.ViewMember.as_view(), name='ViewMember'),
    path('api/viewallmember', views.ViewAllMember.as_view(), name='ViewAllMember'),

    path('swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),

]


path = r"C:\Users\Herman\Desktop\PROGRAMMERING\Projekt\Advent_of_code\adv2.txt"

with open(path, "r") as f:
    lines = f.read().splitlines()

start_idx = 0
for this_idx, this_li in enumerate(lines):
    for comp_idx, comp_li in enumerate(lines):
        mismatch_count = 0
        if this_idx < comp_idx:
            for this_ch_idx, this_ch in enumerate(this_li):
                if this_ch != comp_li[this_ch_idx]:
                    mismatch_count += 1
        if mismatch_count == 1:
            for this_ch_idx, this_ch in enumerate(this_li):
                if this_ch == comp_li[this_ch_idx]:
                    print(this_ch, end="")
            break


'''
Testing final model
Team 29
Nov30 2021

'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets, transforms, utils
import numpy as np
import os
import matplotlib.pyplot as plt
import torchvision.models

'''
Parameters
'''
torch.backends.cudnn.benchmark = True
dtype = torch.cuda.FloatTensor
torch.manual_seed(24)
'''
Data processing
'''
image_transform = transforms.Compose([
                                transforms.Resize(64),
                                transforms.CenterCrop(64),
                                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
                                #transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

                              ])
'''
Setting up the custom dataset class
'''
class ImageDataset(torch.utils.data.Dataset):
    def __init__(self, folder_path, transform):
        self.path = folder_path
        self.file_path = os.listdir(self.path)
        self.data = []
        self.transform = transform
        for file_paths in self.file_path:
            image = plt.imread(os.path.join(self.path, file_paths))
            self.data.append(np.array(image))

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        self.intToFloat = torch.nn.Sequential(transforms.ConvertImageDtype(torch.float32))
        image = self.intToFloat(torch.from_numpy(self.data[idx]).transpose(0,2))
        return self.transform(image)

def showImg(image):
    figure = plt.figure(figsize=(3,3))
    figure.add_subplot(1,1,1)
    normalized_img = image * 0.5 + 0.5
    plt.imshow(normalized_img.transpose(0,2))

'''
Generator

Note that not all layer are used in forward, some are kept to be compatible with older saved state.
'''
class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()
        self.conv1 = nn.Conv2d(3, 8, 3, 1, 1, bias = False)
        self.conv2 = nn.Conv2d(8, 16, 5, 2, 2, bias = False)
        self.conv3 = nn.Conv2d(16, 32, 6, 2, 2, bias = False)

        self.convt1 = nn.ConvTranspose2d(32, 16, 6, 2, 2, bias = False)
        self.convt2 = nn.ConvTranspose2d(16, 8, 4, 2, 2, bias = False)
        self.convt3 = nn.ConvTranspose2d(8, 3, 3, 1, 0, bias = False)

        self.c1 = nn.Conv2d(3, 12, 3, 1, 1, bias = False)
        self.c2 = nn.Conv2d(12, 24, 4, 2, 1, bias = False)
        self.c3 = nn.ConvTranspose2d(24, 12, 4, 2, 1, bias = False)
        self.c4 = nn.ConvTranspose2d(12, 3, 3, 1, 1, bias = False)

        self.c5 = nn.Conv2d(3, 3, 3, 1, 1, bias = False)
        self.cnorm1 = nn.BatchNorm2d(12)
        self.cnorm2 = nn.BatchNorm2d(24)

        self.norm1 = nn.BatchNorm2d(8)
        self.norm2 = nn.BatchNorm2d(16)
        self.norm3 = nn.BatchNorm2d(32)
        self.norm4 = nn.BatchNorm2d(16)
        self.norm5 = nn.BatchNorm2d(8)
        self.norm6 = nn.BatchNorm2d(3)

        self.drop = nn.Dropout(p=0.12)
    def forward(self, x):

        x = F.relu(self.norm1(self.conv1(x)))
        x = self.drop(x)

        x = F.relu(self.norm2(self.conv2(x)))
        x = self.drop(x)

        x = F.relu(self.norm3(self.conv3(x)))
        x = self.drop(x)

        x = F.relu(self.norm4(self.convt1(x)))

        x = F.relu(self.norm5(self.convt2(x)))

        x = F.tanh(self.convt3(x))

        return x

def showTensorImg(net, tensor):
    showImg(net(tensor.cuda().unsqueeze(0)).detach().cpu()[0])

'''
Model
'''
GEN_A = Generator().cuda()
GEN_B = Generator().cuda()

print("DONE")

'''
Loading in the model state and putting them into evaluation mode.
'''
GEN_A.load_state_dict(torch.load("/content/GA_save_4152"))
GEN_A.eval()
GEN_B.load_state_dict(torch.load("/content/GB_save_4152"))
GEN_B.eval()

"""Loading in data for testing"""

#Data path should be a folder containing all the images you want for testing
#You do not have to load anime faces if you only want to convert human to anime
#Run this cell if you want to setup anime to human faces conversion
anime_data = ImageDataset("/content/anime", image_transform)
print("anime data loaded...")

#Run this cell if you want to setup human to anime faces conversion
human_data = ImageDataset("/content/human", image_transform)
print("human data loaded...")

"""Showing Human faces to anime faces"""

'''
Generating output using our Generator B with testing data
'''

#Showing unselected output of our model using testing data from flicker HQ.
#These images are diverse in facial expression, races, genders, background and ages. Thus hard to convert.
for j in range(24): #range determines amount of faces shown.
    i = j+24 #offset for data number, For example, +40 and range(5) will give data number 40 to 45
    showImg(human_data[i])
    showTensorImg(GEN_B, human_data[i])

"""Showing anime faces to human faces"""

'''
Generating output using our Generator A with testing data
Note: This was not the purpose of our model so Generator A has worse performance than generator B since our hyperparamter is not tuned
for generator A.
'''

#We can invetigate the latent space of our generator with this code.
for j in range(10):
    i = j + 15
    showImg(anime_data[i])
    showTensorImg(GEN_A, anime_data[i])


# Base Parameters
assets           = asset_list('FX')

# Trading Parameters
horizon = 'H1'
pair    = 0

# Mass Imports
my_data = mass_import(pair, horizon)

def signal(Data, close, tii_col, ma_col, buy, sell):

    Data = adder(Data, 10)

    for i in range(len(Data)):

        if Data[i, tii_col] > 60 and \
           Data[i - 1, tii_col] < 60 and \
           Data[i, close] > Data[i, ma_col]:

               Data[i, buy] = 1

        if Data[i, tii_col] < 40 and \
           Data[i - 1, tii_col] > 40 and \
           Data[i, close] < Data[i, ma_col]:

               Data[i, sell] = -1

    return Data

lookback_ma  = 100
lookback_tii = 14

def ma(Data, lookback, close, where):

    Data = adder(Data, 1)

    for i in range(len(Data)):

            try:
                Data[i, where] = (Data[i - lookback + 1:i + 1, close].mean())

            except IndexError:
                pass

    # Cleaning
    Data = jump(Data, lookback)

    return Data

def trend_intensity_indicator(Data, lookback, what, where):

    Data = adder(Data, 5)

    # Calculating the Moving Average
    Data = ma(Data, lookback, what, where)

    # Deviations
    for i in range(len(Data)):

        if Data[i, what] > Data[i, where]:
            Data[i, where + 1] = Data[i, what] - Data[i, where]

        if Data[i, what] < Data[i, where]:
            Data[i, where + 2] = Data[i, where] - Data[i, what]

    # Trend Intensity Index
    for i in range(len(Data)):

        Data[i, where + 3] = np.count_nonzero(Data[i - lookback + 1:i + 1, where + 1])

    for i in range(len(Data)):

        Data[i, where + 4] = np.count_nonzero(Data[i - lookback + 1:i + 1, where + 2])

    for i in range(len(Data)):

        Data[i, where + 5] = ((Data[i, where + 3]) / (Data[i, where + 3] + Data[i, where + 4])) * 100

    Data = deleter(Data, where, 5)

    return Data

my_data = trend_intensity_indicator(my_data, lookback_tii, 3, 4)
my_data = ma(my_data, lookback_ma, 3, 5)
my_data = signal(my_data, 3, 4, 5, 6, 7)

# indicator_plot_double(my_data, 0, 1, 2, 3, 4, window = 250)
# signal_chart_bars(my_data, 3, 6, 7, window = 1000)
# plt.plot(my_data[-1000:, 5], label = '100-period Simple Moving Average')
# plt.legend()

# Variable Period Strategy
my_data = performance_variable_period(my_data, 3, 6, 7, 8, 9, 10)

# Fixed Period Strategy - Must Not be Used Directly After the Previous Performance Function
my_data = performance_fixed_period(my_data, 3, 6, 7, 15, 8, 9, 10)


"""
You are given a 2D integer array coordinates and an integer k, where coordinates[i] = [xi, yi] are the coordinates of the ith point in a 2D plane.

We define the distance between two points (x1, y1) and (x2, y2) as (x1 XOR x2) + (y1 XOR y2) where XOR is the bitwise XOR operation.

Return the number of pairs (i, j) such that i < j and the distance between points i and j is equal to k.

Example 1:

Input: coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5
Output: 2
Explanation: We can choose the following pairs:
- (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5.
- (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5.

"""

class Solution:
    def countPairs(self, coordinates: List[List[int]], k: int) -> int:
        # math
        # x1^x2 = xDistance
        # x1^x2+y1^y2=k; y1^y2 = k-x1^x2; y1^y2 = k-xDistance; y2 = (k-xDistance)^y1
        # k distance from (x1, y1) is the count of points (x1^xDistance, (k-xDistance)^y1)
        # [[1,3],[1,3],[1,3],[1,3],[1,3]], k=5
        counter = Counter()
        res = 0

        for x, y in coordinates:
            for xDistance in range(k + 1):
                d_x = x ^ xDistance
                d_y = (k - xDistance) ^ y
                res += counter[(d_x, d_y)]
            counter[(x, y)] += 1
        return res

math/2857. Count Pairs of Points With Distance k.py


import os
word = []
list_word = []
list_number = []
list_word_number = []
cant_word = int(input("Enter Total Amount Word: "))
# min_char = int(input("Enter Minimal Chars: "))
num = int(input("Total Digits Number (max 4): "))

if num < 0 or num > 4:
    num = 1

i = 0
s = str(i)
ls = len(s)

while ls <= num:
    if i < 10:
        w = '000' + s
    elif i < 100:
        w = '00' + s
    elif i < 1000:
        w = '0' + s
    else:
        w = s
    list_number.append(w)
    i += 1
    s = str(i)
    ls = len(s)

index = cant_word

while index:
    w = input("Enter Word: ")
    word.append(w)
    index -= 1

while index < cant_word:
    index2 = 0
    while index2 < cant_word:
        w = word[index] + word[index2]
        x = word[index] + " " + word[index2]
        y = word[index] + "y" + word[index2]
        z = word[index] + " y " + word[index2]
        a = word[index] + "Y" + word[index2]
        b = word[index] + " Y " + word[index2]
        list_word.append(w)
        list_word.append(x)
        list_word.append(y)
        list_word.append(z)
        list_word.append(a)
        list_word.append(b)
        index2 += 1
    index += 1

index = 0

while index < cant_word:
    index2 = 0
    while index2 < cant_word:
        index3 = 0
        while index3 < cant_word:
            w = word[index] + word[index2] + word[index3]
            x = word[index] + " " + word[index2] + " " + word[index3]
            list_word.append(w)
            list_word.append(x)
            index3 += 1
        index2 += 1
    index += 1

lon_word = len(list_word)
lon_number = len(list_number)

index = 0

while index < lon_word:
    index2 = 0
    while index2 < lon_number:
        w = list_word[index] + list_number[index2]
        x = list_number[index2] + list_word[index]
        list_word_number.append(w)
        list_word_number.append(x)
        index2 += 1
    index += 1

lon_word_number = len(list_word_number)
i = 0

file = open('capture/password.txt','wb')

while i < lon_word:
    file.write(list_word[i].encode())
    s = os.linesep.encode()
    file.write(s)
    i += 1

i = 0

while i < lon_number:
    file.write(list_number[i].encode())
    s = os.linesep.encode()
    file.write(s)
    i += 1

i = 0

while i < lon_word_number:
    file.write(list_word_number[i].encode())
    s = os.linesep.encode()
    file.write(s)
    i += 1


# processing
from operator import methodcaller
import csv
import re
import numpy as np
import pandas as pd
from pprint import pprint

# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel

# plotting tools
import pyLDAvis
import pyLDAvis.gensim
import matplotlib.pyplot as plt

blacklist = next(csv.reader(open("blacklist.csv", 'r')))

def main():

    execute("input.csv", "out.csv", 10, 70)

def execute(inPath, outPath, wordBound, charBound):

    inFile = open(inPath, 'r')
    inReader = csv.reader(inFile)

    outFile = open(outPath, 'w')
    outWriter = csv.writer(outFile)

    docTokens = dict()

    next(inReader)
    for inRow in inReader:

        charDist = int(inRow[0])
        wordDist = int(inRow[1])

        if wordDist < wordBound and charDist < charBound:

            #predTerm, subTerm, objTerm = map(methodcaller("split", ":"), inRow[2:5])
            #allTerms = predTerm + subTerm + objTerm

            subTerm, objTerm = map(methodcaller("split", ":"), inRow[3:5])
            allTerms = subTerm + objTerm

            tokens = list()

            for term in allTerms:
                if term.isalpha() and not term in blacklist and len(term) > 2:
                    tokens.append(term)

            docID = inRow[5]

            if docID in docTokens:
                docTokens[docID] += tokens
            else:
                docTokens[docID] = tokens

    data = list(docTokens.values())

    # get bigrams
    bigram = gensim.models.Phrases(data, min_count=5, threshold=100)
    bigram_mod = gensim.models.phrases.Phraser(bigram)

    data = [bigram_mod[doc] for doc in data]

    id2word = corpora.Dictionary(data)
    texts = data

    corpus = [id2word.doc2bow(text) for text in texts]

    lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
                                           id2word=id2word,
                                           num_topics=20,
                                           random_state=100,
                                           update_every=1,
                                           chunksize=100,
                                           passes=10,
                                           alpha='auto',
                                           per_word_topics=True)

    pprint(lda_model.print_topics())
    doc_lda = lda_model[corpus]

    pyLDAvis.enable_notebook()
    vis = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)
    vis

if __name__ == "__main__":
    main()


from pathlib import Path
parent_dir = Path(__file__).parent
file_name = Path(__file__).stem

import sys
sys.stdin = open(f"{parent_dir}\{file_name} input.txt")
input = sys.stdin.readline

"""
큐에 (중요도, 초기 위치값)을 같이 넣기.
인쇄할지 말지는 중요도를 비교하고,
인쇄하고 나서는 초기 위치값을 비교.
"""

T = int(input())
for test_case in range(T):
    page_num, wanted = map(int, input().split())
    pages = enumerate(map(int, input().split()))

    # 원형 큐 사용
    size = 2 * page_num
    Q = [[] for _ in range(size)]
    front = -1
    rear = page_num - 1

    # 큐에 원소 전부 채워놓기
    for idx, value in pages :
        Q[idx] = (value, idx)

    page_order = 0
    # 큐가 빌 때까지
    while front != rear:
        # 큐의 첫 번째 원소 뽑기
        front = (front + 1) % size
        value, idx = Q[front]

        cur = front
        # 다음 원소부터 마지막 원소까지 순회
        while cur != rear:
            # NOTE: rear 전에 +1 하니까, rear까지 해당
            cur = (cur + 1) % size
            # 중요도 비교 후, 높은 게 있으면 뒤에 넣기
            if Q[cur][0] > value:
                rear = (rear + 1) % size
                Q[rear] = (value, idx)
                break
        # 중요도 높은 게 없으면 프린트 출력
        else:
            page_order += 1
            # 원하는 인덱스면 번호 출력 후 시행 종료
            if idx == wanted:
                print(page_order)
                break

problems/Baekjoon_Online_Judge/1111 문제 풀이/1966. 프린터 큐.py


from namedlist import namedlist

PolygonShape = namedlist('PolygonShape', ["points"])

Position = namedlist('Position', ["x", "y"])

Orientation = namedlist('Orientation', ["angle"])

Color = namedlist('Color', ["r", "g", "b"])

MoveSpeed = namedlist('MoveSpeed', ["speed"])

TurnSpeed = namedlist('TurnSpeed', ["speed"])

Health = namedlist('Health', ["amount"])

FoodSeen = namedlist('FoodSeen', ["number"])

# Collider = namedlist('Collider', ["entity", "bounding_square", "shape"])

class Collider(object):
    def __init__(self, entity, bounding_square, shape):
        self.entity = entity
        self.bounding_square = bounding_square
        self.shape = shape

    def __repr__(self):
        repr_string = "{}(entity={}, bounding_square={}, shape={})"
        name = self.__class__.__name__
        return repr_string.format(name, self.entity, self.bounding_square, self.shape)


list_message = []

def send_message(bot, chat_id, text, replymarkup=None):
    if len(list_message) == 2:
        message = list_message.pop(0)
        bot.delete_message(message.chat.id, message.message_id)
        bot.delete_message(message.chat.id, message.message_id - 1)
    list_message.append(bot.send_message(chat_id, text, reply_markup=replymarkup))

"""
    send_message успешно удаляет сообщения,
    если их количество парное (команда юзера и сообщение бота),
    требует исправления
"""


import numpy as np

# Artificial sdata
true_w = np.array([1,2,3,4,5])
d = len(true_w)
points = []

for i in range(1000):
    x = np.random.randn(d)
    y = true_w.dot(x) + np.random.randn()
    points.append((x, y))

# Gradient descent

def F(w):
    return sum((w.dot(x) - y) ** 2 for x, y in points) / len(points)

def dF(w):
    return sum(2 * (w.dot(x) - y) * x for x, y in points) / len(points)

def gradientDescent(F, dF, d):
    w = np.zeros(d)
    eta = 0.01

    for t in range(1000):
        value = F(w)
        gradient = dF(w)
        w = w - eta * gradient
        print('iteration {}: w = {}, F(w) = {}'.format(t, w, value))

gradientDescent(F, dF, d)


from odoo.addons.mail.tests.common import MailCommon, mail_new_test_user
from odoo.exceptions import UserError, AccessError
from odoo.tests.common import users

class TestPortalWizard(MailCommon):
    def setUp(self):
        super(TestPortalWizard, self).setUp()

        self.partner = self.env['res.partner'].create({
            'name': 'Testing Partner',
            'email': 'testing_partner@example.com',
        })

        self.public_user = mail_new_test_user(
            self.env,
            name='Public user',
            login='public_user',
            email='public_user@example.com',
            groups='base.group_public',
        )

        self.portal_user = mail_new_test_user(
            self.env,
            name='Portal user',
            login='portal_user',
            email='portal_user@example.com',
            groups='base.group_portal',
        )

        self.internal_user = mail_new_test_user(
            self.env,
            name='Internal user',
            login='internal_user',
            email='internal_user@example.com',
            groups='base.group_user',
        )

    def test_portal_wizard_acl(self):
        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).create({})

        with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'):
            self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).with_user(self.user_employee).create({})

        with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'):
            portal_wizard.with_user(self.user_employee).welcome_message

        with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'):
            portal_wizard.user_ids.with_user(self.user_employee).email

    @users('admin')
    def test_portal_wizard_partner(self):
        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).create({})

        self.assertEqual(len(portal_wizard.user_ids), 1)

        portal_user = portal_wizard.user_ids

        self.assertFalse(portal_user.user_id.id)
        self.assertFalse(portal_user.is_portal)
        self.assertFalse(portal_user.is_internal)

        portal_user.email = 'first_email@example.com'
        with self.mock_mail_gateway():
            portal_user.action_grant_access()
        new_user = portal_user.user_id

        self.assertTrue(new_user.id, 'Must create a new user')
        self.assertTrue(new_user.has_group('base.group_portal'), 'Must add the group to the user')
        self.assertEqual(self.partner.email, 'first_email@example.com', 'Must write on the email of the partner')
        self.assertEqual(new_user.email, 'first_email@example.com', 'Must create the user with the right email')
        self.assertSentEmail(self.env.user.partner_id, [self.partner])

    @users('admin')
    def test_portal_wizard_public_user(self):
        """Test to grant the access to a public user.

        Should remove the group "base.group_public" and add the group "base.group_portal"
        """
        group_public = self.env.ref('base.group_public')
        public_partner = self.public_user.partner_id
        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[public_partner.id]).create({})

        self.assertEqual(len(portal_wizard.user_ids), 1)
        portal_user = portal_wizard.user_ids

        self.assertEqual(portal_user.user_id, self.public_user)
        self.assertFalse(portal_user.is_portal)
        self.assertFalse(portal_user.is_internal)

        portal_user.email = 'new_email@example.com'
        with self.mock_mail_gateway():
            portal_user.action_grant_access()

        self.assertTrue(portal_user.is_portal)
        self.assertFalse(portal_user.is_internal)

        self.assertTrue(self.public_user.has_group('base.group_portal'), 'Must add the group portal')
        self.assertFalse(self.public_user.has_group('base.group_public'), 'Must remove the group public')
        self.assertEqual(public_partner.email, 'new_email@example.com', 'Must change the email of the partner')
        self.assertEqual(self.public_user.email, 'new_email@example.com', 'Must change the email of the user')
        self.assertSentEmail(self.env.user.partner_id, [public_partner])

        with self.mock_mail_gateway():
            portal_user.action_revoke_access()

        self.assertEqual(portal_user.user_id, self.public_user, 'Must keep the user even if it is archived')
        self.assertEqual(group_public, portal_user.user_id.groups_id, 'Must add the group public after removing the portal group')
        self.assertFalse(portal_user.user_id.active, 'Must have archived the user')
        self.assertFalse(portal_user.is_portal)
        self.assertFalse(portal_user.is_internal)
        self.assertNotSentEmail()

    @users('admin')
    def test_portal_wizard_internal_user(self):
        """Internal user can not be managed from this wizard."""
        internal_partner = self.internal_user.partner_id
        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[internal_partner.id]).create({})

        self.assertEqual(len(portal_wizard.user_ids), 1)
        portal_user = portal_wizard.user_ids

        self.assertTrue(portal_user.is_internal)

        with self.assertRaises(UserError, msg='Should not be able to manage internal user'), self.mock_mail_gateway():
            portal_wizard.user_ids.action_grant_access()

        self.assertNotSentEmail()

        with self.assertRaises(UserError, msg='Should not be able to manage internal user'):
            portal_wizard.user_ids.action_revoke_access()

    @users('admin')
    def test_portal_wizard_error(self):
        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.portal_user.partner_id.id]).create({})

        self.assertEqual(len(portal_wizard.user_ids), 1)
        portal_user = portal_wizard.user_ids

        self.internal_user.login = 'test_error@example.com'

        portal_user.email = 'test_error@example.com'
        with self.assertRaises(UserError, msg='Must detect the already used email.'):
            portal_user._assert_user_email_uniqueness()
        self.assertEqual(portal_user.email_state, 'exist', msg='Must detect the already used email.')

        portal_user.email = 'wrong email format'
        with self.assertRaises(UserError, msg='Must detect wrong email format.'):
            portal_user._assert_user_email_uniqueness()
        self.assertEqual(portal_user.email_state, 'ko', msg='Must detect wrong email format.')

        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.internal_user.partner_id.id]).create({})
        portal_user = portal_wizard.user_ids
        with self.assertRaises(UserError, msg='Must not be able to change internal user group.'):
            portal_user.action_revoke_access()

    def test_portal_wizard_multi_company(self):
        company_1 = self.company_admin
        company_2 = self.company_2

        partner_company_2 = self.env['res.partner'].with_company(company_2).create({
            'name': 'Testing Partner',
            'email': 'testing_partner@example.com',
            'company_id': company_2.id,
        })

        portal_wizard = self.env['portal.wizard'].with_context(active_ids=[partner_company_2.id]).create({})
        portal_user = portal_wizard.user_ids

        portal_user.with_company(company_1).action_grant_access()

        self.assertEqual(portal_user.user_id.company_id, company_2, 'Must create the user in the same company as the partner.')


import tensorflow.compat.v1 as tf
import tensorflow.contrib as contrib
import numpy as np
import os, sys
import random

def set_seed(seed = 0, dataset = None):
    tempseed = seed
    if dataset in [3, 4]:
        tempseed = 0 # For CIFAR100, Sim-CIFAR100 (but why?)
    np.random.seed(tempseed)
    tf.random.set_random_seed(seed)
    os.environ["PYTHONHASHSEED"] = str(tempseed)
    os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
    random.seed(tempseed)
    session_config = tf.ConfigProto(
        intra_op_parallelism_threads = 1,
        inter_op_parallelism_threads = 1
    )
    session_config.gpu_options.allow_growth = True
    return session_config

def dense(x, i, o):
    seed = int(os.environ["PYTHONHASHSEED"])
    init = tf.initializers.glorot_uniform(seed = seed)
    init_bias = tf.zeros_initializer()
    W = tf.Variable(init([i, o]))
    b = tf.Variable(init_bias([1, o]))
    return tf.add(tf.matmul(x, W), b)

# Named
def dense2(x, i, o, name):
    seed = int(os.environ["PYTHONHASHSEED"])
    init = tf.initializers.glorot_uniform(seed = seed)
    init_bias = tf.zeros_initializer()
    with tf.variable_scope(name):
        W = tf.Variable(init([i, o]), name = "w")
        b = tf.Variable(init_bias([1, o]), name = "b")
    return tf.add(tf.matmul(x, W), b)

def average(xs):
    if len(xs) == 1:
        return xs[0]
    else:
        return tf.keras.layers.average(xs)

def waverage(xs, r, n):
    assert(n >= 1)
    ret = tf.constant(0.0, dtype = tf.float32)
    for i in range(n):
        ret += tf.gather(xs, i) * tf.gather(r, i)
    ret /= tf.reduce_sum(r)
    return ret

def get_var(name):
    for var in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=""):
        if var.name.startswith(name):
            if var.name.split(":")[0] != name:
                print("Requested: %s, Returning: %s" % (name, var.name))
            return var
    return None

def say(*args):
    return tf.print(*args, output_stream = sys.stdout)

def softplus_inv(x):
    return tf.math.log(tf.math.exp(x)-1)

def get_activation(aname):
    allowed_activations = {
        "relu": tf.nn.relu,
        "softplus": tf.nn.softplus,
        "tanh": tf.nn.tanh
    }
    assert(aname in allowed_activations.keys())
    return allowed_activations[aname]

def sum_up(var_list):
    return tf.reduce_sum([tf.reduce_sum(item) for item in var_list])

# https://zhuanlan.zhihu.com/p/38716569
def conv2d(x, kernel_shape, strides = [1, 1, 1, 1], padding = 'SAME'):
    kernel = tf.Variable(tf.truncated_normal(kernel_shape, dtype = tf.float32,
        stddev = 1e-1))
    b = tf.Variable(tf.zeros_initializer()([kernel_shape[-1]]))
    c = tf.nn.conv2d(x, kernel, strides, padding = padding)
    return tf.nn.bias_add(c, b)

def gradient_clip_minimize_op(opt, loss, var_list = None):
    gradients, variables = zip(*opt.compute_gradients(loss, var_list = var_list))
    gradients, _ = tf.clip_by_global_norm(gradients, 5.0)
    return opt.apply_gradients(zip(gradients, variables))


"""API Module."""

import sys
import json
from fastapi import FastAPI, Request
import pandas as pd
import base64
from io import StringIO
import json

# Plotting
import plotly.express as px
from plotly.io import to_html, to_json
import plotly.figure_factory as ff
from starlette.responses import HTMLResponse

app = FastAPI()

@app.get("/api/python")
def python():
    """Demo function printing python version."""
    return {"Python Version": sys.version}

# class CsvFile(BaseModel):
#     file: str

# API endpoint to upload file & analyse
@app.post("/api/analyse", response_class=HTMLResponse)
async def analyse(request: Request):
    """
    Endpoint that accepts any type of request body.

    :param request: FastAPI Request object
    :return: JSON response
    """
    # Access the request body as bytes
    request_body = await request.body()

    result = {}

    # Process the request_body as needed (e.g., parse JSON, decode, etc.)
    try:
        data = json.loads(request_body.decode())

        # Split the data URI to extract the base64-encoded data
        _, base64_data = data["file"].split(",", 1)

        # Decode the base64 data
        decoded_data = base64.b64decode(base64_data)

        # Convert the decoded data to a string
        csv_content = decoded_data.decode("utf-8")

        # Create a file-like object from the CSV content using StringIO
        csv_file = StringIO(csv_content)

        df = pd.read_csv(csv_file)
        print(df.head())

        min = df["Values3"].min()
        max = df["Values3"].max()
        min_range = (min * 1.2) if min < 0 else (min * 0.8)
        max_range = (max * 1.2) if max > 0 else (max * 0.8)

        # PLOTLY FIGURE - DISTPLOT
        dist_plot = ff.create_distplot(
            [df["Values3"].dropna()],
            ["Value"],
            bin_size=(max - min) / 50,
            show_rug=False,
            curve_type="normal",
        )
        dist_plot.update_xaxes(range=[min_range, max_range])
        dist_json = json.loads(to_json(dist_plot, pretty=True))

        result["distplot"] = dist_json

        return json.dumps(result)
    except json.JSONDecodeError as error:
        return {"error": "Invalid JSON data", "data": error.msg}


import abc
import re
from typing import Dict, List, Optional, Text

import six
from tf_coder.benchmarks import benchmark as benchmark_module
from tf_coder.value_search import all_operations
from tf_coder.value_search import operation_base
from tf_coder.value_search import value_search_settings as settings_module

@six.add_metaclass(abc.ABCMeta)
class DescriptionHandler(object):
  """Handles a natural language description of a task.

  Attributes:
    operations: A list of operations that the handler knows about.
    all_names: A list of operation names, in the same order as the `operations`
      list.
  """

  def __init__(self,
               operations: Optional[List[operation_base.Operation]] = None):
    """Initializes the handler.

    Args:
      operations: A list of operations that the scorer should handle. Exposed
        for testing.
    Raises:
      ValueError: If there are duplicate operation names.
    """
    self.operations = (
        operations if operations
        else all_operations.get_operations(include_sparse_operations=True))
    self.all_names = [operation.name for operation in self.operations]
    if len(set(self.all_names)) != len(self.operations):
      raise ValueError('Duplicate operation name.')

  @abc.abstractmethod
  def get_operation_multipliers(
      self, benchmark: benchmark_module.Benchmark,
      settings: settings_module.Settings) -> Dict[Text, float]:
    """Returns a map from operation names to their weight multiplier.

    The weight multiplier should be between 0 and 1 if the operation should be
    prioritized, or greater than 1 if it should be deprioritized.

    Args:
      benchmark: Benchmark object corresponding to the TF-Coder task.
      settings: A Settings object storing settings for this search.

    Returns:
      A map from operation name to weight multiplier, such that the operation
      with that name should have its weight modified by that multiplier. If the
      dict does not contain a key, it means the weight should not be modified
      (equivalent to a multiplier of 1).
    """

  def __repr__(self) -> Text:
    """Returns a string containing details about this handler and parameters."""
    return self.__class__.__name__

class NoChangeDescriptionHandler(DescriptionHandler):
  """A description handler that does not change any operation weights."""

  def get_operation_multipliers(
      self, benchmark: benchmark_module.Benchmark,
      settings: settings_module.Settings) -> Dict[Text, float]:
    """See base class."""
    return {}

class FunctionNameDescriptionHandler(DescriptionHandler):
  """Prioritizes functions with names that appear in the docstring."""

  def __init__(self,
               operations: Optional[List[operation_base.Operation]] = None,
               multiplier: float = 0.75):
    """Creates a FunctionNameDescriptionHandler.

    Args:
      operations: A list of operations that the scorer should handle. Exposed
        for testing.
      multiplier: The multiplier applied to an operation's weight if it is
        prioritized.
    """
    super(FunctionNameDescriptionHandler, self).__init__(operations)
    self.multiplier = multiplier

  def get_operation_multipliers(
      self, benchmark: benchmark_module.Benchmark,
      settings: settings_module.Settings) -> Dict[Text, float]:
    """See base class."""
    description = benchmark.description.lower()
    multipliers = {}
    for name in self.all_names:
      if name.startswith('tf.') and '(' in name:
        function_name = name[len('tf.') : name.index('(')].lower()
        function_name_parts = re.split(r'[._]', function_name)
        if all(part in description for part in function_name_parts):
          if settings.printing.prioritized_operations:
            print('FunctionNameDescriptionHandler prioritized {}'.format(name))
          multipliers[name] = self.multiplier
    return multipliers

  def __repr__(self) -> Text:
    """See base class."""
    return '{}(multiplier={})'.format(self.__class__.__name__, self.multiplier)


import os
import re

__AUTHOR__ = 'Vitaliy Danevych'
__COPYRIGHT__ = 'Lifecell UA Company, 2018 Kiev, Ukraine'
__version__ = '0.4'
__license__ = "GPL"
__email__ = "oss_gxxx@lifexxx.cxx.ua"
__status__ = "Production"

def savetoFILE(out_file, header, list_my):
    with open(out_file, 'w+') as f:
        #f.write(header)
        f.write("\n")
        for each in list_my:
            f.write("%s" % each)
            f.write("\n")

def parseTXT(txtfile):
    """ TXT parser function """
    with open(txtfile, 'rt') as f:  ## open xml file for parsing
        sites = set()
        list_my = []
        cell_name = None
        adm_state = None
        oper_state = None
        #line_num = 0
        for line in f:
            #line_num +=1
            #cell name
            try:
                matched = re.search(r'^SubNetwork=ONRM_RootMo_R.+?EUtranCellFDD=([ERBS_]*?\w{2}\d{4}L\d{2})', line)
            except TypeError as e:
                print('TypeError occurs1', e)
            if matched:
                cell_name = matched.group(1)
                cell_name = cell_name.replace('ERBS_', '').strip()
                #print('cell_name: ', cell_name)

            #Adm state
            try:
                matched = re.search(r'^.*AdmState\):\s+(\d{1})$', line)
            except TypeError as e:
                print('TypeError occurs2', e)
            if matched:
                adm_state = matched.group(1).strip()
                if adm_state == '1':
                    adm_state = 'UNLOCKED'
                elif adm_state == '0':
                    adm_state = 'LOCKED'
                else:
                    adm_state = 'UNKNOWN'
                #print('adm_state: ', adm_state)

            #Oper State
            try:
                matched = re.search(r'^.*OperState\s+ro\):\s+(\d{1})$', line)
            except TypeError as e:
                print('TypeError occurs3', e)
            if matched:
                oper_state = matched.group(1).strip()
                if oper_state == '1':
                    oper_state = 'ENABLED'
                elif oper_state == '0':
                    oper_state = 'DISABLED'
                else:
                    oper_state = 'UNKNOWN'
                #print('oper_state: ', oper_state)

                #Make the whole line and add it to array
                if cell_name not in sites:
                    sites.add(cell_name)
                    if (cell_name is not None) and (adm_state is not None) and (oper_state is not None):
                        whole_line = cell_name + ';' + adm_state + ';' + oper_state
                        list_my.append(whole_line)
                        #if (cell_name == 'KI0085L11') or (cell_name == 'KI0417L13'):
                        #    print('line_num: ', line_num, ' whole_line: ', whole_line)

    return list_my

def main():
    in_file = '4g_cells_all.txt'
    out_file = '4g_cells_all.csv'
    abs_out_file = os.getcwd() + os.sep + out_file
    if os.name == 'posix':
        abs_in_file = '/home/fmuser2/scripts/4g_cell_status' + os.sep + in_file
    elif os.name == 'nt':
        abs_in_file = os.getcwd() + os.sep + 'in' + os.sep + in_file

    header = 'MO;AdmState;Op.State'  # csv file header for sqlloader

    try:
        list_my = parseTXT(abs_in_file)
    except TypeError as e:
        print('TypeError occurs', e)
        print('Exception!')

    savetoFILE(abs_out_file, header, list_my)

if __name__ == "__main__":
    main()


class Solution:
  def largestVariance(self, s: str) -> int:
    # kadane's algorithm

    freq = [0] * 26
    ctoi = lambda x: ord(x) - ord('a')
    for c in s:
      freq[ctoi(c)] += 1

    best_sum = 0
    for a in string.ascii_lowercase:
      for b in string.ascii_lowercase:
        if a == b or not freq[ctoi(a)] or not freq[ctoi(b)]:
          continue
        a_freq, b_freq = 0, 0
        b_rem = freq[ctoi(b)]
        for c in s:
          if c == a:
            a_freq += 1
          elif c == b:
            b_freq += 1
            b_rem -= 1
          if b_freq > 0:
            best_sum = max(best_sum, a_freq - b_freq)
          if a_freq - b_freq < 0 and b_rem > 0:
            a_freq, b_freq = 0, 0

    return best_sum

Problems/2272. (H) Substring With Largest Variance/Python3/solution.py


# create a pirate class
# it should have 2 methods
# drink_rum()
# hows_goin_mate()
# if the drink_rum was called at least 5 times:
# hows_goin_mate should return "Arrrr!"
# "Nothin'" otherwise

# Added attributes name and rounds needed to get drunk and option to drink more shots in a round.

class Pirate():

    def __init__(self, name, limit):
        self.rounds = 0
        self.name = name
        self.getdrunk = limit

    def drink_rum(self, shots):
        self.rounds += shots

    def hows_it_goin_mate(self):
        if self.rounds >= self.getdrunk:
            print("Arrrr!")
        else:
            print("Nothin'")

pirate1 = Pirate("Roger", 7)
pirate2 = Pirate("Davies", 3)

pirate1.drink_rum(3)
pirate1.hows_it_goin_mate()


def dif(long, short):
    for i in range(len(short)):
        if short[i] == long[i]:
            continue
        else:
            return long[i]
    return long[-1]

def mistakes_analyzer(errors: "list[tuple[str, str]]"):
    """Analyze mistakes made by model.
    :param errors - list of (model_ans, correct_ans)
    :returns (loose_symbol, error_symbols, undefined)
            loose_symbol - {symbol: loos_count}
            error_symbols - {correct_symbol: {model_answer: count}} (count=int)
            undefined - list of other mistakes list[tuple[str, str]]
    """
    loose_symbol = {}
    error_symbols = {}
    undefined = []
    for ans, correct_ans in errors:
        if len(ans) != len(correct_ans):
            # if we skip a character
            if len(correct_ans) == len(ans)+1:
                loosed_sym = dif(correct_ans, ans)
                if loosed_sym not in loose_symbol:
                    loose_symbol[loosed_sym] = 0
                loose_symbol[loosed_sym] += 1
            else:
                undefined.append((ans, correct_ans))
            continue
        for sym_correct, sym_fail in zip(correct_ans, ans):
            if sym_correct != sym_fail:
                # if we recognize it incorrectly
                if sym_correct not in error_symbols: error_symbols[sym_correct] = {}
                if sym_fail not in error_symbols[sym_correct]: error_symbols[sym_correct][sym_fail] = 0
                error_symbols[sym_correct][sym_fail] += 1
    return loose_symbol, error_symbols, undefined


from collections import deque

class MovingAverage:

    def __init__(self, size: int):
        self.queue = deque()
        self.size = size
        self.curr_total = 0

    def next(self, val: int) -> float:
        if len(self.queue) == self.size:
            self.curr_total -= self.queue[0]
            self.queue.popleft()

        self.queue.append(val)
        self.curr_total += val

        return self.curr_total / len(self.queue)

# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)


class BankAccount:
    balance = 0
    accounts = []
    # don't forget to add some default values for these parameters!
    def __init__(self, int_rate, balance):
        self.int_rate = int_rate
        self.balance = balance
        BankAccount.accounts.append(self)
        # your code here! (remember, instance attributes go here)
        # don't worry about user info here; we'll involve the User class soon
    def deposit(self, amount):
        self.balance+=amount
        return self
        # your code here
    def withdraw(self, amount):
        if(self.balance - amount) >= 0:
            self.balance -= amount
        else:
            print("Insufficient Funds: Charging a $5 fee")
            self.balance -= 5
        return self
        # your code here
    def display_account_info(self):
        print('Balance: ' + str("{:.2f}".format(self.balance)))
        return self
        # your code here
    def yield_interest(self):
        if self.balance > 0:
            self.balance += (self.balance * self.int_rate)
        return self
        # increases the account balance by the current balance * the interest rate (as long as the balance is positive)

    @classmethod
    def AllAccounts(cls):
        for account in cls.accounts:
            account.display_account_info()

account1 = BankAccount(0.05, 500)
account2 = BankAccount(0.09, 1000)

account1.deposit(500).deposit(100).deposit(400).withdraw(200).yield_interest().display_account_info()
account2.deposit(200).deposit(50).withdraw(100.5).withdraw(300).withdraw(60).withdraw(400).yield_interest().display_account_info()

BankAccount.AllAccounts()


# function to extract cutout image
import math
from astropy.nddata import Cutout2D
import astropy.io.fits as fits
from astropy.wcs import WCS

def extract_pair(ra, dec, *, img_pair, cutout_width, mosaic_pix_scale):
    """Extract cutouts from the science and background images in `img_pair`.

    If `img_pair` contains only one element, extract the cutout once and return it for both.

    Parameters:
    -----------
    ra, dec : float
        celestial coordinates for measuring photometry
    img_pair : tuple
        Pair of images for science and background respectively.
        If the tuple only contains one element, the same image will be used for both cutouts.
        A tuple element can be a fits.ImageHDU or the path to a FITS file as a string.
    cutout_width : int
        width of desired cutout in arcseconds
    mosaic_pix_scale : float
        Pixel scale of the image

    Returns:
    --------
    cutout:
        Cropped science image data.
    bkg_cutout:
        Cropped background image data.
    x, y:
        Pixel coordinates of the target in the science cutout.
    cutout_wcs:
        `WCS` for the science cutout.
    """
    # extract science image cutout
    img = img_pair[0]
    subimage, x1, y1, subimage_wcs = extract(
        ra, dec, hdu=img, cutout_width=cutout_width, mosaic_pix_scale=mosaic_pix_scale
    )

    # extract sky background cutout
    # if there's only 1 HDU in the "pair", it doubles for the background
    if len(img_pair) == 1:
        bkgsubimage = subimage
    else:
        img = img_pair[1]
        bkgsubimage, _, _, _ = extract(
            ra, dec, hdu=img, cutout_width=cutout_width, mosaic_pix_scale=mosaic_pix_scale
        )

    return subimage, bkgsubimage, x1, y1, subimage_wcs

def extract(ra, dec, *, hdu, cutout_width, mosaic_pix_scale):
    '''Extract an image cutout from `hdu` at `ra` and `dec`.

    Parameters:
    -----------
    ra, dec : float
        celestial coordinates for measuring photometry
    hdu : fits.ImageHDU or str
        Image data to extract the cutout from.
        If this is a `str`, it should be the path to a FITS file -- the primary HDU
        will be loaded and used.
    cutout_width : int
        width of desired cutout in arcseconds
    mosaic_pix_scale : float
        Pixel scale of the image

    Returns:
    --------
    cutout:
        Cropped image data.
    x, y:
        Pixel coordinates of the target in the cutout.
    cutout_wcs:
        `WCS` for the cutout.
    '''
    if isinstance(hdu, str):
        # hdu is a file path. load the primary HDU
        hdu = fits.open(hdu)[0]
    wcs_info = WCS(hdu)

    # convert ra and dec into x, y
    x0, y0 = wcs_info.all_world2pix(ra, dec, 1)
    position = (x0, y0)

    # make size array in pixels
    # how many pixels are in cutout_width
    size = (cutout_width / mosaic_pix_scale)
    size = int(math.ceil(size))  # round up the nearest integer

    # make the cutout
    cutout = Cutout2D(hdu.data, position, size, mode="trim", wcs=wcs_info)
    subimage = cutout.data
    subimage_wcs = cutout.wcs

    # now need to set the values of x1, y1 at the location of the target *in the cutout*
    x1, y1 = subimage_wcs.all_world2pix(ra, dec, 1)
    #print('x1, y1', x1, y1)

    return subimage.data, x1, y1, subimage_wcs


import pymysql
import web3_ganache
# import toll_blocks_web3_script
import schedule
import time

def get_data_from_db():

    # Open database connection
    db = pymysql.connect("localhost","dbadmin","disha_shinde","toll_blocks" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Prepare SQL query to SELECT records from the database.
    sql = """
            SELECT distinct road_id_id, sum(amount)
                FROM toll_blocks.testing_transaction
                group by road_id_id
                having road_id_id IN
                (
                    SELECT road_id_id FROM toll_blocks.testing_transaction where DATE(created_at)=CURDATE()
                );
         """
    try:
        # Execute the SQL command
        cursor.execute(sql)
        # Fetch all the rows in a list of lists.
        results = cursor.fetchall()
        if len(results) == 0:
            print("No new transactions today.")
            return False
        else:
            new_data = []
            for row in results:
                road_id = row[0]
                total_amount = row[1]
                #print("0", road_id, total_amount)

                # Add collected amount to the corresponding road's collected amount field
                sql = "UPDATE toll_blocks.testing_road SET collected_amount = collected_amount + %f where road_id = '%s';" %(total_amount, road_id)
                cursor.execute(sql)
                # Get the contract amount and collected amount of the road in order to find the remaining amount to be collected
                sql = "SELECT contract_amount, collected_amount FROM toll_blocks.testing_road where road_id = '%s';" %(road_id)
                cursor.execute(sql)
                result = cursor.fetchone()
                remaining_amount = result[0] - result[1]                    # contract_amount - collected_amount

                new_data.append([road_id, remaining_amount])

            return new_data

    except:
       print ("Error: unable to fetch data")

    # disconnect from server
    db.close()

# update data on blockchain
def send_data_to_blockchain():
    new_data = get_data_from_db()
    if new_data == False:
        return False

    else:
        for row in new_data:
            # toll_blocks_web3_script.update_contract(str(row[0]), str(row[1]))
            web3_ganache.update_contract(str(row[0]), str(row[1]))

# Task scheduling
# After every 1 min send_data_to_blockchain() is called.
schedule.every(1).minutes.do(send_data_to_blockchain)

# After every hour send_data_to_blockchain() is called.
# schedule.every().hour.do(send_data_to_blockchain)

# Every day at 12am or 00:00 time send_data_to_blockchain() is called.
# schedule.every().day.at("00:00").do(send_data_to_blockchain)

# Loop so that the scheduling task keeps on running all time.
while True:
	# Checks whether a scheduled task is pending to run or not
	schedule.run_pending()
	time.sleep(1)


"""
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

"""

class TreeNode:
    def __init__(self,x):
        self.val = x

class Solution:
    def buildTree(self,preorder, inorder):
        if len(preorder) == 0:return None
        if len(preorder) == 1:return TreeNode(preorder[0])
        root = TreeNode(preorder[0])
        index = inorder.index(root.val)
        root.left = self.buildTree(preorder[1:index+1],inorder[:index])
        root.right = self.buildTree(preorder[index+1:],inorder[index+1:])
        return root

专题训练/数组/中等/从前序和中续遍历构造二叉树.py

从前序和中续遍历构造二叉树.py


import odoo.tests
from odoo.addons.pos_self_order.tests.self_order_common_test import SelfOrderCommonTest

@odoo.tests.tagged("post_install", "-at_install")
class TestSelfOrderMobile(SelfOrderCommonTest):
    def test_self_order_mobile(self):
        self.pos_config.write({
            'self_ordering_takeaway': True,
            'self_ordering_mode': 'mobile',
            'self_ordering_pay_after': 'each',
            'self_ordering_service_mode': 'table',
        })

        self.pos_config.with_user(self.pos_user).open_ui()
        self_route = self.pos_config._get_self_order_route()

        # Mobile, each, table
        self.start_tour(self_route, "self_mobile_each_table_takeaway_in")
        self.start_tour(self_route, "self_mobile_each_table_takeaway_out")

        self.pos_config.write({
            'self_ordering_service_mode': 'counter',
        })

        # Mobile, each, counter
        self.start_tour(self_route, "self_mobile_each_counter_takeaway_in")
        self.start_tour(self_route, "self_mobile_each_counter_takeaway_out")

        self.pos_config.write({
            'self_ordering_pay_after': 'meal',
            'self_ordering_service_mode': 'table',
        })

        # Mobile, meal, table
        self.start_tour(self_route, "self_mobile_meal_table_takeaway_in")
        self.start_tour(self_route, "self_mobile_meal_table_takeaway_out")

        self.pos_config.write({
            'self_ordering_service_mode': 'counter',
        })

        # Mobile, meal, counter
        self.start_tour(self_route, "self_mobile_meal_counter_takeaway_in")
        self.start_tour(self_route, "self_mobile_meal_counter_takeaway_out")

        # Cancel in meal
        self.start_tour(self_route, "self_order_mobile_meal_cancel")

        self.pos_config.write({
            'self_ordering_pay_after': 'each',
        })

        # Cancel in each
        self.start_tour(self_route, "self_order_mobile_each_cancel")


from typing import List
import time
import random
import bisect

def binary_insertion_sort(a: List[int]) -> None:
    n = len(a)
    for i in range(1, n):
        val = a[i]
        left, right = 0, i - 1
        while True:
            if left == right:
                if a[left] <= val:
                    p = left + 1
                else:
                    p = left
                break
            if left + 1 == right:
                if val < a[left]:
                    p = left
                elif val < a[right]:
                    p = right
                else:
                    p = right + 1
                break
            mid = (left + right) // 2
            if val <= a[mid]:
                right = mid
                continue
            else:
                left = mid + 1
                continue
        for j in range(i, p, -1):
            a[j] = a[j - 1]
        a[p] = val

def binary_insertion_sort2(a: List[int]) -> None:
    for i in range(1, len(a)):
        bisect.insort(a, a.pop(i), 0, i)

def binary_insertion_sort3(a: List[int]) -> None:
    """２分挿入ソート"""
    n = len(a)
    for i in range(1, n):
        key = a[i]
        pl = 0      # 探索範囲の先頭要素の添字
        pr = i - 1  # 探索範囲の末尾要素の添字

        while True:
            pc = (pl + pr) // 2     # 探索範囲の中央要素の添字
            if a[pc] == key:        # 探索成功
                break
            elif a[pc] < key:
                pl = pc + 1
            else:
                pr = pc - 1
            if pl > pr:
                break
        # 挿入すべき位置の添字
        pd = pc + 1 if pl <= pr else pr + 1

        for j in range(i, pd, -1):
            a[j] = a[j - 1]
        a[pd] = key
    return a

if __name__ == "__main__":
    import copy
    num = int(input("input an integer: "))
    l = [random.randint(0, num) for _ in range(num)]
    start = time.time()
    b = copy.copy(l)
    binary_insertion_sort3(b)
    end = time.time()
    print(l)
    print(b)
    print(end - start)


import time
import pytest
from PageObjects.CartPage import CartPage
from PageObjects.HomePage import HomePage
from PageObjects.confirmPage import ConfirmPage
from TestData import HomePageData
from utility.BaseClass import BaseClass

class TestOne(BaseClass):

    def test_e2e(self, getData):
        log = self.getlogger()
        log.info("Below are used for Logging")
        homePage = HomePage(self.driver)
        cartPage = CartPage(self.driver)
        confirmPage = ConfirmPage(self.driver)

        # list2 =s []
        # homePage.SearchProduct().send_keys("ber")
        homePage.SearchProduct().send_keys(getData)
        # homePage.SearchProduct().send_keys(getData["search1"])
        time.sleep(1)
        sCunt = homePage.count()
        # print(sCunt)
        log.info("Count is ==>"+str(sCunt))
        assert sCunt == 3
        homePage.proceed_checkout()
        time.sleep(2)
        cartPage.print_veggies()
        confirmPage.confirmOrder()

    # @pytest.fixture(params=[{"search1":"ber"}, {"search2":"Ser"}])
    @pytest.fixture(params=HomePageData.TestHomePageData.TestDataHomePage)
    def getData(self, request):
        return request.param


# -*- coding: utf-8 -*-
"""
Functions for spatial filtering of points.

@author: Michelle M. Fink, michelle.fink@colostate.edu
         Colorado Natural Heritage Program, Colorado State University
Created on 03/26/2018 - Built on python 2.7.14, geopandas 0.3.0, and pysal 1.14.3

Code licensed under the GNU General Public License version 3.
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see https://www.gnu.org/licenses/
"""

import os
import pysal
import geopandas as gpd

def filter_duplicates(infile, idfield, rankfield, otherfld=None, epsg=None):
    '''Removes spatial duplicates and returns unique shapes with the maximum
    value of specified rankfield. Output is a geopandas dataframe.

    infile: (string) path, filename, and extension of input geodata file (e.g., shapefile)
    idfield: (string) fieldname that uniquely identifies each record
    rankfield: (string) fieldname of a numeric ranking field
    otherfld: (string, optional) a third field to save in the output, only the
        first encountered value among the duplicates is retained.
    epsg: (string, optional) in the form 'epsg:<number>' representing coordinate
        projection of the geodata.
    '''
    geodf = gpd.read_file(infile)
    if epsg is not None:
        geodf.crs = {'init': epsg}
    geodf['xy'] = geodf['geometry'].apply(lambda x: str(x))
    if otherfld is None:
        fldlist = [idfield, 'xy', rankfield, otherfld, 'geometry']
        flddict = {idfield: 'min', rankfield: 'max', otherfld: 'first'}
    else:
        fldlist = [idfield, 'xy', rankfield, 'geometry']
        flddict = {idfield: 'min', rankfield: 'max'}
    geodf = geodf[fldlist]
    nodups = geodf.dissolve(by='xy', aggfunc=flddict)
    return nodups

def filter_by_distance_rank(infile, dist, rankfield):
    '''Thins out a point geodataset so that the selected points represent
    the maximum rankfield value of all points within the specified distance.
    Output is a geopandas dataframe.

    infile: (string) path, filename, and extension of input geodata file (e.g., shapefile)
    dist: (number, float or integer) minimum distance, in projection units
    rankfield: (string) fieldname of a numeric ranking field
    '''
    indf = pysal.pdio.read_files(infile)
    wdist = pysal.weights.DistanceBand.from_dataframe(indf, dist, silent=True)
    wdw = wdist.weights
    wdn = wdist.neighbors

    for fid in wdist:
        nwpairs = [(k, indf[rankfield][k]) for k in fid[1].iterkeys()]
        newdic = dict(nwpairs)
        wdw.update({fid[0]:newdic.values()})
        wdn.update({fid[0]:newdic.keys()})

    wnew = pysal.W(wdn, wdw, silent_island_warning=True)
    keeplst = []
    procd = []

    for nwfid in wnew:
        idx = nwfid[0]
        if len(nwfid[1].keys()) > 0:
            fdict = nwfid[1]
            iwght = indf[rankfield][idx]
            fdict.update({idx:iwght})
            winner = fdict.keys()[fdict.values().index(max(fdict.values()))]
            if winner not in procd:
                keeplst.append(winner)
                procd = procd + wdn[winner]
                procd.append(winner)
        else:
            keeplst.append(idx)
            procd.append(idx)

    keeplst = list(set(keeplst))
    return indf.iloc[keeplst]

if __name__ == "__main__":
    wd = r"D:\GIS\Projects\WYNDD\Final_inputs"
    infile = "Absence_pts_train_raw.shp"
    outfile = "Absence_pts_train_1km.shp"
    infile = os.path.join(wd, infile)
    outfile = os.path.join(wd, outfile)
    # Filter points
    kpdf = filter_by_distance_rank(infile, 1000, 'QRank')
    pysal.pdio.write_files(kpdf, outfile)

    # Remove duplicates
    #NAD83(2011) / Conus Albers = 'epsg:6350'
    outgdf = filter_duplicates(infile, 'OBJECTID', 'QRank', 'Pres_Abs', 'epsg:6350')
    outgdf.to_file(outfile)


import numpy as np
import math
from cap6635.agents.blindsearch.vacuum import Vacuum

from cap6635.utilities.constants import (
    MOVE_UP, MOVE_DOWN, MOVE_LEFT, MOVE_RIGHT
)

class MazeRunner(Vacuum):
    '''
    Base MazeRunner Class
    - See parent class for more details
    - Every step taken is (-1)
    '''

    def __init__(self, environ, policy, state=0,
                 start=(1, 1), elements_in_row=10):
        super(MazeRunner, self).__init__(environ, start)
        self._policy = policy
        self._state = state
        self._elements_in_row = elements_in_row

    @property
    def state(self):
        return self._state

    def move(self):
        action = np.where(self._policy[self._state] == 1)[0][0]
        if action == MOVE_UP:
            self._state -= self._elements_in_row
        elif action == MOVE_DOWN:
            self._state += self._elements_in_row
        elif action == MOVE_LEFT:
            self._state -= 1
        elif action == MOVE_RIGHT:
            self._state += 1
        self._y = (self._state % self._elements_in_row) + 1
        self._x = (math.floor(self._state / self._elements_in_row)) + 1
        self.utility = -1
        self.add_to_path((self._x, self._y))
        self.time = 1


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        self.bstList=[]
        self.inorder(root)
        for i in range(1,len(self.bstList)):
            if self.bstList[i]>self.bstList[i-1]:
                continue
            else:
                return False
        return True
    def inorder(self,root):
        #base condition
        if root==None:
            return
        self.inorder(root.left)
        #stack.pop()
        print("UP at line 23")
        print("root.val at 24",root.val)

        ###This is where root goes inside the bstList
        self.bstList.append(root.val)
        print("bstList=",self.bstList)
        self.inorder(root.right)
        #stack.pop()
        print("DOWN at line 30")
        print("root.val at line 31",root.val)


"""
생각보다 점화식을 생각해내는데 시간이 오래 걸렸다.
정답 비율이 49%라서 쉬울 줄 알았는데, 역시 내가 부족한가보다.

우선 문제에서 스티커를 떼어내면 그 스티커의 왼쪽,오른쪽,위,아래를 못쓴다고 한다.
그렇다면 최대 점수는 대각선으로만 더해가면 도출할 수 있지않을까?

하지만 아니었다. 만약 대각선이 아니더라도 i-2의 같은 행에 있는 스티커 또한 고를 수 있었다.

그렇다면 bottom up 방식으로 왼쪽에서 오른쪽으로 최대값을 보장해나가면서 i-1번째 대각선과 i-2번째 같은 행의 값의 최대값을 골라서 더해가면 될 것 같다.

점화식은 다음과 같다.

P[0][i] = max(P[1][i-1], P[0][i-2]) + Data[0][i]

P[1][i] = max(P[0][i-1], P[1][i-2]) + Data[1][i]

"""

import sys

T = int(input())

for _ in range(T):
  N = int(sys.stdin.readline())

  data =[]
  dp = [[0,0,0],[0,0,0]]

  for _ in range(2):
    data.append(list(map(int,sys.stdin.readline().split())))

  for i in range(N):

    if i==0:
      dp[0][0] = data[0][i]
      dp[1][0] = data[1][i]

    elif i==1:
      dp[0][1] = dp[1][0]+data[0][i]
      dp[1][1] = dp[0][0]+data[1][i]

    else:
      dp[0][2] = max(dp[1][1], dp[1][0])+data[0][i]
      dp[1][2] = max(dp[0][1], dp[0][0])+data[1][i]

      dp[0][0] = dp[0][1]
      dp[1][0] = dp[1][1]

      dp[0][1] = dp[0][2]
      dp[1][1] = dp[1][2]

  print(max(dp[0][2],dp[1][2]))


import Queue
#from queue import Queue
import copy
import random

que = Queue.Queue()
s = set()
literal_map = {}
friends = []
enemies = []
KB = []
tables = 0
guests = 0

def main():
    """"start the program"""
    try:
        ifile = open('input.txt')
    except:
        return 0

    inputgrid = []
    for line in ifile:
        inputgrid.append(line.strip())

    copy_input_grid(inputgrid)
    covert_to_cnf()
    is_satisfy = pl_resolve(KB)
    if is_satisfy:
        WalkSAT()
    else:
        ofile = open("output.txt", mode='w')
        ofile.write("no")
        ofile.close()

class Literal:
    def __init__(self, person, table, is_negated):
        self.person = person
        self.table = table
        self.is_negated = is_negated

    def __str__(self):
        return "{}, {}, {}".format(self.person, self.table, self.is_negated)

    def __repr__(self):
        return "[{}, {}, {}]".format(self.person, self.table, self.is_negated)

    def is_negated_of(self, l):
        if self.person == l.person and self.table == l.table and self.is_negated != l.is_negated:
            return True
        else:
            return False

def copy_input_grid(inputgrid):
    global tables, guests
    igrid = inputgrid[0].split(' ')
    guests = igrid[0]
    tables = igrid[1]

    for i in range(len(inputgrid) - 1):
        igrid = inputgrid[i + 1].split(' ')
        if igrid[2] == "F":
            friends.append([int(igrid[0]) - 1, int(igrid[1]) - 1])
        else:
            enemies.append([int(igrid[0]) - 1, int(igrid[1]) - 1])

def covert_to_cnf():
    # add Friends conditions
    for f in friends:
        for t in range(int(tables)):
            newfriendclause1 = []
            newfriendclause2 = []

            l1 = Literal(f[0], t, True)
            l2 = Literal(f[0], t, False)
            l3 = Literal(f[1], t, True)
            l4 = Literal(f[1], t, False)

            newfriendclause1.append(l1)
            newfriendclause1.append(l4)
            newfriendclause2.append(l2)
            newfriendclause2.append(l3)

            for i in newfriendclause1:
                literal_map.setdefault(str(i), []).append(newfriendclause1)
            for i in newfriendclause2:
                literal_map.setdefault(str(i), []).append(newfriendclause2)

            KB.append(newfriendclause1)
            KB.append(newfriendclause2)

    # add Enemies coditions
    for e in enemies:
        for t in range(int(tables)):
            newenemyclause1 = []

            l1 = Literal(e[0], t, True)
            l2 = Literal(e[1], t, True)
            newenemyclause1.append(l1)
            newenemyclause1.append(l2)

            for i in newenemyclause1:
                literal_map.setdefault(str(i), []).append(newenemyclause1)
            KB.append(newenemyclause1)

    # add one guest only at one table condition
    for g in range(int(guests)):
        personatleastonetable = []
        for t in range(int(tables)):
            l1 = Literal(g, t, False)
            personatleastonetable.append(l1)

        for m in personatleastonetable:
            literal_map.setdefault(str(m), []).append(personatleastonetable)
        KB.append(personatleastonetable)

        for i in range(int(tables) - 1):
            for j in range(i + 1, int(tables)):
                personatmaxonetable = []
                l1 = Literal(g, i, True)
                l2 = Literal(g, j, True)
                personatmaxonetable.append(l1)
                personatmaxonetable.append(l2)

                for k in personatmaxonetable:
                    literal_map.setdefault(str(k), []).append(personatmaxonetable)
                KB.append(personatmaxonetable)

def pl_resolve(PKB):
    LKB = PKB

    for i in LKB:
        que.put(i)
        st = set()
        for j in i:
            st.add(str(j))
        stemp = sorted(st)
        strr = ""
        strr = ", ".join(str(e) for e in stemp)
        s.add(strr)

    while not que.empty():
        l1 = que.get()
        for i in range(len(l1)):
            line_new = str(l1[i]).split(' ')
            nvalue = line_new[0] + " " + line_new[1] + " " + str(False if line_new[2] == str("True") else True)

            for j in literal_map[nvalue]:
                resolved = resolve(l1, j)
                if que.qsize() > 100001:
                    return True
                if resolved == False:
                    return False
    return True

def resolve(l1, l2):
    temp = []
    ncount = 0
    l1r, l2r = [], []
    for i in range(len(l1)):
        for j in range(len(l2)):
            if l1[i].is_negated_of(l2[j]):
                l1r.append(i)
                l2r.append(j)
                ncount += 1

    all_compliment = ncount == len(l1) == len(l2)
    only_one = ncount == len(l1) == len(l2) == 1
    for i in range(len(l1)):
        if not all_compliment and not l1r.__contains__(i):
            temp.append(l1[i])

    for j in range(len(l2)):
        if not all_compliment and not l2r.__contains__(j):
            temp.append(l2[j])

    if all_compliment and only_one:
        return False
    elif all_compliment:
        return True

    if len(temp) == 0:
        return False

    st = set()
    for j in temp:
        st.add(str(j))
    stemp = sorted(st)
    strr = ""
    strr = ", ".join(str(e) for e in stemp)

    if s.__contains__(strr) == False:
        s.add(strr)
        que.put(temp)
        for i in st:
            literal_map.setdefault(str(i), []).append(temp)

def WalkSAT():
    outfile = open("output.txt", mode='w')
    outfile.write("yes")
    friend_map = {}
    enemy_map = {}
    final_map = {}
    for fri in friends:
        friend_map.setdefault(fri[0], []).append(fri[1])

    for eny in enemies:
        enemy_map.setdefault(eny[0], []).append(eny[1])
        enemy_map.setdefault(eny[1], []).append(eny[0])

    people_map = {}
    for gue in range(int(guests)):
        people_map.setdefault(gue, False)

    def friends_of(f, flist):
        flist.append(f)
        people_map[f] = True
        if friend_map.__contains__(f):
            for fi in friend_map[f]:
                friends_of(fi, flist)

    for t in range(int(tables)):
        for fmap in friend_map:
            if False == people_map[fmap]:
                flist = []
                friends_of(fmap, flist)
                final_map.setdefault(t, flist)
                t += 1

    original_map = copy.deepcopy(final_map)

    if len(final_map) > int(tables):
        for i in range(len(final_map)-1, 0, -1):
            bre = False
            if final_map.__contains__(i):
                for j in final_map[i]:
                    if bre: break
                    if final_map.__contains__(i-1):
                        for k in final_map[i-1]:
                            if enemy_map.__contains__(j):
                                if enemy_map[j][0] == k:
                                    bre = True
                                    break

                if bre == False:
                    temp = final_map[i]
                    temp1 = final_map[i-1]
                    final_map[i-1] = temp + temp1
                    del final_map[i]

    t, g, j = 0, 0, 0
    for g in range(int(guests)):
        if people_map[g] == False:
            if enemy_map.__contains__(g):
                for t in range(int(tables)):
                    if len(final_map) == 0:
                        final_map.setdefault(t, []).append(g)
                        people_map[g] = True
                        for p in enemy_map[g]:
                            final_map.setdefault(t+1, []).append(p)
                            people_map[p] = True
                        break
                    else:
                        list = final_map[t]
                        l = 0
                        enemy_exists = False
                        for l in list:
                            if enemy_exists == True:
                                break
                            for e in enemy_map[g]:
                                if e == l:
                                    enemy_exists = True
                                    break
                        people_map[g] = True
                        if enemy_exists == False:
                            final_map.setdefault(t, []).append(g)
                        elif t > 0:
                            final_map.setdefault(t-1, []).append(g)
                        else:
                            final_map.setdefault(t+1, []).append(g)
                        break
            else:
                final_map.setdefault(t, []).append(g)
                people_map[g] = True

    if len(final_map) > int(tables):
        def check_enemy(a, b):
            for p in a:
                for q in b:
                    if enemy_map.__contains__(p):
                        for e in enemy_map[p]:
                            if q == e:
                                return True
            return False

        final_map = original_map
        satisfied = False
        table_assign = []
        key_of = []
        for key1 in final_map:
            table_assign.append(0)
            key_of.append(key1)

        for i in range(0, 10000):
            if(satisfied):
                break
            else:
                enemy_count = 0
                for i1 in range(0, len(final_map)):
                    for i2 in range(0, len(final_map)):
                        if i1 != i2 and table_assign[i1] == table_assign[i2]:
                            if check_enemy(final_map[key_of[i1]], final_map[key_of[i2]]):
                                enemy_count+=1
                                if random.randint(0,1) == 0:
                                    table_assign[i1] = random.randint(0, int(tables)-1)
                                    break
                                else:
                                    table_assign[i2] = random.randint(0, int(tables) - 1)
                                    break
                    if enemy_count != 0:
                        break
                if enemy_count == 0:
                    satisfied = True

        final_map = {}
        for i in range(0, len(table_assign)):
            final_map.setdefault(table_assign[i], [])
            for val in original_map[key_of[i]]:
                final_map.setdefault(table_assign[i], []).append(val)

    stri = ""
    arra = []
    for r in range(int(guests)+1):
        arra.append(-1)
    for fm in final_map:
        for z in final_map[fm]:
            arra[z+1]=fm+1

    for q in range(1,int(guests)+1,1):
        stri = "\n"+str(q)+" "+str(arra[q])
        outfile.write(stri)
    outfile.close()

if __name__ == "__main__": main()


#import modules
import os
import csv
#defining path
csv_path = os.path.join("Resources", "election_data.csv")
output = ""
with open(csv_path) as csv_file:
    # CSV reader specifies delimiter and variable that holds contents
    csv_reader = csv.reader(csv_file, delimiter=',')
    #printing header for output
    output ="Election Results\n-------------------------\n"
    next(csv_reader)
     #number of votes
    row_count = sum(1 for row in csv_file)
    output = output +"Total Votes: " + str(row_count)+"\n-------------------------\n"
#finds the unique candidates and puts them in a list
with open(csv_path) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter = ',')
    Candidate = {}
    for row in csv_reader:
        if row[2] not in Candidate:
            Candidate[row[2]]=0

Candidate.pop('Candidate')
#print(Candidate)
#finds the number of votes for each candidate
with open(csv_path) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter = ',')
    next(csv_reader)
    winner = ""
    most = 0
    for row in csv_reader:
        Candidate[row[2]] = Candidate[row[2]] + 1
    for key in Candidate:
        per = (Candidate[key]/row_count)*100
        output = output + key + " " + "{:.2f}".format(per) + "% (" + str(Candidate[key])+ ") votes \n"
        if most < Candidate[key]:
            most = Candidate[key]
            winner = key
    output = output +"\n-------------------------\nThe winner is: " + winner
    print(output)
file1 = open("myresults.txt","w")
file1.write(output)
file1.close()


import os, re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from loguru import logger

logger.info('Import OK')

input_folder = 'src/'
output_folder = 'results/manuscript/compile_snakemake/'

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# list of python scripts
paths = [os.path.join(root, filename).replace('\\', '/') for root, dirs, files in os.walk(input_folder, topdown=False) for filename in files if 'utilities' not in root]

paths = [path for path in paths if 'snakemake' not in path]

# Read each script and generate example rules
components = [
    "rule all:\n",
    "    input:\n",
    "        ['results/one.csv', \n",
    "        'results/two.csv',  \n",
    "        'results/three.svg', \n",
    "        'results/four.png']\n",
    "    shell:\n",
    "        'echo \"Initiating all rules\"'\n\n\n"
]
for filepath in paths:
    script_name = filepath.split('/')[-1].replace('.py', '')
    if 'fluorescence' in filepath:
        components.extend([f'rule fluorescence_{script_name}:\n'])
    elif 'proteomics' in filepath:
        components.extend([f'rule proteomics_{script_name}:\n'])
    elif 'comparison' in filepath:
        components.extend([f'rule comparison_{script_name}:\n'])
    elif 'manuscript' in filepath:
        components.extend([f'rule manuscript_{script_name}:\n'])
    components.extend(['    input: \n        ', '\n    output: \n        ', '\n    script:\n        ', f'"{filepath}"\n\n\n'])

# Write to  template file with some basic snakemake boilerplate
with open(f'{output_folder}snakefile', 'w') as f:
    for line in components:
        f.write(line)

# -----------CURATE SNAKEMAKE FILE WITH INPUTS AND OUTPUTS FOR EACH STAGE-----------
# Move compiled.txt into root directory and relabel as 'snakemake'
# Run using ```snakemake -p --cores 1``` at the command line

## NOTE: The compile file must be edited manually to ensure accurate curation of the inputs and outputs for each script!
## NOTE: A initial rule "all" is added at the top of the script - it should contain as input all the output files, and prints a success message:
# rule all:
#     input:
#         ["results/one.csv",
#         "results/two.csv",
#         "results/three.svg",
#         "results/four.png"]
#     shell:
#         'echo "Initiating all rules"'


from typing import Union
from pick import pick
from dateutil.parser import parse as dateparse
from os import system

class _Prompt:
    def __init__(self, name, validate=None, default=None) -> None:
        self.imperative = "Enter"
        self.name = name
        self.validate = validate
        self.default = default

        self.__repr__ = lambda self: f"{self.__class__.__name__} prompt type"

    def __repr__(self) -> str:
        return "Prompt superclass"

    @property
    def title(self):
        return f"{self.imperative} {self.name}: "

    def parse(self, response):
        return response

    @staticmethod
    def clear():
        system("cls")
        system("clear")

    def prompt(self):
        self.clear()
        while True:
            if self.default:
                response = input(
                    f"{self.imperative} {self.name} (default: {self.default}): "
                )
            else:
                response = input(self.title)
            try:
                if not response:
                    if self.default:
                        response = self.default
                    else:
                        raise ValueError

                response = self.parse(response)

                if self.validate:
                    if self.validate(response):
                        break
                    else:
                        raise ValueError
                else:
                    break

            except Exception:
                _Prompt.clear()
                print(f"Invalid {self.name} '{response}'")

        _Prompt.clear()
        return response

class List(_Prompt):
    def __init__(
        self, name, options: Union[dict, list], indicator="->", default=None
    ) -> None:
        self.imperative = "Select"
        self.options = options
        self.indicator = indicator
        self.default = default

        super().__init__(name)

    def prompt(self):
        index = 0
        if isinstance(self.options, dict):
            if self.default:
                index = list(self.options.keys()).index(self.default)
            return self.options[
                pick(
                    list(self.options.keys()),
                    self.title,
                    self.indicator,
                    default_index=index,
                )[0]
            ]
        else:
            if self.default:
                index = self.options.index(self.default)
            return pick(self.options, self.title, self.indicator, default_index=index)[
                0
            ]

class Int(_Prompt):
    def __init__(self, name, validate=None, default=None) -> None:
        super().__init__(name, validate=validate, default=default)

    def parse(self, response):
        return int(response)

class Text(_Prompt):
    def __init__(self, name, validate=None, default=None) -> None:
        super().__init__(name, validate=validate, default=default)

class Date(_Prompt):
    def __init__(self, name, validate=None, default=None) -> None:
        super().__init__(name, validate=validate, default=default)

    def parse(self, response):
        date = dateparse(response)
        return date.strftime("%Y-%m-%d")

class Form:
    def __init__(self, prompts):
        self.prompts = prompts

    def execute(self):
        new = {}
        for key, prompt in self.prompts.items():
            new[key] = prompt.prompt()
        return new


# Խնդիր 4։ Գրել ծրագիր, որը պահանջում է ներմուծել մարդու
#          անուն։ Եթե այդ անունը վերջանում է «ուհի» վերջածանցով,
#          ապա տպում է «Ողջույն տիկին <անուն>», հակառակ
#          դեպքում «տիկին» բառի փոխարեն տպում է «պարոն»։

name = input('Անունը. ')

if name.endswith('ուհի'):
    print(f'Ողջույն տիկին {name}։')
else:
    print(f'Ողջույն պարոն {name}։')


import pandas as pd
import seaborn as sns
import collections
import numpy as np
from matplotlib import pyplot as plt
from preprocessing import PreProcessing
from graphs import Graphs
import time
from clustering import Clustering
from frequent_pattern import FrequentPattern
from sklearn.decomposition import PCA
from yellowbrick.cluster import KElbowVisualizer
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from mlxtend.preprocessing import TransactionEncoder

#cols = ["Channel","Region","Fresh","Milk","Grocery","Frozen","Detergents_Paper","Delicassen"]
df = pd.read_csv("test.csv",header=None,names=range(11))
all_labels = pd.unique(df.values.ravel('K'))
all_labels = all_labels[:-1]
#df = df.replace(np.nan, '', regex=True)
print(all_labels)
pp = PreProcessing()
gr = Graphs()
fp = FrequentPattern()
clustering  = Clustering()
#pp.categorize(df)
#gr.get_visual_data(df)

#df = df.drop(['Channel'], axis=1)
#df = df.drop(['Region'], axis=1)
start_time = time.time()
data_list = df.to_numpy()
new_data_list = []
for entry in data_list:
    new_entry = []
    for element in entry:
        if((element in all_labels) == True):
            new_entry.append(element)
    new_data_list.append(new_entry)
end_time = time.time()
print(end_time-start_time)
#print(new_data_list)

te = TransactionEncoder()
te_ary = te.fit(new_data_list).transform(new_data_list)
new_df = pd.DataFrame(te_ary, columns=te.columns_)
print(new_df)

min = 0.001

frequent_itemsets_apriori = fp.apriori(new_df,min,1)
print(frequent_itemsets_apriori.sort_values(by=['support'],ascending=False))

frequent_itemsets_fpgrowth = fp.fpgrowth(new_df,min,1)
print(frequent_itemsets_fpgrowth.sort_values(by=['support'],ascending=False))

frequent_itemsets_eclat =  fp.eclat(frequent_itemsets_apriori,min)
print(frequent_itemsets_eclat.sort_values(by=['support'],ascending=False))

list_of_datasets = [frequent_itemsets_apriori, frequent_itemsets_fpgrowth, frequent_itemsets_eclat]
min_supports = [0.100, 0.150, 0.200]
def get_all_graphs(list_of_datasets,min_supports):
    for dataset in list_of_datasets:
        gr.get_single_graph(dataset)
        for support in min_supports:
            gr.get_single_graph(dataset,support)
    gr.get_multiple_graph(list_of_datasets[0], list_of_datasets[1], list_of_datasets[2])
    for support in min_supports:
        gr.get_multiple_graph(list_of_datasets[0], list_of_datasets[1], list_of_datasets[2],filter_support=support)

get_all_graphs(list_of_datasets,min_supports)

df = pd.read_csv("data.csv")
df.drop(['Channel', 'Region'], axis=1)
colors = ['red', 'green', 'blue', 'orange']
pca = PCA(n_components=2, random_state=1)
pca_result = pca.fit_transform(df)
# Determine the number of clusters for KMeans and AGNES algorithms
n_clusters_kmeans = clustering.elbow_chart(df, model_type='Kmeans')
n_clusters_agnes = clustering.elbow_chart(df, model_type='AGNES')
clustering.kmeans_clustering(df, pca_result, colors, n_clusters_kmeans)
clustering.agnes_clustering(df, pca_result, colors, n_clusters_agnes)
# Selecting epsilon for DBSCAN by running an NearestNeighbours algorihm
# The optimal eps value is 0.3 as can be shown from the plot
clustering.eps_selection(pca_result)
clustering.dbscan_clustering(df, pca_result, eps=0.3, min_samples=15)