import curses
from collections import deque

class TargetWindow:
    target_aps = None
    target_display_limit = 10
    prio_x = 1
    bssid_x = 6
    avg_power_x = 27
    nr_associations_x = 38
    essid_x = 51

    def __init__(self):
        self.target_wnd = curses.newwin(15, 70, 0, 0)
        self.target_wnd.border(0)
        self.target_wnd.box()

    def draw_headers(self):
        self.target_wnd.addstr(0, 2, " Targets ", curses.COLOR_GREEN)
        self.target_wnd.addstr(1, self.prio_x, "Prio")
        self.target_wnd.addstr(1, self.bssid_x, "BSSID")
        self.target_wnd.addstr(1, self.avg_power_x, "Avg. Power")
        self.target_wnd.addstr(1, self.nr_associations_x, "# clients")
        self.target_wnd.addstr(1, self.essid_x, "ESSID")

    def draw_targets(self):
        prio = 1
        y = 2
        for ap in self.target_aps:
            if prio <= self.target_display_limit:
                self.target_wnd.addstr(y, self.prio_x, str(prio))
                self.target_wnd.addstr(y, self.bssid_x, ap.mac)
                self.target_wnd.addstr(y, self.avg_power_x, str(ap.get_avg_power()))
                self.target_wnd.addstr(y, self.nr_associations_x, str(len(ap.associations)))
                self.target_wnd.addstr(y, self.essid_x, ap.essid)
                y += 1
            else:
                remaining = len(self.target_aps) - self.target_display_limit
                self.target_wnd.addstr(y + 1, self.bssid_x, str(remaining) + " More ..")

            prio += 1

    def draw(self):
        self.target_wnd.erase()
        self.target_wnd.box()
        self.draw_headers()
        if self.target_aps:
            self.draw_targets()
        self.target_wnd.noutrefresh()

class StatusWindow:
    status_wnd = None
    wnd_width = None
    wnd_height = None

    max_items = 13
    items = None

    def __init__(self, height, width, y, x):
        self.wnd_width = width
        self.wnd_height = height
        self.status_wnd = curses.newwin(self.wnd_height, self.wnd_width, y, x)
        self.status_wnd.border(0)
        self.status_wnd.box()

        #init list
        self.items = list()
        self.max_items = self.wnd_height - 2

    def draw_headers(self):
        self.status_wnd.addstr(0, 2, " Status ", curses.COLOR_GREEN)

    def draw_messages(self):
        y = 1
        items = deque(self.items, self.max_items)
        for item in items:
            self.status_wnd.addstr(y, 2, item)
            y += 1

    def draw(self):
        self.status_wnd.box()
        self.draw_headers()
        self.draw_messages()
        self.status_wnd.noutrefresh()

class Dispay():
    screen = None
    target_wnd = None
    status_wnd = None

    def __init__(self, screen):
        self.screen = screen
        self.target_wnd = TargetWindow()
        self.status_wnd = StatusWindow(15, 70, 15, 0)
        self.update()

    def add_status_message(self, message):
        self.status_wnd.items.append(message)

    def set_target_aps(self, aps):
        self.target_wnd.target_aps = aps

    def update(self):
        self.target_wnd.draw()
        self.status_wnd.draw()
        self.screen.refresh()

    def wait_for_quit(self):
        self.add_status_message("Press 'q' to exit")
        self.update()
        while True:
            if self.screen.getkey() == 'q':
                break


import sys
import unittest

sys.path.append(".")
sys.path.append("..")

from jim.decorators import log

class TestUtils(unittest.TestCase):
    def _testing_function(self):
        return 42

    def test_unchanged(self):
        """
        Our decorator should not change init funcion behaviour.
        """
        self.assertEqual(
            log(self._testing_function)(), self._testing_function()
        )

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


from django.conf.urls.defaults import *

from cyder.cydns.nameserver.views import *
from cyder.cydns.urls import cydns_urls

urlpatterns = cydns_urls('nameserver')

urlpatterns += patterns('',
   url(r'(?P<domain>[\w-]+)/create_delegated/$',
       create_ns_delegated, name='nameserver-delegated-create'),
   url(r'(?P<domain>[\w-]+)/create/$',
       NSCreateView.as_view(), name='nameserver-by-domain-create'),
)


from django.http import HttpResponse
from rest_framework import viewsets, authentication, permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.exceptions import *
from utils.tools import *
from utils.custom_schema import CustomSchema
import coreapi
import coreschema

from .models import CaptchaBasic
import io
from utils.captcha_image import CaptchaImageGenerate

# 教程
# 视图 http://www.iamnancy.top/djangorestframework/Views/
# 视图集 http://www.iamnancy.top/djangorestframework/Viewsets/
# Schema http://www.iamnancy.top/djangorestframework/Schemas/

class CaptchaViewSet(viewsets.ViewSet):
    '''图形验证码 错误码10xxx'''

    schema = CustomSchema(manual_fields={
        'GET:/captcha/': [
            coreapi.Field("from", required=False, location="query",
                          description='请求来源：\n[wxapp:openid]\n后续陆续增加种类'),
        ],
        'GET:/captcha/image/': [
            coreapi.Field("token", required=True,
                          location="query", description='图形验证码 token'),
        ],
        'POST:/captcha/verify/': [
            coreapi.Field("token", required=True, location="form",
                          description='图形验证码 token'),
            coreapi.Field("code", required=True, location="form",
                          description='用户输入的验证码字符串'),
        ],
    })

    def list(self, request, format=None):
        '''获取图形验证码信息 token'''
        # 获取请求信息
        ip_addr = request.META.get('REMOTE_ADDR')
        request_sourse = request.query_params.get('from')
        # 生成验证码
        ins = CaptchaUtil.generate(ip_addr, request_sourse)
        return Response(res_format({'token': ins}))

    @action(detail=False)
    def image(self, request, format=None):
        '''通过 token 获取验证码图片'''
        # 提取 token 获取验证码 code
        token = request.query_params.get('token')
        code, fontSize, fontColor, noise = CaptchaUtil.get_code(token)
        # 将图形验证码写入 IO 流
        stream = io.BytesIO()
        inst = CaptchaImageGenerate(
            code=code, fontSize=fontSize, fontColor=fontColor, noise=noise)
        img = inst.create()
        img.save(stream, "PNG")
        # 返回图片
        return HttpResponse(stream.getvalue(), content_type='image/png')

    @action(methods=['post'], detail=False)
    def verify(self, request, format=None):
        '''校验图形验证码和用户输入的是否一致，通过则返回认证标识，否则返回新验证码 token'''
        # 获取及检查参数
        params = ['token', 'code']
        token, code = get_dict_values(request.data, params)
        if check_none(token, code):
            raise ParseError('缺少参数：' + ', '.join(params))
        # 验证
        result = CaptchaUtil.verify_by_code(token, code)
        # 验证失败则将原验证码弃用，并返回新的验证码 token
        if not result:
            ip_addr = request.META.get('REMOTE_ADDR')
            request_sourse = request.query_params.get('from')
            refresh_token = CaptchaUtil.generate(ip_addr, request_sourse)
            return Response(res_format({'authenticate': result, 'refresh_token': refresh_token}))
        return Response(res_format({'token': token, 'authenticate': result}))

class CaptchaUtil():
    '''图形验证码工具类'''
    @staticmethod
    def generate(ip_addr=None, request_sourse=None):
        '''在数据库中生成一份验证码'''
        record = CaptchaBasic(
            ipAddr=ip_addr,
            requestSourse=request_sourse
        )
        record.save()
        return record.token

    @staticmethod
    def get_code(token):
        '''通过验证码 token 获取验证码'''
        try:
            record = CaptchaBasic.objects.get(token=token)
            record.save()
            return (record.code, 28, '#7CB305', True)
        except CaptchaBasic.DoesNotExist:
            return ('请重新获取', 20, '#FF0000', False)

    @staticmethod
    def verify_by_code(token, code):
        '''校验图形验证码和用户输入的是否一致'''
        try:
            record = CaptchaBasic.objects.get(token=token)
            if record.available and record.code.lower() == code.lower():
                if record.authenticate is None:
                    record.authenticate = generate_unique_token32()
                record.save()
                return record.authenticate
            else:
                record.available = False
                record.save()
                return False
        except CaptchaBasic.DoesNotExist:
            return False

    @staticmethod
    def _verify_by_authenticate(token, authenticate):
        '''内部接口，检查图形验证码是否校验通过'''
        try:
            record = CaptchaBasic.objects.get(token=token)
            if record.authenticate == authenticate and record.available:
                record.available = False
                record.save()
                return True
            else:
                return False
        except CaptchaBasic.DoesNotExist:
            return False


import numpy as np
import load_data as ld
import convlstm as md
import torch
import convlstm_training as tr
import evaluation as ev
import torch.nn as nn
from sgnht import Sampler

# Random seed

def main():
    # Training data
    grid_seqs = ld.load_batch_seq_data()
    input_seqs, target_meo_seqs, _, _ = tr.seq_preprocessing(grid_seqs)
    # Dev data
    dev_grid_seqs = ld.load_batch_dev_seq_data()
    dev_input_seqs, dev_target_meo_seqs, _, _ = \
        tr.seq_preprocessing(dev_grid_seqs)
    # Test data
    test_grid_seqs = ld.load_batch_test_seq_data()
    test_input_seqs, test_target_meo_seqs, avg_grid, std_grid = \
        tr.seq_preprocessing(test_grid_seqs)
    np.save('avg.npy', avg_grid)
    np.save('std.npy', std_grid)

    model = md.ConvLSTMForecast2L((21, 31), 256, 3, 1).cuda() #256
    snapshots = []
    losses = []
    dev_losses = []
    test_losses = []
    sampler = Sampler(model, nn.L1Loss(), momentum=0.9, lr=0.0005, wdecay=0.0, total=10000, A = 10.0)
    for i in range (60): #20
        model, loss, dev_loss = tr.train(
            model, input_seqs, target_meo_seqs, dev_input_seqs, dev_target_meo_seqs,
            snapshots, iterations=1, lr=0.001, sampler=sampler)

        test_loss = ev.compute_dev_set_loss(
            model,
            test_input_seqs,
            test_target_meo_seqs)

        losses.append(loss)
        dev_losses.append(dev_loss)
        test_losses.append(test_loss)

        print('Epoch: {}, Train loss: {}, Dev loss: {}, Test loss: {}'.format(
            i, loss, dev_loss, test_loss))
        if i >= 50:
            outputs = ev.prediction(model,test_input_seqs)
            outputs = {'prediction': outputs, 'truth': test_target_meo_seqs}
            np.savez_compressed('./models/point_epo{}.npz'.format(i), **outputs)
            print('Predictions saved as epo{}.npz'.format(i))

    # for i in range (70): #50
    #     model, loss, dev_loss = tr.train(
    #         model, input_seqs, target_meo_seqs, dev_input_seqs, dev_target_meo_seqs,
    #         snapshots, iterations=1, lr=0.0001)

    #     test_loss = ev.compute_dev_set_loss(
    #         model,
    #         test_input_seqs,
    #         test_target_meo_seqs)

    #     losses.append(loss)
    #     dev_losses.append(dev_loss)
    #     test_losses.append(test_loss)

    #     print('Epoch: {}, Train loss: {}, Dev loss: {}, Test loss: {}'.format(
    #         i, loss, dev_loss, test_loss))
    #     if (i+1)%10 == 0:
    #         outputs = ev.prediction(model,test_input_seqs)
    #         np.save('./point_epo{}.npy'.format(i+120), outputs)
    #         print('Predictions saved as epo{}.npy'.format(i+120))

    losses = np.array(losses)
    dev_losses = np.array(dev_losses)
    test_losses = np.array(test_losses)
    np.save('loss.npy', np.stack([losses,dev_losses,test_losses]))

if __name__ == "__main__":
    main()


import torch
import torch.nn as nn

