import os, sys
import math

import torch
import torch.nn as nn

from torchsummary import summary

class Flatten(nn.Module):
    def forward(self, x):
        return x.view(x.size(0), -1)

class LinearBlock(nn.Module):
    def __init__(self, in_c, out_c, kernel_size=1, stride=1, padding=0, groups=1):
        super(LinearBlock, self).__init__()
        self.conv = nn.Conv2d(in_c, out_c, kernel_size, groups=groups, stride=stride,
                padding=padding, bias=False)
        self.bn = nn.BatchNorm2d(out_c)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)

        return x

class ConvBNPReLU(nn.Module):
    def __init__(self, in_c, out_c, kernel_size=1, stride=1, padding=0, groups=1):
        super(ConvBNPReLU, self).__init__()
        self.conv = nn.Conv2d(in_c, out_c, kernel_size, groups=groups, stride=stride,
                padding=padding, bias=False)
        self.bn = nn.BatchNorm2d(out_c)
        self.prelu = nn.PReLU(out_c)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        x = self.prelu(x)

        return x

class DepthWiseBlock(nn.Module):
    def __init__(self, in_c, out_c, kernel_size=3, stride=2, padding=1, groups=1):
        super(DepthWiseBlock, self).__init__()
        self.p_conv = ConvBNPReLU(in_c, groups, 1, 1, 0)
        self.d_conv = ConvBNPReLU(groups, groups, kernel_size, stride=stride,
                                    padding=padding, groups=groups)
        self.project = LinearBlock(groups, out_c, 1, 1, 0)
        if in_c == out_c  and stride == 1:
            self.residual = True
        else:
            self.residual = False

    def forward(self, x):
        x_ = x
        x = self.p_conv(x)
        x = self.d_conv(x)
        x = self.project(x)
        if self.residual:
            output = x_ + x
        else:
            output = x
        return output

class ResidualBlock(nn.Module):
    def __init__(self, c, num_blocks, groups, kernel_size=3, stride=1, padding=1):
        super(ResidualBlock, self).__init__()
        modules = []
        for _ in range(num_blocks):
            modules.append(DepthWiseBlock(c, c, kernel_size, stride, padding, groups))
        self.model = nn.Sequential(*modules)

    def forward(self, x):
        return self.model(x)

def l2_norm(x, axis=1):
    norm = torch.norm(x, p=2, dim=axis, keepdim=True)
    x = torch.div(x, norm)
    return x

class MobileFaceNet(nn.Module):
    def __init__(self, feature_dim=512):
        super(MobileFaceNet, self).__init__()
        self.conv_1 = ConvBNPReLU(3, 64, 3, 2, 1)
        self.conv_2_dw = ConvBNPReLU(64, 64, 3, 1, 1, groups=64)
        self.conv_23 = DepthWiseBlock(64, 64, 3, 2, 1, groups=128)
        self.conv_3 = ResidualBlock(64, 4, 128, 3, 1, 1)
        self.conv_34 = DepthWiseBlock(64, 128, 3, 2, 1, groups=256)
        self.conv_4 = ResidualBlock(128, 6, 256, 3, 1, 1)
        self.conv_45 = DepthWiseBlock(128, 128, 3, 2, 1, groups=512)
        self.conv_5 = ResidualBlock(128, 2, 256, 3, 1, 1)
        self.conv_6_sep = ConvBNPReLU(128, 512, 1, 1, 0)
        self.conv_6_dw = LinearBlock(512, 512, 7, 1, 0, groups=512)
        self.conv_6_flatten = Flatten()
        self.linear = nn.Linear(512, feature_dim, bias=False)
        self.bn = nn.BatchNorm1d(feature_dim)

        # weight initialization
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2./n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def forward(self, x):
        x = self.conv_1(x)
        x = self.conv_2_dw(x)
        x = self.conv_23(x)
        x = self.conv_3(x)
        x = self.conv_34(x)
        x = self.conv_4(x)
        x = self.conv_45(x)
        x = self.conv_5(x)
        x = self.conv_6_sep(x)
        x = self.conv_6_dw(x)
        x = self.conv_6_flatten(x)
        x = self.linear(x)
        x = self.bn(x)
        return l2_norm(x)
        # return l2_norm(x)*20
        # return x

class MobileFaceNetHalf(nn.Module):
    def __init__(self, feature_dim=512):
        super(MobileFaceNetHalf, self).__init__()
        self.conv_1 = ConvBNPReLU(3, 32, 3, 2, 1)
        self.conv_2_dw = ConvBNPReLU(32, 32, 3, 1, 1, groups=32)
        self.conv_23 = DepthWiseBlock(32, 32, 3, 2, 1, groups=64)
        self.conv_3 = ResidualBlock(32, 4, 64, 3, 1, 1)
        self.conv_34 = DepthWiseBlock(32, 64, 3, 2, 1, groups=128)
        self.conv_4 = ResidualBlock(64, 6, 128, 3, 1, 1)
        self.conv_45 = DepthWiseBlock(64, 64, 3, 2, 1, groups=256)
        self.conv_5 = ResidualBlock(64, 2, 128, 3, 1, 1)
        self.conv_6_sep = ConvBNPReLU(64, 256, 1, 1, 0)
        self.conv_6_dw = LinearBlock(256, 256, 7, 1, 0, groups=256)
        self.conv_6_flatten = Flatten()
        self.linear = nn.Linear(256, feature_dim, bias=False)
        self.bn = nn.BatchNorm1d(feature_dim)

        # weight initialization
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2./n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def forward(self, x):
        x = self.conv_1(x)
        x = self.conv_2_dw(x)
        x = self.conv_23(x)
        x = self.conv_3(x)
        x = self.conv_34(x)
        x = self.conv_4(x)
        x = self.conv_45(x)
        x = self.conv_5(x)
        x = self.conv_6_sep(x)
        x = self.conv_6_dw(x)
        x = self.conv_6_flatten(x)
        x = self.linear(x)
        x = self.bn(x)
        return x

if __name__ == "__main__":
    net = MobileFaceNetHalf()
    torch.save(net.state_dict(), 'tmp.pth')
    summary(net.cuda(), (3, 112, 112))


from distiller.utils import yaml_ordered_save, yaml_ordered_load
import ipdb
import argparse
import os

def read_prune_schedule(sdict):
    sched = []
    pruners = list(sdict['pruners'].keys())
    for pruner in pruners:
        rate = sdict['pruners'][pruner]['desired_sparsity']
        sched.append(rate)
    return sched

def write_prune_schedule(sdict, sched):
    pruners = list(sdict['pruners'].keys())
    for i in range(len(sched)):
        sdict['pruners'][pruners[i]]['desired_sparsity'] = sched[i]
    return sdict

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='validate the detectors')
    parser.add_argument('-f', '--file', type=str, help='yaml file')
    args = parser.parse_args()

    with open(args.file, 'r') as stream:
        sched_dict = yaml_ordered_load(stream)

    schedule = read_prune_schedule(sched_dict)

    count = 0
    while schedule[-1] < 0.9:
        schedule1 = []
        for rate in schedule:
            if rate < 0.9:
                schedule1.append(rate+0.1)
            else:
                schedule1.append(rate)
        new_sched_dict = write_prune_schedule(sched_dict, schedule1)

        schedule_dir = '../extended_doublenet_search/'
        os.makedirs(schedule_dir, exist_ok=True)
        yaml_ordered_save(os.path.join(schedule_dir, 'filter_rank.'+str(count)+'.yaml'), new_sched_dict)
        schedule = schedule1
        count += 1


#encoding=utf8

import sys,os

if __name__ == '__main__':
    if (len(sys.argv) < 4):
        sys.exit(1)

    curWorkingPath = os.getcwd()
    curPythonScriptPath = os.path.split(os.path.realpath(sys.argv[0]))[0]

    os.chdir(curPythonScriptPath)

    os.execl(sys.argv[1], sys.argv[1], "a", sys.argv[2], sys.argv[3])

    os.chdir(curWorkingPath)


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import argparse
import logging
from contextlib import suppress

import generator

AP = argparse.ArgumentParser(description = "Search path in graph")
AP.add_argument("first", type = str, help = "First vertex in path")
AP.add_argument("last", type = str, help = "Last vertex in path")
AP.add_argument("--data-path", "-d", dest = "path", action = "store", type = str, default = ".", help = "Path to directory where data files are located")
AP.add_argument("--nodes", "-n", dest = "nodes", action = "store", type = str, default = "nodes.csv", help = "Name of nodes file")
AP.add_argument("--links", "-l", dest = "links", action = "store", type = str, default = "links.csv", help = "Name of links file")
AP.add_argument("--debug", dest = "loglevel", action = "store_const", const = logging.DEBUG, default = logging.WARNING, help = "log level = DEBUG")
AP.add_argument("--error", dest = "loglevel", action = "store_const", const = logging.ERROR, default = logging.WARNING, help = "log level = ERROR")

ARGS = AP.parse_args()

# В папке пользователя .depth
LogPath = os.path.expanduser(os.path.join("~", ".depth"))
# подавляем исключени (компактная запись)
with suppress(OSError):
	# создаем папку
	os.mkdir(LogPath)

logging.basicConfig(
	level = ARGS.loglevel,
	style = "{",
	format = "{levelname:8} {asctime} {name:10} {message}",
	# filename = "./log/error.log",
	# filename = os.path.join(LogPath, "general.log")
)

# Абсолютный путь
data_path = os.path.abspath(ARGS.path)

logging.debug("First: {0.first} Last: {0.last}".format(ARGS))
logging.debug("Data path: {0.path} ({1})".format(ARGS, data_path))
logging.debug("Nodes: {0.nodes} Links: {0.nodes}".format(ARGS))
logging.info("Test")
logging.warning("Test")
logging.error("Test")
logging.critical("Test")

# data_path = os.path.join("D:", "\\", "Project", "python", "point", "data")
# print(data_path)
Graph, Names = generator.read_all(data_path, ARGS.nodes, ARGS.links)

First = Names[ARGS.first]['number']
Last = Names[ARGS.last]['number']

for path in generator.in_depth(Graph, First, Last):
	print(path)


