#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
from qframer.qt import QtGui
from qframer.qt import QtCore

'''
1：不要在顶层窗口（无父类的窗口）中使用setStyleSheet() ，否则其一父窗口的背景不会改变，
    其次其子窗口的背景设置方法变得局限唯一，不能再使用其它方法！
2：如果一个一般窗口（非顶层窗口）还有子窗口，那最好不要使用setStyleSheet()来设置其背景颜色，
    因为虽然此时该窗口的背景设置是生效的，但是其子窗口的背景设置也变得局限唯一，只能使用setStyleSheet，而不能使用其它方法！
    当然：你如果就是只想使用这种方法，那也完全可以！！

说白了就是：不要再MainWindow中使用setStyleSheet()！
    而上边之所以强调拓宽子窗口设置背景的方法范围，这是
    因为：如果只能用setStyleSheet样式表来设置背景图片的话，
    该图片是无法缩放的，如果其大小与widget窗口大小不相符，则我们无法用程序来实现图片的缩放，
    除非我们直接处理图片使其大小与widget窗口相符； 而如果不局限于用setStyleSheet样式表来设置的话，
    我们可以选择用QPalette调色版，其内部setBrush()之前，我们完全可以先对图片进行scale缩放再刷到窗口上，
    这样就避免直接去处理图片，灵活性强一点！
==========================================================================
'''

def set_bg(widget, bg=None):
    '''
        设置背景颜色或者图片
    '''
    if bg is None:
        bg = QtGui.QColor('#ABABAB')
    palette = QtGui.QPalette(widget)
    palette.setBrush(widget.backgroundRole(), QtGui.QBrush(bg))
    widget.setPalette(palette)
    setattr(widget, 'bg', bg)

def set_skin(app, qssfile, style=''):
    with open(qssfile, 'r') as f:
        app.setStyleSheet(f.read() + style)

def movecenter(w):
    qr = w.frameGeometry()
    cp = QtGui.QDesktopWidget().availableGeometry().center()
    qr.moveCenter(cp)
    w.move(qr.topLeft())

class QMessageBox(QtGui.QDialog):

    def __init__(self, parent=None):
        super(QMessageBox, self).__init__(parent)
        self.setObjectName('QMessageBox')
        self.setGeometry(300, 300, 400, 200)
        self.center()
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinimizeButtonHint)  # 无边框， 带系统菜单， 可以最小化
        set_skin(self, os.sep.join(['skin', 'qss', 'MetroDialog.qss']))  # 设置弹出框样式
        self.setWindowIcon(QtGui.QIcon('icons/Write.png'))
        self.setModal(True)

    def center(self):
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def information(self, info):
        infoButton = QtGui.QPushButton('info')
        infoButton.setObjectName('Info' + 'Button')
        info = QtGui.QTextEdit(info)
        info.setReadOnly(True)
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(infoButton)
        mainLayout.addWidget(info)
        # mainLayout.addStretch(4)
        infoButton.clicked.connect(self.clickReturn)
        self.setLayout(mainLayout)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.exec_()

    def clickReturn(self):
        self.close()