def diceCoeff(pr, gt, beta=1, eps=1e-7, threshold=None, activation='sigmoid'):
    """
    Args:
        pr (torch.Tensor): A list of predicted elements（预测的元素）
        gt (torch.Tensor):  A list of elements that are to be predicted（待预测的元素）
        eps (float): epsilon to avoid zero division（防止0作为分母的情况发生）
        threshold: threshold for outputs binarization（输出二元值时候使用的阈值）
    Returns:
        float: IoU (Jaccard) score（IoU分数）
    """

    if activation is None or activation == "none":
        activation_fn = lambda x: x
    elif activation == "sigmoid":
        activation_fn = nn.Sigmoid()
    elif activation == "softmax2d":
        activation_fn = nn.Softmax2d()
    else:
        raise NotImplementedError(
            "Activation implemented for sigmoid and softmax2d 激活函数的操作"
        )

    pr = activation_fn(pr)

    if threshold is not None:
        pr = (pr > threshold).float()

    N = gt.size(0)
    pr_flat = pr.view(N, -1)
    gt_flat = gt.view(N, -1)
    tp = torch.sum(gt_flat * pr_flat, dim=1)  # 真正
    fp = torch.sum(pr_flat, dim=1) - tp  # 假正
    fn = torch.sum(gt_flat, dim=1) - tp  # 假负

    score = ((1 + beta ** 2) * tp + eps) / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + eps)
    return score.sum() / N

class DiceLoss(nn.Module):
    __name__ = 'dice_loss'

    def __init__(self, eps=1e-7, activation='sigmoid'):
        super(DiceLoss, self).__init__()
        self.activation = activation
        self.eps = eps

    def forward(self, y_pr, y_gt):
        return 1 - diceCoeff(y_pr, y_gt, beta=1.,
                        eps=self.eps, threshold=None,
                        activation=self.activation)

if __name__ == "__main__":
    import torch

    pr = torch.Tensor([[[[0.9]],
                        [[0.9]],
                        [[0.9]]],
                       [[[0.9]],
                        [[0.9]],
                        [[0.9]]],
                       [[[0.9]],
                        [[0.9]],
                        [[0.9]]],
                       [[[0.9]],
                        [[0.9]],
                        [[0.9]]]])
    gt = torch.Tensor([[[[1]],
                        [[1]],
                        [[1]]],
                       [[[1]],
                        [[1]],
                        [[1]]],
                       [[[1]],
                        [[1]],
                        [[1]]],
                       [[[1]],
                        [[1]],
                        [[1]]]])

    loss_fn = DiceLoss()
    loss = loss_fn(pr, gt)
    dice = diceCoeff(pr, gt)
    print(dice)
    print(loss)


"""Class for working with FITS images
"""

class fits_image:

    def __init__(self, file_path):
        self.fits = fits.open(file_path)
        self.image = self.fits[0]
        self.imdata = self.image.data.squeeze()

    def plot_image(self, colorbar = True):
        plt.imshow(self.imdata, origin='lower')
        if colorbar:
            plt.colorbar()

    def fit_bivariate_gaussian(self, noise_thresh):
        X = range(len(self.imdata[0]))
        Y = range(len(self.imdata))
        Z = self.imdata
        Z = np.nan_to_num(Z,  0)

        Z[Z<(noise_thresh)] = 0  # remove noise in figure
        X, Y = np.meshgrid(X, Y)
        pos = np.dstack((X, Y))
        x1_bar = np.average(X, weights=Z)      #Weighted X mean
        x2_bar = np.average(Y, weights=Z)      #Weighted Y mean
        x1_var = np.average((X-x1_bar)**2, weights=Z)  #Weighted X variance
        x2_var = np.average((Y-x2_bar)**2, weights=Z)  #Weighted Y variance
        x_cov = np.average(X*Y, weights=Z)-x1_bar*x2_bar #Weighted Covariance

        cov_mat = np.array([[x1_var, x_cov],[x_cov, x2_var]]) #Covariance matrix

        self.gaussian_mean = [x1_bar, x2_bar]
        self.gaussian_cov = cov_mat

        return([x1_bar, x2_bar, cov_mat])

        rv = stats.multivariate_normal([x1_bar, x2_bar], cov_mat) #Fitting a new Gaussian Normal with our parameters.

#TODO: finish plot fit function
    # def plot_gaussian_fit(self):

    def get_noise_level(self, nchunks = 3, rms_quantile = 0):
        '''
        nchunks = number of chunks for grid, must be odd
        rms_quantile = quantile of chunk RMS to use for noise level (0 = min RMS, 0.5 = median, etc)
        '''

        id1 = np.argwhere(np.isnan(self.imdata))[:,0]
        id2 = np.argwhere(np.isnan(self.imdata))[:,1]

        imdata = self.imdata.copy()

        imdata = np.delete(imdata, id1, axis=0)
        imdata = np.delete(imdata, id2, axis=1)

        #now break the image into chunks and do the same analysis;
        # one of the chunks should have no signal in and give you an estimate of the noise (= rms).# number of chunks in each direction:
        # an odd value is used so that the centre of the image does not correspond to the edge of chunks;
        # when you ask for observations with ALMA, you usually specify that the object of interest be in the
        # center of your image.
        size = [i//nchunks for i in imdata.shape]
        remain = [i % nchunks for i in imdata.shape]
        chunks = dict()
        k = 0
        for j,i in itertools.product(range(nchunks),range(nchunks)):
            chunks[k] = size.copy()
            k += 1# next, account for when the image dimensions are not evenly divisible by `nchunks`.
        row_remain, column_remain = 0, 0
        for k in chunks:
            if k % nchunks < remain[0]:
                row_remain = 1
            if k // nchunks < remain[1]:
                column_remain = 1
            if row_remain > 0:
                chunks[k][0] += 1
                row_remain -= 1
            if column_remain > 0:
                chunks[k][1] += 1
                column_remain -= 1# with that in hand, calculate the lower left corner indices of each chunk
        indices = dict()
        for k in chunks:
            indices[k] = chunks[k].copy()
            if k % nchunks == 0:
                indices[k][0] = 0
            elif k % nchunks != 0:
                indices[k][0] = indices[k-1][0] + chunks[k][0]
            if k >= nchunks:
                indices[k][1] = indices[k-nchunks][1] + chunks[k][1]
            else:
                indices[k][1] = 0
        stddev_chunk = dict()
        rms_chunk = dict()
        for k in chunks:
            i,j = indices[k]
            di,dj = chunks[k]
            x = imdata[i:i+di,j:j+dj]
            stddev_this = np.nanstd(x)
            rms_this = np.sqrt(np.nanmean(x**2))
            stddev_chunk[k] = stddev_this
            rms_chunk[k] = rms_this

        noise = np.quantile(list(noise_all.values()), q = rms_quantile)
        self.noise = noise
        return(noise)


import datetime as dt, sys, os

from shutil import copy, make_archive, rmtree

from fpdf import FPDF

sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))

from app import app, db, models

def create_pdf_note_summaries(paths):

    for path in paths:

        pdf_file_name = path.split('/')[-1] + '_notes_summary.pdf'
        notes_summary_pdf = FPDF()

        notes_summary_pdf.set_font('Arial', size = 12)

        files = os.listdir(path)
        files.sort()

        for f in files:
            if 'txt' == f.split('.')[1]:
                with open(os.path.join(path, f), 'r') as txt_file:
                    text = txt_file.read()

                    text_no_latin = text.encode('latin-1', 'replace').decode('latin-1')

                    notes_summary_pdf.add_page()
                    notes_summary_pdf.multi_cell(190, 10, txt = text_no_latin)

        notes_summary_pdf.output(os.path.join(path, pdf_file_name))

    return True

def write_appt_notes(appts, archive_dir, pdfs=False):

    appt_summary = {}

    client_paths = set()

    for appt in appts:

        client_name = ' '.join((appt.client.first_name, appt.client.last_name))
        client_folder = '_'.join([str(appt.client.uci_id),client_name.lower().replace(' ','_')])
        client_path = os.path.join(archive_dir,appt.appt_type.name,client_folder)

        if appt.appt_type.name.lower() == 'treatment':
            client_paths.add(client_path)

        os.makedirs(client_path, exist_ok=True)

        appt_summary[appt.appt_type.name] = appt_summary.get(appt.appt_type.name,{})
        appt_summary[appt.appt_type.name]['count'] = appt_summary[appt.appt_type.name].get('count',0) + 1

        new_appt = ' - '.join([appt.start_datetime.strftime('%b %d, %Y %H:%M'),client_name])
        appt_summary[appt.appt_type.name]['appts'] =  appt_summary[appt.appt_type.name].get('appts',[])
        appt_summary[appt.appt_type.name]['appts'].append(new_appt)

        appt_file_name = '_'.join([client_name.lower().replace(' ','_'), appt.appt_type.name, appt.start_datetime.strftime('%Y_%m_%d'), str(appt.id)])

        with open(os.path.join(client_path, appt_file_name + '.txt'), 'w') as note_file:

            note_file.write('Client:      {}\n'.format(client_name))
            note_file.write('Appt Type:   {}\n'.format(appt.appt_type.name))
            note_file.write('Appt Date:   {}\n'.format(appt.start_datetime.strftime('%b %d, %Y %H:%M')))

            therapist_name = ' '.join([appt.therapist.user.first_name, appt.therapist.user.last_name])
            note_file.write('Therapist:   {}\n\n'.format(therapist_name))

            note_file.write('Appt Note:\n\n')
            if appt.note:
                note_file.write(appt.note.note)
            else:
                note_file.write('NO NOTE')

        if appt.appt_type.name == 'evaluation':
            try:
                client_dir = os.path.join(archive_dir, '..', '..','..','clients', str(appt.client.id), 'evaluations')

                eval_file =  [f for f in os.listdir(client_dir) if str(appt.id) in f][0]

                copy(os.path.join(client_dir, eval_file), client_path)

            except:
                # print(appt.id,appt.client.first_name, appt.client.last_name)
                continue

    if pdfs:
        create_pdf_note_summaries(client_paths)

    return appt_summary

def create_financial_archive(start_date, end_date, regional_center_id):

    rc = models.RegionalCenter.query.get(regional_center_id)

    directory_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'docs',str(rc.company_id))
    # directory_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'docs','1')

    archive_name = '{}_financial_archive_from_{}_to_{}'.format(rc.name.lower(), start_date.strftime('%b_%Y'), end_date.strftime('%b_%Y')).lower()

    archive_path = os.path.join(directory_path, 'tmp', archive_name)

    os.makedirs(archive_path, exist_ok = True)

    included_invoices = []

    with app.app_context():

        billing_files = models.BillingXml.query.filter(models.BillingXml.billing_month.between(start_date, end_date),
                                                       models.BillingXml.regional_center_id == regional_center_id).all()

        for f in billing_files:

            bill_archive = os.path.join(archive_path,'bill_month_{}_submitted_{}'.format(f.billing_month.strftime('%Y_%m_%d'),f.created_date.strftime('%Y_%m_%d')))

            os.makedirs(bill_archive, exist_ok=True)

            copy(os.path.join(directory_path, 'billing',f.file_name), bill_archive)

            appt_summary = write_appt_notes(f.appts.order_by(models.ClientAppt.start_datetime).all(), bill_archive, True)

            with open(os.path.join(bill_archive, f.file_name.split('.')[0]  + '_summary.txt'), 'w') as summary_file:

                summary_file.write('Billing Invoice: {}\n'.format(f.file_name))
                summary_file.write('Billing Month: {}\n'.format(f.billing_month.strftime('%Y_%m_%d')))
                summary_file.write('Submitted Date: {}\n\n'.format(f.created_date.strftime('%Y_%m_%d')))

                for type in sorted(appt_summary.keys()):
                    summary_file.write(type.capitalize() + '\n')
                    summary_file.write('Total Appts: {}\n'.format(appt_summary[type]['count']))
                    summary_file.write('Appts:\n\n')
                    summary_file.write('\n'.join(appt_summary[type]['appts'])+'\n\n')

            included_invoices.append(f.file_name)

    make_archive(os.path.join(directory_path,'tmp',archive_name),'zip', archive_path)

    rmtree(archive_path, ignore_errors=True)

    return (os.path.join(directory_path, 'tmp'), archive_name + '.zip')


# -*- coding: utf-8 -*-
"""
Created on Wed Apr  4 13:02:14 2018

@author: mastu
"""

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

df_real = pd.read_csv('../Dataset/PCA_Dataset_v1.csv', encoding='latin-1')
df_real = df_real.replace(r'\s+', np.nan, regex=True)
df_real = df_real.dropna(subset=['History of complications'])
#df_real.set_index('Patient Index', inplace=True)

df_imputed = pd.read_csv('../Dataset/missForest_imputed.csv', encoding='latin-1')
#df_imputed.set_index('Patient Index', inplace=True)

df_real_matrix = df_real.values
df_imputed_matrix = df_imputed.values

x = np.arange(0.0, 778.0)
y1 = df_real_matrix[:,152]