#calss header
class _MEDIATE():
	def __init__(self,):
		self.name = "MEDIATE"
		self.definitions = [u'to talk to two separate people or groups involved in a disagreement to try to help them to agree or find a solution to their problems: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'verbs'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


from easydict import EasyDict as edict

__C = edict()
# Consumers can get config by: from config import cfg

cfg = __C

# YOLO options
__C.YOLO = edict()

__C.YOLO.CLASSES              = "D:/Anacoda/YOLO_v3_s/data/classes/coco.names"
__C.YOLO.ANCHORS              = "D:/Anacoda/YOLO_v3_s/data/anchors/baseline_anchors.txt"
__C.YOLO.STRIDES              = [8, 16, 32]
__C.YOLO.ANCHOR_PER_SCALE     = 3
# 影响：
__C.YOLO.IOU_LOSS_THRESHOLD = 0.5

# Train options
__C.TRAIN                     = edict()

__C.TRAIN.ANNOT_PATH          = "./data/dataset/yymnist_train.txt"
__C.TRAIN.BATCH_SIZE          = 4
# __C.TRAIN.INPUT_SIZE            = [320, 352, 384, 416, 448, 480, 512, 544, 576, 608]
__C.TRAIN.INPUT_SIZE          = [416]
__C.TRAIN.DATA_AUG            = True
__C.TRAIN.LR_INIT             = 1e-3
__C.TRAIN.LR_END              = 1e-6
__C.TRAIN.WARMUP_EPOCHS       = 2
__C.TRAIN.EPOCHS              = 30

# test options
__C.TEST                      = edict()

__C.TEST.ANNOT_PATH           = "./data/dataset/yymnist_test.txt"
__C.TEST.BATCH_SIZE           = 2
__C.TEST.INPUT_SIZE           = 544
__C.TEST.DATA_AUG             = False
__C.TEST.DECTECTED_IMAGE_PATH = "./data/detection/"
__C.TEST.SCORE_THRESHOLD      = 0.3
__C.TEST.IOU_THRESHOLD        = 0.45


import unittest
from os.path import abspath, normpath
from pathlib import PurePath

from importlib import import_module

class TestBeerRecommender(unittest.TestCase):

    def test_index_template(self):
        flask_app = import_module('beer_recommender')
        flask_app.app.testing = True
        base = PurePath(abspath(__file__))
        template = normpath(PurePath(base, '../../templates/index.html'))
        with open(template, 'r') as f:
            whole_str = f.read()

        with flask_app.app.test_client() as c:
            result = c.get('/')
            self.assertEqual(result.data.decode('utf-8'), whole_str.strip())

    def test_result_render(self):
        flask_app = import_module('beer_recommender')
        flask_app.app.testing = True
        abv = 5.0
        ibu = 15.5
        with flask_app.app.test_client() as c:
            result = c.post('/result', data=dict(abv=abv, ibu=ibu), follow_redirects=True)
            as_text = result.get_data(as_text=True)
            self.assertTrue('度数: {}'.format(abv) in as_text,
                            'HTMLが正しくコーディングされていません')
            self.assertTrue('IBU: {}'.format(ibu) in as_text,
                            'HTMLが正しくコーディングされていません')

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


import turtle, random

def tree(branchLen, t):
    if branchLen > 5:
        t.forward(branchLen)
        rightAngle = random.randrange(15, 45)
        t.right(rightAngle)
        tree(branchLen - 10, t)
        t.left(random.randrange(15, 45))
        tree(branchLen - 10, t)
        t.right(rightAngle)
        t.backward(branchLen)

t = turtle.Turtle()
window = turtle.Screen()

t.color('green')
tree(100, t)
window.exitonclick()


#encoding: utf-8
from OpenOrange import *
from Report import Report
from SalesOrder import SalesOrder

class InvoicePendingSalesOrdersReport(Report):

    def defaults(self):
        record = self.getRecord()
        record.SalesMan = currentUser()
        record.FromDate = addDays(today(), -14)
        record.ToDate = addDays(today(), +7)
        record.OnlyDelivered = True

    def genInvoice(self, param, value):
        if askYesNo("Esta seguro de facturar la orden %s" % param):
            from SalesOrder import SalesOrder
            so = SalesOrder.bring(int(param))
            #Se anula lo siguiente ya que no debe ser standard. Si algún cliente lo necesita, se debería customizarselo
            """if so.isFullDelivered():
                inv = so.genInvoice(FromDeliveries = True)
                if inv:
                    res = inv.save()
                    if not res:
                        message(res)
                        from InvoiceWindow import InvoiceWindow
                        w = InvoiceWindow()
                        w.setRecord(inv)
                        w.open()
                    else:
                        commit()
                        self.refresh()
            else:
                inv = so.genInvoice(FromDeliveries = True)
                if inv:
                    res = inv.save()
                    if not res:
                        message(res)
                        return
                    from SalesOrder import SalesOrderItemRow
                    from SalesOrderWindow import SalesOrderWindow
                    newso = so.clone()
                    newso.SerNr = None
                    newso.ToSerNr = None
                    newso.TransDate = today()
                    newso.AuthorizedBy = ""
                    newso.Status = 0
                    newso.Closed = False
                    newso.Items.clear()
                    itemsstatus = so.getItemsStatus()
                    save_so = False
                    for sorw in so.Items:
                        itemstatus = itemsstatus[sorw.rowNr]
                        if itemstatus["Ordered"] > itemstatus["Delivery"][1] + itemstatus["Delivery"][2]:
                            sorw.Qty = itemstatus["Delivery"][1] + itemstatus["Delivery"][2]
                            sorw.sumUp(so)
                            save_so = True
                    if save_so:
                        so.sumUp()
                        res = so.store()
                        if not res: return
                    for rownr in itemsstatus:
                        itemstatus = itemsstatus[rownr]
                        if itemstatus["Ordered"] > itemstatus["Delivery"][1] + itemstatus["Delivery"][2]:
                            sorw = SalesOrderItemRow()
                            sorw.ArtCode = itemstatus["ArtCode"]
                            sorw.Qty = itemstatus["Ordered"] - (itemstatus["Delivery"][1] + itemstatus["Delivery"][2])
                            sorw.pasteArtCode(newso)
                            sorw.Price = so.Items[rownr].Price
                            sorw.pastePrice(so)
                            sorw.sumUp(so)
                            newso.Items.append(sorw)
                    newso.sumUp()
                    res = newso.save()
                    if not res: return
                    wnd = SalesOrderWindow()
                    wnd.setRecord(newso)
                    wnd.open()
                    commit()
                    self.refresh()"""
            #Se remplaza por lo siguiente
            inv = so.genInvoice(FromDeliveries = True)
            if inv:
                res = inv.save()
                if not res:
                    message(res)
                    from InvoiceWindow import InvoiceWindow
                    w = InvoiceWindow()
                    w.setRecord(inv)
                    w.open()
                else:
                    commit()
                    self.refresh()

    def run(self):
        self.getView().resize(700,500)
        specs = self.getRecord()
        self.printReportTitle("Sales Orders with Invoicing Pending")
        self.startTable()
        self.header("Status", "Order", "Customer", "Delivery Date", "From", "To", "Pending","Neto","Total", "Action","")

        query = Query()
        query.sql = "SELECT SO.SerNr FROM SalesOrder SO "
        query.sql += "INNER JOIN [Customer] C ON C.Code = SO.CustCode "
        query.sql += "WHERE?AND SO.FullInvoiced = i|0|  "
        query.sql += "WHERE?AND SO.DeliveryDate BETWEEN d|%s| AND d|%s| " % (specs.FromDate, specs.ToDate)
        if specs.CustCode: query.sql += "WHERE?AND SO.CustCode = s|%s| " % specs.CustCode
        if specs.GroupCode: query.sql += "WHERE?AND C.GroupCode = s|%s| " % specs.GroupCode
        if specs.Office: query.sql += "WHERE?AND SO.Office = s|%s| " % specs.Office
        if specs.SalesMan: query.sql += "WHERE?AND SO.SalesMan = s|%s| " % specs.SalesMan
        query.sql += "WHERE?AND (SO.Invalid = i|0| OR SO.Invalid IS NULL) "
        query.sql += "WHERE?AND (SO.Closed = i|0| OR SO.Closed IS NULL) "
        query.sql += "WHERE?AND SO.Status = i|1| "
        if specs.DeliveryOrder:
            query.sql += "ORDER BY SO.DeliveryDate "

        tamount = 0.0
        GSubTotal = 0
        GTotal = 0

        if query.open():
            for rec in query:
                so = SalesOrder.bring(rec.SerNr)
                if not so.isFullInvoiced(OnlyDelivered=specs.OnlyDelivered):
                    amount = so.getInvoicePendingAmount(OnlyDelivered=specs.OnlyDelivered)
                    self.startRow()
                    self.addValue("Estado", CallMethod="showSalesOrderStatus", Parameter=rec.SerNr,Color="#0000CC")
                    self.addValue(rec.SerNr, Window="SalesOrderWindow", FieldName="SerNr")
                    self.addValue(so.CustName)
                    self.addValue(so.DeliveryDate)
                    self.addValue(so.DelFromTime)
                    self.addValue(so.DelToTime)
                    self.addValue(amount)
                    self.addValue(so.SubTotal)
                    self.addValue(so.Total)
                    tamount += amount
                    GSubTotal += so.SubTotal
                    GTotal += so.Total

                    if not so.isFullDelivered():
                        self.addValue("Parcial",Color="#FF3300")
                    else:
                        self.addValue("Completa",Color="#009900")
                    self.addValue("Facturar", CallMethod="genInvoice", Parameter=rec.SerNr)
                    self.endRow()
        self.startHeaderRow()
        self.addValue("",ColSpan=6)
        self.addValue(tamount)
        self.addValue(GSubTotal)
        self.addValue(GTotal)
        self.addValue("",ColSpan=2)
        self.endHeaderRow()
        self.endTable()

    def showSalesOrderStatus(self,param,value):
        from SalesOrderStatusReport import SalesOrderStatusReport
        report = SalesOrderStatusReport()
        report.getRecord().SalesOrderNr = param
        report.open(False)


from modeller import *
from modeller.automodel import *    # Load the automodel class

log.verbose()

env = environ()

# directories for input atom files
env.io.atom_files_directory = ['.', '../atom_files']

a = automodel(env,
    alnfile  = 'prot.seq',
    knowns   = 'prot',
    sequence = 'prot_fill',
    assess_methods=(assess.DOPE,
                    assess.GA341))
a.starting_model= 1
a.ending_model  = 1

a.make()


import csv
import sys

from itertools import zip_longest

items = []

data = list(csv.reader(open(sys.argv[1], 'r')))
for row in data:
    if not row:
      continue
    name, page, image = row
    items.append({
      'name': name.strip(),
      'link': '/esphomeyaml/{}.html'.format(page.strip()),
      'image': '/esphomeyaml/images/{}'.format(image.strip()),
    })

TABLE_ITEM_LENGTH = 50
TABLE_COLUMNS = 3

def create_row_str(type):
    return ' '.join([(type * TABLE_ITEM_LENGTH) for _ in range(TABLE_COLUMNS)])

# https://stackoverflow.com/a/3415150/8924614
def grouper(n, iterable, fillvalue=None):
    """grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"""
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)

print(create_row_str('='))
prev_row = False

for value in grouper(TABLE_COLUMNS, items):
    row1 = []
    row2 = []
    for x in value:
        if x is None:
            continue
        row1.append('|{}|_'.format(x['name']).ljust(TABLE_ITEM_LENGTH))
        row2.append('`{}`_'.format(x['name']).ljust(TABLE_ITEM_LENGTH))
    if prev_row:
        print(create_row_str('-'))
    prev_row = True
    print(' '.join(row1).rstrip())
    print(create_row_str('-'))
    print(' '.join(row2).rstrip())

print(create_row_str('='))
print()

for item in items:
    print('.. |{}| image:: {}'.format(item['name'], item['image']))
    print('    :class: component-image')
    print('.. _{}: {}'.format(item['name'], item['link']))

print()


from SCons.Script import AlwaysBuild, Import

Import("env")

# Added in PIO Core 4.4.0
if not hasattr(env, "AddPlatformTarget"):

    def AddPlatformTarget(
        env,
        name,
        dependencies,
        actions,
        title=None,
        description=None,
        always_build=True,
    ):
        target = env.Alias(name, dependencies, actions)
        if always_build:
            AlwaysBuild(target)
        return target

    env.AddMethod(AddPlatformTarget)


import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

class IpiviTermsOfUse(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_terms_of_use(self):
        driver = self.driver
        driver.maximize_window()
        driver.get("http://www.ipivi.com")
        element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located
                                                  ((By.XPATH, '//a[contains(@href, "/page/terms-of-use")]')))
        element.click()
        assert "အသံုးျပဳမႈစည္းကမ္းမ်ား" in driver.title

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


import pandas as pd
import os
import pickle
from deepoverflow.config import DATA_ROOT

posts_path = os.path.join(DATA_ROOT, 'incoming', 'Posts.csv')
posts_info = pd.read_csv(posts_path, encoding="ISO-8859-1", low_memory=False)

posts = posts_info[['Id', 'Tags', 'PostTypeId']]

id_to_tags = {}
for index, row in posts.iterrows():
    if int(row['PostTypeId']) == 2:
        continue
    str_idx = int(row['Id'])
    if row['Tags'] is not None and row['Tags'] != '':
        id_to_tags[str_idx] = row['Tags']