class QInputDialog(QtGui.QDialog):

    def __init__(self, parent=None):
        super(QInputDialog, self).__init__(parent)
        self.setObjectName('QInputDialog')
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinimizeButtonHint)  # 无边框， 带系统菜单， 可以最小化
        set_skin(self, os.sep.join(['skin', 'qss', 'MetroDialog.qss']))  # 设置弹出框样式
        self.setWindowIcon(QtGui.QIcon('icons/Write.png'))
        self.setModal(True)
        self.setGeometry(500, 600, 400, 100)
        self.createNavigation()

    def createNavigation(self):
        buttons = ['Ok', 'Cancel']
        self.navigation = QtGui.QWidget()
        navigationLayout = QtGui.QHBoxLayout()
        for item in buttons:
            button = item + 'Button'
            setattr(self, button, QtGui.QPushButton(item))
            getattr(self, button).setObjectName(button)
            navigationLayout.addWidget(getattr(self, button))
        self.navigation.setLayout(navigationLayout)
        # self.navigation.setMaximumHeight(10)
        self.navigation.setContentsMargins(0, 0, 0, 0)

        getattr(self, 'Cancel' + 'Button').clicked.connect(self.clickReturn)
        getattr(self, 'Ok' + 'Button').clicked.connect(self.clickReturn)

    def getInteger(self, title, intLabel, value, minvalue=-2147483647, maxvalue=2147483647, step=1):
        titleLabel = QtGui.QLabel(title)
        intLabel = QtGui.QLabel(intLabel)
        intValue = QtGui.QSpinBox()
        intValue.setMaximum(maxvalue)
        intValue.setValue(value)
        intValue.setMinimum(minvalue)
        intValue.setSingleStep(step)
        intValue.lineEdit().setReadOnly(False)

        intwidget = QtGui.QWidget()
        Layout = QtGui.QGridLayout()
        Layout.addWidget(titleLabel, 0, 0)
        Layout.addWidget(intLabel, 1, 0)
        Layout.addWidget(intValue, 1, 1)
        intwidget.setLayout(Layout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(intwidget)
        mainLayout.addWidget(self.navigation)
        self.setLayout(mainLayout)
        self.layout().setContentsMargins(0, 0, 0, 0)
        mainLayout.addStretch(1)

        self.intValue = intValue
        self.value = self.intValue.value()
        self.flag = False

        movecenter(self)
        self.exec_()
        return self.intValue.value(), self.flag

    def getDouble(self, title, doubleLabel, value, minvalue=-2147483647, maxvalue=2147483647, step=1.0, decimals=5):
        titleLabel = QtGui.QLabel(title)
        doubleLabel = QtGui.QLabel(doubleLabel)
        doubleValue = QtGui.QDoubleSpinBox()
        doubleValue.setMaximum(maxvalue)
        doubleValue.setValue(value)
        doubleValue.setMinimum(minvalue)
        doubleValue.setSingleStep(step)
        doubleValue.setDecimals(decimals)
        doubleValue.lineEdit().setReadOnly(False)

        doublewidget = QtGui.QWidget()
        Layout = QtGui.QGridLayout()
        Layout.addWidget(titleLabel, 0, 0)
        Layout.addWidget(doubleLabel, 1, 0)
        Layout.addWidget(doubleValue, 1, 1)
        doublewidget.setLayout(Layout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(doublewidget)
        mainLayout.addWidget(self.navigation)
        self.setLayout(mainLayout)
        self.layout().setContentsMargins(0, 0, 0, 0)
        mainLayout.addStretch(1)

        self.doubleValue = doubleValue
        self.exec_()
        return self.doubleValue.value(), self.flag

    def getText(self, title, textLabel, text, mode=QtGui.QLineEdit.Normal):
        titleLabel = QtGui.QLabel(title)
        textLabel = QtGui.QLabel(textLabel)
        textValue = QtGui.QLineEdit(text)
        textValue.setEchoMode(mode)

        textwidget = QtGui.QWidget()
        Layout = QtGui.QGridLayout()
        Layout.addWidget(titleLabel, 0, 0)
        Layout.addWidget(textLabel, 1, 0)
        Layout.addWidget(textValue, 1, 1)
        textwidget.setLayout(Layout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(textwidget)
        mainLayout.addWidget(self.navigation)
        self.setLayout(mainLayout)
        self.layout().setContentsMargins(0, 0, 0, 0)
        mainLayout.addStretch(1)

        self.textValue = textValue
        self.exec_()
        return unicode(self.textValue.text()), self.flag

    def getItem(self, title, itemLabel, items, index, editable=True):
        titleLabel = QtGui.QLabel(title)
        itemLabel = QtGui.QLabel(itemLabel)
        itemValue = QtGui.QComboBox()
        for item in items:
            itemValue.addItem(item)
        itemValue.setCurrentIndex(0)
        itemValue.setEditable(editable)

        itemwidget = QtGui.QWidget()
        Layout = QtGui.QGridLayout()
        Layout.addWidget(titleLabel, 0, 0)
        Layout.addWidget(itemLabel, 1, 0)
        Layout.addWidget(itemValue, 1, 1)
        itemwidget.setLayout(Layout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(itemwidget)
        mainLayout.addWidget(self.navigation)
        self.setLayout(mainLayout)
        self.layout().setContentsMargins(0, 0, 0, 0)
        mainLayout.addStretch(1)

        self.itemValue = itemValue
        self.exec_()
        return unicode(self.itemValue.currentText()), self.flag

    def clickReturn(self):
        self.close()
        if self.sender() is getattr(self, 'Ok' + 'Button'):
            self.flag = True
        elif self.sender() is getattr(self, 'Cancel' + 'Button'):
            self.flag = False


"""Python implementation of the TextRank algorithm.
From this paper:
    https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf
Based on:
    https://gist.github.com/voidfiles/1646117
    https://github.com/davidadamojr/TextRank
"""
import editdistance
import itertools
import networkx as nx

def filter_for_tags(tagged, tags=None):
    """Apply syntactic filters based on POS tags."""
    if tags is None:
        tags = ['NOUN', 'ADJ', 'PROPN']

    return [item for item in tagged if item[1] in tags]

def normalize(tagged):
    """Return a list of tuples with the first item's periods removed."""
    return [(item[0].replace('.', ''), item[1]) for item in tagged]

def unique_everseen(iterable, key=None):
    """List unique elements in order of appearance.
    Examples:
        unique_everseen('AAAABBBCCDAABBB') --> A B C D
        unique_everseen('ABBCcAD', str.lower) --> A B C D
    """
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in [x for x in iterable if x not in seen]:
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

def build_graph(nodes):
    """Return a networkx graph instance.
    :param nodes: List of hashables that represent the nodes of a graph.
    """
    gr = nx.Graph()  # initialize an undirected graph
    gr.add_nodes_from(nodes)
    node_pairs = list(itertools.combinations(nodes, 2))

    # add edges to the graph (weighted by Levenshtein distance)
    for pair in node_pairs:
        first_string = pair[0]
        second_string = pair[1]
        lev_distance = editdistance.eval(first_string, second_string)
        gr.add_edge(first_string, second_string, weight=lev_distance)

    return gr

def extract_key_phrases(pos_tagged, keywords_length=10, keywords_length_pct=0.1):
    """Return a set of key phrases.
    """
    text_list = [(x[0], x[2]) for x in pos_tagged]

    tagged = filter_for_tags(pos_tagged)
    tagged = normalize(tagged)

    unique_word_set = unique_everseen([x[0] for x in tagged])
    word_set_list = list(unique_word_set)

    # this will be used to determine adjacent words in order to construct
    # key phrases with two words

    graph = build_graph(word_set_list)

    # pageRank - initial value of 1.0, error tolerance of 0,0001,
    calculated_page_rank = nx.pagerank(graph, weight='weight')

    # most important words in ascending order of importance
    key_phrases = sorted(calculated_page_rank, key=calculated_page_rank.get, reverse=True)

    # the number of key phrases returned will be relative to the size of the
    # text (based on percentage)
    index = min(keywords_length, int(len(key_phrases) * keywords_length_pct))
    key_phrases = key_phrases[0:index + 1]

    # take key phrases with multiple words into consideration as done in the
    # paper - if two words are adjacent in the text and are selected as
    # keywords, join them together
    modified_key_phrases = set([])
    # keeps track of individual keywords that have been joined to form a
    # key phrase
    dealt_with = set([])
    i = 0
    j = 1
    while j < len(text_list):
        first_lemma = text_list[i][0]
        first_word = text_list[i][1]
        second_lemma = text_list[j][0]
        second_word = text_list[j][1]
        if first_lemma in key_phrases and second_lemma in key_phrases:
            key_phrase = first_word + ' ' + second_word
            modified_key_phrases.add(key_phrase)
            dealt_with.add(first_lemma)
            dealt_with.add(second_lemma)
        else:
            if first_lemma in key_phrases and first_lemma not in dealt_with:
                modified_key_phrases.add(first_word)

            # if this is the last word in the text, and it is a keyword, it
            # definitely has no chance of being a key phrase at this point
            if j == len(text_list) - 1 and second_lemma in key_phrases and second_lemma not in dealt_with:
                modified_key_phrases.add(second_word)

        i = i + 1
        j = j + 1

    return modified_key_phrases

def extract_sentences(sentence_tokens, summary_length=100, summary_length_pct=0.1, clean_sentences=True):
    """Return a paragraph formatted summary of the source text.
    :param summary_length_pct: Desired summary length as percentage from the total
    :param sentence_tokens: List of sentences
    :param clean_sentences: When True will only return complete sentences
    :param summary_length: Desired summary length as absolute value (if this is smaller than percentage it will win)
    """
    graph = build_graph(sentence_tokens)

    calculated_page_rank = nx.pagerank(graph, weight='weight')

    # most important sentences in ascending order of importance
    sentences = sorted(calculated_page_rank, key=calculated_page_rank.get, reverse=True)

    # return a summary_length word summary
    summary = ' '.join(sentences)
    summary_words = summary.split()

    # Pick the minimum from summary_length and the summary_length_pct but it must have at least one complete sentence
    # if possible
    summary_length_pct = int(len(summary_words) * summary_length_pct)
    summary_words_pct = summary_words[0:summary_length_pct]
    dot_indices_pct = [idx for idx, word in enumerate(summary_words_pct) if word.find('.') != -1]

    summary_words_abs = summary_words[0:summary_length]
    dot_indices_abs = [idx for idx, word in enumerate(summary_words_abs) if word.find('.') != -1]

    there_are_no_dots = len(dot_indices_pct) == 0 and len(dot_indices_abs) == 0
    there_are_dots_in_both = len(dot_indices_abs) > 0 and len(dot_indices_pct) > 0

    if there_are_no_dots or there_are_dots_in_both:
        # Doesn't matter, pick the smallest one
        summary_length = min(summary_length_pct, summary_length)

    if summary_length_pct > summary_length and (not dot_indices_abs):
        summary_length = summary_length_pct

    # Find closest dot position
    if clean_sentences:
        before = summary_words[0:summary_length]
        before_dot_indices = [idx for idx, word in enumerate(before) if word.find('.') != -1]

        after = summary_words[summary_length:]
        after_dot_indices = [idx for idx, word in enumerate(after) if word.find('.') != -1]

        diff_before = 0
        if before_dot_indices:
            dot_before = max(before_dot_indices)
            diff_before = summary_length - dot_before

        diff_after = summary_length
        if after_dot_indices:
            diff_after = min(after_dot_indices)

        if diff_after <= diff_before:
            summary_length = summary_length + diff_after
        else:
            summary_length = dot_before

    summary_words = summary_words[0:summary_length + 1]
    summary = ' '.join(summary_words)

    return summary


def monta_combinacoes(lista_combinacoes, numero, indice_atual, resto_subtracao):
    """
    Calcula e imprime todas as possíveis combinacoes de soma para o número 'numero', cujos termos estão em ordem crescente.
    """

    if resto_subtracao < 0:
        return None

    elif resto_subtracao == 0:

        for j in range(indice_atual):
            if(j + 1 == indice_atual):
                print(lista_combinacoes[j], end="")
            else:
                print(lista_combinacoes[j], end="+")

        print(f"={numero}")
        return None

    if indice_atual != 0:
        numero_anterior = lista_combinacoes[indice_atual - 1]
    else:
        numero_anterior = 1

    for i in range(numero_anterior, numero + 1):
        lista_combinacoes[indice_atual] = i
        monta_combinacoes(lista_combinacoes, numero, indice_atual + 1, resto_subtracao - i)

def main():
    numero = int(input())
    lista_combinacoes = [0 * elemento for elemento in range(numero)]
    monta_combinacoes(lista_combinacoes, numero, 0, numero)

main()


#!/usr/bin/env python

# Make a csv file, that matches Kevin's spreadsheet, from the TNA Archive dump

import os
import sys
import json
import argparse
from calendar import monthrange

parser = argparse.ArgumentParser()
parser.add_argument("--rg", help="Record group", type=int, required=True)
parser.add_argument(
    "--subgroup", help="Record group file", type=int, required=False, default=None
)
parser.add_argument("--series", help="Series", type=int, required=True)
parser.add_argument("--match", help="Filter", type=str, required=False, default=None)
parser.add_argument("--title", default=False, action="store_true")
args = parser.parse_args()

# Write to stdout
fw = sys.stdout

# Input files
fileN = []
filed = "%s/WW2_US_logs/US_TNA_Catalog/record-groups/rg_%03d/" % (
    os.getenv("SCRATCH"),
    args.rg,
)
if args.subgroup is not None:
    fileN.append("%s/rg_%03d-%03d.json" % (filed, args.rg, args.subgroup))
else:
    files = os.listdir(filed)
    for fn in files:
        fileN.append("%s/%s" % (filed, fn))

# Get the date (month) from the title, where posible
mnames = (
    "january",
    "february",
    "march",
    "april",
    "may",
    "june",
    "july",
    "august",
    "september",
    "october",
    "november",
    "december",
)

def getMonthFromTitle(title):
    hIdx = title.rfind("-")
    title = title[hIdx:].lower()
    # year is the last 4 characters
    year = int(title[-4:])
    # which month matches
    mmatch = -1
    for count in range(len(mnames)):
        if title.find(mnames[count]) > -1:
            mmatch = count + 1
            break
    if mmatch < 1:
        raise Exception("Month not found")
    return [year, mmatch]

# Get the date at the end of the valid month
def getEndDate(record):
    try:
        (year, month) = getMonthFromTitle(record["title"])
        return [year, month, monthrange(year, month)[1]]
    except Exception:
        ed = record["coverageDates"]["coverageEndDate"]
        if "logicalDate" in ed:
            return (
                int(ed["logicalDate"][:4]),
                int(ed["logicalDate"][5:7]),
                int(ed["logicalDate"][8:10]),
            )
        else:
            return (
                int(ed["year"]),
                int(ed["month"]),
                monthrange(int(ed["year"]), int(ed["month"]))[1],
            )

# Add the column titles if requested
if args.title:
    fw.write(
        "Ship Name, Hull Symbol, Record Group, Series NAID, Record Entry, Container, "
        + "StartDate, EndDate, Nara URL, #Images, Document URL\n"
    )

for filen in fileN:
    fd = open(filen, "r")
    while True:
        line = fd.readline()
        if not line:
            break
        if line[0] == ",":
            continue
        if args.match is not None and args.match not in line:
            continue
        if line[:2] == "{[":
            line = line[2:]
        if line[-3:-1] == "]}":
            line = line[:-3] + "\n"
        try:
            fj = json.loads(line)
        except:
            print(line)
            break
        try:
            base = fj["description"]["fileUnit"]
        except Exception:
            continue
        try:
            if int(base["parentSeries"]["naId"]) != args.series:
                continue
        except Exception:
            continue

        # Name is the portion of the title before the parentheses
        try:
            shipName = base["title"]
            pIdx = base["title"].find("(")
            if pIdx > 0:
                shipName = base["title"][: (pIdx - 1)]
            fw.write('"%-30s",' % shipName)
        except Exception:
            fw.write("%-30s," % " ")

        # Hull number is the portion of the title between parentheses
        try:
            hullNo = ""
            pIdx1 = base["title"].find("(")
            pIdx2 = base["title"].find(")")
            if pIdx1 > 0 and pIdx2 > pIdx1:
                hullNo = base["title"][(pIdx1 + 1) : (pIdx2)]
            fw.write('"%-10s",' % hullNo)
        except Exception:
            fw.write("%-10s," % " ")

        # Fixed data - record group and parent series
        fw.write("%-5d," % args.rg)
        fw.write("%-8d," % args.series)

        # Record entry?
        try:
            vcn = base["variantControlNumberArray"]["variantControlNumber"]
            for entry in vcn:
                if entry["type"]["naId"] == "10675882":
                    fw.write("%-10s," % entry["number"])
                    break
        except Exception as e:
            # sys.stderr.write(repr(e))
            fw.write("%-10s," % " ")

        # Container
        try:
            pFile = base["physicalOccurrenceArray"]["fileUnitPhysicalOccurrence"]
            cid = pFile["mediaOccurrenceArray"]["mediaOccurrence"]["containerId"]
            fw.write("%-5s," % cid)
        except Exception as e:
            # sys.stderr.write(repr(e))
            fw.write("%-5s," % " ")

        # dates
        try:
            ed = getEndDate(base)
            fw.write("%04d-%02d-%02d," % (ed[0], ed[1], 1))
            fw.write("%04d-%02d-%02d," % (ed[0], ed[1], ed[2]))
        except Exception as e:
            fw.write("%10s,%10s," % (" ", " "))

        # Nara URL
        try:
            fw.write("https://catalog.archives.gov/id/%s," % base["naId"])
        except Exception:
            fw.write("%-40s," % " ")

        # Count of images
        try:
            nImages = len(fj["objects"]["object"]) - 1  # Don't count the pdf
            fw.write("%-5d," % nImages)
        except Exception as e:
            # sys.stderr.write(repr(e))
            fw.write("%-5s," % " ")

        # Get the pdf url, if there is one
        try:
            docs = fj["objects"]["object"]
            pdfU = None
            for doc in docs:
                a_url = doc["file"]["@url"]
                ftype = a_url[-3:].lower()
                if ftype == "pdf":
                    pdfU = a_url
                    break
            if pdfU is not None:
                fw.write("%s," % pdfU)
            else:
                fw.write("%10s," % " ")
        except Exception:
            fw.write("%10s," % " ")
        fw.write("\n")
    fd.close()


import os

from troposphere import Template, Ref, Parameter
from troposphere.ec2 import SecurityGroup, Instance

t = Template("Create EC2")
t.set_version()

bucket_name = t.add_parameter(Parameter(
    'BucketName',
    Type='String'
))

security_group_ingress = []

cidrs = ["10.0.1.0/24",
         "10.0.2.0/24",
         "10.0.3.0/24",
         "10.0.4.0/24",
         "10.0.5.0/24",
         "10.0.10.0/24"]
for cidr_ip in cidrs:
    security_group_ingress.append({'FromPort': 22,
                                   'ToPort': 22,
                                   'IpProtocol': 'tcp',
                                   'CidrIp': cidr_ip})

security_group = t.add_resource(SecurityGroup(
    'XKESecurityGroup',
    SecurityGroupIngress=security_group_ingress,
    VpcId='vpc-1234',
    GroupDescription='Enable SSH access to the EC2 machine'
))

environment = os.getenv('ENVIRONMENT', 'dev')

def get_instance_type():
    if environment == 'dev':
        return 't2.micro'
    elif environment == 'prod':
        return 'm5.large'
    raise ValueError("Environment {} unknown".format(environment))

t.add_resource(Instance(
    'XKEInstance',
    ImageId='ami-951945d0',
    DisableApiTermination=True,
    InstanceType=get_instance_type(),
    KeyName='xke-key',
    SecurityGroupIds=[Ref(security_group)],
    SubnetId='subnet-1234',
))

print(t.to_yaml())


import re
from mymodul import *

def grep(syntax,file):
    with open(file,'r') as text:
        for line in text:

            start_code = "\033[{}m".format(93)
            end_code="\033[0m"

            match=re.finditer(syntax,line)

            if match:
                for i in match:
                    start_code = "\033[{}m".format(94)
                    end_code="\033[0m"
                    change=start_code + i.group() + end_code
                    print(i.group())
                    line=re.sub(syntax,change,line)
                    print(line)
                print(line)

if __name__ == '__main__':
    reg=r"bb"
    grep(reg,sys.argv[1])
    txt="aabbbcccc is the real"
    start_code = "\033[{}m".format(94)
    end_code="\033[0m"
    change=start_code + 'cc' + end_code
    tx=re.sub("bb",change,txt)
    print(tx)


#! /usr/bin/env python

import pymongo

# 取点赞最多的前10条短评
with pymongo.MongoClient(host = "192.168.0.105") as client:
    comments = client.douban.movie_26752088_comments

    for doc in comments.find().sort([("vote", -1)]).limit(10):
        print("author = {}, date = {}, vote = {}, comment = {}".format(
            doc.get("author"),
            doc.get("date"),
            doc.ger("vote"),
            doc.get("comment")
        ))


from django import forms
import datetime
from .models import Akun

class AkunForm(forms.ModelForm):

    nama = forms.CharField()
    foto_src = forms.CharField(widget=forms.HiddenInput, required=False)
    kota_domisili = forms.CharField()
    alamat = forms.CharField(widget=forms.Textarea, required=False)
    jenis_kelamin = forms.ChoiceField(widget=forms.RadioSelect)
    aktif = forms.ChoiceField(widget=forms.RadioSelect)
    tanggal_lahir = forms.DateField(initial=datetime.date.today)
    email = forms.EmailField()
    tempat_lahir = forms.CharField()
    no_telepon = forms.IntegerField(min_value=10)
    status = forms.ChoiceField(widget=forms.Select)
    verification_code = forms.IntegerField(disabled=True)
    verification = forms.ChoiceField(widget=forms.Select)

    nama.widget.attrs.update({
        'class': 'form-control', 'placeholder': 'Nama lengkap.'
    })
    kota_domisili.widget.attrs.update({
        'class': 'form-control', 'placeholder': 'Kota yang ditempati sekarang.'
    })
    alamat.widget.attrs.update({
        'class': 'form-control',
        'placeholder': 'Alamat tempat tinggal sekarang.',
        'rows': 4
    })
    email.widget.attrs.update({
        'class': 'form-control', 'placeholder': 'Alamat Email.'
    })
    tempat_lahir.widget.attrs.update({
        'class': 'form-control', 'placeholder': 'Tempat Lahir.'
    })
    no_telepon.widget.attrs.update({
        'class': 'form-control', 'placeholder': 'Nomor Telepon/Handphone.'
    })
    status.widget.attrs.update({
        'class': 'form-control', 'placeholder': 'Status Akun'
    })
    status.choices = [
        ('admin', 'Admin'),
        ('staf', 'Staf'),
        ('member', 'Member'),
    ]

    jenis_kelamin.widget.attrs.update({
        'class': 'form-check-input',
    })
    jenis_kelamin.widget.choices = [
        (False, 'Perempuan'),
        (True, 'Laki-laki')
    ]
    aktif.widget.attrs.update({
        'class': 'form-check-input',
    })
    aktif.widget.choices = [
        (True, 'Ya'),
        (False, 'Tidak')
    ]
    verification.choices = [
        (True, 'Ya'),
        (False, 'Tidak')
    ]

    tanggal_lahir.widget.attrs.update({
        'class': 'form-control',
        'placeholder': 'Tanggal Lahir.',
        'id': 'id_tanggal_lahir',
    })

    class Meta:
        model = Akun
        fields = ['nama', 'foto_src', 'kota_domisili', 'alamat', 'tanggal_lahir',
                  'jenis_kelamin', 'aktif', 'email', 'tempat_lahir', 'no_telepon', 'status', 'verification_code']


from random import randint
from time import sleep

def sorteio(lista):
    print('Sorteio dos numeros ')
    for contador in range (0,6):
        num = randint(1,10)
        lista.append(num)
        print(f'{num}',end=' ')
        sleep(0.3)
    print('Ai está ')
def somarPar (lista):
    soma = 0
    for valor in lista:
        if valor %2 ==0:
            soma += valor
    print('Soma dos numeros pares são',soma)
numeros = list()
sorteio(numeros)
somarPar(numeros)


import time

from botocore.exceptions import ClientError

from syndicate.commons.log_helper import get_logger
from syndicate.core.conf.processor import ALL_REGIONS
from syndicate.core.helper import unpack_kwargs
from syndicate.core.resources.base_resource import BaseResource
from syndicate.core.resources.helper import (build_description_obj,
                                             create_args_for_multi_region,
                                             validate_params)

_LOG = get_logger('syndicate.core.resources.cloud_watch_resource')
ARN_KEY = 'Arn'

def _create_ec2_rule(rule_name, rule_meta, cw_conn):
    cw_conn.create_ec2_rule(name=rule_name,
                            instances=rule_meta.get('instance_ids'),
                            instance_states=rule_meta.get(
                                'instance_states'))

def _create_schedule_rule(rule_name, rule_meta, cw_conn):
    cw_conn.create_schedule_rule(name=rule_name,
                                 expression=rule_meta['expression'])

def _create_api_call_rule(rule_name, rule_meta, cw_conn):
    cw_conn.create_api_call_rule(name=rule_name,
                                 aws_service=rule_meta.get('aws_service'),
                                 operations=rule_meta.get('operations'),
                                 custom_pattern=rule_meta.get(
                                     'custom_pattern'))

RULE_TYPES = {
    'schedule': _create_schedule_rule,
    'ec2': _create_ec2_rule,
    'api_call': _create_api_call_rule
}

def validate_cloud_watch_rule_params(name, meta):
    # validation depends on rule type
    required_parameters = ['rule_type']
    rule_type = meta.get('rule_type')
    if rule_type:
        if rule_type == 'schedule':
            required_parameters.append('expression')
    validate_params(name, meta, required_parameters)

def get_event_bus_arn(event_bus, region):
    target_arn = 'arn:aws:events:{0}:{1}:event-bus/default'.format(
        region,
        event_bus)
    return target_arn

class CloudWatchResource(BaseResource):

    def __init__(self, cw_events_conn_builder, account_id) -> None:
        self.cw_events_conn = cw_events_conn_builder()
        self._cw_events_conn_builder = cw_events_conn_builder
        self.account_id = account_id

    def describe_rule(self, name, meta, region, response=None):
        if not response:
            response = self._cw_events_conn_builder(region).get_rule(name)
        arn = response[ARN_KEY]
        del response[ARN_KEY]
        return {arn: build_description_obj(response, name, meta)}

    def describe_rule_from_meta(self, name, meta):
        new_region_args = create_args_for_multi_region(
            [
                {'name': name,
                 'meta': meta}
            ], ALL_REGIONS)
        responses = []
        for arg in new_region_args:
            rule = self._cw_events_conn_builder(arg['region']).get_rule(name)
            if rule:
                responses.append(rule)

        description = []
        for rule in responses:
            arn = rule[ARN_KEY]
            del rule[ARN_KEY]
            description.append({arn: build_description_obj(rule, name, meta)})
        return description

    def create_cloud_watch_rule(self, args):
        """ Create an event rule from meta in region/regions.

        :type args: list
        """
        new_region_args = create_args_for_multi_region(args, ALL_REGIONS)
        return self.create_pool(self._create_cloud_watch_rule_from_meta,
                                new_region_args)

    @unpack_kwargs
    def _create_cloud_watch_rule_from_meta(self, name, meta, region):
        validate_cloud_watch_rule_params(name=name, meta=meta)
        rule_type = meta['rule_type']
        event_buses = meta.get('event_bus_accounts')
        response = self._cw_events_conn_builder(region).get_rule(name)
        if response:
            _LOG.warn('%s rule exists in %s.', name, region)
            return self.describe_rule(name=name, meta=meta, region=region,
                                      response=response)
        try:
            func = RULE_TYPES[rule_type]
            func(name, meta, self._cw_events_conn_builder(region))
            if event_buses:
                time.sleep(5)
                self._attach_tenant_rule_targets(name, region, event_buses)
            _LOG.info('Created an event rule %s in %s.', name, region)
            response = self._cw_events_conn_builder(region).get_rule(name)
            time.sleep(5)
            return self.describe_rule(name=name, meta=meta, region=region,
                                      response=response)
        except KeyError:
            raise AssertionError(
                'Invalid rule type: {0} for resource {1}. '
                'Please, change rule type with existing: '
                'schedule|ec2|api_call.'.format(rule_type, name))

    def _attach_tenant_rule_targets(self, rule_name, region, event_buses):
        for event_bus in event_buses:
            target_arn = get_event_bus_arn(event_bus=event_bus,
                                           region=region)
            existing_targets = self._cw_events_conn_builder(
                region).list_targets_by_rule(
                rule_name=rule_name)
            for target in existing_targets:
                if target[ARN_KEY] == target_arn:
                    _LOG.debug('Target to event bus %s is already attached',
                               target_arn)
                    return
            self._cw_events_conn_builder(region).add_rule_target(
                rule_name=rule_name,
                target_arn=target_arn)

    def _handle_deactivation_for_cw_resources(self, cw_conn, region,
                                              rule_name):
        targets = cw_conn.list_targets_by_rule(rule_name)
        home_eb_arn = f'arn:aws:events:' \
                      f'{region}:{self.account_id}:event-bus/default'
        _LOG.debug('Home account event bus arn: %s', home_eb_arn)
        for target in targets:
            resource_arn = target[ARN_KEY]
            if resource_arn == home_eb_arn:
                cw_conn.remove_targets(rule_name, [target['Id']])
                _LOG.debug('Target %s removed', resource_arn)
        targets = cw_conn.list_targets_by_rule(rule_name)
        if targets:
            _LOG.debug('Will not remove rule, targets attached')
        else:
            _LOG.debug('Going to remove rule %s', rule_name)
            cw_conn.remove_rule(rule_name)
            _LOG.debug('Rule %s removed', rule_name)

    def remove_cloud_watch_rules(self, args):
        self.create_pool(self._remove_cloud_watch_rule, args)

    @unpack_kwargs
    def _remove_cloud_watch_rule(self, arn, config):
        region = arn.split(':')[3]
        resource_name = config['resource_name']
        try:
            self._cw_events_conn_builder(region).remove_rule(resource_name)
            _LOG.info('Rule %s was removed', resource_name)
        except ClientError as e:
            exception_type = e.response['Error']['Code']
            if exception_type == 'ResourceNotFoundException':
                _LOG.warn('Rule %s is not found', resource_name)
            else:
                raise e


import pathlib
import parse

def parse_input(puzzle_input):
    '''take the puzzle input data and convert it into usable data'''
    fish_dictionary = {}
    for x in range(-1, 9):
        fish_dictionary[x] = 0
    fish_list = list(map(int, puzzle_input.split(',')))

    for fish in fish_list:
        if fish in fish_dictionary:
            fish_dictionary[fish] += 1

    return fish_dictionary

def part1(puzzle_data):
    '''solve part 1 and return answer'''
    duration = 80
    for _ in range(duration):
        for x in range(0, 9):
            puzzle_data[x - 1] = puzzle_data[x]
        puzzle_data[8] = puzzle_data[-1]
        puzzle_data[6] += puzzle_data[-1]
        puzzle_data[-1] = 0
    return sum(puzzle_data.values())

def part2(puzzle_data):
    '''solve part 2 and return answer'''
    duration = 256
    for _ in range(duration):
        for x in range(0, 9):
            puzzle_data[x - 1] = puzzle_data[x]
        puzzle_data[8] = puzzle_data[-1]
        puzzle_data[6] += puzzle_data[-1]
        puzzle_data[-1] = 0
    return sum(puzzle_data.values())

def solve(puzzle_input):
    """Solve the puzzle for the given input"""
    data = parse_input(puzzle_input)
    solution1 = part1(parse_input(puzzle_input))
    solution2 = part2(parse_input(puzzle_input))
    return data, solution1, solution2

if __name__ == '__main__':
    PUZZLE_DIR = pathlib.Path(__file__).parent
    puzzle_input = (PUZZLE_DIR / "input.txt").read_text().strip()
    data, solution1, solution2 = solve(puzzle_input)
    print(solution1)
    print(solution2)


import scrapy

class HouseSpider(scrapy.Spider):
    name = "HouseSpider"

    def start_requests(self):
        urls = [
            'https://www.rent.com/texas/dallas-apartments/the-wilson-reviews-5-4929771',
            # 'https://www.rent.com/texas/dallas-apartments/the-wilson-4-4929771',
            # 'https://www.rent.com/alabama/alabaster-apartments/the-view-apartment-homes-4-100017784',
            # 'https://www.rent.com/texas/texas-city-apartments',
            # 'https://www.rent.com/texas/texas-city-houses',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # print('response', response.css('._348mM._3UPGk').get())

        # for item in response.css('._348mM._3UPGk'):

        #     PRICE_SELECTOR_CSS = 'div._3csYd.Kv8CE._1_8Hm'
        #     PRICE_SELECTOR_XPATH = './/span/text()'
        #     item_price = item.css(PRICE_SELECTOR_CSS).xpath(PRICE_SELECTOR_XPATH).extract_first()

        #     yield {
        #         'price': item_price,
        #     }

        # NEXT_PAGE_SELECTOR = '._qkIB a::attr(href)'
        # next_page = response.css(NEXT_PAGE_SELECTOR).extract_first()
        # print('next page', next_page)
        # if next_page:
        #     yield scrapy.Request(
        #         response.urljoin(next_page),
        #         callback = self.parse
        #     )
        filename = 'quotes-reviews-house-item.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)


import os
import time
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from config import BASE_URL, LOGIN_URL, BASE_DIR, CHROMEDRIVER_PATH

def get_driver():
    try:
        chrome_options = Options()
        chrome_options.debugger_address = "127.0.0.1:9222"
        # chrome_options.add_argument('--headless')
        # chrome_options.add_argument('--disable-gpu')
        service = Service(CHROMEDRIVER_PATH)
        driver = webdriver.Chrome(service=service, options=chrome_options)
        driver.set_page_load_timeout(60)
        time.sleep(1)
        return driver
    except:
        raise Exception("启动Chrome失败!")

def retrive_cookie(cookies):
    d = {}
    for c in cookies:
        d[c['name']] = c['value']
    res = f"_ga={d['_ga']}; _gid={d['_gid']}; fetchRankedUpdate={d['fetchRankedUpdate']}; x-jike-access-token={d['x-jike-access-token']}; x-jike-refresh-token={d['x-jike-refresh-token']}"
    return res

def save_cookie(cookie):
    filePath = os.path.join(BASE_DIR, 'COOKIE')
    with open(filePath, "w") as f:
        f.write(cookie)

def login(driver):
    driver.get(LOGIN_URL)
    mobile = input(">> mobile:")
    driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[2]/input[1]").send_keys(
        mobile)  # 输入手机号
    driver.find_element(By.XPATH,
                        "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[3]/div[1]/button[1]").click()  # 发送验证码
    verify_code = input(">> verify_code:")
    driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[3]/input[1]").send_keys(
        verify_code)  # 填写验证码
    driver.find_element(
        By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[4]/label[1]/div[1]/*[name()='svg'][2]"
    ).click()  # 勾选同意《用户协议》
    driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/div[1]/button[1]").click()  # 点击登录
    time.sleep(2)

def init_cookie():
    driver = get_driver()
    do_login = input(">> 是否重新登录? (y / N)\n")
    if do_login == 'Y' or do_login == 'y':
        login(driver)
    driver.get(BASE_URL)
    time.sleep(2)
    cookie = retrive_cookie(driver.get_cookies())
    if cookie is None:
        print("No cookie found.")
        return
    print(cookie)
    save_cookie(cookie)

if __name__ == "__main__":
    init_cookie()


import pyPamtra
import numpy as np

reload(pyPamtra)

pam = pyPamtra.pyPamtra()

pam.df.addHydrometeor(("ice", -99., -1, 917., 130., 3.0, 0.684, 2., 3, 1, "mono_cosmo_ice", -99., -99., -99., -99., -99., -99., "mie-sphere", "heymsfield10_particles",0.0))

pam = pyPamtra.importer.createUsStandardProfile(pam,hgt_lev=[100,200,300])

pam.set["verbose"] = 3
#pam.set["pyVerbose"] = 3
#pam.nmlSet['ground_type'] = 'F'
pam.p['sfc_type'][:] = 0.
pam.p['groundtemp'][:] = 277.
#pam.p['wind10u'][:] = np.sqrt(25.)
#pam.p['wind10v'][:] = np.sqrt(24.)

pam.runPamtra(35)

plt.figure()
pyPamtra.plot.plotTB(pam,levels=[1,400])


from django.db import models
import core.personality as p

# Create your models here.
class Note(models.Model):
    body = models.TextField()
    created_at = models.DateTimeField(auto_now=True)
    personality = models.TextField()

#   A string representation of just the body of the Note object
    def __str__(self):
        return self.body

#   My official representation of the object with body and personality
    def __repr__(self):
        return " Text: {}, HELLO: {}".format(self.body, self.personality)

#   Gets the description of the personality type of the Note object
    def get_description(self):
        mb = self.personality
        mbti = {'INTJ': ('Architect: Imaginative and strategic thinkers, ' +
                         'with a plan for everything'),
                'INTP': ('Logician: Innovative inventors with an ' +
                         'unquenchable thirst for knowledge'),
                'ENTJ': ('Commander: Bold, imaginative and strong-willed ' +
                         'leaders, always finding a way – or making one'),
                'ENTP': ('Debater: Smart and curious thinkers who cannot ' +
                         'resist an intellectual challenge'),
                'INFJ': ('Advocate: Quiet and Mystical, yet very inspiring ' +
                         'and tireless idealists'),
                'INFP': ('Mediator: Poetic, kind, altruistic. Always eager' +
                         'to help a good cause'),
                'ENFJ': ('Protagonist: Charismatic and inspiring leaders, ' +
                         'able to mesmerize their listeners'),
                'ENFP': ('Campaigner: Enthusiastic, creative, and sociable' +
                         ' free spirits; can always find a reason to smile'),
                'ISTJ': ('Logistician: Practical and fact-minded individuals' +
                         ' whose reliability cannot be doubted'),
                'ISFJ': ('Defender: Very dedicated and warm protectors, ' +
                         'always ready to defend their loved ones'),
                'ESTJ': ('Executive: Excellent administrators, unsurpassed ' +
                         'at managing things or people'),
                'ESFJ': ('Consul: Extraordinarily caring, social and popular' +
                         ' people, always eager to help'),
                'ISTP': ('Bold and practical experimenters, masters of all ' +
                         'kinds of tools'),
                'ISFP': ('Adventurer: Flexible and charming artists, always ' +
                         ' ready to explore and experience something new'),
                'ESTP': ('Entreprenuer: Smart, energetic and very perceptive' +
                         ' people, who truly enjoy living on the edge'),
                'ESFP': ('Entertainer: Spontaneous, energetic and enthusiastic'
                         + ' people – life is never boring around them.')}
        return mbti.get(mb)


while True:
    s=input()
    if s=='EOI': break
    s=s.lower()

    flag = False
    for i in range(len(s)):
        if s[i: i+4] =='nemo':
            flag = True
            break
    if flag==True: print("Found")
    else: print("Missing")


##################################################
# postfix_eval_typed
##################################################
def postfix_eval_typed(chaine, result_type):
    """
    a postfix evaluator, using a parametric type
    that can be either `int`, `float` or `Fraction` or similars
    """
    operators = {
        '+': lambda x, y: x+y,
        '-': lambda x, y: x-y,
        '*': lambda x, y: x*y,
        '/': lambda x, y: x//y if issubclass(result_type, int) else x/y,
    }

    stack = []
    for token in chaine.split():
        if token in operators:
            # compute operation on last 2 entries
            try:
                rhs = stack.pop()
                lhs = stack.pop()
            except:
                return "error-empty-stack"
            result = operators[token](lhs, rhs)
            stack.append(result)
        else:
            try:
                stack.append(result_type(token))
            except:
                return 'error-syntax'
            # parse as int and stack up
    if len(stack) != 1:
        return 'error-unfinished'
    return stack.pop()


import pandas as pd
from Bio import SeqIO
import argparse
import numpy as np

parser= argparse.ArgumentParser(add_help=False)
parser.add_argument("-h", "--help", action="help", default=argparse.SUPPRESS, help= "Given a path_matching pattern, get reads and subgaf for it")
parser.add_argument("-g", help= "-g: gaf file output of Graphaligner", required = "True")
parser.add_argument("-p", help= "-p: pattern to search on patch_matching field", required = "True")
args = parser.parse_args()
m_names=('queryname','query_length','query_start','query_end','strand', 'path_matching','path_length','path_start','path_end', 'residue_matches', 'alignm_length', 'mapping_qual', 'other1', 'other2', 'other3', 'identity', 'other4')
mytypes={'mapping_qual':'Int64'}
df4=pd.read_csv(args.g, names=m_names,  sep="\t", dtype=mytypes)
df5=df4[df4['path_matching' ]== args.p]
df5.to_csv("{}_filtered.gaf".format(args.p), index=False, sep="\t")
df5[['queryname']].to_csv("{}_filtered.reads.id".format(args.p), index=False, sep="\t", header=None)


import tensorflow as tf

# 使用和保存模型代码中一样的方式来声明变量
v1 = tf.Variable(tf.constant(1.0, shape=[1]), name='v1')
v2 = tf.Variable(tf.constant(2.0, shape=[1]), name='v2')
result = v1 + v2

# 声明tf.train.Saver类用于保存模型
saver = tf.train.Saver()

'''
参数 初始化
'''
with tf.Session() as sess:
    # 加载已经保存的模型，并通过已经保存的模型中变量的值来计算加法
    saver.restore(sess, "Saved_model/model.ckpt")
    print(sess.run(result))


# -*- coding: utf-8 -*-
"""
CODE CHALLENGE

Q1. (Create a program that fulfills the following specification.)
mushrooms.csv

Import mushrooms.csv file

This dataset includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family Mushroom drawn from The Audubon Society Field Guide to North American Mushrooms (1981). Each species is identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended. This latter class was combined with the poisonous one.

Attribute Information:

classes: edible=e, poisonous=p (outcome)

cap-shape: bell=b,conical=c,convex=x,flat=f, knobbed=k,sunken=s

cap-surface: fibrous=f,grooves=g,scaly=y,smooth=s

cap-color: brown=n, buff=b,cinnamon=c,gray=g,green=r,pink=p,purple=u,red=e,white=w,yellow=y

bruises: bruises=t, no=f

odor: almond=a,anise=l,creosote=c,fishy=y,foul=f,musty=m,none=n,pungent=p,spicy=s

gill-attachment: attached=a,descending=d,free=f,notched=n

gill-spacing: close=c,crowded=w,distant=d

gill-size: broad=b,narrow=n

gill-color: black=k,brown=n,buff=b,chocolate=h,gray=g,

green=r,orange=o,pink=p,purple=u,red=e,white=w,yellow=y

stalk-shape: enlarging=e,tapering=t

stalk-root: bulbous=b,club=c,cup=u,equal=e,rhizomorphs=z,rooted=r,missing=?

stalk-surface-above-ring: fibrous=f,scaly=y,silky=k,smooth=s

stalk-surface-below-ring: fibrous=f,scaly=y,silky=k,smooth=s

stalk-color-above-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o,pink=p,red=e,white=w,yellow=y

stalk-color-below-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o,pink=p,red=e,white=w,yellow=y

veil-type: partial=p,universal=u

veil-color: brown=n,orange=o,white=w,yellow=y

ring-number: none=n,one=o,two=t

ring-type: cobwebby=c,evanescent=e,flaring=f,large=l,none=n,pendant=p,sheathing=s,zone=z

spore-print-color: black=k,brown=n,buff=b,chocolate=h,green=r,orange=o,purple=u,white=w,yellow=y

population: abundant=a,clustered=c,numerous=n,scattered=s,several=v,solitary=y

habitat: grasses=g,leaves=l,meadows=m,paths=p,urban=u,waste=w,woods=d

Perform Classification on the given dataset to predict if the mushroom is edible or poisonous w.r.t. it’s different attributes.
(you can perform on habitat, population and odor as the predictors)
Check accuracy of the model.

"""

""" KNN is a type of Classification Supervised ML Algo. It predict as per the
according the surrounding data points where no. of data points is referred by
k. It is lazy execution meaning that at the time of execution, it fits and
predicts """

""" Importing time module to check the exceution time of both KNN and Logistic
Regression on this code challenge """
import time
start = time.time()

# kNN Algorithm - k nearest neighbour algorithm
# Importing the preprocessing modules
import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt

# Sklearn modules
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix

# Importing the contextlib for exception handling
import contextlib

with contextlib.suppress((AttributeError, TypeError)):
    # Loading the dataset
    mushroom_data = pd.read_csv("mushrooms.csv")

    # Replacing the label data with 0 and 1 means Binary classification
    mushroom_data['class'] = mushroom_data['class'].replace(['p','e'],[0,1])

    # Splitting the features and labels
    features = mushroom_data.iloc[:, [22,21,5]].values
    labels = mushroom_data.iloc[:, 0].values

    # Preprocessing stage - applying Label Encoding and Onehot Encoding on
    # categorical features and avoiding dummy variable trap
    labelencoder1 = LabelEncoder()
    features[:, 0] = labelencoder1.fit_transform(features[:, 0])

    labelencoder2 = LabelEncoder()
    features[:, 1] = labelencoder1.fit_transform(features[:, 1])

    labelencoder3 = LabelEncoder()
    features[:, 2] = labelencoder1.fit_transform(features[:, 2])

    onehotencoder1 = OneHotEncoder(categorical_features= [0], sparse= False)
    features = onehotencoder1.fit_transform(features)
    features = features[:, 1:]

    onehotencoder2 = OneHotEncoder(categorical_features= [6], sparse= False)
    features = onehotencoder2.fit_transform(features)
    features = features[:, 1:]

    onehotencoder3 = OneHotEncoder(categorical_features= [11], sparse= False)
    features = onehotencoder3.fit_transform(features)
    features = features[:, 1:]

    """labelencoder = LabelEncoder()
    labels = labelencoder.fit_transform(labels)"""

    # Splitting the training and testing data

    features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.2, random_state=0)

    # training phase
    #log_classifier = LogisticRegression()
    #log_classifier.fit(features_train, labels_train)
    classifier = KNeighborsClassifier(n_neighbors = 5, p = 2)
    classifier.fit(features_train, labels_train)

    # Testing phase
    labels_pred = classifier.predict(features_test)

    #labels_pred2 = log_classifier.predict(features_test)
    print("Train score:", classifier.score(features_test, labels_test))
    print("Test Score:", classifier.score(features_train, labels_train))

    # confusion matrix
    cm = confusion_matrix(labels_test, labels_pred)
    print("confusion matrix:", cm)

    #cm2 = confusion_matrix(labels_test, labels_pred2) # labels_test, labels_pred

# Checking the Exceution time
print(time.time() - start)

"""  confusion matrix -      predicted
                            no        yes
                           _________________
                          !       !         !
                     no   !     x ! o       !
 actual                   !_______!________ !
                          !       !         !
                     yes  !     0'!  x'     !
                          !_______!_________!

total = x+x'+o+0'
score = (x+x')/total
"""

Machine Learning programs/Supervised ML programs/Classification SML Programs/kNN classification/kNNclassification.py


import logging

from zero_3rdparty.error import (
    BaseError,
    Code,
    KwargsError,
    is_crash,
    is_error,
    is_ok,
    is_timeout,
)

logger = logging.getLogger(__name__)

class MyError(KwargsError):
    pass

def test_kwargs_exception_str():
    error = MyError(dummy=True, error="test_error", number=3)
    assert str(error) == "MyError(dummy=True,error='test_error',number=3)"
    assert error.dummy
    assert error.error == "test_error"
    assert error.number == 3
    assert error.number == 3
    assert is_crash(error)
    assert not is_error(error)
    assert not is_ok(error)
    assert not is_timeout(error)

class MyBaseError(BaseError):
    def __init__(self, name: str):
        self.name = name

def test_base_error():
    error = MyBaseError("ok")
    error.code = Code.OK
    assert is_ok(error)
    assert is_ok(Code.OK)
    error.code = Code.TIMEOUT
    assert is_timeout(error)
    assert is_timeout(Code.TIMEOUT)
    error.code = Code.INVALID_ARGUMENT
    assert is_error(error)
    assert is_error(Code.INVALID_ARGUMENT)


from unittest import TestCase
from pyspark.sql import SparkSession
from lib.utils import load_df, df_aggregation

# define a class per each unit test
class UtilsTestCase(TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.spark: SparkSession = (
            SparkSession.builder.master("local[3]").appName("SparkTest").getOrCreate()
        )

        return super().setUpClass()

    @classmethod
    def tearDownClass(cls) -> None:
        cls.spark.stop()

    def test_datafile_loading(self) -> None:
        sample_df = load_df(self.spark, data_conf={"path": "data/sample.csv"})
        result_count = sample_df.count()
        self.assertEqual(result_count, 9, "Record count should be 9")

    def test_country_count(self):
        sample_df = load_df(self.spark, data_conf={"path": "data/sample.csv"})
        country_list = df_aggregation(sample_df).collect()
        country_dict = {}

        for row in country_list:
            country_dict[row["Country"]] = row["count"]

        self.assertEqual(country_dict["Canada"], 2, "Count for canada should be 2")
        self.assertEqual(
            country_dict["United States"], 4, "Count for united state should be 4"
        )
        self.assertEqual(
            country_dict["United Kingdom"], 1, "Count for united kingdom should be 1"
        )


from max6675 import MAX6675
from machine import Pin
import time

so = Pin(12, Pin.IN)
sck = Pin(14, Pin.OUT)
cs = Pin(16, Pin.OUT)

max = MAX6675(sck, cs , so)

for _ in range(10):
    print(max.read())
    time.sleep(1)


class WordDictionary:

    def __init__(self):
        self.dict={}

    def addWord(self, word: str) -> None:
        if len(word) in self.dict:
            self.dict[len(word)].append(word)
            return
        self.dict[len(word)]=[word]

    def search(self, word: str) -> bool:
         if len(word) not in self.dict:
                return False
         if "." not in word:
            return word in self.dict[len(word)]
         for i in self.dict[len(word)]:
                count=len(word)
                for j in range(len(word)):
                    if word[j]!="." and word[j]!=i[j]:
                        count-=1
                        break
                if count==len(word):
                    return True
         return False

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)


import argparse
from logging import Logger, getLogger
from pathlib import Path
from typing import Set

from cp_problem_maker.problem import Problem
from cp_problem_maker.config import Config
from cp_problem_maker.compile import compile_solution, compile_generator, compile_verifier
from cp_problem_maker.testcase import GeneratorType, TestCase
from cp_problem_maker.subcommand import gen_params

logger: Logger = getLogger(__name__)

def add_parser(subparsers):
    parser_gen: argparse.ArgumentParser = subparsers.add_parser(
        "gen-case", description="generate testcases"
    )
    parser_gen.add_argument(
        "-p", "--path",
        type=str,
        default="."
    )
    parser_gen.add_argument(
        "--allow-replace",
        action="store_true"
    )

def run(path: Path, *, parents=False, exist_ok=False):
    gen_params.run(path, exist_ok=exist_ok)

    problem = Problem(path)
    config = Config(problem.config_file)

    compile_solution(problem.solution_file)
    compile_verifier(problem.verifier_file)

    unused_gen_files: Set[str] = set()
    for gen_file in problem.gen_folder.glob("*.cpp"):
        unused_gen_files.add(gen_file.name)
    unused_example_files: Set[str] = set()
    for gen_file in problem.gen_folder.glob("*.in"):
        unused_example_files.add(gen_file.stem)

    for testcase_config in config.testcase_config.values():
        name = testcase_config.name
        number = testcase_config.number
        generator_file = problem.gen_folder / Path(name)
        if GeneratorType.from_file(generator_file) == GeneratorType.CPP:
            compile_generator(generator_file)
        unused_gen_files.discard(name)
        for case_no in range(number):
            testcase = TestCase(generator_file, case_no)
            try:
                testcase.generate_input(
                    problem.in_folder,
                    parents=parents,
                    exist_ok=exist_ok
                )
                testcase.verify_input(
                    input_folder=problem.in_folder,
                    verifier_file=problem.verifier_file
                )
                testcase.generate_output(
                    input_folder=problem.in_folder,
                    output_folder=problem.out_folder,
                    solution_file=problem.solution_file,
                    config=config,
                    parents=parents,
                    exist_ok=exist_ok
                )
            except FileExistsError as e:
                logger.exception(e)
                logger.error(
                    "If you want to allow file replacement, give the '--allow-replace' flag."
                )
                exit(1)
            if testcase.generator_type == GeneratorType.EXAMPLE:
                unused_example_files.discard(testcase.case_name_with_no)

    for unused_gen_file in unused_gen_files:
        logger.warning(
            f'The configuration for "{unused_gen_file}" is missing and was not used to generate test cases. Check if the configuration is correct.'
        )
    for unused_example_file in unused_example_files:
        logger.warning(
            f'"{unused_example_file}" was not used as input. Check if the configuration is correct.'
        )


import re, csv, json, os
from pprint import pprint
from dateutil import parser
from rdflib import URIRef, Literal, Namespace, Graph
from rdflib.namespace import RDF, OWL, SKOS, DCTERMS, XSD, RDFS, FOAF

ELI = Namespace("http://data.europa.eu/eli/ontology#")
OIR = Namespace("http://oireachtas.ie/ontology#")
CEN = Namespace("http://www.metalex.eu/metalex/2008-05-02#")
FRBR= Namespace("http://purl.org/vocab/frbr/core#")
ORG = Namespace("http://www.w3.org/ns/org#")
DBO = Namespace("http://dbpedia.org/ontology/")
TIME = Namespace("http://www.w3.org/2006/time#")
DBP = Namespace("http://dbpedia.org/resource/")

oir = Namespace("http://oireachtas.ie/ie/oireachtas/")
eli = Namespace("http://oireachtas.ie/eli/ie/oir/")

DATADIR = "../data"

GRAPH_FILE = "../data/member.ttl"

def load_graph():
    g.parse(GRAPH_FILE)

def initialize_graph(g):
    #for initialzing new graphs
    g.bind("eli", ELI)
    g.bind("oir", OIR)
    g.bind("owl", OWL)
    g.bind("metalex", CEN)
    g.bind("frbr", FRBR)
    g.bind("foaf", FOAF)
    g.bind("skos", SKOS)
    g.bind("dcterms", DCTERMS)
    g.bind("org", ORG)
    g.bind("dbo", DBO)
    g.bind("time", TIME)

def house_triples(g):
    with open(os.path.join(DATADIR, "dail.json")) as f:
        dail = json.load(f)
    with open(os.path.join(DATADIR, "seanad.json")) as f:
        seanad = json.load(f)
    houses = seanad+dail
    for i, house in enumerate(houses):
        hnum = house['houseNum']
        uri = house["houseURI"][1:]
        g.add((oir[uri], RDF.type, OIR.HouseTerm))
        if uri.split("/")[-2] == "seanad":
            chamber = "seanad"
        else:
            chamber = "dail"
        if chamber == "seanad" and len(hnum) == 4:
            other_label = "First Seanad"
            g.add((oir[uri], SKOS.altLabel, Literal(other_label, lang="en")))
        g.add((oir[uri], OIR.termOf, oir[chamber]))
        g.add((oir[uri], RDFS.label, Literal(house['houseName'], lang="en")))
        end = house['end'] if type(house['end']) != float else None
        commenced = "{}/start/{}".format(uri, house['start'])
        g.add((oir[uri], OIR.start, oir[commenced]))
        g.add((oir[commenced], CEN.xsdDate, Literal(house['start'], datatype=XSD.date)))
        g.add((oir[commenced], RDF.type, OIR.EventDate))
        if hnum != "1" and hnum != "1922":
            if chamber == "seanad" and (len(hnum) == 4 or hnum == "2"):
                if hnum == "2":
                    pre = "1934"
                else:
                    pre = str(int(hnum) - 3)
            else:
                pre = str(int(hnum)-1)
            preceding = uri.replace(hnum, pre)
            g.add((oir[uri], OIR.precededBy, oir[preceding]))
            g.add((oir[preceding], OIR.succeededBy, oir[uri]))
            #print(uri, "=====", preceding)
        if chamber == "dail":
            cabURI = "cabinet/dail/{}".format(hnum)
            cabLabel = "Government of the "+house['houseName']
            cabAltLabel = "Cabinet of the "+house['houseName']
            cabStart = house['start']
            g.add((oir[cabURI], RDF.type, OIR.Cabinet))
            g.add((oir[cabURI], OIR.cabinetOf, oir[uri]))
            g.add((oir[cabURI], RDFS.label, Literal(cabLabel, lang="en")))
            g.add((oir[cabURI], SKOS.altLabel, Literal(cabAltLabel, lang="en")))
            cabCommenced = "{}/start/{}".format(cabURI, cabStart)
            g.add((oir[cabURI], OIR.start, oir[cabCommenced]))
            g.add((oir[cabCommenced], CEN.xsdDate, Literal(cabStart, datatype=XSD.date)))
            g.add((oir[cabCommenced], RDF.type, OIR.EventDate))
        if end:
            dissolved = "{}/end/{}".format(uri, end)
            g.add((oir[uri], OIR.end, oir[dissolved]))
            g.add((oir[dissolved], CEN.xsdDate, Literal(house['end'], datatype=XSD.date)))
            g.add((oir[dissolved], RDF.type, OIR.EventDate))
            if chamber == "dail" and i+1 < len(houses):
                cabEnd = houses[i+1]['start']
                cabEndURI = "{}/end/{}".format(cabURI, cabEnd)
                g.add((oir[cabURI], OIR.ended, oir[cabEndURI]))
                g.add((oir[cabEndURI], CEN.xsdDate, Literal(cabEnd, datatype=XSD.date)))
                g.add((oir[cabEndURI], RDF.type, OIR.EventDate))

def members_triples(g):
    with open(os.path.join(DATADIR, "members.json")) as f:
        members = json.load(f)
    for m in members:
        uri = m['eId'][1:]
        db = "http://dbpedia.org/resource/"+m['wikiTitle'].replace(" ", "_")
        g.add((oir[uri], RDF.type, OIR.Member))
        g.add((oir[uri], ORG.memberOf, OIR.Oireachtas))
        g.add((oir[uri], OWL.sameAs, URIRef(db)))
        g.add((oir[uri], FOAF.name, Literal(m['fullName'])))
        g.add((oir[uri], FOAF.firstName, Literal(m['firstName'])))
        g.add((oir[uri], FOAF.familyName, Literal(m['lastName'])))
        for d in ["date_of_birth", "date_of_death"]:
            if m.get(d):
                g.add((oir[uri], DBO[d], Literal(m[d], datatype=XSD.date)))
        if m.get("memberid"):
            mId = "members-hist/default.asp?housetype=&MemberID="+m['memberid']
            g.add((oir[uri], OIR.MemberId, oir[mId]))
        for t in ['profession', "details", "showAs", "pId"]:
            if m.get(t):
                g.add((oir[uri], OIR[t], Literal(m[t], lang="en")))

def service_triples(g):
    with open(os.path.join(DATADIR, "service.json")) as f:
        service = json.load(f)
    g.add((OIR.EventDate, RDFS.subClassOf, TIME.TemporalEntity))
    for s in service:
        eId = s['eId'][1:]

        house = s["houseURI"][1:]
        #serviceURI in json ends with dail.31 - turning that into dail/31
        service_uri = s['serviceURI'][1:].split("/")
        service_uri = "/".join(service_uri[:-1]+[service_uri[-1].replace(".", "/")])
        period = "{}/period".format(service_uri)
        if s['elected'] is not None:
            elected = "{}/elect/{}".format(service_uri, s['elected'])
        commenced = "{}/start/{}".format(service_uri, s['periodStart'])
        concluded = "{}/end/{}".format(service_uri, s['periodEnd']) if type(s['periodEnd']) != float else None

        if house.split("/")[-2] == "dail":
            title = "Deputy"
        else:
            title = "Senator"
        g.add((oir[eId], ORG.member, oir[service_uri]))
        g.add((oir[service_uri], RDF.type, ORG.Membership))
        g.add((oir[service_uri], ORG.role, OIR[title]))
        g.add((oir[service_uri], ORG.organisation, oir[house]))
        g.add((oir[service_uri], ORG.memberDuring, oir[period]))
        for c in s['constURI']:
            g.add((oir[service_uri], OIR.represent, oir[c]))
        g.add((oir[period], RDF.type, TIME.ProperInterval))
        if s['elected'] is not None:
            g.add((oir[period], OIR.elect, oir[elected]))
            g.add((oir[elected], RDF.type, OIR.EventDate))
            g.add((oir[elected], CEN.xsdDate, Literal(s['elected'], datatype=XSD.date)))
        g.add((oir[period], OIR.start, oir[commenced]))
        g.add((oir[commenced], CEN.xsdDate, Literal(s['periodStart'], datatype=XSD.date)))
        g.add((oir[commenced], RDF.type, OIR.EventDate))
        if concluded:
            g.add((oir[period], OIR.end, oir[concluded]))
            g.add((oir[concluded], RDF.type, OIR.EventDate))
            g.add((oir[concluded], CEN.xsdDate, Literal(s['periodEnd'], datatype=XSD.date)))

def government_member_triples(g):
    with open(os.path.join(DATADIR, "government_members.json")) as f:
            government_members = json.load(f)
    for s in government_members:
        eId = s['eId'][1:]
        role = "role"+s['uri']
        label = s['office']
        g.add((oir[role], RDF.type, OIR.Minister))
        g.add((oir[role], RDFS.label, Literal(label, lang="en")))
        if "functions" in s.keys():
            for function in s['functions']:
                function_label = function.replace("_", " ").title()
                function_uri = "minister/function/"+function
                g.add((oir[role], OIR.hasMinisterialFunction, oir[function_uri]))
                g.add((oir[function_uri], OIR.ministerialFunctionOf, oir[role] ))
                g.add((oir[function_uri], RDF.type, OIR.MinisterialFunction))
                g.add((oir[function_uri], RDFS.label, Literal(function_label, lang="en") ))
        for cab in s['cabinets']:
            try:
                cabinet = cab['cabinet'].split("oireachtas/")[1]
            except IndexError:
                cabinet = cab['cabinet'][1:]
            if cabinet[0] != "c":print(cabinet)
            cab_membership = eId + "/" + cabinet + s['uri']
            period = cab_membership + "/period"
            start = cab_membership + "/start/" + cab['start']
            g.add((oir[cab_membership], ORG.organisation, oir[cabinet]))
            g.add((oir[cab_membership], RDF.type, ORG.Membership))
            g.add((oir[cab_membership], ORG.role, oir[role]))

            g.add((oir[eId], ORG.member, oir[cab_membership]))

            g.add((oir[cab_membership], ORG.memberDuring, oir[period]))
            g.add((oir[period], RDF.type, TIME.ProperInterval))
            g.add((oir[period], OIR.start, oir[start]))
            g.add((oir[start], CEN.xsdDate, Literal(cab['start'], datatype=XSD.date)))
            g.add((oir[start], RDF.type, OIR.EventDate))
            if cab['end'] is not None:
                end = cab_membership + "/end/" + cab['end']
                g.add((oir[period], OIR.end, oir[end]))
                g.add((oir[end], CEN.xsdDate, Literal(cab['end'], datatype=XSD.date)))
                g.add((oir[end], RDF.type, OIR.EventDate))

def party_triples(g):
    with open(os.path.join(DATADIR, "parties.json")) as f:
            party_members = json.load(f)
    for p in party_members:
        member = p['member'][1:] if p['member'].startswith("/") else p['member']
        dbp = "http://dbpedia.org/resource/"+p['party']
        start = p['start']
        end = p['end']
        party_membership = "{}/{}".format(p['uri'], p['oir_party'])
        party_membership = party_membership[1:] if party_membership.startswith("/") else party_membership
        period = party_membership+"/period/"+start
        g.add((oir[member], ORG.member, oir[party_membership]))
        g.add((oir[party_membership], RDF.type, ORG.Membership))
        g.add((oir[party_membership], ORG.organisation, oir[p['oir_party']]))
        g.add((oir[p['oir_party']], RDFS.label, Literal(p['oir_party'].replace("_", " "), lang="en") ))
        g.add((oir[p['oir_party']], RDF.type, OIR.Party))
        g.add((oir[party_membership], URIRef("http://dbpedia.org/property/party"), URIRef(dbp)))
        g.add((oir[party_membership], ORG.memberDuring, oir[period]))
        g.add((oir[period], RDF.type, TIME.ProperInterval))
        g.add((oir[period], OIR.start, oir[start]))
        g.add((oir[start], CEN.xsdDate, Literal(p['start'], datatype=XSD.date)))
        g.add((oir[start], RDF.type, OIR.EventDate))
        if p['end'] is not None:
            end = party_membership + "/end/" + p['end']
            g.add((oir[period], OIR.end, oir[end]))
            g.add((oir[end], CEN.xsdDate, Literal(p['end'], datatype=XSD.date)))
            g.add((oir[end], RDF.type, OIR.EventDate))

def serialize_graph(g, file_name):
    g.serialize(destination=(os.path.join(DATADIR, file_name)), format="turtle")

def main():
    #initialize graph
    g= Graph()
    print("Graph Initialized")
    initialize_graph(g)
    house_triples(g)
    print("houses:", len(g))
    members_triples(g)
    print("members:", len(g))
    service_triples(g)
    print("service:", len(g))
    government_member_triples(g)
    print("cabinets:", len(g))
    party_triples(g)
    print("party triples:", len(g))
    #file_name = "parties.ttl"
    file_name = "oireachtas.ttl"
    serialize_graph(g, file_name)
    print("Graph serialized")

if __name__ == '__main__':
    main()


from typing import TypeVar, KeysView, Optional, List, Generic
import copy
from sympy import *
import math

K = TypeVar('K')

class Node(Generic[K]):
    """
    Adjacency list representation of a weighted graph node, implemented using a python dictionary
    """

    def __init__(self, vertex: int):
        self.index = vertex
        self.adjacent_dict = {}
        self.dijkstra_distance = None
        self.dijkstra_pred = None
        self.importance = None
        self.hierarchy = None
        self.binheap_index = None

    def __str__(self) -> str:
        return str(self.index) + ' adjacent: ' + str([x.index for x in self.adjacent_dict])

    def add_connected_node(self, connected_node: Generic[K], weight: K = 1) -> None:
        """
        Function which adds a node to the adjacency list of the node,
        with the corresponding weight of the edge

        Parameters
        ----------
        connected_node: index of the connected node
        weight: weight of the edge
        -------

        """
        if weight < 0:
            raise RuntimeError('Weights cannot be negative')

        else:
            self.adjacent_dict[connected_node] = weight

    def get_connections(self) -> KeysView:
        """
        Function which returns the indexes of the connected nodes

        Returns
        -------
        Keys of the adjacency list dictionary

        """
        return self.adjacent_dict.keys()

    def get_connections_indexes(self) -> List:
        """
        Function which returns the indexes of the connected nodes

        Returns:
        -------
        Keys of the adjacency list dictionary

        """
        return [x.index for x in self.adjacent_dict]

    def edge_weight(self, connected_node: Generic[K]) -> K:
        """
        Function which returns the weight of the edge to a specific node.

        Parameters
        ----------
        connected_node the connected node whose edge we are interested in

        Returns
        -------
        The weight of the edge
        """
        return self.adjacent_dict[connected_node]

    def set_distance(self, d: K) -> None:
        """
        Function which set the attribute dijkstra_distance to the distance of the node from the origin
        during an application of the dijkstra algorithm

        Parameters
        ----------
        d the distance calculated by the dijkstra algorithm
        -------

        """
        self.dijkstra_distance = d

    def set_pred(self, pred: int) -> None:
        """
        Function which set the attribute dijkstra_pred to the index of the precedent node found
        according to an application of the dijkstra algorithm

        Parameters
        ----------
        pred the index of the precedent node calculated by the dijkstra algorithm
        -------

        """
        self.dijkstra_pred = pred

    def set_importance(self, importance: K) -> None:
        """
        Function which set the attribute importance to the desired value calculated heuristically, it is used
        for the evaluation of the contraction hierarchies

        Parameters
        ----------
        importance importance of the node
        -------

        """
        self.importance = importance

class Graph(Generic[K]):
    """
    Adjacency list representation of a weighted graph,implemented using a python dictionary
    """

    def __init__(self, A: Optional[dict] = None):
        if A is None:
            self.length_graph = 0
            self.graph = {}
        elif isinstance(A, int):
            self.length_graph = 0
            self.graph = {A}
        else:
            self.length_graph = len(A)
            self.graph = A

    def __iter__(self):
        return iter(self.graph.values())

    def add_node(self, index: int) -> Generic[K]:
        """
        Function which add a new node with a given index to the graph

        Parameters
        ----------
        index index of the new node

        Returns
        -------
        The node
        """
        if index in self.graph:
            raise RuntimeError('Node with the same index already present')
        else:
            self.length_graph = self.length_graph + 1  # Increase the length of the graph
            new_node = Node(index)  # Create a node with the given index
            self.graph[index] = new_node  # Put the new node in the graph
            return new_node

    def get_node(self, index: int) -> Optional[Node]:
        """
        Function which returns a node in the graph.

        Parameters
        ----------
        index index of the node of interest

        Returns
        -------
        The node of interest

        """
        if index in self.graph:
            return self.graph[index]
        else:
            raise RuntimeError('Node not in the graph')

    def add_edge(self, start: int, end: int, weight: K = 0) -> None:
        """
        Function which create an edge between two nodes.

        Parameters
        ----------
        start: index of the starting node
        end: index of the ending node
        weight: weight of the edge
        -------

        """

        if start not in self.graph:
            raise RuntimeError('Starting node not in the graph')
        if end not in self.graph:
            raise RuntimeError('Ending node not in the graph')
        self.graph[start].add_connected_node(self.graph[end], weight)

    def get_nodes(self) -> KeysView:
        """
        Function which return a list of all the nodes in the graph

        Returns
        -------
        List of all the nodes in the graph.

        """
        return self.graph.keys()

    def get_nodes_list(self) -> List:
        """
        Function which returns a list of the index of all the nodes in the graph

        Returns
        -------
        List of all the nodes in the graph.
        """
        return list(self.graph.keys())

    def get_distances(self) -> List:
        """
        After an application of the Dijkstra algorithm, the function which returns a list of the distances
        of all nodes from the origin.
        """
        distances = [self.get_node(v).dijkstra_distance for v in self.graph]
        return distances

    def get_pred(self) -> List:
        """
        Function which return the list of the precedent node for all the nodes in the graph.
        """
        pred = [self.get_node(v).dijkstra_pred for v in self.graph]
        return pred

    @staticmethod
    def _get_path(end) -> List:
        """
        After an application of the Dijkstra algorithm, the function return the node path from the origin
        to the node given in input.

        Parameters
        ----------
        end Aimed node
        -------

        """
        path = [end]
        while end.dijkstra_pred is not None:
            path.append(end.dijkstra_pred)
            end = end.dijkstra_pred
        return path

    def copy(self):
        """
        Performs a deep copy of the graph

        Returns
        -------
        Deep copy of the graph

        """
        return copy.deepcopy(self)

    def remove_node(self, node: Generic[K]) -> None:
        """
        Function which removes a node creating shortcuts between the remaining ones.

        Parameters
        ----------
        node The node to remove
        -------

        """
        node = self.get_node(node)
        starting_nodes = [self.get_node(v) for v in self.graph if node in self.get_node(v).adjacent_dict]
        for n in starting_nodes:  # for all the nodes that points to the one to remove
            for m in node.adjacent_dict:  # for all the nodes the one to remove points to
                # if the nodes points at each other, or the
                # there already is a shorter path, skip the iteration
                if m == n or (m in n.adjacent_dict) and (n.edge_weight(m) < n.edge_weight(node) + node.edge_weight(m)):
                    continue
                else:
                    self.add_edge(n.index, m.index, n.edge_weight(node) + node.edge_weight(m))
            # Delete the node, and all its references in the adjacent_dict of all the others nodes
            del n.adjacent_dict[node]
        del self.graph[node.index]

    def just_node(self, index: int) -> None:
        """
        Function which removes from the graph all the nodes except the ones which shares an edge with the node given
        in input

        Parameters
        ----------
        index index of the input node
        -------

        """
        node = self.get_node(index)
        to_erase = []
        # Get all the node to pop
        for i in self.graph:
            if (self.get_node(i) != node) and (self.get_node(i) not in node.adjacent_dict) and (
                    node not in self.get_node(i).adjacent_dict):
                to_erase.append(i)
        # Pop all the useless edges
        for i in self.graph:
            edge_to_erase = []
            for j in self.get_node(i).adjacent_dict:
                if j.index in to_erase:
                    edge_to_erase.append(j.index)
            for j in edge_to_erase:
                self.get_node(i).adjacent_dict.pop(self.get_node(j), None)
        # Pop all the nodes
        for i in to_erase:
            self.graph.pop(i, None)

    @staticmethod
    def vertex_coord(nodes_number: int) -> List:
        """
        Function which, given a number of nodes as input, returns a list of pairs of coordinates to place them
        on the edge of a regular shape

        Parameters
        ----------
        nodes_number number of required nodes

        Returns
        -------
        List of coordinates pairs

        """
        return [(nodes_number * math.cos(2 * math.pi * i / nodes_number),
                 nodes_number * math.sin(2 * math.pi * i / nodes_number)) for i in range(nodes_number)]

    def plotter(self, mode: str = "standard", name: str = "graph", display: str = 'file') -> None:
        """
        Function which plot the graph as Latex image. It accept different kinds of input depending on the required plot.
        Because of the Latex compiling time limitation, the function might find some difficulties in rendering very
        large graphs, or very connected graph
        Parameters
        ----------
        mode Kind of plot required
        name Name to give to the output file
        display How the image is displayed. Choose None to automatically open the image at the end of the computation.
        -------

        """
        nodes_list = list(self.graph.keys())
        vertexes = self.vertex_coord(len(nodes_list))
        preamble = "\\RequirePackage{luatex85}\n" \
                   "\\documentclass{article} \n" \
                   "\\usepackage[paperwidth=5700mm, paperheight=5700mm, margin=0mm]{geometry} \n" \
                   "\\usepackage{tkz-graph}\n" \
                   "\\begin{document}\n" \
                   "\\thispagestyle{empty}"
        starting = "\\begin{figure}\n " \
                   "\\centering \n" \
                   "\\resizebox{4000mm}{!}{\n" \
                   "\\begin{tikzpicture} \n " \
                   "\\tikzstyle{EdgeStyle}=[pre] \n"

        if mode == "standard":
            text = self.show_graph(nodes_list, vertexes)
        elif mode == "dijkstra":
            text = self.show_dijkstra(nodes_list, vertexes)
        elif mode == "importance":
            text = self.show_importance(nodes_list, vertexes)
        elif mode == "path":
            end = input("Enter node index you want to reach: ")
            text = self.show_path(nodes_list, vertexes, int(end))
        else:
            raise RuntimeError(f'{mode} is not an available plot')

        ending = "\\end{tikzpicture}} \n" \
                 "\\end{figure}"
        formula = starting + text + ending
        preview(formula, output='pdf', viewer=display, filename=f'{name}.pdf', euler=False, preamble=preamble)

    def show_graph(self, nodes_list: List, vertexes: List) -> str:
        """
        Utility function to get the latex text to renders the graph into LaTeX image.

        Parameters
        ----------
        nodes_list List of nodes in the graph
        vertexes List of the coordinates of each node

        Returns
        -------
        Latex string

        """
        nodes = str()
        edges = str()
        for i in range(len(nodes_list)):
            nodes = nodes + f"\\Vertex[x={vertexes[i][0]},y={vertexes[i][1]}] { {nodes_list[i]} } \n"
            connections = self.graph[nodes_list[i]].get_connections_indexes()
            for j in connections:
                if j == nodes_list[i]:
                    edges = edges + f"\\Loop[dir=NO,dist=2cm,label=$" \
                                    f"{self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]({nodes_list[i]}) \n"
                else:
                    edges = edges + f"\\Edge[label=${self.graph[nodes_list[i]].edge_weight(self.graph[j])}$](" \
                                    f"{j})({nodes_list[i]}) \n"
        return nodes + edges

    def show_dijkstra(self, nodes_list: List, vertexes: List) -> str:
        """
        Utility function to get the latex text to renders the graph into LaTeX image,
        indicating for each node its dijkstra distance.

        Parameters
        ----------
        nodes_list List of nodes in the graph
        vertexes List of the coordinates of each node

        Returns
        -------
        Latex string

        """
        nodes = str()
        edges = str()
        for i in range(len(nodes_list)):
            nodes = nodes + f"\\Vertex[x={vertexes[i][0]},y={vertexes[i][1]}," \
                            f"L=${self.graph[nodes_list[i]].dijkstra_distance}$] { {nodes_list[i]} } \n"
            connections = self.graph[nodes_list[i]].get_connections_indexes()
            for j in connections:
                if j == nodes_list[i]:
                    edges = edges + f"\\Loop[dir=NO,dist=2cm,label=$" \
                                    f"{self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]({nodes_list[i]}) \n"
                else:
                    edges = edges + f"\\Edge[label=${self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]({j})" \
                                    f"({nodes_list[i]}) \n"
        return nodes + edges

    def show_path(self, nodes_list: List, vertexes: List, end: int) -> str:
        """
        Utility function to get the latex text to renders the graph into LaTeX image, showing in red in the graph
        the path to a node given in input (after an the dijkstra algorithm was applied). Requires an user input
        for the aimed node.

        Parameters
        ----------
        nodes_list List of nodes in the graph
        vertexes List of the coordinates of each node
        end index of the end-node of interest

        Returns
        -------
        Latex string
        """

        nodes = str()
        edges = str()
        path = self._get_path(self.get_node(end))  # Collect the path to the node
        path.reverse()
        for i in range(len(nodes_list)):  # For all the node in the graph
            nodes = nodes + f"\\Vertex[x={vertexes[i][0]},y={vertexes[i][1]}] { {nodes_list[i]} } \n"  # Add the nodes
            connections = self.graph[nodes_list[i]].get_connections_indexes()  # For all nodes, make a list of the edges
            for j in connections:  # For all the ending node of the edges of th node studied at the moment
                if j == nodes_list[i]:  # If the node end where it starts, make a loop
                    edges = edges + f"\\Loop[dir=NO,dist=2cm,label=$" \
                                    f"{self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]({nodes_list[i]}) \n"
                else:
                    if self.get_node(nodes_list[i]) in path and self.get_node(
                            j) in path:  # If the starting and ending node are both in path (they are surely subsiquent)
                        edges = edges + f"\\Edge[label=${self.graph[nodes_list[i]].edge_weight(self.graph[j])}$," \
                                        f" color=red]({j})({nodes_list[i]}) \n"
                        path.remove(self.get_node(nodes_list[i]))
                    else:
                        edges = edges + f"\\Edge[label=${self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]" \
                                        f"({j})({nodes_list[i]}) \n"
        return nodes + edges

    def show_importance(self, nodes_list: List, vertexes: List) -> str:
        """
        Utility function to get the latex text to renders the graph into LaTeX image,
        indicating for each node its importance.

        Parameters
        ----------
        nodes_list List of nodes in the graph
        vertexes List of the coordinates of each node

        Returns
        -------
        Latex string
        """
        nodes = str()
        edges = str()
        for i in range(len(nodes_list)):
            nodes = nodes + f"\\Vertex[x={vertexes[i][0]},y={vertexes[i][1]}," \
                            f"L=${self.graph[nodes_list[i]].importance}$] { {nodes_list[i]} } \n"
            connections = self.graph[nodes_list[i]].get_connections_indexes()
            for j in connections:
                if j == nodes_list[i]:
                    edges = edges + f"\\Loop[dir=NO,dist=2cm,label=$" \
                                    f"{self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]({nodes_list[i]}) \n"
                else:
                    edges = edges + f"\\Edge[label=${self.graph[nodes_list[i]].edge_weight(self.graph[j])}$]" \
                                    f"({j})({nodes_list[i]}) \n"
        return nodes + edges


import pygame

import random

images = ['images/rocketBackground.bmp', 'images/rocketBackground2.bmp']

class Rocket():
    """Класс для отображения ракеты."""

    def __init__(self, mfg_settings, screen):
        """Инициализация персонажа и присвоение ему начальной позиции"""
        self.screen = screen
        self.mfg_settings = mfg_settings
        self.image = pygame.image.load('images/rocketBackground.bmp')
        # Флаг для картинки
        self.switch = True
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # Начальная позиция
        self.rect.centerx = self.screen_rect.centerx
        self.rect.centery = self.screen_rect.centery
        self.centerx = float(self.rect.centerx)
        self.centery = float(self.rect.centery)
        # Флаги перемещения
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self):
        """Обновляет позицию ракеты с учетом флагов."""
        if (self.moving_left and self.rect.left > 0):
            self.centerx -= self.mfg_settings.rocket_speed
        if (self.moving_right and
            self.rect.right < self.screen_rect.right):
            self.centerx += self.mfg_settings.rocket_speed

        if (self.moving_up and self.rect.top > 0):
            self.centery -= self.mfg_settings.rocket_speed
        if (self.moving_down and
            self.rect.bottom < self.screen_rect.bottom):
            self.centery += self.mfg_settings.rocket_speed

        self.rect.centerx = self.centerx
        self.rect.centery = self.centery

    def print_rocket(self):
        """Выводит изображение ракеты."""
        self.screen.blit(self.image, self.rect)

    def switch_image(self):
        """Меняет картинку огня ракеты."""
        if self.switch:
            self.image = pygame.image.load(images[1])
            self.switch = False
        else:
            self.image = pygame.image.load(images[0])
            self.switch = True


"""
    解析系统配置文件: conf/*.ini
    注意：底层基础工具，禁止引入过多依赖
"""
import os
import json
import configparser

class ConfigUtil(object):
    @staticmethod
    def get_sys_path(py_file, sys_name=None):
        file_path = str(os.path.abspath(py_file))
        idx_sys_name = -1
        if sys_name and len(str(sys_name)) > 0:
            idx_sys_name = file_path.rfind(sys_name)

        idx_src = file_path.rfind("/src/")
        idx_tests = file_path.rfind("/tests/")

        if idx_sys_name > 0:
            sys_path = file_path[0:idx_sys_name + len(sys_name)]
        elif idx_src > 0:
            sys_path = file_path[0:idx_src]
        elif idx_tests > 0:
            sys_path = file_path[0:idx_tests]
        else:
            sys_path = "../"
        return sys_path

    @staticmethod
    def get_env(conf_file, conf_section="sys_info", conf_key="sys_env"):
        config_reader = ConfigReader.get_instance(conf_file)
        sys_env = config_reader.get(conf_section, conf_key)
        return sys_env

    @staticmethod
    def is_dev(conf_file, conf_section="sys_info", conf_key="sys_env"):
        # 判断是否为开发环境
        return "DEV" == ConfigUtil.get_env(conf_file, conf_section, conf_key)

    @staticmethod
    def is_test(conf_file, conf_section="sys_info", conf_key="sys_env"):
        # 判断是否为测试环境
        return "TEST" == ConfigUtil.get_env(conf_file, conf_section, conf_key)

    @staticmethod
    def is_prod(conf_file, conf_section="sys_info", conf_key="sys_env"):
        # 判断是否为生产环境
        return (ConfigUtil.get_env(conf_file, conf_section, conf_key)).startswith("PROD")

    @staticmethod
    def read_conf(conf_file):
        """
            读取配置文件
        :param conf_file: 配置文件
        :return: {
            section: {
                k1: v1,
                k2: v2,
            }
        }
        """
        if not os.path.exists(conf_file) or not os.path.isfile(conf_file):
            raise BaseException(">> [ConfigReader.read_conf] file not exist! {}".format(conf_file))
        conf_parse = configparser.ConfigParser()
        conf_parse.read(conf_file, "utf-8")

        conf_dict = {}
        conf_sections = conf_parse.sections()
        for section in conf_sections:
            section_dict = {}
            keys = conf_parse.options(section)
            for key in keys:
                section_dict[key] = conf_parse.get(section, key)
            conf_dict[section] = section_dict
        # end for
        return conf_dict

class ConfigReader(object):
    def __init__(self, conf_dict):
        self.conf_dict = conf_dict

    @staticmethod
    def get_instance(conf_file):
        conf_dict = ConfigUtil.read_conf(conf_file)
        instance = ConfigReader(conf_dict)
        return instance

    def get(self, section, key):
        result = ''
        if section in self.conf_dict:
            section_dict = self.conf_dict[section]
            if key in section_dict:
                result = section_dict[key]
        return result

    def get_int(self, section, key):
        result = 0
        if section in self.conf_dict:
            section_dict = self.conf_dict[section]
            if key in section_dict:
                result = int(section_dict[key])
        return result

    def get_float(self, section, key):
        result = 0
        if section in self.conf_dict:
            section_dict = self.conf_dict[section]
            if key in section_dict:
                result = float(section_dict[key])
        return result

    def get_dict(self, section, key):
        result = {}
        if section in self.conf_dict:
            section_dict = self.conf_dict[section]
            if key in section_dict:
                value = section_dict[key]
                result = json.loads(value)
        return result

    def get_section_dict(self, section):
        result = {}
        if section in self.conf_dict:
            result = self.conf_dict[section]
        return result

    def get_env(self, conf_section="sys_info", conf_key="sys_env"):
        sys_env = self.get(conf_section, conf_key)
        return sys_env

    def is_dev(self, conf_section="sys_info", conf_key="sys_env"):
        # 判断是否为开发环境
        return "DEV" == self.get_env(conf_section, conf_key)

    def is_test(self, conf_section="sys_info", conf_key="sys_env"):
        # 判断是否为测试环境
        return "TEST" == self.get_env(conf_section, conf_key)

    def is_prod(self, conf_section="sys_info", conf_key="sys_env"):
        # 判断是否为生产环境
        return (self.get_env(conf_section, conf_key)).startswith("PROD")

if "__main__" == __name__:
    # res = ConfigReader.read_conf("oversea_channel.ini")
    # print(res)
    pass


from . import config
from . import computations

def cmv_calculator(parameters, num_points, x, y):
    # Create an LIC judgement object.
    lic = computations.LaunchInterceptorConditions(parameters, num_points, x, y)

    # Iterate through all condition judgement functions in LICs.
    for function, i in zip(lic.function_list, range(15)):
        config.cmv[i] = function(lic)

def pum_calculator(cmv, lcm):
    # Calculate pum and assign it to config.
    for i in range(len(cmv)):
        for j in range(i):
            if i == j:  # diagonal element in pum
                config.pum[i][j] = cmv[i]
            elif lcm[i][j] == config.CONNECTORS[0]:  # If lcm[i][j] is "NOTUSED".
                config.pum[i][j] = config.pum[j][i] = True
            elif lcm[i][j] == config.CONNECTORS[1]:  # If lcm[i][j] is "ORR".
                config.pum[i][j] = config.pum[j][i] = cmv[i] or cmv[j]
            elif lcm[i][j] == config.CONNECTORS[2]:  # If lcm[i][j] is "ANDD".
                config.pum[i][j] = config.pum[j][i] = cmv[i] and cmv[j]
    return

def fuv_calculator(puv, pum):
    # Calculate fuv and assign it to config.fuv
    for i in range(len(config.fuv)):
        if not (puv[i]) or (all(pum[i][0:i]) and all(pum[i][i + 1:])):
            config.fuv[i] = True
    return

def decide(parameters=config.parameters, num_points=config.num_points,
           x=config.X, y=config.Y, lcm=config.lcm, puv=config.puv):
    # Decide whether to launch the nuclear bomb or not
    cmv_calculator(parameters, num_points, x, y)
    pum_calculator(config.cmv, lcm)
    fuv_calculator(puv, config.pum)
    config.launch = all(config.fuv)
    return "YES" if config.launch else "NO"


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

import gevent
import gevent.socket
import socket

from contextlib import (
    closing,
    contextmanager,
)
from datetime import timedelta

@contextmanager
def udpsocket(host='127.0.0.1', port=0):
    """Create, bind and automtically close a UDP socket."""
    s = gevent.socket.socket(
        socket.AF_INET,
        socket.SOCK_DGRAM,
        socket.IPPROTO_UDP,
    )
    with closing(s):
        s.bind((host, port))
        yield s

@contextmanager
def concurrently(function, *args, **kwds):
    """Create, schedule and automatically cancel and join a task."""
    task = gevent.spawn(function, *args, **kwds)
    try:
        yield task
    finally:
        task.kill()

def to_seconds(timeout):
    """Convert the timeout to seconds."""
    if isinstance(timeout, timedelta):
        timeout = timeout.total_seconds()
    return timeout

__all__ = (
    'concurrently',
    'udpsocket',
)