y2 = df_imputed_matrix[:,152]
fig = plt.figure()
plt.scatter(x,y2,c="r")
plt.scatter(x,y1)
plt.xlabel("Patient Index")
plt.ylabel("Urinary.protein.at.12M")
plt.show()
fig.savefig("Urinary.protein.at.12M.png")

##x = df_imputed[:,0]
#x = np.arange(0.0, 779.0)
#y2 = df_imputed[:,35]
##print(x)
#
#plt.scatter(x,y)
#plt.show()


import json
import os
import time
import unittest
import logging
from typing import Dict

import oauthlib.oauth2
import requests_oauthlib

from edc_ogc.mdi import Mdi
from edc_ogc.configapi import ConfigAPI
from edc_ogc.ogc.wms import dispatch_wms_get_map

HAS_SH_CREDENTIALS = 'SH_CLIENT_ID' in os.environ and 'SH_CLIENT_SECRET' in os.environ
REQUIRE_SH_CREDENTIALS = 'requires SH credentials'

logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

TEST_EVALSCRIPT = """//VERSION=3
function setup() {
  return {
    input: ["B02", "B03", "B04"],
    output: { bands: 3 }
  };
}

function evaluatePixel(sample) {
  return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
}
"""

class ConfigClientMock:
    def get_evalscript_and_defaults(self, *args):
        return TEST_EVALSCRIPT, {
            "type": "S2L1C",
            "mosaickingOrder": "mostRecent",
            "maxCloudCoverage": 50,
            "temporal": False,
        }

class MdiTest(unittest.TestCase):

    def get_mdi(self) -> Mdi:
        client_id = os.environ.get('SH_CLIENT_ID')
        client_secret = os.environ.get('SH_CLIENT_SECRET')
        # instance_id = os.environ.get("SH_INSTANCE_ID")

        client = oauthlib.oauth2.BackendApplicationClient(client_id=client_id)
        session = requests_oauthlib.OAuth2Session(client=client)

        mdi = Mdi(
            client_id=client_id,
            client_secret=client_secret
        )
        return mdi

    # @unittest.skipUnless(HAS_SH_CREDENTIALS, REQUIRE_SH_CREDENTIALS)
    # def test_image(self):
    #     mdi = self.get_mdi()
    #     output = mdi.process_image(
    #         sources=['S2L1C'],
    #         bbox=(14.043549, 46.580095, 14.167831, 46.652688),
    #         # crs='http://www.opengis.net/def/crs/OGC/1.3/CRS84',
    #         crs='EPSG:4326',
    #         width=512,
    #         height=512,
    #         format='image/png',
    #         evalscript=TEST_EVALSCRIPT,
    #     )
    #     with open('out.png', 'wb') as f:
    #         f.write(output)

    # def test_dispatch_get_map(self):
    #     class ConfigClientMock:
    #         def get_evalscript_and_defaults(self, *args):
    #             return TEST_EVALSCRIPT, {
    #                 "type": "S2L1C",
    #                 "mosaickingOrder": "mostRecent",
    #                 "maxCloudCoverage": 50,
    #                 "temporal": False,
    #             }

    #     class WMSRequest:
    #         version = (1, 3, 0)
    #         layers = ['TRUE_COLOR']
    #         styles = ['default']
    #         crs = 'EPSG:4326'
    #         bbox = (46.580095, 14.043549, 46.652688, 14.167831)
    #         width = 512
    #         height = 512
    #         format = 'image/png'
    #         time = None

    #     mdi = self.get_mdi()
    #     config_client = ConfigClientMock()
    #     wms_request = WMSRequest()

    #     with open('out.png', 'wb') as f:
    #         f.write(
    #             dispatch_wms_get_map(mdi, config_client, wms_request)
    #         )

    def test_capabilities(self):
        from edc_ogc.ogc.wms import dispatch_wms_get_capabilities

        #dispatch_wms_get_capabilities(None, None)

    def test_parse_request(self):
        from edc_ogc.configapi import ConfigAPIDefaultLayers
        from edc_ogc.ogc.client import OGCClient, OGCRequest
        from edc_ogc.ogc.wms import WMS11GetMapDecoder, WMS13GetMapDecoder

        decoders = [
            WMS11GetMapDecoder('service=WMS&version=1.1.0&request=GetMap&layers=a&styles=b&srs=EPSG:4326&bbox=-180,-90,180,90&width=512&height=256&format=image/png'),
            WMS13GetMapDecoder('service=WMS&version=1.3.0&request=GetMap&layers=a&styles=b&crs=EPSG:4326&bbox=-90,-180,90,180&width=512&height=256&format=image/png'),
        ]

        for decoder in decoders:
            assert decoder.bbox
            self.assertEqual('EPSG:4326', decoder.crs)

        client_id = os.environ.get('SH_CLIENT_ID')
        client_secret = os.environ.get('SH_CLIENT_SECRET')
        client = OGCClient(ConfigAPIDefaultLayers(client_id, client_secret), 'None')

        # response, _ = client.dispatch(OGCRequest(
        #     method='GET',
        #     query='service=WMS&version=1.3.0&request=GetMap&layers=TRUE_COLOR&styles=&crs=EPSG:4326&bbox=46.580095,14.043549,46.652688,14.167831&width=512&height=512&format=image/png',
        # ))

        response, _ = client.dispatch(OGCRequest(
            method='GET',
            query='service=WMS&version=1.3.0&request=GetMap&layers=S2L1C__TRUECOLOR&styles=&crs=EPSG:3857&bbox=1500000,1500000,1600000,1600000&width=512&height=512&format=image/png',
            base_url='http://testserver.org/',
        ))

        with open('out.png', 'wb') as f:
            f.write(response)

        response, _ = client.dispatch(OGCRequest(
            method='GET',
            query='service=WMS&version=1.1.0&request=GetMap&layers=S2L1C__NDVI&styles=&srs=EPSG:4326&bbox=14.043549,46.580095,14.167831,46.652688&width=512&height=512&format=image/png',
            base_url='http://testserver.org/',
        ))

        with open('out2.png', 'wb') as f:
            f.write(response)

        response, _ = client.dispatch(OGCRequest(
            method='GET',
            query='service=WMS&version=1.1.0&request=GetCapabilities',
            base_url='http://testserver.org/',
        ))

        with open('out.xml', 'wb') as f:
            f.write(response)

    # @unittest.skipUnless(HAS_SH_CREDENTIALS, REQUIRE_SH_CREDENTIALS)
    # def test_woerthersee(self):
    #     request = Mdi.prepare_request(
    #         'S2L2A',
    #         ['B04', 'B03', 'B02'],
    #         ['t0', 't1', 't2', 't3'],
    #         (512, 512),
    #         ("2019-06-10T00:00:00Z", "2019-06-20T00:00:00Z"),
    #         (14.043549,46.580095,14.167831,46.652688)
    #     )

    #     with open(os.path.join(os.path.dirname(__file__), 'request_woerthersee.json'), 'w') as fp:
    #         json.dump(request, fp, indent=2)

    #     mdi = Mdi()

    #     t1 = time.perf_counter()
    #     mime_type, data = mdi.post_request(request)
    #     t2 = time.perf_counter()
    #     print(f"test_single_band: took {t2 - t1} secs")

    #     self.assertEqual('application/tar', mime_type)

    #     with open(os.path.join(os.path.dirname(__file__), 'response_woerthersee.tar'), 'wb') as fp:
    #         fp.write(data)

    #     mdi.close()

# class ConfigAPITest(unittest.TestCase):

#     def test_layers(self):
#         client_id = os.environ.get('SH_CLIENT_ID')
#         client_secret = os.environ.get('SH_CLIENT_SECRET')
#         instance_id = os.environ["SH_INSTANCE_ID"]

#         print('client_id', client_id)
#         print('client_secret', client_secret)
#         print('instance_id', instance_id)

#         # )
#         # client = oauthlib.oauth2.BackendApplicationClient(client_id=client_id)
#         # session = requests_oauthlib.OAuth2Session(client=client)
#         # token = session.fetch_token(
#         #     token_url='https://services.sentinel-hub.com/oauth' + '/token',
#         #     client_id=client_id,
#         #     client_secret=client_secret
#         # )

#         client_id = client_id or os.environ.get('SH_CLIENT_ID')
#         client_secret = client_secret or os.environ.get('SH_CLIENT_SECRET')

#         client = oauthlib.oauth2.BackendApplicationClient(client_id=client_id)
#         session = requests_oauthlib.OAuth2Session(client=client)

#         oauth2_url= 'https://services.sentinel-hub.com/oauth'
#         token = session.fetch_token(token_url=oauth2_url + '/token',
#                                                 client_id=client_id,
#                                                 client_secret=client_secret)

#         print(token)
#         api = ConfigAPI(session, instance_id)
#         api.get_layers()


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

from base import BaseDocument, connection, db_bool_repr, db_link_repr
from bson.objectid import ObjectId
from counter import Counter
import datetime

@connection.register
class BillDB(BaseDocument):

    __collection__ = 'bill'
    __title__ = u'Счёт'

    skeleton = {
                    'id': int,
                    'user': ObjectId,
                    'contractor': ObjectId, # контрагент
                    'template': ObjectId,   # шаблон, если есть
                    'task': ObjectId,       # задание, если есть
                    'content': ObjectId,    # содержимое
                    'number': int,          # номер счёта
                    'date_created': datetime.datetime,  # дата, когда был создан (и отправлен)
                    'send': bool,            # отправлен
                    'paid': bool,            # оплачен
                }
    @property
    def name(self):
        from content import ContentDB
        return ContentDB.get_by_id(self['content']).name

    @staticmethod
    def create_simple(user_id, contractor_id, content_id, number, date_created):
        b = connection.BillDB()
        b['user'] = user_id
        b['contractor'] = contractor_id
        b['content'] = content_id
        b['number'] = number
        b['date_created'] = date_created
        b['id'] = Counter.insert('bill')
        b.save()
        return b

    """ Вспомогательные функции для внутреннего использования """

    @staticmethod
    def get_table_cols():
        return [(u'Id', 'id'),
                (u'Юзер', 'db_user'),
                (u'Контрагенты', 'db_contractors'),
                (u'Содержимое', 'db_content'),
                (u'Отправлен', 'db_send'),
                (u'Оплачен', 'db_paid'),]

    @property
    def db_user(self):
        from user import UserDB
        return db_link_repr(UserDB, self['user'])

    @property
    def db_content(self):
        from content import ContentDB
        return db_link_repr(ContentDB, self['content'])

    @property
    def db_contractors(self):
        from contactor import ContactorDB
        return db_link_repr(ContactorDB, self['contractor'])

    @property
    def db_send(self):
        return db_bool_repr(self['send'])

    @property
    def db_paid(self):
        return db_bool_repr(self['paid'])