with open('id_to_tags.pickle', 'wb') as handle:
    pickle.dump(id_to_tags, handle, protocol=pickle.HIGHEST_PROTOCOL)


from os import listdir, mkdir
from os.path import isfile, join
import json
from github import Github

def github_push_from_variable(contentVariable, repoName, fileTargetPath, message, globalUser, token):
    from github import Github
    g = Github(token)
    repo = g.get_organization(globalUser).get_repo(repoName)
    try:
        file = repo.get_contents("/" + fileTargetPath)
        update = True
    except:
        update = False
    if update:
        repo.update_file(fileTargetPath, message, contentVariable, file.sha)
    else:
        repo.create_file(fileTargetPath, message, contentVariable, "master")

def open_json(fileUrl):
    import json
    import requests
    if fileUrl[0:4] == "http":
        # es URL
        pointer = requests.get(fileUrl)
        return json.loads(pointer.content.decode('utf-8'))
    else:
        # es file
        file = open(fileUrl, "r")
        return json.loads(file.read())

def keyvalues2normalized(keyvaluesPayload):
    import json

    keyvaluesDict = json.loads(keyvaluesPayload)
    output = {}
    # print(normalizedDict)
    for element in keyvaluesDict:
        item = {}
        print(keyvaluesDict[element])
        if isinstance(keyvaluesDict[element], list):
            # it is an array
            item["type"] = "array"
            item["value"] = keyvaluesDict[element]
        elif isinstance(keyvaluesDict[element], dict):
            # it is an object
            item["type"] = "object"
            item["value"] = keyvaluesDict[element]
        elif isinstance(keyvaluesDict[element], str):
            # it is an string
            item["type"] = "string"
            item["value"] = keyvaluesDict[element]
        elif keyvaluesDict[element] == True:
            # it is an boolean
            item["type"] = "boolean"
            item["value"] = True
        elif keyvaluesDict[element] == False:
            # it is an boolean
            item["type"] = "boolean"
            item["value"] = False
        elif isinstance(keyvaluesDict[element], int) or isinstance(keyvaluesDict[element], float):
            # it is an number
            item["type"] = "number"
            item["value"] = keyvaluesDict[element]
        else:
            print("*** other type ***")
            print("I do now know what is it")
            print(keyvaluesDict[element])
            print("--- other type ---")
        output[element] = item
    if "id" in output:
        output["id"] = output["id"]["value"]
    if "type" in output:
        output["type"] = output["type"]["value"]

    print(output)
    return output

def create_examples_payloads(repoName, dataModel, globalUser, token, *options):
    # options[0] could be schema (default) or in a future from example
    import requests
    if len(options) == 0 or options == None:
        mode = "schema"
    else:
        mode = options[0]

    serviceNGSIKeyvaluesExample = "https://smartdatamodels.org/extra/ngsi-ld_generator_keyvalues_v0.95.php"
    serviceNGSINormalizedExample = "https://smartdatamodels.org/extra/ngsi-ld_generator_v0.95.php"
    g = Github(token)
    repo = g.get_organization(globalUser).get_repo(repoName)
    if mode == "schema":
        urlSchema = "https://raw.githubusercontent.com/smart-data-models/" + repoName + "/master/" + dataModel + "/schema.json"
        urlToRequestNormalized = serviceNGSINormalizedExample + "?schemaUrl=" + urlSchema + "&email=alberto.abella@fiware.org"
        urlToRequestKeyvalues = serviceNGSIKeyvaluesExample + "?schemaUrl=" + urlSchema + "&email=alberto.abella@fiware.org"
        try:
            print(urlToRequestKeyvalues)
            pointer = requests.get(urlToRequestKeyvalues, timeout=10)
            keyvaluesLDPayload = pointer.content.decode('utf-8').replace("False", "false").replace("True", "true")
            keyvaluesLDPayloadDict = json.loads(keyvaluesLDPayload)
            keyvaluesLDPayload = json.dumps(keyvaluesLDPayloadDict, indent=4)  # just formatting
            print(keyvaluesLDPayload)
        except:
            return "Problem with keyvalues example"
        try:
            print(urlToRequestNormalized)
            pointer2 = requests.get(urlToRequestNormalized, timeout=10)
            print(pointer2)
            content = pointer2.content.decode('utf-8').replace("False", "false").replace("True", "true")
            print(type(content))
            print(content)
            normalizedLDPayloadDict = json.loads(content)
            normalizedLDPayload = json.dumps(normalizedLDPayloadDict, indent=4)
        except:
            return "Problem with normalized example"
        keyvaluesV2Payload = keyvaluesLDPayload
        keyvaluesV2PayloadDict = json.loads(keyvaluesV2Payload)
        contextUrl = keyvaluesV2PayloadDict.pop("@context", None)
        keyvaluesV2Payload = json.dumps(keyvaluesV2PayloadDict, indent=4)
        normalizedV2Payload = json.dumps(keyvalues2normalized(keyvaluesV2Payload), indent=4)
        # write the examples in the directory
        message = "Key values V2 Example generated automatically"
        print(keyvaluesV2Payload)
        github_push_from_variable(keyvaluesV2Payload, repoName, dataModel + "/examples/example.json", message, globalUser, token)

        message = "Key values LD Example generated automatically"
        print(keyvaluesLDPayload)
        github_push_from_variable(keyvaluesLDPayload, repoName, dataModel + "/examples/example.jsonld", message, globalUser, token)

        message = "Normalized LD Example generated automatically"
        print(normalizedLDPayload)
        github_push_from_variable(normalizedLDPayload, repoName, dataModel + "/examples/example-normalized.jsonld", message, globalUser, token)

        message = "Normalized V2 Example generated automatically"
        print(normalizedV2Payload)
        github_push_from_variable(normalizedV2Payload, repoName, dataModel + "/examples/example-normalized.json", message, globalUser, token)
    else:
        print("this is the mode:" + mode)

credentialsFile = "/home/aabella/transparentia/CLIENTES/EU/FIWARE/credentials.json"
# credentials = "/home/fiware/credentials.json
credentials = open_json(credentialsFile)
token = credentials["token"]
globalUser = credentials["globalUser"]

repoName = "incubated"
dataModel = "SMARTSENSORING/MEASUREMENT"
output = "don't know"
output = create_examples_payloads(repoName, dataModel, globalUser, token, "schema")
print(output)


import numpy
def deliver(house_list):
    f = open(house_list, 'r')
    houses = f.read().strip('\n')
    visited = numpy.zeros(shape=(len(houses), len(houses)))
    row = 0
    col = 0
    count = 0
    for i in range(len(houses)):
        symbol = houses[i]
        if symbol == '>': row += 1
        elif symbol == '<': row -= 1
        elif symbol == '^': col += 1
        elif symbol == 'v': col -= 1
        house = visited[row][col]
        if house == 0:
            count += 1
            visited[row][col] = 1
    print(count)


# 第一：需要反转链表，所以肯定需要设定三个指针。分别为prev指向前一个结点，cur指向当前结点，next指向下一个结点。
# 例如 2->3->4, 当前结点为3，要想3->2时候，需要设定三个指针。prev指向2，cur指向3，next指向4。
# 进行的逻辑为首先设置next指向结点4，cur.next = 2, 然后prev移到3，cur移到4。
# 第二：因为不是整个链表反转，只是部分反转，所以我们还需要一个额外的指针定锚在发生反转点之前。该额外指针将要求，部份反转结束以后，将未反转
# 的部份重现连入到反转部份当中。
# 第三：因为我们的部分反转的发生点可能就发生在头部，并且需要记录发生反转的发生点之前的结点，在结束反转后，需要进行node.next.next操作取重新连接链表。
# 所以不能只设置None.需要一个dummyNode.
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        # 新建一个dummyNode
        dummyNode = ListNode()
        # 该dummyNode连到头部
        dummyNode.next = head
        # node指针用于记录需要反转部份之前的那个结点,一开始时候，应该在head的左边就是dummyNode
        node = dummyNode
        i = 1
        # 通过循环找到反转部份之前的那个结点
        while i < left:
            node = head
            head = head.next
            i += 1
        # node用于锚点
        # 反转链表需要三个指针。next, cur, prev. 并且随着反转移动。
        # next指针从每次循环中取，所以还需要在反转开始前prev = node创建一个指针。cur变为此时的head
        prev = node
        while i <= right:
            nextPointer = head.next
            head.next = prev
            prev = head
            head = nextPointer
            i += 1
        # 反转结束以后。 node这个锚点，负责把链表组合起来。
        # node.next.next为将反转区间的第一个元素，连到反转区间右边,未反转后部份
        # node.next为将未反转前部分连到反转区间的最后一个元素
        node.next.next = head
        node.next = prev
        return dummyNode.next


import re
import os
import shlex
import urllib
import urllib2
import subprocess
from django.core.management.base import BaseCommand
from django.conf import settings

class Command(BaseCommand):
    args = '<pdf_file pdf_file ...>'
    help = 'Pull down the BreakAway PDF files and convert these to text files'

    def handle(self, *args, **options):
        pdf_files = self.get_pdf_files()

        if os.name == "nt":
            self.stderr.write("You probably don't want to run this on Windows...")
            return

        for pdf_filename in pdf_files:
            self.process_file(pdf_filename)

    @staticmethod
    def get_pdf_files():
        """
        This method finds all PDF files linked from http://breakawaysports.com/current-league.php
        and returns them as a list of URLs to the PDF documents for later processing
        @return: A list of pdf files (urls)
        """
        pdf_files = []
        response = urllib2.urlopen('http://breakawaysports.com/current-league.php')
        html = response.read()
        matches = re.findall(".*href=\"(.*\.pdf)\".*", html)

        for match in matches:
            pdf_files.append("http://breakawaysports.com%s" % match)

        return pdf_files

    def process_file(self, pdf_uri):
        """
        This method takes a URL of a PDF file, downloads it, and converts it
        into two different text files using the UNIX pdftotext utility.

        One text file is generated using the -layout option to maintain the original PDF's layout.
        This format is used for parsing game data.

        One text file is generated without the -layout option.  This format is used for parsing
        team data.

        @param pdf_uri: A URL to a PDF file to download
        """

        pdf_filename = os.path.join(settings.BASE_DIR, "import", os.path.basename(pdf_uri))
        urllib.urlretrieve(pdf_uri, pdf_filename)

        with open(pdf_filename, 'r') as pdf_file:
            self.convert_pdf_to_text(pdf_file, 0)  # non-layout version

        with open(pdf_filename, 'r') as pdf_file:
            self.convert_pdf_to_text(pdf_file, 1)  # layout version

        self.stdout.write('Successfully imported "%s"' % pdf_uri)

    def convert_pdf_to_text(self, pdf_file, layout):
        """
        @param pdf_file: open PDF file to convert
        @param layout: boolean indicator if the PDF should be parsed into a
            layout or non-layout text document
        @return: text version of the PDF
        """

        base, ext = os.path.splitext(os.path.basename(pdf_file.name))
        if layout:
            text_filename = os.path.join(settings.BASE_DIR, "import", "%s-layout.txt" % base)
        else:
            text_filename = os.path.join(settings.BASE_DIR, "import", "%s-plain.txt" % base)

        #self.stdout.write("Generating text file: %s." % text_filename)

        if layout:
            cmd = "pdftotext -layout '%s' '%s'" % (pdf_file.name, text_filename)
            proc = subprocess.Popen(shlex.split(cmd))
            out, err = proc.communicate()
        else:
            cmd = "pdftotext '%s' '%s'" % (pdf_file.name, text_filename)
            proc = subprocess.Popen(shlex.split(cmd))
            out, err = proc.communicate()

        if err:
            self.stdout.write("ERROR: %s" % err)

        return text_filename


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 24 15:38:51 2021