def center_window(window):
    """
    centers the given window/widget on the screen

    Args:

        window: the tk window (root/toplevel) instance to center

    """
    window.update_idletasks()
    # get current window width & height
    width = window.winfo_width()
    height = window.winfo_height()
    # calculate centered x and y
    x = (window.winfo_screenwidth() // 2) - (width // 2)
    y = (window.winfo_screenheight() // 2) - (height // 2)
    # resize window
    window.geometry('{0}x{1}+{2}+{3}'.format(width, height, x, y))

    # this prevents window from temporarily appearing in its original position
    window.withdraw()
    window.deiconify()

def position_window(window, x, y):
    """
    sends the given window to the given x, y position

    Args:

        window: the tk window (root/toplevel) instance to move

        x: pixel x-position to move to

        y: pixel y-position to move to

    """
    window.update_idletasks()

    window.geometry('+{}+{}'.format(x, y))

    window.withdraw()
    window.deiconify()


#0316  貨幣轉美金 GUI使用  entry 美化 >>>>>0317 messagebox

import tkinter as tk
from tkinter import StringVar
from PIL import ImageTk, Image
from tkinter import ttk
from tkinter import  messagebox

#

win = tk.Tk()

messagebox.showinfo("Basic Example", "歡迎來到此程式")

def event1():
    global entry1
    global label3Str
    t1=entry1.get()
    print(t1)
    comStr=comboExample.get()
    if comStr=="台幣":
        dollar=float(t1)/28.8
    elif  comStr=="日幣":
        dollar=float(t1)/0.0092
    elif  comStr=="韓元":
        dollar=float(t1)/0.00088
    label3Str.set(str(dollar))   #匯率 美金 1 : 台幣 28.23
#視窗調整
win.wm_title("Hello, JING,金錢轉換")     #設定視窗標題
win.minsize(width=380, height=400)                      #視窗最小尺寸
win.maxsize(width=380, height=400)                      #視窗最大尺寸
win.resizable(width=False, height=False)                #是否可調整視窗大小

#背景
backgroundImg = ImageTk.PhotoImage(Image.open("backgroud.png"))
backgroundLabel =tk.Label(win,image=backgroundImg)
backgroundLabel.place(x=0,y=0)
#下拉式選單
labelTop = tk.Label(win,text = "↓↓↓ 請選擇 幣別 ↓↓↓")
labelTop.place(x=120, y=15)

comboExample = ttk.Combobox(win,            #ttk 要安裝函式庫
                            values=[
                                    "台幣",
                                    "韓元",
                                    "日幣"])
print(dict(comboExample))                   #<----dict?
comboExample.place(x=110, y=50)
comboExample.current(0)
print(comboExample.current(), comboExample.get())

label1 =tk.Label(win,bg="blue",text="請輸入金額:",fg="yellow",font=20)     #放上啥文字 顏色
label1.place(x=30, y=90)                                            #位置

entry1=tk.Entry(win)
entry1.place(x=140,y=90)

img = ImageTk.PhotoImage(Image.open("button2.png"))
btn1 =tk.Button(win,text="轉換",image=img,command=event1)
btn1.place(x=110,y=160)

label2 =tk.Label(win,bg="red",text="美金:",fg="yellow",font=20)
label2.place(x=80, y=290)

label3Str=StringVar()
label3=tk.Label(win,text="...",textvariable=label3Str)
label3.place(x=140,y=290)

win.mainloop()


import json, hashlib
from exceptions import ValidationError, DatabaseError

months = {
	'01':31,
	'02':28,
	'03':31,
	'04':30,
	'05':31,
	'06':30,
	'07':31,
	'08':31,
	'09':30,
	'10':31,
	'11':30,
	'12':31,
}

customer_file = json.loads(open('people.json').read())
menu_file = json.loads(open('menu.json').read())
orders = {}

def get_customer_id(name, dob):
    return str(hashlib.sha256("{}-{}".format(name, dob).encode('utf-8')).hexdigest())

def validate_dob(dob):
	#len check (8 digits)
	if len(dob) != 8:
		raise ValidationError('dob has too many digits: {}'.format(len(dob)))

	#all characters are digits
	for i in list(dob):
		if i not in '1234567890':
			raise ValidationError('dob contains invalid character: {}'.format(i))

	#valid month
	if not dob[2:4] in months.keys():
		raise ValidationError('dob is in an invalid month: {}'.format(dob[2:4]))

	if not int(dob[:2])<=months[dob[2:4]]:
		raise ValidationError('dob contains invalid day: {}'.format(dob[:2]))

def add_customer(name, dob):
	validate_dob(dob)
	customer_id = str(hashlib.sha256("{}-{}".format(name, dob).encode('utf-8')).hexdigest())
	customer_info = {
		'name':name,
		'dob':dob
    }
	if not customer_id in customer_file.keys():
		customer_file[customer_id] = customer_info
	else:
		raise DatabaseError("Customer is already in database")

def retrieve_customer(name, dob):
	customer_id = get_customer_id(name, dob)
	try:
		return customer_file[customer_id]
	except KeyError:
		raise KeyError("Customer not found")

def delete_customer(name, dob):
	try:
		print(customer_file.pop(get_customer_id(name, dob)))
	except:
		raise KeyError("Customer not found")

def new_order(name, dob):
	orders[get_customer_id(name, dob)] = []

# Sample JSON
# {'id': [hash(surname_firstname-dob)],name': [surname_firstname], 'dob': [ddmmyyyy]}

'''
try:
	print(add_customer('Smith_Joe', '06061999'))
except:
	print(retrieve_customer('Smith_Joe', '06061999'))
'''
delete_customer('Bloggs_Joe', '01012000')
json.dump(customer_file, open('people.json', 'w'), indent=4)


import uiScriptLocale

window = {
	"name" : "RefineDialog",
	"style" : ("movable", "float",),

	"x" : SCREEN_WIDTH - 400,
	"y" : 70 * 800 / SCREEN_HEIGHT,

	"width" : 0,
	"height" : 0,

	"children" :
	(
		{
			"name" : "Board",
			"type" : "board",
			"style" : ("attach",),

			"x" : 0,
			"y" : 0,

			"width" : 0,
			"height" : 0,

			"children" :
			(
				{
					"name" : "TitleBar",
					"type" : "titlebar",
					"style" : ("attach",),

					"x" : 8,
					"y" : 8,

					"width" : 0,
					"color" : "red",

					"children" :
					(
						{
							"name" : "TitleName",
							"type" : "text",
							"text" : uiScriptLocale.REFINE_TTILE,
							"horizontal_align" : "center",
							"text_horizontal_align" : "center",
							"x" : 0,
							"y" : 3,
						},
					),
				},
				{
					"name" : "SuccessPercentage",
					"type" : "text",
					"text" : uiScriptLocale.REFINE_INFO,
					"horizontal_align" : "center",
					"vertical_align" : "bottom",
					"text_horizontal_align" : "center",
					"x" : 0,
					"y" : 70,
				},
				{
					"name" : "Cost",
					"type" : "text",
					"text" : uiScriptLocale.REFINE_COST,
					"horizontal_align" : "center",
					"vertical_align" : "bottom",
					"text_horizontal_align" : "center",
					"x" : 0,
					"y" : 54,
				},
				{
					"name" : "AcceptButton",
					"type" : "button",

					"x" : -35,
					"y" : 35,

					"text" : uiScriptLocale.OK,
					"horizontal_align" : "center",
					"vertical_align" : "bottom",

					"default_image" : "d:/ymir work/ui/public/Middle_Button_01.sub",
					"over_image" : "d:/ymir work/ui/public/Middle_Button_02.sub",
					"down_image" : "d:/ymir work/ui/public/Middle_Button_03.sub",
				},
				{
					"name" : "CancelButton",
					"type" : "button",

					"x" : 35,
					"y" : 35,

					"text" : uiScriptLocale.CANCEL,
					"horizontal_align" : "center",
					"vertical_align" : "bottom",

					"default_image" : "d:/ymir work/ui/public/Middle_Button_01.sub",
					"over_image" : "d:/ymir work/ui/public/Middle_Button_02.sub",
					"down_image" : "d:/ymir work/ui/public/Middle_Button_03.sub",
				},
			),
		},
	),
}


#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import webapp2
import os
import jinja2
import re
import logging
from google.appengine.ext import db
from google.appengine.api import users
import urllib2
import time
import json
import cgi
from google.appengine.api import memcache

CLIENT_ID = "478095448209-ff2evbl57jb3rdbc0vl0fkfi5pv88t0j.apps.googleusercontent.com"
template_dir = os.path.join(os.path.dirname(__file__),'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape=True)

class Handler(webapp2.RequestHandler):
    def write(self,*a,**kw):
        self.response.out.write(*a,**kw)
    def render_str(self,template,**params):
        t = jinja_env.get_template(template)
        return t.render(params)
    def render(self,template,**kw):
        self.write(self.render_str(template,**kw))
    def userin(self):
        id = self.request.cookies.get("name")
        if id:
            return True
        else:
            self.redirect('/login')
    def userdata(self):
        id = str(self.request.cookies.get("name"))
        user = memcache.get(id)
        return user

class MainHandler(Handler):
    def get(self):
        self.render("home.html")

class Blog(db.Model):
    subject = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)
    name = db.StringProperty()
    picture = db.LinkProperty()
    comments = db.IntegerProperty(default=0)
    views = db.IntegerProperty(default=0)
    TitlePicture = db.StringProperty()
    BlogSubTitle = db.StringProperty()
    BlogFooterPicture = db.StringProperty()
    BlogFooter = db.StringProperty()

class Comments(db.Model):
    blogid = db.IntegerProperty(required = True)
    name = db.StringProperty(required = True)
    email = db.EmailProperty(required = True)
    picture = db.LinkProperty()
    comment = db.StringProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)

class BlogHandler(Handler):
    def get(self):
        self.userin()
        bloggql = Blog.gql("order by created desc limit 100")
        blogs = list(bloggql)
        memcache.add(key = "blogs", value = blogs, time=3600)
        self.response.set_cookie('blogs',str(len(blogs)),path='/')
        id = str(self.request.cookies.get("name"))
        user = memcache.get(id)
        p = re.compile(r'<.*?>')
        self.render('BlogFeed.html',blogs=blogs[:10],user=user,p=p)
        #temp = ""
        #for entry in q.run(limit=10):
        #    temp = temp + ("
"+entry.subject+"
"+entry.content+"

")
        #self.write(temp)
    def post(self):
         i = int(self.request.cookies.get("blogs"))
         #i = i -10;
         if i >0 :
             txt = '''

%(subject)s
 By %(name)s

%(content)s...

Read More

%(views)s
                        %(comments)s

'''
             blogs = memcache.get("blogs")
             temp = '';
             i = (i-10) if (i-10)>0 else 0
             start = len(blogs) - i
             end = (start +10) if (start +10)<=len(blogs) else (len(blogs))
             for j in range(start,end):
                 temp =  temp + txt % {"subject":cgi.escape(blogs[j].subject,quote=True),
                                       "picture":blogs[j].picture,
                                       "name":blogs[j].name,
                                       "content":cgi.escape(blogs[j].content,quote=True),
                                       "views":blogs[j].views,
                                       "comments":blogs[j].comments,
                                       "id":blogs[j].key().id()}
             self.response.set_cookie('blogs',str(i),path='/')
             self.response.out.write(temp)

class NewPostHandler(Handler):
    def get(self):
        self.userin()
        user = self.userdata()
        self.render("CreateBlog.html",user=user)
        #id = self.request.cookies.get("name")
        #if id:
        #    self.render("newpost.html")
        #else:
        #    self.redirect('/login')
    def post(self):
        user = self.userdata()
        if user:
            if 'picture' in user.keys():
                picture = user['picture']
            else :
                picture = "https://placehold.it/150"
            name = user['name']
            subject = self.request.get('subject')
            content = self.request.get('content')
            if self.request.get('TitlePicture'):
                TitlePicture = self.request.get('TitlePicture')
            else:
                TitlePicture = "/images/Clocks.jpg"
            BlogSubTitle = self.request.get('BlogSubTitle')
            if self.request.get('BlogFooterPicture'):
                BlogFooterPicture = self.request.get('BlogFooterPicture')
            else:
                BlogFooterPicture = "/images/Clocks.jpg"
            BlogFooter = self.request.get('BlogFooter')
            b = Blog(subject = subject, content = content,
                picture = picture, name = name,
                TitlePicture = TitlePicture,
                BlogSubTitle = BlogSubTitle,
                BlogFooterPicture = BlogFooterPicture,
                BlogFooter = BlogFooter)
            b.put()
            self.redirect('/blog/'+ str(b.key().id()))

class PostHandler(Handler):
    def get(self,post_id):
        data = Blog.get_by_id(int(post_id))
        data.views = data.views + 1
        data.put()
        #id = str(self.request.cookies.get("name"))
        user = self.userdata()
        #if user:
        comments = Comments.gql('where blogid = '+ post_id)
        self.render("BlogTemplatenew.html",data = data, comments = comments, user=user)
        #else:
         #   self.render("BlogTemplate.html",user = None, data = data)
    def post(self,post_id):
        #name = self.request.get('name')
        #email = self.request.get('email')
        comment = self.request.get('comment')
        id = str(self.request.cookies.get("name"))
        user = memcache.get(id)
        blogid = int(post_id)
        if 'picture' in user.keys():
            picture = user['picture']
        else :
            picture = "https://placehold.it/150"
        c = Comments(blogid = blogid, name = user['name'], email = db.Email(user['email']), comment = comment, picture=picture)
        c.put()
        data = Blog.get_by_id(int(post_id))
        data.comments = data.comments + 1
        data.put()
        self.redirect('/blog/'+ post_id)

class LoginHandler(Handler):
    def get(self):
        user = users.get_current_user()
        if user:
            self.render("Login.html",name = user.nickname())
        else:
            self.render("Login.html",name = "None")
    def post(self):
        token = self.request.get('idtoken')
        gurl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token="
        check = urllib2.urlopen(gurl+token)
        if check.getcode() == 200:
            user = json.loads(check.read())
            try:
                if user["aud"] != CLIENT_ID:
                    raise "Invalid!!"
                if user['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
                    raise "Invalid!!"
                if user['exp'] < time.time():
                    raise "Invalid!!"
            except "Invalid!!":
                self.response.out.write("not valid")
            else:
                self.response.set_cookie('name',user['sub'],path='/')
                self.response.out.write(user['given_name'])
                memcache.add(key = user['sub'], value = user, time=3600)

class AboutPageHandler(Handler):
    def get(self):
        self.render("about.html")

class AboutPageHandler2(Handler):
	def get(self):
		self.render("about2.html")

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/about',AboutPageHandler),
    ('/blog',BlogHandler),
    ('/blog/newpost',NewPostHandler),
    ('/login', LoginHandler),
	('/about2',AboutPageHandler2),
    (r'/blog/(\d+)',PostHandler)
], debug=True)


import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

INPUTS_FILE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data'))
INPUTS_FILE = os.path.join(INPUTS_FILE_PATH, 'training.csv')

COLS = ["sentiment", "id", "date", "query", "user", "text"]
COLS_TO_KEEP = ["sentiment", "text"]

OUTPUTS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../output'))
OUTPUTS_FILE = os.path.join(OUTPUTS_DIR, 'outputs.csv')

CHECKPOINT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../checkpoint'))

OUTPUTS_MODELS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../models'))

EMB_DIM = 200

NB_FILTERS = 100
FFN_UNITS = 256
NB_CLASSES = 2

DROPOUT_RATE = 0.2

BATCH_SIZE = 32
NB_EPOCHS = 5


import datetime
from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort

from qx.auth import login_required
from qx.db import get_db

bp = Blueprint('queue', __name__)

@bp.route('/')
def index():
    db = get_db()
    appointments = db.execute(
        'SELECT ap.id, customer_id, status, waiting_since, username, email'
        ' FROM appointments ap JOIN user u ON ap.customer_id = u.id'
        ' ORDER BY waiting_since DESC'
    ).fetchall()
    return render_template('queue/index.html', appointments=appointments)

@bp.route('/create', methods=('GET', 'POST'))
@login_required
def create():
    if request.method == 'POST':
        status = request.form['status']
        error = None

        if not status:
            error = 'Status is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'INSERT INTO appointments (status, customer_id, waiting_since)'
                ' VALUES (?, ?, ?)',
                (status, g.user['id'], datetime.datetime.now())
            )
            db.commit()
            return redirect(url_for('queue.index'))

    return render_template('queue/create.html')

def get_appointment(id, check_customer=True):
    appointment = get_db().execute(
        'SELECT ap.id, status, waiting_since, customer_id, username'
        ' FROM appointments ap JOIN user u ON ap.customer_id = u.id'
        ' WHERE ap.id = ?',
        (id,)
    ).fetchone()

    if appointment is None:
        abort(404, "Appointment id {0} doesn't exist.".format(id))

    if check_customer and appointment['customer_id'] != g.user['id']:
        abort(403)

    return appointment

@bp.route('/<int:id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
    appointment = get_appointment(id)

    if request.method == 'POST':
        status = request.form['status']
        error = None

        if not status:
            error = 'Status is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'UPDATE appointments SET status = ?'
                ' WHERE id = ?',
                (status, id)
            )
            db.commit()
            return redirect(url_for('queue.index'))

    return render_template('queue/update.html', appointment=appointment)

@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(id):
    get_appointment(id)
    db = get_db()
    db.execute('DELETE FROM appointments WHERE id = ?', (id,))
    db.commit()
    return redirect(url_for('queue.index'))


import os
from copy import deepcopy

def simulate_step(previous_state, seating, adjacencies):
    for r in range(len(seating)):
        for c in range(len(seating[0])):
            if previous_state[r][c] == "L":
                for adjacency in adjacencies:
                    valid = True

                    try:
                        if previous_state[9999 if r + adjacency[0] < 0 else r + adjacency[0]][9999 if c + adjacency[1] < 0 else c + adjacency[1]] == "#":
                            valid = False
                            break
                    except:
                        pass

                if valid:
                    seating[r][c] = "#"

            elif previous_state[r][c] == "#":
                occupied_count = 0

                for adjacency in adjacencies:
                    try:
                        if previous_state[9999 if r + adjacency[0] < 0 else r + adjacency[0]][9999 if c + adjacency[1] < 0 else c + adjacency[1]] == "#":
                            occupied_count += 1
                    except:
                        pass

                if occupied_count >= 4:
                    seating[r][c] = "L"

def check_seating_equality(previous_state, current_state):
    for r in range(len(previous_state)):
        for c in range(len(current_state)):
            if previous_state[r][c] != current_state[r][c]:
                return False

    return True

file_path = os.path.join(os.path.dirname(__file__), "input.txt")

with open(file_path, 'r') as input:
    all_lines = input.readlines()

for i in range(len(all_lines)):
    all_lines[i] = all_lines[i].strip('\n')
    all_lines[i] = list(all_lines[i])

adjacencies = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]

previous_state = deepcopy(all_lines)
simulate_step(previous_state, all_lines, adjacencies)

while not check_seating_equality(previous_state, all_lines):
    previous_state = deepcopy(all_lines)
    simulate_step(previous_state, all_lines, adjacencies)

occupied_count = 0

for seat in [seat for row in all_lines for seat in row]:
    if seat == "#":
        occupied_count += 1

print(occupied_count)


from constantes import *
from pickle import *
from socket import *
from paquete import *

def create_socket():
	UDPsocket = socket(AF_INET, SOCK_DGRAM)
	UDPsocket.bind((RECEPTOR_IP, RECEPTOR_PORT))
	return UDPsocket

def extract(packet):
	data = paquete.get_datos() # habia puesto Packet.get_data por eso no andaba
	return data

def deliver_data(data):
	print(data)

def rdt_rcv(sock):
	data =sock.recv(2048) #luego de esta linea estaba printeando
	emisor, paquete=loads(data) # decodifica
	return emisor, paquete

def corrupto(paquete):
	if calcular_checksum(paquete) == 0:
		return True
	else:
		return False

def make_pckt(dato):
	pkt = Paquete(RECEPTOR_PORT, EMISOR_PORT, dato, 0)
	checksum = calcular_checksum(paquete)
	paquete.set_checksum(dato)
	return pkt

def udp_send(socket, receptor, paquete):
	dato = dumps((receptor, paquete))
	socket.sendto(dato, (NETWORK_IP, NETWORK_PORT))

def close_socket(socket, signal, frame):
	print ("\rCerrando socket")
	socket.close()
	exit(0)

if __name__ == "__main__":
	# Creamos el socket "receiver"
	receptor = create_socket()
	# Registramos la senial de salida
	signal.signal(signal.SIGINT, partial(close_socket, receptor))
	# Imprimimos el cartel "Listo para recibir mensajes..."
	print('recibiendo mensaje: ')

	secuencia = 0
	# Iteramos indefinidamente
	while True:
		# Recibimos un paquete de la red
		emisor, paquete = rdt_rcv(receptor)
		if corrupto(paquete) == 0:
			emisor = (EMISOR_IP, EMISOR_PORT)
			pkt = make_pckt("NAK")
			udp_send(receptor, emisor, pkt)
		else:
			emisor = (EMISOR_IP, EMISOR_PORT)
			pkt1 = make_pckt("ACK")
			udp_send(receptor, emisor, pkt1)
		# Extraemos los datos
		data = extract(paquete) #aca pedia un paquete no definido antes. ahora anda
		#print(data.get_data)
		# Entregamos los datos a la capa de aplicacion
		deliver_data(data)
		#pkt = make_pckt(data)
		# Establecemos el destinatario

		# Enviamos el mensaje

	close_socket(receptor)


#!/usr/bin/python

import os
import subprocess
from subprocess import call

# cpuskarz 11/25/2015 autoconfig.py v1
# Program is an enhancement to EEM/GIT example in the Cisco NX-OS Programmability Guide.
# Program is triggered from EEM script on N9k via copy running-config startup-config
# Moves the output file to a directory on local GIT repo (in guestshell)
# Git adds and commits the file then pushes to a remote GIT repo

# Read running-counter file
fh1 = open("runningcounter.txt", "r")
countset = fh1.read()
fh1.close()

# Reopen running-counter file and write incremental counter
fh2 = open("runningcounter.txt", "w")
inp_count = int(countset) + 1
set_count = str(inp_count)
fh2.write(set_count)
fh2.close()
set_message = "Changed configuration, version: %s" % set_count

# Create file for  output or errors
f = open("autoouptput.txt", "w")
os.chdir("/home/guestshell/autoconfig2.git")

call(["mv", "/bootflash/autoconfig/running.latest", "/home/guestshell/autoconfig2.git/n9k1/running"])
call(["git", "add", "n9k1/running"])
call(['git', 'commit', '-m', set_message])