@author: seimit
"""
import os
import tempfile
import gzip
import bz2
import lzma
import zipfile
import time
from Semi_ATE import STDF

def test_records_from_file():

    print("\n")

#   Make 2 records and put them into one temporary file

    record = STDF.FAR()
    data = record.__repr__()

    exp_atdf_far = 'FAR:A|4|2|U'
    exp_stdf_far = 'FAR (0,10) @ V4\n\
      REC_LEN = \'2\' [U*2] (Bytes of data following header)\n\
      REC_TYP = \'0\' [U*1] (Record type)\n\
      REC_SUB = \'10\' [U*1] (Record sub-type)\n\
      CPU_TYPE = \'2\' [U*1] (CPU type that wrote this file)\n\
      STDF_VER = \'4\' [U*1] (STDF version number)\n'

    record = STDF.WIR()

    rec_len = 0;

    head_num = 1
    record.set_value('HEAD_NUM', head_num)
    rec_len += 1;

    site_grp = 1
    record.set_value('SITE_GRP', site_grp)
    rec_len += 1;

    start_t = 1609462861
    record.set_value('START_T', start_t)
    rec_len += 4;

    t = ""
    if os.name == "nt":
        t = time.strftime("%#H:%#M:%#S %#d-%b-%Y", time.gmtime(start_t))
    else:
        t = time.strftime("%-H:%-M:%-S %-d-%b-%Y", time.gmtime(start_t))
    t = t.upper()

    t1 = ""
    if os.name == "nt":
        t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_t))
    else:
        t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_t))
    t1 = t1.upper()

    data += record.__repr__()

    exp_atdf_wir = 'WIR:1|'+t+'|1|'

    exp_atdf = [exp_atdf_far, exp_atdf_wir]

    exp_stdf_wir = '   WIR (2,10) @ V4\n\
      REC_LEN = \'7\' [U*2] (Bytes of data following header)\n\
      REC_TYP = \'2\' [U*1] (Record type)\n\
      REC_SUB = \'10\' [U*1] (Record sub-type)\n\
      HEAD_NUM = \'1\' [U*1] (Test head number)\n\
      SITE_GRP = \'1\' [U*1] (Site group number)\n\
      START_T = \'1609462861\' [U*4] (Date and time first part tested) = '+t1+'\n\
      WAFER_ID = \'\' [C*n] (Wafer ID)\n'

    exp_stdf = [exp_stdf_far, exp_stdf_wir]

    f = tempfile.NamedTemporaryFile(mode="w+b", delete = False)
    file_name = f.name
    f.write(data)
    f.close()

    f = open(file_name)

    print("\nTest standard printing of STDF record\n")

    i=0
    for REC in STDF.records_from_file(file_name):
        print(REC)
        assert exp_stdf[i].replace(" ", "") == REC.__str__().replace(" ", "")
        i+=1

    print("\nTest ATDF printing of STDF record\n")

    i=0
    for REC in STDF.records_from_file(file_name):
        print(REC.to_atdf())
        assert exp_atdf[i] == REC.to_atdf()
        i+=1

    f.close()
    os.remove(file_name)

    print("\nTest printing from gzip compressed STDF record\n")

    gz = tempfile.NamedTemporaryFile(mode="w+b", delete=False)

    with gzip.open(gz, 'wb') as f_gz:
        f_gz.write(data)
    gz.close()

    i=0
    for REC in STDF.records_from_file(gz.name):
        print(REC)
        assert exp_stdf[i].replace(" ", "") == REC.__str__().replace(" ", "")
        i+=1

    os.remove(gz.name)

    print("\nTest printing from bz2 compressed STDF record\n")

    bz = tempfile.NamedTemporaryFile(mode="w+b", delete=False)

    with bz2.open(bz.name, "wb") as f_bz:
        f_bz.write(data)
    bz.close()

    i=0
    for REC in STDF.records_from_file(bz.name):
        print(REC)
        assert exp_stdf[i].replace(" ", "") == REC.__str__().replace(" ", "")
        i+=1

    os.remove(bz.name)

    print("\nTest printing from lzma compressed STDF record\n")

    lz = tempfile.NamedTemporaryFile(mode="w+b", delete=False)

    with lzma.open(lz.name, "wb") as f_lz:
        f_lz.write(data)
    lz.close()

    i=0
    for REC in STDF.records_from_file(lz.name):
        print(REC)
        assert exp_stdf[i].replace(" ", "") == REC.__str__().replace(" ", "")
        i+=1

    os.remove(lz.name)

    print("\nTest printing from zip compressed STDF record\n")

    zo = tempfile.NamedTemporaryFile(mode="w+b", delete=False)
    zo.write(data)
    zo.close()

    z = tempfile.NamedTemporaryFile(mode="w+b", delete=False)

    with zipfile.ZipFile(z.name, "w") as f_z:
        f_z.write(zo.name)
    z.close()

    i=0
    for REC in STDF.records_from_file(z.name):
        print(REC)
        assert exp_stdf[i].replace(" ", "") == REC.__str__().replace(" ", "")
        i+=1

    os.remove(z.name)
    os.remove(zo.name)

def test_dict_to_rec():

    record = STDF.WIR()

    rec_len = 0;

    head_num = 1
    record.set_value('HEAD_NUM', head_num)
    rec_len += 1;

    site_grp = 1
    record.set_value('SITE_GRP', site_grp)
    rec_len += 1;

    start_t = 1609462861
    record.set_value('START_T', start_t)
    rec_len += 4;

    waf_id = 'NAS12345'
    record.set_value('WAFER_ID', waf_id)
    rec_len += 9;

    rec_dict = record.to_dict();
    rec = STDF.utils.dict_to_rec(rec_dict, '<')

    assert rec.get_value('REC_LEN') == rec_len
    assert rec.get_value('HEAD_NUM') == head_num
    assert rec.get_value('SITE_GRP') == site_grp
    assert rec.get_value('START_T') == start_t
    assert rec.get_value('WAFER_ID') == waf_id


from mobiauto.mobiauto import MobiEzApp, MobiConfig, MobiUiMap
from mobiauto.mobidecor import MobiDecor
from selenium.common.exceptions import *
import logging
import time

class Gmail_v5_10(object):
    def __init__(self, app, cfg, ui):
        """

        :param app:
        :type app: MobiEzApp
        :param cfg:
        :type cfg: MobiConfig
        :param ui:
        :type ui: MobiUiMap
        :return:
        """
        self.app = app
        self.cfg = cfg
        self.ui = ui
        self.timeout = int(self.cfg.get("TIME", "timeout-5"))
        self.loading_timeout = int(self.cfg.get("TIME", "timeout-1"))

    #*****************************************************************************
    #                              ACTION FLOWS                                  *
    #*****************************************************************************
    @MobiDecor.start_end_flow
    def skip_welcome(self):
        """
        Skip all Welcome screen of Gmail app

        End of flow: Primary screen of one gmail

        Device: Phone
        """
        try:
            self.app.wait_for_visibility_of_element_located(self.ui.get_element("title", "welcome", check_screen=False), timeout=self.loading_timeout)
            self.app.click_on_element_by_pair_value(self.ui.get_element("got_it_btn", "welcome", check_screen=False), timeout=self.loading_timeout)
            self.app.click_on_element_by_pair_value(self.ui.get_element("take_me_btn", "welcome", check_screen=False), timeout=self.loading_timeout)
        except (TimeoutException, NoSuchElementException):
            logging.info("Current screen is NOT: Welcome")

    @MobiDecor.start_end_flow
    def select_gmail_menu(self):
        """
        Select Menu button on Gmail screen

        End of flow: Vertical navigation bar is displayed

        Device: Phone
        """
        self.app.click_on_element_by_pair_value(self.ui.get_element("menu_btn", "gmail_inbox", check_screen=False), timeout=self.loading_timeout)

    @MobiDecor.start_end_flow
    def switch_account(self, email_addr):
        """
        Switch to target account at vertical navigation bar
        :param email_addr: email's address

        End of flow: Gmail screen pf a folder

        Device: Phone
        """
        cur_acc = self.app.find_element_by_pair_value(self.ui.get_element("current_email_txt", "gmail_nav", check_screen=False)).text
        if cur_acc != email_addr:
            self.app.click_on_element_by_pair_value(self.ui.get_element("acc_list_btn", "gmail_nav", check_screen=False), timeout=self.loading_timeout)
            self.app.click_on_element_by_name(email_addr, timeout=self.loading_timeout)
        else:
            self.app.press_key_back()

    @MobiDecor.start_end_flow
    def select_folder(self, folder_name):
        """
        Select a folder in vertical navigation bar

        End of flow: Gmail screen of this folder
        :param folder_name: folder's name

        Device: Phone
        """
        self.app.scroll_down_to_element_by_name(self.app.find_element_by_pair_value(self.ui.get_element("nav_lv", "gmail_nav", check_screen=False)),
                                                name=folder_name, offset=int(self.cfg.get("SETTINGS", "offset-3")))
        self.app.click_on_element_by_name(folder_name, timeout=self.loading_timeout)

    @MobiDecor.start_end_flow
    def select_email_by_index(self, index=0):
        """
        Select an email of a folder by index

        :param index: index number. Default: 0

        Device: Phone
        """
        timeout = time.time() + self.loading_timeout + 10
        while time.time() < timeout:
            email_list = self.app.find_element_by_pair_value(self.ui.get_element("emails_lv", "gmail_inbox", check_screen=False))
            emails = email_list.find_elements_by_class_name(self.ui.get_class_name("email_cell", "gmail_inbox"))
            if len(emails) > 0:
                emails[index].click()
                break

    @MobiDecor.start_end_flow
    def select_print(self):
        """
        Click on Print button for an email

        End of flow: HPPS via system UI

        Device: Phone
        """
        self.app.click_on_element_by_pair_value(self.ui.get_element("option_btn", "email", check_screen=False), timeout=self.loading_timeout)
        self.app.click_on_element_by_pair_value(self.ui.get_element("print_btn", "email", check_screen=False), timeout=self.loading_timeout)

    @MobiDecor.start_end_flow
    def refresh_emails_list(self):
        """
        Refresh an email list by swiping down

        Device: Phone
        """
        self.app.wait_for_visibility_of_element_located_by_id(self.ui.get_id("email_frame_layout", "gmail_inbox"), timeout=self.loading_timeout)
        self.app.swipe_down(self.app.find_element_by_id(self.ui.get_id("email_frame_layout", "gmail_inbox")), offset=int(self.cfg.get("SETTINGS", "offset-2")))
        self.app.wait_for_visibility_of_element_located_by_id(self.ui.get_id("emails_lv", "gmail_inbox"), timeout=self.loading_timeout)


# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv

listofreport = [('accepted.orders','Accepted Orders'),('working.process','Working Process')]
class wizard_kderp_job_contract_area_summary(osv.osv_memory):
    _name = 'wizard.kderp.job.contract.area.summary'
    _description = 'Job Contract Area Summary Wizard'

    def print_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        formData = self.browse(cr, uid, ids[0])

        nameofreport = formData.nameofreport

        datas = {'ids': context.get('active_ids',[])}

        titleofreport = 'Summary of %s' % dict(listofreport)[nameofreport]
        # datas['model'] = 'account.analytic.account'
        datas['parameters'] = {'pdateinput': formData.month}
        datas['title'] = titleofreport

        report_name= "kderp.report.summary.of.%s.xls" % nameofreport

        return {
            'type': 'ir.actions.report.xml',
            'report_name': report_name,
            'datas': datas,
            'context': context,
            'name': titleofreport,
            'nodestroy': True,
            'target': 'new'
            }

    def _get_month_list(self, cr, uid, context):
        res = []
        cr.execute("""Select
                        Distinct
                        kcc.registration_date - extract(day from kcc.registration_date)::integer + 1,
                        to_char(kcc.registration_date,'Mon-YYYY')
                    from
                        account_analytic_account aaa
                    left join
                        kderp_contract_job_area kjca on aaa.id = job_id
                    left join
                        kderp_contract_client kcc on contract_id = kcc.id
                    where
                        aaa.state not in ('cancel','closed') and kcc.registration_date is not null
                    Order by
                        kcc.registration_date - extract(day from kcc.registration_date)::integer + 1 desc""")
        for dt, my in cr.fetchall():
            res.append((dt, my))
        return res

    _columns = {
                'month':fields.selection(_get_month_list, 'Month', required=True),
                'nameofreport':fields.selection(listofreport, 'Report', required=True),
                }


#!/usr/bin/env python3

#https://codeforces.com/problemset/problem/1320/A
#直观的DP好像需要O(N**2), 因为n=2e5, 会超时..
#用dsu或tree?
#性质: 只能是一条线,不可能像树一样分叉
#技巧: 全部-i就得到分组
#并非DP,但外表很像

n   = int(input())
bl  = list(map(int,input().split()))
nl  = [(bl[i],bl[i]-i) for i in range(n)]
nl.sort(key = lambda b:b[1])
p   = nl[0]
s   = p[0]
mx  = s
for i in range(1,n):
    if nl[i][1]==p[1]:
        s += nl[i][0]
    else:
        if s>mx:
            mx = s
        s  = nl[i][0]
    p = nl[i]
print(max(s,mx))


import argparse
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from skimage import measure
from scipy import linalg, special

# define functions for use in the program

def lam(i):
    alpha = 0.001
    beta = 1.9
    return alpha*beta**i

def norm(i,L):
    """normalisation factor"""
    return np.sqrt( 2*(2*lam(i))**(L+1.5) / special.gamma(L + 1.5) )

def overlap(i, j, L):
    """overlap matrix elements"""
    return norm(i,L)*norm(j,L)*special.gamma(L+1.5) / ( 2*(lam(i)+lam(j))**(L+1.5) )

def kinetic(i, j, L):
    """kinetic matrix elements"""
    return norm(i,L)*norm(j,L)*special.gamma(L+2.5)*lam(i)*lam(j) / (lam(i)+lam(j))**(L+2.5)

def potential(i, j, L, Z):
    """potential matric elements"""
    return -Z*norm(i,L)*norm(j,L)*special.factorial(L) / (2*(lam(i)+lam(j))**(L+1))

def build_matrices(dim, charge, L):
    """ builds the overlap and hamiltonian matrices """
    S = np.zeros((dim, dim))
    T = np.zeros((dim, dim))
    V = np.zeros((dim, dim))
    for i in range(dim):
        for j in range(i,dim):
            S[i, j] = overlap(i, j, L)
            S[j, i] = S[i, j]
            T[i, j] = kinetic(i, j, L)
            T[j, i] = T[i, j]
            V[i, j] = potential(i, j, L, charge)
            V[j, i] = V[i, j]
    return S, T, V

def basis_func(i, L, M, r, theta, phi):
    """ S type gaussian basis function """
    N = norm(i,L)
    return N*r**(L)*np.exp(-lam(i)*r**2)*special.sph_harm(M,L,phi,theta)

def wavefunction(eigenvecs, n, L, M, r, theta, phi):
    """ returns nth excited state wavefunction for corresponding atom at x,y,z """
    total = 0
    for i, coeff in enumerate(eigenvecs[:, n]):
        total += coeff * basis_func(i,L,M,r,theta,phi)
    return total

def probability_density(eigenvecs, n, L, M, x, y, z,real):
    """returns probability density for the atom in the n, L, M state at x,y,z"""
    r = np.sqrt(x**2+y**2+z**2)
    theta = np.arccos(z/r)
    phi = np.arctan2(y,x)
    if real:
        return np.absolute(np.real(wavefunction(eigenvecs, n, L, M, r, theta, phi)))
    else:
        return np.absolute(wavefunction(eigenvecs, n, L, M, r, theta, phi))

def plot_orbital(orbital, size, iso, charge=1, dim=20, real=False, points = 50j, title=True):

    # naming dictionaries
    atom = {1:'Hydrogen',2:'Helium',3:'Lithium',4:'Beryllium'}
    L_val = {'s':0,'p':1,'d':2,'f':3,'g':4,'h':5}

    # identify quantum numbers of given orbital
    n,L,M = int(orbital[0]), L_val[orbital[1]], int(orbital[2])
    level = n-(L+1)
    if level<0 or np.abs(M)>L:
        raise ValueError("The orbital you are trying to plot does not exist")

    # solve the eigenvalue equation
    S, T, V = build_matrices(dim, charge, L)
    eigenvals, eigenvecs = linalg.eigh(T+V, S)

    # plot
    X,Y,Z = np.mgrid[-size:size:points, -size:size:points, -size:size:points]
    surf_vals = probability_density(eigenvecs, level, L, M, X, Y, Z, real)
    verts, faces, _, _ = measure.marching_cubes_lewiner(surf_vals, iso*np.amax(surf_vals))
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    if title: plt.title(f"{atom[charge]} {orbital} orbital")
    ax.plot_trisurf(verts[:, 0], verts[:,1], faces, verts[:, 2], cmap='plasma', lw=0.05, edgecolors='black')
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    plt.axis('off')
    plt.show()

# main program
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("orbital_name")
    parser.add_argument("range")
    args = parser.parse_args()

    print('\n===============================')
    print(f'PLOTTING {args.orbital_name} HYDROGENIC ORBITAL')
    print('===============================\n')

    plot_orbital(args.orbital_name, float(args.range), 0.1, points=50j, real=True, title=False)


"""
The tool to check domains or IP availability.