p = subprocess.Popen(['chvrf', 'management', 'git', 'push origin master'],  stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = p.communicate()
f.write(out)
f.write(err)
f.close()


from django import forms
from .models import Candidate

class RegisterCandidateForm(forms.ModelForm):
	class Meta:
		model = Candidate
		fields = ['registration_number','first_name','last_name','email','position_vied','description']

	def clean_email(self):
		email = self.cleaned_data.get('email')
		email_base, provider = email.split("@")
		domain,extension,country= provider.split('.')
		if not  provider=="mut.ac.ke" in email:
			raise forms.ValidationError("Please use a valid .mut.ac.ke email address")

		return email


import time

import nltk
import numpy as np
import pandas as pd
from textblob.classifiers import DecisionTreeClassifier
from textblob.classifiers import NaiveBayesClassifier

nltk.download('stopwords')
from nltk.corpus import stopwords

stopset = set(stopwords.words('english'))
ignoreDT = True

def remove_prefix(theList, prefix):
    return [text[len(prefix):] if text.startswith(prefix) else text for text in theList]

def remove_stopwords(theList):
    return [' '.join([word for word in text.split() if word not in stopset]) for text in theList]

if __name__ == '__main__':
    train = pd.read_csv('train.csv')
    test = pd.read_csv('test.csv')
    train_data = remove_stopwords(train.Title)
    train_target = remove_prefix(train.Team, 'UCM ')
    test_data = remove_stopwords(test.Title)
    test_id = test.Id
    test_target = remove_prefix(test.Team, 'UCM ')
    train = list(zip(train_data, train_target))
    test = list(zip(test_data, test_target))

    start_time = time.time()
    cl = NaiveBayesClassifier(train)
    # Compute accuracy
    print("NaiveBayes Accuracy: {0}".format(cl.accuracy(test)))

    # Show 10 most informative features
    cl.show_informative_features(10)
    print(cl.informative_features(10))
    elapsed_time = time.time() - start_time
    print(elapsed_time)

    if (not ignoreDT):
        start_time = time.time()
        cl = DecisionTreeClassifier(train)
        print("DecisionTree Accuracy: {0}".format(cl.accuracy(test)))
        print(cl.pseudocode())
        elapsed_time = time.time() - start_time
        print(elapsed_time)

    start_time = time.time()
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_extraction.text import TfidfTransformer
    from sklearn.naive_bayes import MultinomialNB
    from sklearn.pipeline import Pipeline

    class StemmedCountVectorizer(CountVectorizer):
        def build_analyzer(self):
            analyzer = super(StemmedCountVectorizer, self).build_analyzer()
            return lambda doc: ([stemmer.stem(w) for w in analyzer(doc)])

    from nltk.stem.snowball import SnowballStemmer

    stemmer = SnowballStemmer("english", ignore_stopwords=True)
    stemmed_count_vect = StemmedCountVectorizer(stop_words='english')

    text_clf = Pipeline([('vect', stemmed_count_vect),
                         ('tfidf', TfidfTransformer()),
                         ('clf', MultinomialNB()),
                         ])

    text_clf.fit(train_data, train_target)
    predicted = text_clf.predict(test_data)
    print("MultinomialNB Accuracy: {0}".format(np.mean(predicted == test_target)))
    df = pd.DataFrame(list(zip(test_data, predicted, test_target)))
    df.to_csv('MB_list.csv', index=False)
    elapsed_time = time.time() - start_time
    print(elapsed_time)

    start_time = time.time()
    from sklearn.linear_model import SGDClassifier

    text_clf = Pipeline([('vect', stemmed_count_vect),
                         ('tfidf', TfidfTransformer()),
                         ('clf', SGDClassifier(loss='hinge', penalty='l2',
                                               alpha=1e-3, random_state=42)),
                         ])
    text_clf.fit(train_data, train_target)

    predicted = text_clf.predict(test_data)
    print("SGD Accuracy: {0}".format(np.mean(predicted == test_target)))
    df = pd.DataFrame(list(zip(test_id, test_data, predicted, test_target)))
    df.to_csv('SGD_list.csv', index=False)

    elapsed_time = time.time() - start_time
    print(elapsed_time)

    from sklearn import metrics

    print(metrics.classification_report(test_target, predicted))


from typing import List

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        temp = [0 for _ in range(n)]
        for i in range(n):
            temp[(i+k)%n] = nums[i]
        nums[:] = temp


import lxml.etree as et
import xml.etree.ElementTree as ET
import math

def txt_xml(filename,savdir):
    """ Parse a PASCAL VOC xml file """
    filenames = 'Annotations/'+filename + '.xml'
    tree = ET.parse(filenames)
    objects = []
    for obj in tree.findall('object'):
        # if not check(obj.find('name').text):
        #     continue
        obj_struct = {}
        obj_struct['name'] = obj.find('name').text
        bbox = obj.find('bndbox')
        obj_struct['bbox'] = [int(bbox.find('xmin').text) - 1,
                              int(bbox.find('ymin').text) - 1,
                              int(bbox.find('xmax').text) - 1,
                              int(bbox.find('ymax').text) - 1]
        # Read the original coordination
        x1=int(bbox.find('xmin').text)
        y1=int(bbox.find('ymin').text)
        x2=int(bbox.find('xmax').text)
        y2=int(bbox.find('ymax').text)

        # Transformation
        arr ='(' + str(x1)+ ',' + str(y1)+'),('+str(x2)+','+str(y2)+'),'+str(obj_struct['name']) + '\n'
        print (arr)
        #temp = str(temp)+(arr)
        #print(temp)
        #j=j+1
        filenametxt = savdir+filename+'.txt'
        a = open(filenametxt, 'a')
        a.write(str(arr))
        a.close()

#txt_xml("test2.xml")


import os
import pathlib

#import matplotlib.pyplot as plt
import numpy as np
#import seaborn as sns
import tensorflow as tf
import time

from tensorflow.keras.layers.experimental import preprocessing
from tensorflow.keras import layers
from tensorflow.keras import models
#from IPython import display

# Set seed for experiment reproducibility
seed = 42
tf.random.set_seed(seed)
np.random.seed(seed)
time_start = time.perf_counter()

data_dir = pathlib.Path('data/mini_speech_commands')
if not data_dir.exists():
  tf.keras.utils.get_file(
      'mini_speech_commands.zip',
      origin="http://storage.googleapis.com/download.tensorflow.org/data/mini_speech_commands.zip",
      extract=True,
      cache_dir='.', cache_subdir='data')

commands = np.array(tf.io.gfile.listdir(str(data_dir)))
commands = commands[commands != 'README.md']
print('Commands:', commands)

filenames = tf.io.gfile.glob(str(data_dir) + '/*/*')
filenames = tf.random.shuffle(filenames)
num_samples = len(filenames)
print('Number of total examples:', num_samples)
print('Number of examples per label:',
      len(tf.io.gfile.listdir(str(data_dir/commands[0]))))
print('Example file tensor:', filenames[0])

train_files = filenames[:6400]
val_files = filenames[6400: 6400 + 800]
test_files = filenames[-800:]

print('Training set size', len(train_files))
print('Validation set size', len(val_files))
print('Test set size', len(test_files))

def decode_audio(audio_binary):
  audio, _ = tf.audio.decode_wav(audio_binary)
  return tf.squeeze(audio, axis=-1)

def get_label(file_path):
  parts = tf.strings.split(file_path, os.path.sep)

  # Note: You'll use indexing here instead of tuple unpacking to enable this
  # to work in a TensorFlow graph.
  return parts[-2]

def get_waveform_and_label(file_path):
  label = get_label(file_path)
  audio_binary = tf.io.read_file(file_path)
  waveform = decode_audio(audio_binary)
  return waveform, label

AUTOTUNE = tf.data.AUTOTUNE
files_ds = tf.data.Dataset.from_tensor_slices(train_files)
waveform_ds = files_ds.map(get_waveform_and_label, num_parallel_calls=AUTOTUNE)

def get_spectrogram(waveform):
  sample_rate = 16000.0

  # Padding for files with less than 16000 samples
  zero_padding = tf.zeros([16000] - tf.shape(waveform), dtype=tf.float32)

  # Concatenate audio with padding so that all audio clips will be of the
  # same length
  waveform = tf.cast(waveform, tf.float32)
  equal_length = tf.concat([waveform, zero_padding], 0)
  spectrogram = tf.signal.stft(
      equal_length, frame_length=1024, frame_step=512)

  spectrogram = tf.abs(spectrogram)

  # Warp the linear scale spectrograms into the mel-scale.
  num_spectrogram_bins = spectrogram.shape[-1]
  lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80
  linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz,  upper_edge_hertz)
  mel_spectrogram = tf.tensordot(spectrogram, linear_to_mel_weight_matrix, 1)
  mel_spectrogram.set_shape(spectrogram.shape[:-1].concatenate(linear_to_mel_weight_matrix.shape[-1:]))

  # Compute a stabilized log to get log-magnitude mel-scale spectrograms.
  log_mel_spectrogram = tf.math.log(mel_spectrogram + 1e-6)

  # Compute MFCCs from log_mel_spectrograms and take the first 13.
  spectrogram = tf.signal.mfccs_from_log_mel_spectrograms(log_mel_spectrogram)[..., :13]

  return spectrogram

def get_spectrogram_and_label_id(audio, label):
  spectrogram = get_spectrogram(audio)
  spectrogram = tf.expand_dims(spectrogram, -1)
  label_id = tf.argmax(label == commands)
  return spectrogram, label_id

spectrogram_ds = waveform_ds.map(
    get_spectrogram_and_label_id, num_parallel_calls=AUTOTUNE)

def preprocess_dataset(files):
  files_ds = tf.data.Dataset.from_tensor_slices(files)
  output_ds = files_ds.map(get_waveform_and_label, num_parallel_calls=AUTOTUNE)
  output_ds = output_ds.map(
      get_spectrogram_and_label_id,  num_parallel_calls=AUTOTUNE)
  return output_ds

train_ds = spectrogram_ds
val_ds = preprocess_dataset(val_files)
test_ds = preprocess_dataset(test_files)

batch_size = 64
train_ds = train_ds.batch(batch_size)
val_ds = val_ds.batch(batch_size)

train_ds = train_ds.cache().prefetch(AUTOTUNE)
val_ds = val_ds.cache().prefetch(AUTOTUNE)

for spectrogram, _ in spectrogram_ds.take(1):
  input_shape = spectrogram.shape
print('Input shape:', input_shape)
num_labels = len(commands)

norm_layer = preprocessing.Normalization()
norm_layer.adapt(spectrogram_ds.map(lambda x, _: x))

model = models.Sequential([
    layers.Input(shape=input_shape),
    #preprocessing.Resizing(32, 32),
    norm_layer,
    layers.Conv2D(32, 3, activation='relu'),
    layers.Conv2D(64, 3, activation='relu'),
    layers.MaxPooling2D(),
    layers.Dropout(0.25),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.5),
    layers.Dense(num_labels),
])

model.summary()

model.compile(
    optimizer=tf.keras.optimizers.Adam(),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'],
)

EPOCHS = 50
history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=EPOCHS,
    callbacks=tf.keras.callbacks.EarlyStopping(verbose=0, patience=5),
)

test_audio = []
test_labels = []

for audio, label in test_ds:
  test_audio.append(audio.numpy())
  test_labels.append(label.numpy())

test_audio = np.array(test_audio)
test_labels = np.array(test_labels)

y_pred = np.argmax(model.predict(test_audio), axis=1)
y_true = test_labels

test_acc = sum(y_pred == y_true) / len(y_true)
print(f'Test set accuracy: {test_acc:.0%}')

sample_file = data_dir/'no/01bb6a2a_nohash_0.wav'

sample_ds = preprocess_dataset([str(sample_file)])

for spectrogram, label in sample_ds.batch(1):
  prediction = model(spectrogram)
  print(f'Predictions for "{commands[label[0]]}"')
  print(commands, tf.nn.softmax(prediction[0]))

sample_file = data_dir/'right/3a789a0d_nohash_0.wav'

sample_ds = preprocess_dataset([str(sample_file)])

for spectrogram, label in sample_ds.batch(1):
  prediction = model(spectrogram)
  print(f'Predictions for "{commands[label[0]]}"')
  print(commands, tf.nn.softmax(prediction[0]))

time_end=time.perf_counter()
print(f'Run time {time_end - time_start}')


from collections import Counter
from typing import List

class Solution:

    def find_all(self, a_str, sub):
        start = 0
        while True:
            start = a_str.find(sub, start)
            if start == -1: return
            yield start
            start += 1

    def findSubstring(self, s: str, words: List[str]) -> List[int]:

        if not words:
            return []

        self.len_word = len(words[0])
        self.total_length = self.len_word * len(words)
        lookup_table = {}
        # create lookup table
        for word in set(words):
            for ind in self.find_all(s, word):
                if ind not in lookup_table:
                    lookup_table[ind] = set()
                lookup_table[ind].add(word)

        res = []
        c = Counter(words)
        for i in range(0, len(s) - len(words) * len(words[0]) + 1):
            if self.lookup_word(lookup_table, c, i, i, s):
                res.append(i)

        return res

    def lookup_word(self, table, words, start_ind, ind, s):

        if start_ind + self.total_length == ind:
            return True

        if ind not in table:
            return False
        table_entries = table[ind]

        for item in table_entries:
            if item in words and words[item] > 0:
                words[item] -= 1
                if self.lookup_word(table, words, start_ind, ind + len(item), s):
                    words[item] += 1
                    return True
                words[item] += 1
        return False

if __name__ == '__main__':
    s = Solution()

    st = "barfoothefoobarman"
    words = ["foo", "bar"]

    # st = "wordgoodgoodgoodbestword"
    # words = ["word", "good", "best", "good"]

    print(s.findSubstring(st, words))


import sys
import os
import time
import random

import numpy as np
import tensorflow as tf

from PIL import Image

SIZE = 1280
WIDTH = 32
HEIGHT = 40
NUM_CLASSES = 6
iterations = 200

SAVER_DIR = "parkmanage1/train-saver/province/"

PROVINCES = ("京", "闽", "粤", "苏", "沪", "浙")
nProvinceIndex = 0

# 定义输入节点，对应于图片像素值矩阵集合和图片标签(即所代表的数字)
x = tf.placeholder(tf.float32, shape=[None, SIZE])
y_ = tf.placeholder(tf.float32, shape=[None, NUM_CLASSES])

x_image = tf.reshape(x, [-1, WIDTH, HEIGHT, 1])

time_begin = time.time()

# 定义卷积函数
def conv_layer(inputs, W, b, conv_strides, kernel_size, pool_strides, padding):
    L1_conv = tf.nn.conv2d(inputs, W, strides=conv_strides, padding=padding)
    L1_relu = tf.nn.relu(L1_conv + b)
    return tf.nn.max_pool(L1_relu, ksize=kernel_size, strides=pool_strides, padding='SAME')

# 定义全连接层函数
def full_connect(inputs, W, b):
    return tf.nn.relu(tf.matmul(inputs, W) + b)

if __name__ == '__main__' :
    # 第一次遍历图片目录是为了获取图片总数
    input_count = 0
    for i in range(0, NUM_CLASSES):
        dir = 'D:/tf_car_license_dataset/train_images/training-set/chinese-characters/%s/' % i  # 这里可以改成你自己的图片目录，i为分类标签
        for rt, dirs, files in os.walk(dir):
            for filename in files:
                input_count += 1

    # 定义对应维数和各维长度的数组
    input_images = np.array([[0] * SIZE for i in range(input_count)])
    input_labels = np.array([[0] * NUM_CLASSES for i in range(input_count)])

    # 第二次遍历图片目录是为了生成图片数据和标签
    index = 0
    for i in range(0, NUM_CLASSES):
        dir = 'D:/tf_car_license_dataset/train_images/training-set/chinese-characters/%s/' % i  # 这里可以改成你自己的图片目录，i为分类标签
        for rt, dirs, files in os.walk(dir):
            for filename in files:
                filename = dir + filename
                img = Image.open(filename)
                width = img.size[0]
                height = img.size[1]
                for h in range(0, height):
                    for w in range(0, width):
                        # 通过这样的处理，使数字的线条变细，有利于提高识别准确率
                        if img.getpixel((w, h)) > 230:
                            input_images[index][w + h * width] = 0
                        else:
                            input_images[index][w + h * width] = 1
                input_labels[index][i] = 1
                index += 1

    # 第一次遍历图片目录是为了获取图片总数
    val_count = 0
    for i in range(0, NUM_CLASSES):
        dir = 'D:/tf_car_license_dataset/train_images/validation-set/chinese-characters/%s/' % i  # 这里可以改成你自己的图片目录，i为分类标签
        for rt, dirs, files in os.walk(dir):
            for filename in files:
                val_count += 1

    # 定义对应维数和各维长度的数组
    val_images = np.array([[0] * SIZE for i in range(val_count)])
    val_labels = np.array([[0] * NUM_CLASSES for i in range(val_count)])

    # 第二次遍历图片目录是为了生成图片数据和标签
    index = 0
    for i in range(0, NUM_CLASSES):
        dir = 'D:/tf_car_license_dataset/train_images/validation-set/chinese-characters/%s/' % i  # 这里可以改成你自己的图片目录，i为分类标签
        for rt, dirs, files in os.walk(dir):
            for filename in files:
                filename = dir + filename
                img = Image.open(filename)
                width = img.size[0]
                height = img.size[1]
                for h in range(0, height):
                    for w in range(0, width):
                        # 通过这样的处理，使数字的线条变细，有利于提高识别准确率
                        if img.getpixel((w, h)) > 230:
                            val_images[index][w + h * width] = 0
                        else:
                            val_images[index][w + h * width] = 1
                val_labels[index][i] = 1
                index += 1

    with tf.Session() as sess:
        # 第一个卷积层
        W_conv1_province = tf.Variable(tf.truncated_normal([8, 8, 1, 16], stddev=0.1), name="W_conv1_province")
        b_conv1_province = tf.Variable(tf.constant(0.1, shape=[16]), name="b_conv1_province")
        conv_strides_province = [1, 1, 1, 1]
        kernel_size_province = [1, 2, 2, 1]
        pool_strides_province = [1, 2, 2, 1]
        L1_pool_province = conv_layer(x_image, W_conv1_province, b_conv1_province, conv_strides_province, kernel_size_province, pool_strides_province, padding='SAME')

        # 第二个卷积层
        W_conv2_province = tf.Variable(tf.truncated_normal([5, 5, 16, 32], stddev=0.1), name="W_conv2_province")
        b_conv2_province = tf.Variable(tf.constant(0.1, shape=[32]), name="b_conv2_province")
        conv_strides_province = [1, 1, 1, 1]
        kernel_size_province = [1, 1, 1, 1]
        pool_strides_province= [1, 1, 1, 1]
        L2_pool_province = conv_layer(L1_pool_province, W_conv2_province, b_conv2_province, conv_strides_province, kernel_size_province, pool_strides_province, padding='SAME')

        # 全连接层
        W_fc1_province = tf.Variable(tf.truncated_normal([16 * 20 * 32, 512], stddev=0.1), name="W_fc1_province")
        b_fc1_province = tf.Variable(tf.constant(0.1, shape=[512]), name="b_fc1_province")
        h_pool2_flat_province = tf.reshape(L2_pool_province, [-1, 16 * 20 * 32])
        h_fc1_province = full_connect(h_pool2_flat_province, W_fc1_province, b_fc1_province)

        # dropout
        keep_prob_province = tf.placeholder(tf.float32, name="keep_prob_province")

        h_fc1_drop_province = tf.nn.dropout(h_fc1_province, keep_prob_province, name="h_fc1_drop_province")

        # readout层
        W_fc2_province = tf.Variable(tf.truncated_normal([512, NUM_CLASSES], stddev=0.1), name="W_fc2_province")
        b_fc2_province = tf.Variable(tf.constant(0.1, shape=[NUM_CLASSES]), name="b_fc2_province")

        # 定义优化器和训练op
        y_conv_province = tf.matmul(h_fc1_drop_province, W_fc2_province) + b_fc2_province
        cross_entropy_province = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv_province))
        train_step_province = tf.train.AdamOptimizer((1e-4)).minimize(cross_entropy_province)

        correct_prediction_province = tf.equal(tf.argmax(y_conv_province, 1), tf.argmax(y_, 1))
        accuracy_province = tf.reduce_mean(tf.cast(correct_prediction_province, tf.float32))

        # 初始化saver
        saver = tf.train.Saver(tf.global_variables())

        sess.run(tf.global_variables_initializer())

        time_elapsed = time.time() - time_begin
        print("读取图片文件耗费时间：%d秒" % time_elapsed)
        time_begin = time.time()

        print ("一共读取了 %s 个训练图像， %s 个标签" % (input_count, input_count))

        # 设置每次训练op的输入个数和迭代次数，这里为了支持任意图片总数，定义了一个余数remainder，譬如，如果每次训练op的输入个数为60，图片总数为150张，则前面两次各输入60张，最后一次输入30张（余数30）
        batch_size = 60
        iterations = iterations
        batches_count = int(input_count / batch_size)
        remainder = input_count % batch_size
        print ("训练数据集分成 %s 批, 前面每批 %s 个数据，最后一批 %s 个数据" % (batches_count + 1, batch_size, remainder))

        # 执行训练迭代
        for it in range(iterations):
            # 这里的关键是要把输入数组转为np.array
            for n in range(batches_count):
                train_step_province.run(feed_dict={x: input_images[n * batch_size:(n + 1) * batch_size],
                                          y_: input_labels[n * batch_size:(n + 1) * batch_size], keep_prob_province: 0.5})
            if remainder > 0:
                start_index = batches_count * batch_size;
                train_step_province.run(feed_dict={x: input_images[start_index:input_count - 1],
                                          y_: input_labels[start_index:input_count - 1], keep_prob_province: 0.5})

            # 每完成五次迭代，判断准确度是否已达到100%，达到则退出迭代循环
            iterate_accuracy = 0
            if it % 5 == 0:
                iterate_accuracy = accuracy_province.eval(feed_dict={x: val_images, y_: val_labels, keep_prob_province: 1.0})
                print ('第 %d 次训练迭代: 准确率 %0.5f%%' % (it, iterate_accuracy * 100))
                if iterate_accuracy >= 0.9999 and it >= 150:
                    break;

        print ('完成训练!')
        time_elapsed = time.time() - time_begin
        print ("训练耗费时间：%d秒" % time_elapsed)
        time_begin = time.time()

        # 保存训练结果
        if not os.path.exists(SAVER_DIR):
            print('不存在训练数据保存目录，现在创建保存目录')
            os.makedirs(SAVER_DIR)
        saver_path = saver.save(sess, "%smodel.ckpt" % (SAVER_DIR))


# -*- coding: utf-8 -*-
import itertools
import os
import re
import subprocess
import sys
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape

import Conf
from github import Github
from langdetect import detect

token = Conf.GITHUB_API_KEY
g = Github(token)

def make(fullname, nlang, plang):
    """与えられたバグ情報，PR情報から，XMLを生成する．

    Parameters
    ----------
    fullname : String
        リポジトリの名前．{username}/{reponame}の形式．
    nlang : String
        自然言語．
    plang : String
        プログラミング言語．

    Returns
    -------
    bugnum : int
        XMLに記載されたバグ数
    """
    reponame = fullname.split('/')[1]
    #バグリポジトリXMLを生成する
    os.makedirs('./BugRepository/'+nlang, exist_ok=True)
    os.makedirs('./BugRepository/'+nlang+'/'+plang, exist_ok=True)
    wf = open('./BugRepository/'+nlang+'/'+plang+'/'+reponame+'.xml',mode='w')
    wf.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n")
    wf.write('<bugrepository name="'+reponame+'">\n')

    #バグ情報XMLから情報を取得する
    tree = ET.parse("./Bug/"+nlang+'/'+plang+"/"+fullname+".xml")
    root = tree.getroot()

    prtree = ET.parse("./Bug/"+nlang+'/'+plang+"/"+fullname+"_PR.xml")
    prroot = prtree.getroot()
    try:
        repo = g.get_repo(fullname)
    except:
        return 0

    #git logにより各コミットでの変更ファイルをgitlog.txtに出力する
    os.chdir("./Bug/"+nlang+'/'+plang+"/"+fullname+".git")
    gl = open("../gitlog.txt","w")
    subprocess.run(["git","log","--branches", "--name-status", "--oneline", "--all","--pretty=format:%H, %s, %ad"],encoding='UTF-8',stdout=gl)
    gl.close()
    os.chdir("./../../../../..")
    bugnum = 0

    #イシューのeventがreferencedとclosedのもののコミット(と変更ファイル)を取得しXMLに書く
    for bug in root:
        print(bug.find("id").text)
        bugid = bug.find("id").text
        issue = repo.get_issue(int(bugid))
        fixed = []

        title = charset(bug.find("title").text)
        if bug.find("body").text is None:
            body = ""
        else:
            body = charset(bug.find("body").text)
        created = charset(bug.find("created").text)
        closed = charset(bug.find("closed").text)

        try:
            if(detect(title) != nlang):
                if(body != ""):
                    bodynostack = re.sub('```(.*?)```','',body)
                    bodynourl = re.sub("https?://[\w!?/+\-_~=;.,*&@#$%()'[\]]+", '', bodynostack)
                    if(detect(body) != nlang):
                        print("\tNot " + nlang +".")
                        continue
                else:
                    print("\tNot " + nlang +".")
                    continue
        except:
            #たまにLangDetectExceptionが出る
            print("\tLangDetectException")
            continue

        #イシューのeventをなめる
        events = issue.get_events()
        for ev in events:
            if ev.event == "referenced" or ev.event == "closed":
                if ev.commit_id != None:
                    commitid = ev.commit_id
                    print("\tcid:" + commitid)
                    fixed.append(get_fixfiles(commitid,fullname,nlang,plang))

        #対象とするPRがあるか検索する(ぜんぶみる)
        prroot = prtree.getroot()
        for pr in prroot:
            if pr.find("to").text == bugid:
                prid = pr.find("number").text
                fixed.append(get_pr_fixfiles(prid,repo))
                break

        files = list(itertools.chain.from_iterable(fixed))
        files_uniq = list(set(files))
        if len(files_uniq) == 0:
            print("\tNone.")
            continue

        bugnum += 1
        wf.write('\t<bug id="'+bugid+'" opendate="'+created+'" fixdate="'+closed+'">\n')
        wf.write('\t\t<buginformation>\n')
        wf.write('\t\t\t<summary>'+escape(title)+'</summary>\n')
        wf.write('\t\t\t<description>'+escape(body)+'</description>\n')
        wf.write('\t\t</buginformation>\n')
        wf.write('\t\t<fixedfiles>\n')
        for file in files_uniq:
            wf.write('\t\t\t<file>')
            wf.write(file)
            wf.write('</file>\n')
        wf.write('\t\t</fixedfiles>\n')
        wf.write('\t</bug>\n')
    wf.write('<bugrepository>\n')
    wf.close()
    if(bugnum == 0):
        os.remove('./BugRepository/'+nlang+'/'+plang+'/'+reponame+'.xml')

    return bugnum

def get_fixfiles(commitid,fullname,nlang,plang):
    fixed = []
    #print(os.getcwd())
    logs = open("./Bug/"+nlang+"/"+plang+'/'+fullname.split('/')[0]+"/gitlog.txt","r")
    flag = False
    for line in logs:
        #print(line)
        if(commitid in line):
            flag = True
        if(flag and line == '\n'):
            break
        if("Merge pull request" in line):
            flag = False
        if(flag):
            if(line.split('\t')[0] == 'A' or line.split('\t')[0] == 'M'):
                filename = line.rstrip().split('\t')[1]
                #TODO:多言語対応
                if(filename.endswith(".java")):
                    fixed.append(filename)
                    print("\t\t"+filename)

    logs.close()

    return fixed

def get_pr_fixfiles(prid,repo):
    fixed = []
    print("\t"+ prid)
    pr = repo.get_issue(int(prid))
    prev = pr.get_events()

    for ev in prev:
        if ev.event == "merged":
            cmsha = ev.commit_id
            print("\tcid:" + cmsha +"(PR)")
            prcm = repo.get_commit(cmsha)
            for file in prcm.files:
                #TODO:多言語対応
                if(file.filename.endswith(".java")):
                    fixed.append(file.filename)
                    print("\t\t"+file.filename)

    return fixed