██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

This submodule will test PyFunceble.helpers

PyFunceble is the little sister of Funceble (https://github.com/funilrys/funceble)
which was archived on 13th March, 2018.

Its main objective is to get and the return domains and IPs availability by
generating an accurate result based on results from WHOIS, NSLOOKUP and HTTP status codes.

In its daily usage, PyFunceble is mostly used to clean `hosts` files or blocklist.
Indeed, it is possible because PyFunceble generates a list of all `ACTIVE` domains
or IPs but in the same time, it creates by default a database of the `INACTIVE`
domains or IPs so we can retest them overtime automatically at the next execution.

PyFunceble is running actively and daily with the help of Travis CI under 60+
repositories. It is used to clean or test the availability of data which are
present in hosts files, list of IP, list of domains, blocklists or even AdBlock
filter lists.

Author:
    Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks to:
    Adam Warner - @PromoFaux
    Mitchell Krog - @mitchellkrogza
    Pi-Hole - @pi-hole
    SMed79 - @SMed79

Contributors:
    Let's contribute to PyFunceble!!

    Mitchell Krog - @mitchellkrogza
    Odyseus - @Odyseus
    WaLLy3K - @WaLLy3K
    xxcriticxx - @xxcriticxx

    The complete list can be found at https://git.io/vND4m

Original project link:
    https://github.com/funilrys/PyFunceble

Original project wiki:
    https://github.com/funilrys/PyFunceble/wiki

License: MIT
    MIT License

    Copyright (c) 2017-2018 Nissar Chababy

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
"""
# pylint: disable=import-error
from unittest import TestCase
from unittest import main as launch_tests

import PyFunceble
from PyFunceble.helpers import Command, Dict, Directory, File, Hash, Regex

class TestHash(TestCase):
    """
    This class will test PyFunceble.helpers.Hash
    """

    def setUp(self):
        """
        This method will initiate everything needed for the tests.
        """

        self.file = "this_file_should_be_deleted"
        self.data_to_write = ["Hello World!", "Thanks for using PyFunceble"]

        self.expected_hashed = {
            "md5": "ba2e0e1774c2e60e2327f263402facd4",
            "sha1": "b5c8520cd2c422019997dc6fdbc9cb9d7002356e",
            "sha224": "863c46d5ed52b439da8f62a791e77c0cbbfb7d92af7c5549279f580d",
            "sha384": "6492f4b5732e0af4b9edf2c29ee4622c62ee418e5d6e0f34b13cb80560a28256c6e21e949119872d26d2327fc112a63b",  # pylint: disable=line-too-long
            "sha512": "f193ad6ee2cfbecd580225d8e6bfb9df1910e5ca6135b21b03ae208a007f71e9b57b55e299d27157551a18ef4dfdde23c96aaea796064846edc6cd25ac7eaf7f",  # pylint: disable=line-too-long
        }

    def test_hash_data(self):
        """
        This method will test Hash.hash_data().
        """

        expected = False
        actual = PyFunceble.path.isfile(self.file)
        self.assertEqual(expected, actual)

        File(self.file).write("\n".join(self.data_to_write))
        expected = True
        actual = PyFunceble.path.isfile(self.file)

        self.assertEqual(expected, actual)

        for algo, result in self.expected_hashed.items():
            self.assertEqual(
                result,
                Hash(self.file).hash_data(algo),
                msg="%s did not passed the test" % repr(algo),
            )

        File(self.file).delete()

        expected = False
        actual = PyFunceble.path.isfile(self.file)

        self.assertEqual(expected, actual)

    def test_get_path_not_exist(self):
        """
        This method will test Hash.get() for the case that the given file does
        not exist.
        """

        expected = False
        actual = PyFunceble.path.isfile(self.file)
        self.assertEqual(expected, actual)

        expected = None
        actual = Hash(self.file).get()
        self.assertEqual(expected, actual)

    def test_get_all(self):
        """
        This method will test Hash.get() for the case that we want all.
        """

        expected = False
        actual = PyFunceble.path.isfile(self.file)
        self.assertEqual(expected, actual)

        File(self.file).write("\n".join(self.data_to_write))
        expected = True
        actual = PyFunceble.path.isfile(self.file)

        self.assertEqual(expected, actual)

        expected = self.expected_hashed
        actual = Hash(self.file, algorithm="all").get()
        self.assertEqual(expected, actual)

        File(self.file).delete()

        expected = False
        actual = PyFunceble.path.isfile(self.file)
        self.assertEqual(expected, actual)

    def test_get_specific_algo(self):
        """
        This method will test Hash.get() for the case that we want a specifig
        algorithm.
        """

        expected = False
        actual = PyFunceble.path.isfile(self.file)
        self.assertEqual(expected, actual)

        File(self.file).write("\n".join(self.data_to_write))
        expected = True
        actual = PyFunceble.path.isfile(self.file)

        self.assertEqual(expected, actual)

        expected = self.expected_hashed["sha512"]
        actual = Hash(self.file, algorithm="sha512", only_hash=True).get()
        self.assertEqual(expected, actual)

        File(self.file).delete()

        expected = False
        actual = PyFunceble.path.isfile(self.file)
        self.assertEqual(expected, actual)

class TestCommand(TestCase):
    """
    This class will test PyFunceble.helpers.Command().
    """

    def test_command(self):
        """
        This method test Command().execute().
        """

        expected = "PyFunceble has been written by Fun Ilrys."
        actual = Command("echo '%s'" % expected).execute()

        self.assertEqual(expected + "\n", actual)

class TestDict(TestCase):
    """
    This class will test PyFunceble.helpers.Dict().
    """

    def setUp(self):
        """
        This method will setup everything needed for the tests.
        """

        self.to_test = {
            "Hello": "world",
            "World": {"world", "hello"},
            "funilrys": ["Fun", "Ilrys"],
            "Py": "Funceble",
            "pyfunceble": ["funilrys"],
        }

    def test_remove_key(self):
        """
        This method will test Dict().remove_key().
        """

        expected = {
            "Hello": "world",
            "World": {"world", "hello"},
            "funilrys": ["Fun", "Ilrys"],
            "pyfunceble": ["funilrys"],
        }

        actual = Dict(self.to_test).remove_key("Py")

        self.assertEqual(expected, actual)

        # Test of the case that a dict is not given
        expected = None
        actual = Dict(["Hello", "World!"]).remove_key("Py")

        self.assertEqual(expected, actual)

    def test_rename_key_not_dict(self):
        """
        This method will test Dict().rename_key() for the case that no dict is
        given.
        """

        expected = None
        actual = Dict(self.to_test).rename_key(["Fun", "Ilrys"])

        self.assertEqual(expected, actual)

    def test_rename_key_single(self):
        """
        This method will test Dict().rename_key() for the case that we want to
        rename only one key.
        """

        # Test of the strict case
        expected = {
            "Hello": "world",
            "World": {"world", "hello"},
            "funilrys": ["Fun", "Ilrys"],
            "PyFunceble": "Funceble",
            "pyfunceble": ["funilrys"],
        }

        actual = Dict(self.to_test).rename_key({"Py": "PyFunceble"})

        self.assertEqual(expected, actual)

        # Test of the non-strict case
        expected = {
            "Hello": "world",
            "World": {"world", "hello"},
            "funilrys": ["Fun", "Ilrys"],
            "PyFunceble": "Funceble",
            "pyfunceble": ["funilrys"],
        }

        actual = Dict(self.to_test).rename_key({"fun": "nuf"}, strict=False)

    def test_to_yaml(self):
        """
        This method will test Dict().to_yaml.
        """
        file_to_read = "this_yaml_is_a_ghost.yaml"

        expected = False
        actual = PyFunceble.path.isfile(file_to_read)

        self.assertEqual(expected, actual)

        to_write = {"hello": ["This is PyFunceble!", "Uhh!"], "world": "Fun Ilrys"}

        expected = """hello: [This is PyFunceble!, Uhh!]
world: Fun Ilrys
"""

        Dict(to_write).to_yaml(file_to_read)

        actual = File(file_to_read).read()
        self.assertEqual(expected, actual)

        File(file_to_read).delete()

        expected = False
        actual = PyFunceble.path.isfile(file_to_read)

        self.assertEqual(expected, actual)

class TestDirectory(TestCase):
    """
    This method will test PyFunceble.helpers.Directory().
    """

    def test_fix_path(self):
        """
        This method will test Directory.fix_path().
        """

        expected = "hello" + PyFunceble.directory_separator + "world" + PyFunceble.directory_separator  # pylint: disable=line-too-long
        actual = Directory("/hello/world").fix_path()

        self.assertEqual(expected, actual)

        actual = Directory("\\hello\\world").fix_path()
        self.assertEqual(expected, actual)

        actual = Directory("hello\\world").fix_path()
        self.assertEqual(expected, actual)

        actual = Directory(r"hello\world").fix_path()
        self.assertEqual(expected, actual)

        actual = Directory(r"hello/world/").fix_path()
        self.assertEqual(expected, actual)

class TestFile(TestCase):
    """
    This class will test PyFunceble.helpers.File()
    """

    def test_write_delete(self):
        """
        This method test File.write() along with File.delete().
        """

        expected = "Hello, World! I'm domain2idna"
        File("hi").write(expected)

        with open("hi") as file:
            actual = file.read()

        self.assertEqual(expected, actual)

        expected = False
        File("hi").delete()
        actual = PyFunceble.path.isfile("hi")

        self.assertEqual(expected, actual)

    def test_write_overwrite_delete(self):
        """
        This metthod test File.write() along with File.write() for the case that
        we want to overwrite the content of a file.
        """

        expected = "Hello, World! I'm domain2idna"
        File("hi").write(expected)

        with open("hi") as file:
            actual = file.read()

        self.assertEqual(expected, actual)

        expected = "Hello, World! Python is great, you should consider learning it!"
        File("hi").write(expected, overwrite=True)

        with open("hi") as file:
            actual = file.read()

        self.assertEqual(expected, actual)

        expected = False
        File("hi").delete()
        actual = PyFunceble.path.isfile("hi")

        self.assertEqual(expected, actual)

    def test_read_delete(self):
        """
        This method test File.read() along with helpers.File.delete.
        """

        expected = "Hello, World! This has been written by Fun Ilrys."
        File("hi").write(expected)
        actual = File("hi").read()

        self.assertEqual(expected, actual)

        expected = False
        File("hi").delete()
        actual = PyFunceble.path.isfile("hi")

        self.assertEqual(expected, actual)

class TestRegex(TestCase):
    """
    This class will test Regex().
    """

    def setUp(self):
        """
        This method will setup everything needed for the tests.
        """

        self.data_list = [
            "hello", "world", "funilrys", "funceble", "PyFunceble", "pyfunceble"
        ]
        self.data = "Hello, this is Fun Ilrys. I just wanted to know how things goes around the tests."  # pylint: disable=line-too-long

    def test_not_matching_list(self):
        """
        This method will test Regex.not_matching_list().
        """

        regex = "fun"
        expected = ["hello", "world", "PyFunceble"]
        actual = Regex(self.data_list, regex).not_matching_list()

        self.assertEqual(expected, actual)

    def test_matching_list(self):
        """
        This method will test Regex.match_list().
        """

        regex = "fun"
        expected = ["funilrys", "funceble", "pyfunceble"]
        actual = Regex(self.data_list, regex).matching_list()

        self.assertEqual(expected, actual)

    def test_match(self):
        """
        This method will test Regex.match() for the case that we want a specific
        group.
        """

        # Test of the rematch case.
        regex = r"([a-z]{1,})\s([a-z]{1,})\s"
        expected = "is"
        actual = Regex(self.data, regex, rematch=True, group=1).match()

        self.assertEqual(expected, actual)

        # Test of the group case
        regex = "e"
        expected = "e"
        actual = Regex(self.data, regex, group=0).match()

        self.assertEqual(expected, actual)

    def test_replace(self):
        """
        This method will test Regex.replace().
        """

        regex = "th"
        expected = "Hello, htis is Fun Ilrys. I just wanted to know how htings goes around hte tests."  # pylint: disable=line-too-long
        actual = Regex(self.data, regex, replace_with="ht").replace()

        self.assertEqual(expected, actual)

        # Test of the case that there is not replace_with
        regex = "th"
        expected = self.data
        actual = Regex(self.data, regex).replace()

        self.assertEqual(expected, actual)

if __name__ == "__main__":
    launch_tests()


# -*- coding: utf-8 -*-
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Common constant and device related information."""

from __future__ import print_function

import os
import time
import subprocess

import hammerd_api

# The root path of the hammertests.
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
IMAGE_DIR = os.path.join(ROOT_DIR, 'images')

BASE_TABLE = {
    'poppy': 'hammer',
    'soraka': 'staff',
    'nocturne': 'whiskers'
}

board_name_cmd = 'grep CHROMEOS_RELEASE_BOARD /etc/lsb-release | cut -d = -f 2'
BOARD_NAME = subprocess.check_output(board_name_cmd, shell=True)
BASE_NAME = BASE_TABLE[BOARD_NAME.rstrip()]

# Device-dependent information.
if BASE_NAME == 'staff':
  BASE_VENDOR_ID = 0x18d1
  BASE_PRODUCT_ID = 0x502b
  BASE_BUS = 1
  BASE_PORT = '2'
  BASE_CONN_GPIO = 'PP3300_DX_BASE'
elif BASE_NAME == 'whiskers':
  BASE_VENDOR_ID = 0x18d1
  BASE_PRODUCT_ID = 0x5030
  BASE_BUS = 1
  BASE_PORT = '7'
  BASE_CONN_GPIO = 'BASE_PWR_EN'
elif BASE_NAME == 'hammer':
  BASE_VENDOR_ID = 0x18d1
  BASE_PRODUCT_ID = 0x5022
  BASE_BUS = 1
  BASE_PORT = '3'
  BASE_CONN_GPIO = 'PP3300_DX_BASE'
else:
  print('Error: unknown board: %s' % BASE_NAME)

# Status of flash protect.
EC_FLASH_PROTECT_RO_AT_BOOT = (1 << 0)
EC_FLASH_PROTECT_RO_NOW = (1 << 1)
EC_FLASH_PROTECT_ALL_NOW = (1 << 2)
EC_FLASH_PROTECT_GPIO_ASSERTED = (1 << 3)
EC_FLASH_PROTECT_ERROR_STUCK = (1 << 4)
EC_FLASH_PROTECT_ERROR_INCONSISTENT = (1 << 5)
EC_FLASH_PROTECT_ALL_AT_BOOT = (1 << 6)
EC_FLASH_PROTECT_RW_AT_BOOT = (1 << 7)
EC_FLASH_PROTECT_RW_NOW = (1 << 8)
EC_FLASH_PROTECT_ROLLBACK_AT_BOOT = (1 << 9)
EC_FLASH_PROTECT_ROLLBACK_NOW = (1 << 10)

# Path of testing image files.
IMAGE = os.path.join(IMAGE_DIR, '%s.bin' % BASE_NAME)
TP = '/lib/firmware/%s-touchpad.fw' % BASE_NAME
RW_DEV = os.path.join(IMAGE_DIR, '%s.dev' % BASE_NAME)
RW_CORRUPT_FIRST_BYTE = os.path.join(
    IMAGE_DIR, '%s_corrupt_first_byte.bin' % BASE_NAME)
RW_CORRUPT_LAST_BYTE = os.path.join(
    IMAGE_DIR, '%s_corrupt_last_byte.bin' % BASE_NAME)
RW_VALID = os.path.join(IMAGE_DIR, '%s.bin' % BASE_NAME)
OLDER_IMAGE = os.path.join(IMAGE_DIR, '%solder.bin' % BASE_NAME)
NEWER_IMAGE = os.path.join(IMAGE_DIR, '%snewer.bin' % BASE_NAME)
# Image should not update RW
RB_LOWER = os.path.join(IMAGE_DIR, '%s.dev.rb0' % BASE_NAME)
# Initial DUT image
RB_INITIAL = os.path.join(IMAGE_DIR, '%s.dev.rb1' % BASE_NAME)
# Image should update RW and RB regions region
RB_HIGHER = os.path.join(IMAGE_DIR, '%s.dev.rb9' % BASE_NAME)

# Common function.
def connect_usb(updater):
  updater.TryConnectUsb()
  assert updater.SendFirstPdu() == True, 'Error sending first PDU'
  updater.SendDone()

def sim_disconnect_connect(updater):
  print('Simulate hammer disconnect/ reconnect to reset base')
  subprocess.call('ectool gpioset ' + BASE_CONN_GPIO + ' 0', shell=True)
  subprocess.call('ectool gpioset ' + BASE_CONN_GPIO + ' 1', shell=True)
  updater.CloseUsb()
  # Need to give base time to be visible to lid
  time.sleep(3)

def disable_hammerd():
  print('Disabling hammerd')
  subprocess.call('mount --bind /dev/null /lib/udev/rules.d/99 hammerd.rules',
                  shell=True)
  subprocess.call('initctl restart udev', shell=True)

def enable_hammerd():
  print ('Enabling hammerd')
  subprocess.call('umount /lib/udev/rules.d/99-hammerd.rules', shell=True)
  subprocess.call('initctl restart udev', shell=True)

def reset_stay_ro(updater):
  # Send immediate reset
  updater.SendSubcommand(hammerd_api.UpdateExtraCommand.ImmediateReset)
  updater.CloseUsb()
  # Wait for base to reappear and send StayInRO
  time.sleep(0.5)
  updater.TryConnectUsb()
  updater.SendSubcommand(hammerd_api.UpdateExtraCommand.StayInRO)
  updater.SendFirstPdu()
  updater.SendDone()
  # Wait to stay in RO
  time.sleep(5)
  print('Current section after StayInRO cmd: %s' % updater.CurrentSection())
  assert updater.CurrentSection() == 0, 'Running section should be 0 (RO)'


import cv2
import os
import numpy as np
import utility
import matplotlib.pyplot as plt

img_dir = 'C:/Users/xiangpu/Downloads/Test/'
pos_dir = 'pos_imgs_Test/'
neg_dir = 'neg_imgs_Test/'
if not os.path.exists(pos_dir):
    os.mkdir(pos_dir)
if not os.path.exists(neg_dir):
    os.mkdir(neg_dir)

def on_click(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        xy = "x: %d, y: %d, value: %d" % (x, y, id_imgs[1][y, x])
        print(xy)

for root, dirs, files in os.walk(img_dir):
    print("there are {0} imgs in dir".format(len(files)))
    for img_idx in range(len(files)):
        print("process {0} img".format(img_idx))
        img = cv2.imread(img_dir + files[img_idx], cv2.IMREAD_GRAYSCALE)  # type:np.ndarray
        hist1 = cv2.calcHist([img], [0], None, [256], [0, 256])
        img_equHist = cv2.equalizeHist(img)
        hist2 = cv2.calcHist([img_equHist], [0], None, [256], [0, 256])
        x = cv2.Sobel(img_equHist, cv2.CV_16S, 1, 0)
        y = cv2.Sobel(img_equHist, cv2.CV_16S, 0, 1)
        absX = cv2.convertScaleAbs(x)
        absY = cv2.convertScaleAbs(y)
        img_sobel = cv2.addWeighted(absX, 1, absY, 1, 0)
        thresh, img_binary = cv2.threshold(img_sobel, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        contours, hierarchy = cv2.findContours(img_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        # print("there are {0} contours".format(len(contours)))
        # i = 0
        # while i < hierarchy.shape[1]:
        #     if hierarchy[0][i][3] != -1:
        #         hierarchy = np.delete(hierarchy, i, axis=1)
        #         del contours[i]
        #         i -= 1
        #     i += 1
        contour_size = []
        for contour in contours:
            contour_size.append(contour.shape[0])
            # print(contour.shape, end=' ')
        # print('')
        sorted_size = sorted(enumerate(contour_size), key=lambda x: x[1])
        id_contours = []
        for i in range(1, len(sorted_size)):
            ratio = sorted_size[i - 1][1] / sorted_size[i][1]
            if 0.8 < ratio < 1.2:
                id_contours.append(contours[sorted_size[i - 1][0]])
                id_contours.append(contours[sorted_size[i][0]])
                break
        if len(id_contours) < 2:
            print("img {} failed".format(img_idx))
            continue
        rects = [cv2.minAreaRect(id_contours[i]) for i in range(2)]
        boxes = [cv2.boxPoints(rects[i]) for i in range(2)]
        for i in range(2):
            rects[i] = list(rects[i])
            rects[i][1] = list(rects[i][1])
            if rects[i][1][0] < rects[i][1][1]:
                rects[i][1][0], rects[i][1][1] = rects[i][1][1], rects[i][1][0]
                rects[i][2] += 90
        # print("size: {0}".format(rects[0][1]))
        show_contour = np.ones(img_binary.shape, np.uint8) * 255
        show_box = np.ones(img_binary.shape, np.uint8) * 255
        for i in range(2):
            for j in range(4):
                cv2.line(show_box, tuple(boxes[i][j]), tuple(boxes[i][(j + 1) % 4]), (0, 0, 0))
        img_clone = img.copy()
        cv2.drawContours(img_clone, id_contours, -1, 0, 1)

        rotation_img = [cv2.warpAffine(img, cv2.getRotationMatrix2D(rects[i][0], rects[i][2], 1), img_equHist.shape)
                        for i in range(2)]
        id_imgs = [rotation_img[i][int(rects[i][0][1] - rects[i][1][1] / 2):int(rects[i][0][1] + rects[i][1][1] / 2),
                   int(rects[i][0][0] - rects[i][1][0] / 2):int(rects[i][0][0] + rects[i][1][0] / 2)] for i in range(2)]
        # cv2.namedWindow("img1")
        # cv2.setMouseCallback("img1", on_click)
        id_filter = [cv2.medianBlur(id_imgs[i], 81)[40:-40, 40:-40] for i in range(2)]
        if id_filter[0].min() < id_filter[1].min():
            id_filter[0], id_filter[1] = id_filter[1], id_filter[0]
            id_imgs[0], id_imgs[1] = id_imgs[1], id_imgs[0]
        # print(id_filter[0].min())
        # print(id_filter[1].min())
        logo_index = np.where(id_filter[1] == id_filter[1].min())
        logo_index = [logo_index[i][len(logo_index[i]) // 2] for i in range(2)]
        # print("logo pos {0}".format(logo_index))
        if logo_index[1] > id_imgs[1].shape[1] / 2:
            id_imgs[1] = cv2.warpAffine(id_imgs[1],
                                        cv2.getRotationMatrix2D((id_imgs[1].shape[1] // 2, id_imgs[1].shape[0] // 2),
                                                                180, 1), id_imgs[1].shape[::-1])
        mser = cv2.MSER_create(_delta=5, _min_area=10, _max_variation=0.7, _max_area=200)
        regions, boxes = mser.detectRegions(id_imgs[0])
        hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
        # cv2.polylines(id_imgs[0], hulls, 1, (0, 255, 0), 1)
        keep = []
        for hull in hulls:
            x, y, w, h = cv2.boundingRect(hull)
            keep.append([x, y, x + w, y + h])
        pick = utility.non_max_suppression_fast(np.array(keep), overlapThresh=0.4)
        mser_sum = 0
        for (startX, startY, endX, endY) in pick:
            # cv2.rectangle(id_imgs[0], (startX, startY), (endX, endY), (0, 0, 255), 1)
            center = ((startX + endX) // 2, (startY + endY) // 2)
            if center[0] > id_imgs[0].shape[1] - 150 and id_imgs[0].shape[0] - 25 < center[1] < id_imgs[0].shape[0] - 10:
                # cv2.circle(id_imgs[0], center, 2, (255, 0, 0))
                mser_sum += 1
        if mser_sum > 5:
            id_imgs[0] = cv2.warpAffine(id_imgs[0],
                                        cv2.getRotationMatrix2D((id_imgs[0].shape[1] // 2, id_imgs[0].shape[0] // 2),
                                                                180, 1), id_imgs[0].shape[::-1])
        # cv2.imshow("img1", id_imgs[0])
        # cv2.imshow("img2", id_imgs[1])
        # cv2.imshow("boxs", show_box)
        # cv2.imshow("img_equhist", img_equHist)
        # cv2.imshow("img_sobel", img_sobel)
        # cv2.imshow("img_binary", img_binary)
        # cv2.imshow("contour", img_clone)
        # cv2.waitKey(0)
        cv2.imwrite(pos_dir + "pos_" + files[img_idx], id_imgs[0])
        cv2.imwrite(neg_dir + "neg_" + files[img_idx], id_imgs[1])
        # if img_idx > 500:
        #     break
    break


"""Plugin for plex media server (www.plexapp.com)."""
from xml.dom.minidom import parse, parseString
import re
import logging
from flexget.utils import requests
from flexget.plugin import register_plugin, PluginError
from flexget.entry import Entry
from socket import gethostbyname
from os.path import basename

log = logging.getLogger('plex')

class InputPlex(object):
    """
    Uses a plex media server (www.plexapp.com) tv section as an input.

    'section'           Required parameter, numerical (/library/sections/<num>) or section name.
    'selection'         Can be set to different keys:
        - all
        - unwatched
        - recentlyAdded
        - recentlyViewed
        - recentlyViewedShows
      'all' and 'recentlyViewedShows' will only produce a list of show names while the other three will produce
      filename and download url.
    'username'          Myplex (http://my.plexapp.com) username, used to connect to shared PMS'.
    'password'          Myplex (http://my.plexapp.com) password, used to connect to shared PMS'.
    'server'            Host/IP of PMS to connect to.
    'lowercase_title'   Convert filename (title) to lower case.
    'strip_year'        Remove year from title, ex: Show Name (2012) 01x01 => Show Name 01x01
    'original_filename' Use filename stored in PMS instead of transformed name. lowercase_title and strip_year
                        will be ignored.

    Default paramaters:
      server           : localhost
      port             : 32400
      selection        : all
      lowercase_title  : no
      strip_year       : yes
      original_filename: no

    Example:

      plex:
        server: 192.168.1.23
        section: 3
        selection: recentlyAdded
    """

    def validator(self):
        from flexget import validator
        config = validator.factory('dict')
        config.accept('text', key='server')
        config.accept('text', key='selection')
        config.accept('integer', key='port')
        config.accept('text', key='section', required=True)
        config.accept('integer', key='section', required=True)
        config.accept('text', key='username')
        config.accept('text', key='password')
        config.accept('boolean', key='lowercase_title')
        config.accept('boolean', key='strip_year')
        config.accept('boolean', key='original_filename')
        return config

    def prepare_config(self, config):
        config.setdefault('server', '127.0.0.1')
        config.setdefault('port', 32400)
        config.setdefault('selection', 'all')
        config.setdefault('username', '')
        config.setdefault('password', '')
        config.setdefault('lowercase_title', False)
        config.setdefault('strip_year', True)
        config.setdefault('original_filename', False)
        return config

    def on_task_input(self, task, config):
        config = self.prepare_config(config)
        accesstoken = ""
        plexserver = config['server']
        if gethostbyname(config['server']) != config['server']:
            config['server'] = gethostbyname(config['server'])
        if config['username'] and config['password'] and config['server'] != '127.0.0.1':
            header = {'X-Plex-Client-Identifier': 'flexget'}
            log.debug("Trying to to connect to myplex.")
            try:
                r = requests.post('https://my.plexapp.com/users/sign_in.xml',
                    auth=(config['username'], config['password']), headers=header)
            except requests.RequestException as e:
                raise PluginError('Could not login to my.plexapp.com: %s. Username: %s Password: %s'
                    % (e, config['username'], config['password']))
            log.debug("Managed to connect to myplex.")
            if 'Invalid email' in r.text:
                raise PluginError('Could not login to my.plexapp.com: invalid username and/or password!')
            log.debug("Managed to login to myplex.")
            dom = parseString(r.text)
            plextoken = dom.getElementsByTagName('authentication-token')[0].firstChild.nodeValue
            log.debug("Got plextoken: %s" % plextoken)
            try:
                r = requests.get("https://my.plexapp.com/pms/servers?X-Plex-Token=%s" % plextoken)
            except requests.RequestException as e:
                raise PluginError('Could not get servers from my.plexapp.com using authentication-token: %s.'
                    % plextoken)
            dom = parseString(r.text)
            for node in dom.getElementsByTagName('Server'):
                if node.getAttribute('address') == config['server']:
                    accesstoken = node.getAttribute('accessToken')
                    log.debug("Got accesstoken: %s" % plextoken)
                    accesstoken = "?X-Plex-Token=%s" % accesstoken
            if accesstoken == "":
                raise PluginError('Could not retrieve accesstoken for %s.' % config['server'])
        if not isinstance(config['section'], int):
            try:
                r = requests.get("http://%s:%d/library/sections/%s" %
                    (config['server'], config['port'], accesstoken))
            except requests.RequestException as e:
                raise PluginError('Error retrieving source: %s' % e)
            dom = parseString(r.text.encode("utf-8"))
            for node in dom.getElementsByTagName('Directory'):
                if node.getAttribute('title') == config['section']:
                    config['section'] = int(node.getAttribute('key'))
        if not isinstance(config['section'], int):
            raise PluginError('Could not find section \'%s\'' % config['section'])
        try:
            r = requests.get("http://%s:%d/library/sections/%s/%s%s" %
                (config['server'], config['port'], config['section'], config['selection'], accesstoken))
        except requests.RequestException as e:
            raise PluginError('Error retrieving source: %s' % e)
        dom = parseString(r.text.encode("utf-8"))
        entries = []
        plexsectionname = dom.getElementsByTagName('MediaContainer')[0].getAttribute('title1')
        if dom.getElementsByTagName('MediaContainer')[0].getAttribute('viewGroup') == "show":
            for node in dom.getElementsByTagName('Directory'):
                title = node.getAttribute('title')
                if config['strip_year']:
                    title = re.sub(r'^(.*)\(\d+\)$', r'\1', title)
                title = re.sub(r'[\(\)]', r'', title)
                title = re.sub(r'\&', r'And', title)
                title = re.sub(r'[^A-Za-z0-9- ]', r'', title)
                if config['lowercase_title']:
                    title = title.lower()
                e = Entry()
                e['title'] = title
                e['url'] = "NULL"
                e['plexserver'] = plexserver
                e['plexport'] = config['port']
                e['plexsection'] = config['section']
                e['plexsectionname'] = plexsectionname
                entries.append(e)
        elif dom.getElementsByTagName('MediaContainer')[0].getAttribute('viewGroup') == "episode":
            for node in dom.getElementsByTagName('Video'):
                title = node.getAttribute('grandparentTitle')
                season = int(node.getAttribute('parentIndex'))
                if node.getAttribute('parentIndex') == node.getAttribute('year'):
                    season = node.getAttribute('originallyAvailableAt')
                    filenamemap = "%s_%s%s_%s_%s_%s.%s"
                    episode = ""
                elif node.getAttribute('index'):
                    episode = int(node.getAttribute('index'))
                    filenamemap = "%s_%02dx%02d_%s_%s_%s.%s"
                else:
                    log.debug("Could not get episode number for '%s' (Hint, ratingKey: %s)"
                        % (title, node.getAttribute('ratingKey')))
                    break
                for media in node.getElementsByTagName('Media'):
                    vcodec = media.getAttribute('videoCodec')
                    acodec = media.getAttribute('audioCodec')
                    container = media.getAttribute('container')
                    resolution = media.getAttribute('videoResolution') + "p"
                    for part in media.getElementsByTagName('Part'):
                        key = part.getAttribute('key')
                        e = Entry()
                        if config['original_filename']:
                            e['title'] = basename(part.getAttribute('file'))
                        else:
                            if config['strip_year']:
                                title = re.sub(r'^(.*)\(\d+\)$', r'\1', title)
                            title = re.sub(r'[\(\)]', r'', title)
                            title = re.sub(r'\&', r'And', title).strip()
                            title = re.sub(r'[^A-Za-z0-9- ]', r'', title).replace(" ", ".")
                            if config['lowercase_title']:
                                title = title.lower()
                            e['title'] = filenamemap % (title, season, episode, resolution, vcodec, acodec, container)
                        e['url'] = "http://%s:%d%s%s" % (config['server'], config['port'], key, accesstoken)
                        e['plex_server'] = plexserver
                        e['plex_server_ip'] = config['server']
                        e['plex_port'] = config['port']
                        e['plex_section'] = config['section']
                        e['plex_section_name'] = plexsectionname
                        e['plex_path'] = key
                        entries.append(e)
        else:
            raise PluginError('Selected section is not a TV section.')
        return entries

register_plugin(InputPlex, 'plex', api_ver=2)


"""empty message

Revision ID: 411e0ea55c07
Revises: None
Create Date: 2015-04-20 14:14:55.853461

"""

# revision identifiers, used by Alembic.
revision = '411e0ea55c07'
down_revision = None

from alembic import op
import sqlalchemy as sa
import geoalchemy

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('sidewalk_elevation',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('sidewalk_objectid', sa.Integer(), nullable=True),
    sa.Column('coordinates', geoalchemy.geometry.LineString(), nullable=True),
    sa.Column('grade', sa.Float(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('curb',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('sidewalk_objectid', sa.Integer(), nullable=True),
    sa.Column('coordinates', geoalchemy.geometry.Point(), nullable=True),
    sa.Column('angle', sa.Float(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('curb')
    op.drop_table('sidewalk_elevation')
    ### end Alembic commands ###


from sys import maxsize

def swap(list_, a, b):
    list_[a] = list_[b] + list_[a]
    list_[b] = list_[a] - list_[b]
    list_[a] = list_[a] - list_[b]
    return list_

def reverse(list_, start, end):
    while start < end:
        list_ = swap(list_, start, end)
        end -= 1
        start += 1
        pass
    return list_

def run(list_, k):
    # divide
    list_ = reverse(list_, 0, k - 1)
    list_ = reverse(list_, k, len(list_) - 1)
    list_ = reverse(list_, 0, len(list_) - 1)

    print(list_)

if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    run(arr, 3)


from rdflib import Graph, Literal
from rdflib.namespace import Namespace, FOAF
from PracticaECSDI.Constants import Ontologies, FIPAACLPerformatives, Constants

class FlightRequestMessage:
    def __init__(self, uuid, maxprice, initDate, finalDate, departureAirport, arrivalAirport):
        self.uuid = uuid
        self.maxPrice = maxprice
        self.firstDay = initDate
        self.lastDay = finalDate
        self.departureAirport = departureAirport
        self.arrivalAirport = arrivalAirport

    def to_graph(self):
        graph = Graph()
        namespace = Namespace(Constants.ONTOLOGY_NAME)
        flight = namespace.__getattr__('#RequestFlight#' + str(self.uuid))
        graph.add((flight, FOAF.Uuid, Literal(self.uuid)))
        graph.add((flight, FOAF.MaxPrice, Literal(self.maxPrice)))
        graph.add((flight, FOAF.FirstDay, Literal(self.firstDay)))
        graph.add((flight, FOAF.LastDay, Literal(self.lastDay)))
        graph.add((flight, FOAF.DepartureAirport, Literal(self.departureAirport)))
        graph.add((flight, FOAF.ArrivalAirport, Literal(self.arrivalAirport)))
        return graph

    @classmethod
    def from_graph(cls, graph):
        query = """SELECT ?x ?uuid ?maxPrice ?firstDay ?lastDay ?arrivalAirport ?departureAirport
           WHERE {
                ?x ns1:Uuid ?uuid.
                ?x ns1:MaxPrice ?maxPrice.
                ?x ns1:FirstDay ?firstDay.
                ?x ns1:LastDay ?lastDay.
                ?x ns1:DepartureAirport ?departureAirport.
                ?x ns1:ArrivalAirport ?arrivalAirport
           }
        """
        qres = graph.query(query)
        search_res = []
        for f, uuid, maxprice, firstDay, lastDay, arrivalAirport, departureAirport in qres:
            """search_res.append(FlightMessage(
                uuid.toPython(),
                maxprice.toPython(),
                firstDay.toPython(),
                lastDay.toPython(),
                departureAirport.toPython(),
                arrivalAirport.toPython()
            ))"""
            return FlightRequestMessage(uuid.toPython(), maxprice.toPython(), firstDay.toPython(), lastDay.toPython(),
                                        departureAirport.toPython(),arrivalAirport.toPython())
        #return search_res


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

# Usage: python plot.py
# Specify the csv file names in data_files

# data_files = ['s1', 's2', 's5', 's10', 's25', 's50']
data_files = ['s=1', 's=2', 's=5', 's=10', 's=25', 'svr_adaptive', 'cli_adaptive']
data = {}

for file in data_files:
    acc, time = [], []

    with open(f'{file}.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        i = 0
        for row in csv_reader:
            if i != 0:
                acc.append(float(row[2]))
                time.append(float(row[3]))

            i += 1

    data[file] = np.array(acc), np.array(time)

for series in data:
    acc, time = data[series]
    if series == 'svr_adaptive':
        plt.plot(time, acc, 'o-', label=series, color='#e377c2')
    elif series == 'cli_adaptive':
        plt.plot(time, acc, '^-', label=series, color='#8c564b')
    else:
        plt.plot(time, acc, '-.', label=series)

plt.xlabel("Time (sec)")
plt.ylabel("Accuracy")
plt.legend(loc='lower right')
plt.savefig('lenet_adaptive.png', dpi=300)


from subprocess import Popen, PIPE, call
import threading, sys

'''
this is a self defined class as a simple pwntool replacement
when there is not intalled pwntool
'''

class process:
    def __init__(self, cmd):
        self.pipe = Popen(cmd, stdin = PIPE, stdout = PIPE, shell = True)

    def sendline(self, delims):
        self.pipe.stdin.write(delims + b'\n')
        self.pipe.stdin.flush()
        return delims + b'\n'

    def send(self, delims):
        self.pipe.stdin.write(delims)
        self.pipe.stdin.flush()

    def recv(self, count):
        return self.pipe.stdout.read(count)

    def recvline(self):
        return self.pipe.stdout.readline()

    def recvuntil(self, delims):
        buf = b''
        while delims not in buf:
            buf += self.recv(1)
        return buf

    def recvline_startswith(self, delims):
        buf = ''
        while '\n' + delims not in buf:
            buf += self.read(1)

        while True:
            tmp = self.read(1)
            buf += tmp
            if buf == '\n':
                break
        return buf

    def interactive(self):
        print('Switching to interative mode')
        go = threading.Event()
        def recv_thread():
            while not go.isSet():
                try:
                    cur = self.recv(1)
                    sys.stdout.write(cur)
                    sys.stdout.flush()
                except EOFError:
                    print('Got EOF while reading in interactive')
                    break
        t = threading.Thread(target = recv_thread)
        t.setDaemon(True)
        t.start()
        while self.pipe:
            print('$ '),
            while True:
                data = sys.stdin.read(1)
                self.send(data)
                if data == '\n':
                    break


from datetime import datetime
from datetime import timedelta
import importlib
import sys

__author__ = 'vfourrier'

def run(module_path, global_path_utilities, compute_date, result_date):
    module_launcher = module_path
    class_module = module_path.split('.')[-1]
    importlib.import_module(module_launcher)
    run_module = sys.modules[module_launcher]
    run_class = getattr(run_module, class_module)
    run_class(module_path=module_path + class_module, global_path_utilities=global_path_utilities, compute_date=compute_date,
              result_date=result_date)

def main():
    module_path = 'QuantPack.Equity.Products.Options.EQDPriceable'
    compute_date = datetime(2018, 1, 1)
    result_date = compute_date - timedelta(days=1)
    global_path_utilities = r'/Volumes/SECURITY 1/Vincent/BSCM/ATM/Utilities/GetParams/Museum_Wrapper.xlsx'

    run(module_path=module_path, global_path_utilities=global_path_utilities, compute_date=compute_date,
        result_date=result_date)

if __name__ == '__main__':
    main()


from typing import Optional

from mypy_boto3_builder.service_name import ServiceName
from mypy_boto3_builder.constants import MODULE_NAME
from mypy_boto3_builder.import_helpers.import_record import ImportRecord
from mypy_boto3_builder.type_annotations.fake_annotation import FakeAnnotation

class InternalImport(FakeAnnotation):
    is_internal = True

    def __init__(
        self,
        name: str,
        service_name: ServiceName,
        module_name: str = "service_resource",
    ) -> None:
        self.name = name
        self.service_name = service_name
        self.module_name = module_name
        self.real_service_name: Optional[ServiceName] = None

    def render(self) -> str:
        return f"{self.scope}.{self.name}"

    @property
    def scope(self) -> str:
        return f"{self.service_name.module_name}_scope"

    def localize(self, service_name: ServiceName) -> None:
        self.real_service_name = service_name

    def get_import_record(self) -> ImportRecord:
        if self.real_service_name is None:
            raise ValueError("Non-localized ImportString")

        return ImportRecord(
            source=f"{MODULE_NAME}_{self.real_service_name.name}.{self.module_name}",
            alias=self.scope,
        )