#XMLの文字コード調整用
def charset(text):
    return text.encode('ISO-8859-1').decode('UTF-8')

if __name__ == '__main__':
    nlang = sys.argv[1]
    plang = sys.argv[2]
    repos = open("./Bug/"+nlang+'/'+plang+"/ranking-"+nlang+"_"+plang+"_bug.txt","r")

    if(os.path.exists("./BugRepository/"+nlang+'/'+plang+"/"+nlang+"_"+plang+"_result.txt")):
        read = open("./BugRepository/"+nlang+'/'+plang+"/"+nlang+"_"+plang+"_result.txt","r")
        skipline = len(read.readlines())
        read.close()
        results = open("./BugRepository/"+nlang+'/'+plang+"/"+nlang+"_"+plang+"_result.txt","a")

    else:
        os.makedirs("./BugRepository/"+nlang+'/'+plang, exist_ok=True)
        results = open("./BugRepository/"+nlang+'/'+plang+"/"+nlang+"_"+plang+"_result.txt","w")
        skipline = 0
    while True:
        line = repos.readline().split(" ")

        if(skipline > 0):
            skipline = skipline - 1
            continue

        if(len(line) == 0):
            #空行
            break
        try:
            fullname = line[1].rstrip()
        except:
            break

        print("Repository: "+fullname)
        num = make(fullname, nlang, plang)
        results.write(str(num) + " " + fullname+"\n")

    repos.close()
    results.close()


__author__ = 'volodya'

import datetime

import numpy as np

def get_month_diff(date1, date2):
    def convert_date(date):
        if isinstance(date, str):
            assert '/' in date
            year, month = map(int, date.split('/'))
            if year < 100: year += 2000
            return datetime.datetime(year=year, month=month, day=1)
        elif isinstance(date, datetime.datetime):
            year = date.year
            month = date.month
            return datetime.datetime(year=year, month=month, day=1)
        else:
            raise ValueError('end_of_month argument error', date)

    date1 = convert_date(date1)
    date2 = convert_date(date2)

    if date1 > date2:
        date1, date2 = date2, date1

    return (date2.year - date1.year) * 12 + date2.month - date1.month

if __name__ == '__main__':
    dates1 = [datetime.datetime(year=year, month=month, day=1) for year in range(2000, 2020) for month in range(1, 13)]
    dates2 = [datetime.datetime(year=year, month=month, day=10) for year in range(2000, 2020) for month in range(1, 13)]

    for date1 in np.random.choice(dates1, 20):
        for date2 in np.random.choice(dates1, 20):
            print(date1, date2, get_month_diff(date1, date2))


import os,re,requests
def main():
    i=int(input('输入数字：\n1、查询本机ip\n2、查询公网ip\n'))
    if i==1:
        os.system('ipconfig>ip.txt')
        with open('ip.txt') as tmps:
            for tmp in tmps:
                if 'IPv4 地址' in tmp:
                    ip=tmp[tmp.rfind(' ')+1:len(tmp)].strip()
        print(ip)
        os.remove('ip.txt')
    elif i==2:
        resp=requests.get('https://2021.ip138.com',headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)''AppleWebKit/537.36 (KHTML, like Gecko)''Chrome/83.0.4103.97 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;''q=0.9,image/webp,image/apng,*/*;''q=0.8,application/signed-exchange;v=b3;q=0.9','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'})
        ip=re.findall(r'>(.+)</a>](.+)',resp.text)
        print(' '.join(ip[0]))
    else:
        print('请输入对应数字！')
main()
while True:
    i=input('是否继续？q：退出，其它：继续\n')
    if i=='q':
        break
    else:
        os.system('cls')
        main()


import socket
import sys
import os

HOST = input("Ingrese IP del servidor: ")  # The server's hostname or IP address
PORT = int(input("Ingrese el puerto del servidor: "))  # The port used by the server
msgFromClient = "Conexion hecha"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = (HOST, PORT)
bufferSize = 1024

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as UDPClientSocket:
	UDPClientSocket.sendto(bytesToSend, serverAddressPort)  # envia al seridor
	msgFromServer = UDPClientSocket.recvfrom(bufferSize) #Mensaje que viene del srvidpr
	os.system("clear") #para limpiar consola
	print("{}".format(msgFromServer[0].decode()))
	msgFromClient = input("Dificultad: ")
	bytesToSend = str.encode(msgFromClient)
	UDPClientSocket.sendto(bytesToSend, serverAddressPort)
	os.system("clear")

	while True:
		msgFromServer = UDPClientSocket.recvfrom(bufferSize) #Mensaje que viene del srvidpr
		#print("{}".format(msgFromServer[0].decode()))
		msgRecibido=msgFromServer[0].decode()

		if str(msgRecibido)=="Sigue":
			msgFromClient=input("\n Ingrese las coordenadas para tirar (x,y): ")
			bytesToSend = str.encode(msgFromClient)
			UDPClientSocket.sendto(bytesToSend,serverAddressPort)
			os.system("clear")
		elif str(msgRecibido)=="Elije otro":
			os.system("clear")
			print(str(msgRecibido+"\n"))
		elif str(msgRecibido)=="exit":
			break
		else:
			print(str(msgRecibido))

	msgFromServer = UDPClientSocket.recvfrom(bufferSize)
	msgRecibido=msgFromServer[0].decode()
	print(str(msgRecibido))
print("\n\t¡¡¡Fin del juego!!!\n")


#  Copyright 2018 Ocean Protocol Foundation
#  SPDX-License-Identifier: Apache-2.0

import logging
import os
import time

from examples import ExampleConfig, get_account_from_config
from squid_py import ConfigProvider, Metadata, Ocean
from squid_py.agreements.service_agreement import ServiceAgreement
from squid_py.agreements.service_types import ServiceTypes
from squid_py.keeper import Keeper
from tests.resources.helper_functions import get_publisher_account

def _log_event(event_name):
    def _process_event(event):
        print(f'Received event {event_name}: {event}')

    return _process_event

if 'TEST_NILE' in os.environ and os.environ['TEST_NILE'] == '1':
    ASYNC_DELAY = 5  # seconds
else:
    ASYNC_DELAY = 1  # seconds

def buy_asset():
    """
    Requires all ocean services running.

    """
    ConfigProvider.set_config(ExampleConfig.get_config())
    config = ConfigProvider.get_config()

    # make ocean instance
    ocn = Ocean()
    acc = get_publisher_account(config)
    if not acc:
        acc = ([acc for acc in ocn.accounts.list() if acc.password] or ocn.accounts.list())[0]

    # Register ddo
    ddo = ocn.assets.create(Metadata.get_example(), acc, providers=[acc.address])
    logging.info(f'registered ddo: {ddo.did}')
    # ocn here will be used only to publish the asset. Handling the asset by the publisher
    # will be performed by the Brizo server running locally
    keeper = Keeper.get_instance()
    if 'TEST_LOCAL_NILE' in os.environ and os.environ['TEST_LOCAL_NILE'] == '1':
        provider = keeper.did_registry.to_checksum_address(
            '0x413c9ba0a05b8a600899b41b0c62dd661e689354'
        )
        keeper.did_registry.add_provider(ddo.asset_id, provider, acc)
        logging.debug(f'is did provider: '
                      f'{keeper.did_registry.is_did_provider(ddo.asset_id, provider)}')

    cons_ocn = Ocean()
    consumer_account = get_account_from_config(config, 'parity.address1', 'parity.password1')

    # sign agreement using the registered asset did above
    service = ddo.get_service(service_type=ServiceTypes.ASSET_ACCESS)
    # This will send the purchase request to Brizo which in turn will execute the agreement on-chain
    cons_ocn.accounts.request_tokens(consumer_account, 100)
    sa = ServiceAgreement.from_service_dict(service.as_dictionary())

    agreement_id = cons_ocn.assets.order(
        ddo.did, sa.service_definition_id, consumer_account)
    logging.info('placed order: %s, %s', ddo.did, agreement_id)
    i = 0
    while ocn.agreements.is_access_granted(
            agreement_id, ddo.did, consumer_account.address) is not True and i < 30:
        time.sleep(1)
        i += 1

    assert ocn.agreements.is_access_granted(agreement_id, ddo.did, consumer_account.address)

    ocn.assets.consume(
        agreement_id,
        ddo.did,
        sa.service_definition_id,
        consumer_account,
        config.downloads_path)
    logging.info('Success buying asset.')

if __name__ == '__main__':
    buy_asset()


import os.path

class FileExtractor(object):
    def __init__(self):
        self.pattern = ".c"

    def extractFiles(self,path_root = None):
        result = []
        result = self._extractFiles(path_root)
        return result

    def _extractFiles(self, path):
        result = []
        current_content = os.listdir(path)
        for content in current_content:
            content_path = self._get_current_path(path,content)
            is_file = os.path.isfile(content_path)
            if (is_file):
                if (self._file_checked_pattern(content)):
                    result.append(content)

            is_directory = os.path.isdir(content_path)
            if (is_directory):
                result = result + self._extractFiles(content_path)

        return result

    def _get_current_path(self,path,content):
        result = ""
        if (path is None):
            result = content
        else:
            result = path + "/" + content
        return result

    def _file_checked_pattern(self,file_name):
        size = len(file_name)
        return file_name[size-2:] == self.pattern


"""
Type annotations for amplifybackend service literal definitions.

[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_amplifybackend/literals.html)

Usage::

    ```python
    from mypy_boto3_amplifybackend.literals import AdditionalConstraintsElementType

    data: AdditionalConstraintsElementType = "REQUIRE_DIGIT"
    ```
"""
import sys

if sys.version_info >= (3, 8):
    from typing import Literal
else:
    from typing_extensions import Literal

__all__ = (
    "AdditionalConstraintsElementType",
    "AuthResourcesType",
    "AuthenticatedElementType",
    "DeliveryMethodType",
    "ListBackendJobsPaginatorName",
    "MFAModeType",
    "MfaTypesElementType",
    "ModeType",
    "OAuthGrantTypeType",
    "OAuthScopesElementType",
    "RequiredSignUpAttributesElementType",
    "ResolutionStrategyType",
    "ServiceNameType",
    "ServiceType",
    "SignInMethodType",
    "StatusType",
    "UnAuthenticatedElementType",
)

AdditionalConstraintsElementType = Literal[
    "REQUIRE_DIGIT", "REQUIRE_LOWERCASE", "REQUIRE_SYMBOL", "REQUIRE_UPPERCASE"
]
AuthResourcesType = Literal["IDENTITY_POOL_AND_USER_POOL", "USER_POOL_ONLY"]
AuthenticatedElementType = Literal["CREATE_AND_UPDATE", "DELETE", "READ"]
DeliveryMethodType = Literal["EMAIL", "SMS"]
ListBackendJobsPaginatorName = Literal["list_backend_jobs"]
MFAModeType = Literal["OFF", "ON", "OPTIONAL"]
MfaTypesElementType = Literal["SMS", "TOTP"]
ModeType = Literal["AMAZON_COGNITO_USER_POOLS", "API_KEY", "AWS_IAM", "OPENID_CONNECT"]
OAuthGrantTypeType = Literal["CODE", "IMPLICIT"]
OAuthScopesElementType = Literal[
    "AWS_COGNITO_SIGNIN_USER_ADMIN", "EMAIL", "OPENID", "PHONE", "PROFILE"
]
RequiredSignUpAttributesElementType = Literal[
    "ADDRESS",
    "BIRTHDATE",
    "EMAIL",
    "FAMILY_NAME",
    "GENDER",
    "GIVEN_NAME",
    "LOCALE",
    "MIDDLE_NAME",
    "NAME",
    "NICKNAME",
    "PHONE_NUMBER",
    "PICTURE",
    "PREFERRED_USERNAME",
    "PROFILE",
    "UPDATED_AT",
    "WEBSITE",
    "ZONE_INFO",
]
ResolutionStrategyType = Literal["AUTOMERGE", "LAMBDA", "NONE", "OPTIMISTIC_CONCURRENCY"]
ServiceNameType = Literal["S3"]
ServiceType = Literal["COGNITO"]
SignInMethodType = Literal["EMAIL", "EMAIL_AND_PHONE_NUMBER", "PHONE_NUMBER", "USERNAME"]
StatusType = Literal["LATEST", "STALE"]
UnAuthenticatedElementType = Literal["CREATE_AND_UPDATE", "DELETE", "READ"]