import os
import sys
import inspect

import numpy as np
from scipy import stats

# add the parent folder to working directory
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

import distributions
import discrepancy
import matplotlib.pyplot as plt
from matplotlib import rc
import utils_math
import utils_os

def real_KL(mu1,C1,cov1,mu2,C2,cov2):
    mu1, mu2 = np.mat(mu1), np.mat(mu2)
    C1, C2 = np.mat(C1), np.mat(C2)
    cov1, cov2 = np.mat(cov1), np.mat(cov2)

    [dim, dim] = cov1.shape

    det1 = np.linalg.det(C1)**2
    det2 = np.linalg.det(C2)**2
    inv2 = (C2.I).T*C2.I
    partA = np.log(det2/det1)
    partB = -dim
    partC = (inv2*cov1).trace()
    partD = (mu2-mu1)*inv2*(mu2-mu1).T
    kl = ((partA + partB + partC + partD)/2)[0,0]
    return kl

def validate_grid_based_JSD():

    dim = 3
    n_samples = 2000

    # pick the mean, cov for the 1st distribution
    mu1 = np.random.rand(1, dim)
    M = np.matrix(np.random.rand(dim, dim))
    M_tril = np.tril(M, k=-1)
    M_diag = np.matrix(np.diag(np.abs(np.diag(M))))
    C1 = M_tril + M_diag
    cov1 = np.array(C1 * C1.T)

    # samples from the first distribution
    mu1 = np.array(mu1).reshape(-1)
    X1 = distributions.normal_nd.draw_samples(mu1, cov1, n_samples)

    # pick the mean, cov for the 2nd distribution
    mu2 = np.random.rand(1, dim)
    M = np.matrix(np.random.rand(dim, dim))
    M_tril = np.tril(M, k=-1)
    M_diag = np.matrix(np.diag(np.abs(np.diag(M))))
    C2 = M_tril + M_diag
    cov2 = np.array(C2 * C2.T)

    # samples from the second distribution
    mu2 = np.array(mu2).reshape(-1)
    C2 = C1
    cov2 = cov1
    X2 = distributions.normal_nd.draw_samples(mu2, cov2, n_samples)

    def p(x):
        return distributions.normal_nd.pdf(x, mu1, cov1)
    def q(x):
        return distributions.normal_nd.pdf(x, mu2, cov2)

    # calculate the true-KL
    KL = real_KL(mu1,C1,cov1,mu2,C2,cov2)
    print('\n true KL=', KL)

    # calculate the KDE KL
    KL1 = discrepancy.KL(X1, X2)
    print('\n grid-KDE KL=', KL1)

    # calculate the grid-KL
    KL2 = discrepancy.KL2(p, q, X1, X2)
    print('\n grid KL=', KL2)

    # calculate the quasi-KL
    quasi_KL = discrepancy.quasi_KL(X1, X2)
    print('\n quasi-KL=', quasi_KL)

def two_sample_test():

    dim = 3
    n_samples = 1000

    # pick the mean, cov for the 1st distribution
    mu1 = np.random.rand(1, dim)
    M = np.matrix(np.random.rand(dim, dim))
    M_tril = np.tril(M, k=-1)
    M_diag = np.matrix(np.diag(np.abs(np.diag(M))))
    C1 = M_tril + M_diag
    cov1 = np.array(C1 * C1.T)

    mu1_fit, mu2_fit = None, None
    cov1_fit, cov2_fit = None, None
    def p(x):
        return distributions.normal_nd.pdf(x, mu1_fit, cov1_fit)

    def q(x):
        return distributions.normal_nd.pdf(x, mu2_fit, cov2_fit)

    # samples from the first distribution
    JSD_array = []
    mu1 = np.array(mu1).reshape(-1)
    for i in range(100):
        X1 = distributions.normal_nd.draw_samples(mu1, cov1, n_samples)
        X2 = distributions.normal_nd.draw_samples(mu1, cov1, n_samples)

        mu1_fit, cov1_fit = distributions.normal_nd.fit(X1)
        mu2_fit, cov2_fit = distributions.normal_nd.fit(X2)

        JSD = discrepancy.JSD2(p, q, X1, X2)
        JSD_array.append(JSD)
        print('\n JSD=', JSD)

    JSD_array.sort()
    print('\n')
    print('5% error = ', JSD_array[95])

#validate_grid_based_JSD()
two_sample_test()


"""Utility functions."""

__author__ = "730330844"

from csv import DictReader

def read_csv_rows(filename: str) -> list[dict[str, str]]:
    """Read the rows of a csv into a table."""
    result: list[dict[str, str]] = []
    file_handle = open(filename, "r", encoding="utf8")
    csv_reader = DictReader(file_handle)
    for row in csv_reader:
        result.append(row)
    file_handle.close()
    return result

def column_values(table: list[dict[str, str]], column: str) -> list[str]:
    """Produce a list[str] of all vlaues in a single column."""
    result: list[str] = []
    for row in table:
        item: str = row[column]
        result.append(item)
    return result

def columnar(row_table: list[dict[str, str]]) -> dict[str, list[str]]:
    """Transform a row-oriented table to a column-oriended table."""
    result: dict[str, list[str]] = {}
    first_row: dict[str, str] = row_table[0]
    for column in first_row:
        result[column] = column_values(row_table, column)
    return result

def head(column_table: dict[str, list[str]], n: int) -> dict[str, list[str]]:
    """Produce a new column-based table with only the first N rows of data for each column."""
    result: dict[str, list[str]] = {}
 # 1. Establish an empty dictionary that will serve as the returned dictionary this function is building up.
    # 2. Loop through each of the columns in the first row of the table given as a parameter.
    #   A. Inside of the loop, establish an empty list to store each of the first N values in the column
    #   B. Loop through the first N items of the table's column,
    #       a. Appending each item to the previously list established in step 2.1.
    #   C. Assign the produced list of column values to the dictionary established in step 1.
    return result
    # Return the dictionary.

def select(column_table: dict[str, list[str]], names: list[str]) -> dict[str, list[str]]:
    """Produce a new column-based table with only a specific subset of the original columns"""
    result: dict[str, list[str]] = {}
    for item in names:
        result[item] = column_table[item]
    return result

def concat(column_table_one: dict[str, list[str]], column_table_two: dict[str, list[str]]) -> dict[str, list[str]]:
    """Purpose: Produce a new column-based table with two column-based tables combined."""
    result: dict[str, list[str]] = {}
    result = {**column_table_one, **column_table_two}
    for key, value in result.items():
        if key in column_table_one and key in column_table_two:
            result[key] = [value, column_table_one[key]]
    return result


#!/usr/bin/python
# Copyright (c) 2014, Red Hat, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the
#    distribution.
# 3. Neither the name of the Red Hat nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors:  Stanislav Ochotnicky <sochotnicky@redhat.com>
#           Michal Srb <msrb@redhat.com>

from __future__ import print_function

import gzip
import logging
import os.path
import xml
import pickle

from javapackages.metadata.artifact import MetadataArtifact
from javapackages.metadata.dependency import MetadataDependency
from javapackages.metadata.skippedartifact import MetadataSkippedArtifact
from javapackages.metadata.exclusion import MetadataExclusion
import javapackages.common.config as config
import javapackages.metadata.pyxbmetadata as m

import pyxb

class MetadataLoadingException(Exception):
    pass

class MetadataInvalidException(Exception):
    pass

class Metadata(object):

    def __init__(self, path):
        if type(path) == list:
            self.__paths = path
        else:
            self.__paths = [path]
        self.__metadata = []
        for p in self.__paths:
            try:
                self.__load_metadata(p)
            except (pyxb.UnrecognizedContentError,
                    pyxb.UnrecognizedDOMRootNodeError,
                    xml.sax.SAXParseException) as e:
                logging.warning("Failed to parse metadata {path}: {e}"
                                .format(path=path,
                                        e=e))
        if len(self.__metadata) == 0:
            raise MetadataInvalidException("None of metadata paths could be parsed")

    def __load_metadata(self, metadata_path):
        with open(metadata_path, 'rb') as f:
            try:
                gzf = gzip.GzipFile(os.path.basename(metadata_path),
                                    'rb',
                                    fileobj=f)
                data = gzf.read()
            except IOError:
                # not a compressed metadata, just rewind and read the data
                f.seek(0)
                data = f.read()

            self.__metadata.append(m.CreateFromDocument(data))

    def get_provided_artifacts(self):
        """Returns list of Artifact provided by given metadata."""

        artifacts = []
        for metadata in self.__metadata:
            if metadata.artifacts and metadata.artifacts.artifact:
                for a in metadata.artifacts.artifact:
                    artifact = MetadataArtifact.from_metadata(a)
                    if not artifact.version:
                        raise MetadataInvalidException("Artifact {a} does not have version in maven provides".format(a=artifact))
                    artifacts.append(artifact)
        return artifacts

    def get_required_artifacts(self):
        """Returns list of Artifact required by given metadata."""
        artifacts = set()
        for metadata in self.__metadata:
            for a in metadata.artifacts.artifact:
                if not a.dependencies:
                    continue

                for dep in a.dependencies.dependency:
                    artifacts.add(MetadataDependency.from_metadata(dep))

        return list(artifacts)

    def get_skipped_artifacts(self):
        """Returns list of Artifact that were build but not installed"""
        artifacts = set()
        for metadata in self.__metadata:
            if not metadata.skippedArtifacts:
                continue
            for dep in metadata.skippedArtifacts.skippedArtifact:
                artifact = MetadataSkippedArtifact.from_metadata(dep)
                artifacts.add(artifact)
        return list(artifacts)

    def get_excluded_artifacts(self):
        """Returns list of Artifacts that should be skipped for requires"""
        artifacts = set()
        for metadata in self.__metadata:
            for a in metadata.artifacts.artifact:
                if not a.dependencies:
                    continue

                for dep in a.dependencies.dependency:
                    if not dep.exclusions:
                        continue

                    for exclusion in dep.exclusions.exclusion:
                        artifact = MetadataExclusion.from_metadata(exclusion)
                artifacts.add(artifact)
        return list(artifacts)

    def get_java_requires(self):
        """Returns JVM version required by metadata or None"""
        for metadata in self.__metadata:
            if not metadata.properties:
                return None
            for prop in metadata.properties.wildcardElements():
                if prop.tagName == u'requiresJava':
                    return prop.firstChild.value
        return None

    def get_java_devel_requires(self):
        """Returns JVM development version required by metadata or None"""
        for metadata in self.__metadata:
            if not metadata.properties:
                return None
            for prop in metadata.properties.wildcardElements():
                if prop.tagName == u'requiresJavaDevel':
                    return prop.firstChild.value
        return None

    def get_osgi_provides(self):
        provs = {}
        for metadata in self.__metadata:
            if metadata.artifacts and metadata.artifacts.artifact:
                for a in metadata.artifacts.artifact:
                    artifact = MetadataArtifact.from_metadata(a)
                    if artifact.properties:
                        try:
                            osgi_id = artifact.properties["osgi.id"]
                            version = artifact.properties["osgi.version"]
                            provs[osgi_id] = version
                            continue
                        except KeyError:
                            pass
                    if artifact.path:
                        import javapackages.common.osgi as osgi
                        p = osgi.get_provides(artifact.get_buildroot_path())
                        provs.update(p)
        return provs

    def get_osgi_requires(self):
        reqs = set()
        for metadata in self.__metadata:
            if metadata.artifacts and metadata.artifacts.artifact:
                for a in metadata.artifacts.artifact:
                    artifact = MetadataArtifact.from_metadata(a)
                    if artifact.properties:
                        try:
                            content = artifact.properties["osgi.requires"]
                            reqs |= set(content.split(','))
                            continue
                        except KeyError:
                            try:
                                osgi_id = artifact.properties["osgi.id"]
                                # this file was already processed by XMvn and
                                # there are no interesting OSGi requires, move on
                                continue
                            except KeyError:
                                pass
                    if artifact.path:
                        import javapackages.common.osgi as osgi
                        r = osgi.get_requires(artifact.get_buildroot_path())
                        reqs.update(r)
        return reqs

    def contains_only_poms(self):
        """Check if metadata file contains only POM file(s)"""
        for artifact in self.get_provided_artifacts():
            if artifact.extension != "pom":
                return False
        return True

    def write_provided_artifacts_to_cache(self, cachedir):
        cachefile = os.path.join(cachedir, config.prov_artifacts_cache_f)
        return self._write_cache_file(cachefile, self.get_provided_artifacts())

    @staticmethod
    def read_provided_artifacts_from_cache(cachedir):
        cachefile = os.path.join(cachedir, config.prov_artifacts_cache_f)
        return Metadata._read_cache_file(cachefile)

    def write_skipped_artifacts_to_cache(self, cachedir):
        cachefile = os.path.join(cachedir, config.skip_artifacts_cache_f)
        return self._write_cache_file(cachefile, self.get_skipped_artifacts())

    @staticmethod
    def read_skipped_artifacts_from_cache(cachedir):
        cachefile = os.path.join(cachedir, config.skip_artifacts_cache_f)
        return Metadata._read_cache_file(cachefile)

    def write_provided_osgi_to_cache(self, cachedir):
        cachefile = os.path.join(cachedir, config.prov_osgi_cache_f)
        return self._write_cache_file(cachefile, self.get_osgi_provides())

    @staticmethod
    def read_provided_osgi_from_cache(cachedir):
        cachefile = os.path.join(cachedir, config.prov_osgi_cache_f)
        return Metadata._read_cache_file(cachefile)

    def _write_cache_file(self, cachefile, content):
        try:
            cachefile = open(cachefile, 'wb')
            pickle.dump(content, cachefile)
            cachefile.close()
        except IOError:
            return None
        return content

    @staticmethod
    def _read_cache_file(cachefile):
        try:
            cachefile = open(cachefile, 'rb')
            content = pickle.load(cachefile)
            cachefile.close()
        except IOError:
            return None
        return content


# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import clearData,json,pymongo
"""
┏┓　　　┏┓
  ┏┛┻━━━┛┻┓
┃　　　　　　　┃
┃　　　━　　　┃
┃　┳┛　┗┳　┃
┃　　　　　　　┃
┃　　　┻　　　┃
┃　　　　　　　┃
┗━┓　　　┏━┛
┃　　　┃
┃　　　┃
┃　　　┗━━━┓
┃　　　　　　　┣┓
┃　　　　　　　┏┛
┗┓┓┏━┳┓┏┛
┃┫┫　┃┫┫
┗┻┛　┗┻┛
神兽保证代码没bug
"""
class data:

    def save_data_json(self,Dict,file_position='',way=''):

        '''
        将数据通过json的方式保存在txt中。
        :param Dict:以字典形式存放的数据
        :param file_position:如果不存在那么就是默认保存在file文件夹下面，否则是保存在其他路径下.
        :param way:以json格式进行保存
        :return:
        '''

        Dict = clearData.clear_dict_space(Dict)
        if way == '':
            way = 'a'
        f = open(file_position,way)
        Dict = json.dumps(Dict)
        f.write(Dict)
        f.write('\n')
        f.close()

    def save_data_mongodb(self,Dict,mongodbUrl,databaseName,collectionName):

        '''
        :param Dict:以字典形式存放的数据
        :param mongodbUrl:mongodb的地址
        :param databaseName:数据库的名字
        :param collectionName:集合的名字
        :return:
        '''

        Dict = clearData.clear_dict_space(Dict)
        client = pymongo.MongoClient(mongodbUrl)
        db = client[databaseName]
        posts = db[collectionName]
        posts.insert(Dict)
        client.close()


import sqlite3
import random
from PyQt5 import uic
from PyQt5.QtWidgets import QMainWindow, QLineEdit
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QPixmap
from ClickedLabel import ClickedLabel

class Game(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi("resources/ui/game.ui", self)
        self.setFixedSize(1280, 720)
        self.move(0, 0)

        self.userName = None

        self.setupUi()

        self.errors = 0
        self.mainMenu = None
        self.winWindow = None
        self.firstTime = True

        self.sec = 0
        self.timer = QTimer()
        self.setTime()
        self.timer.timeout.connect(self.counter)

        self.randomPic()
        self.makeAllOff()
        self.makeAllDefault()

        self.startButton.clicked.connect(self.start)
        self.stopButton.clicked.connect(self.stop)
        self.exitButton.clicked.connect(self.exit)

        for el in self.labels:
            el.clicked.connect(self.nothing)

    def setupUi(self):
        self.picPart_1 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_1, 0, 0, 1, 1)
        self.picPart_2 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_2, 0, 1, 1, 1)
        self.picPart_3 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_3, 0, 2, 1, 1)
        self.picPart_4 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_4, 0, 3, 1, 1)
        self.picPart_5 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_5, 1, 0, 1, 1)
        self.picPart_6 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_6, 1, 1, 1, 1)
        self.picPart_7 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_7, 1, 2, 1, 1)
        self.picPart_8 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_8, 1, 3, 1, 1)
        self.picPart_9 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_9, 2, 0, 1, 1)
        self.picPart_10 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_10, 2, 1, 1, 1)
        self.picPart_11 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_11, 2, 2, 1, 1)
        self.picPart_12 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_12, 2, 3, 1, 1)
        self.picPart_13 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_13, 3, 0, 1, 1)
        self.picPart_14 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_14, 3, 1, 1, 1)
        self.picPart_15 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_15, 3, 2, 1, 1)
        self.picPart_16 = ClickedLabel()
        self.gridLayout.addWidget(self.picPart_16, 3, 3, 1, 1)
        self.picPart_1.setName("1")
        self.picPart_2.setName("2")
        self.picPart_3.setName("3")
        self.picPart_4.setName("4")
        self.picPart_5.setName("5")
        self.picPart_6.setName("6")
        self.picPart_7.setName("7")
        self.picPart_8.setName("8")
        self.picPart_9.setName("9")
        self.picPart_10.setName("10")
        self.picPart_11.setName("11")
        self.picPart_12.setName("12")
        self.picPart_13.setName("13")
        self.picPart_14.setName("14")
        self.picPart_15.setName("15")
        self.picPart_16.setName("16")

        self.pics = ["resources/pics/auto1.jpeg", "resources/pics/auto2.jpeg", "resources/pics/auto3.jpeg", "resources/pics/auto4.jpeg",
                     "resources/pics/auto5.jpeg", "resources/pics/auto6.jpeg", "resources/pics/auto7.jpeg", "resources/pics/auto8.jpeg",
                     "resources/pics/auto1.jpeg", "resources/pics/auto2.jpeg", "resources/pics/auto3.jpeg", "resources/pics/auto4.jpeg",
                     "resources/pics/auto5.jpeg", "resources/pics/auto6.jpeg", "resources/pics/auto7.jpeg", "resources/pics/auto8.jpeg"]

        self.labels = [self.picPart_1, self.picPart_2, self.picPart_3, self.picPart_4,
                       self.picPart_5, self.picPart_6, self.picPart_7, self.picPart_8,
                       self.picPart_9, self.picPart_10, self.picPart_11, self.picPart_12,
                       self.picPart_13, self.picPart_14, self.picPart_15, self.picPart_16]

        for el in self.labels:
            el.hide()

    # сделал так, так как при setEnabled(False) виджеты окрашивются в серый, а замена на функцию nothing() это исправляет
    def reconnect(self, signal, newhandler=None, oldhandler=None):
        while True:
            try:
                if oldhandler is not None:
                    signal.disconnect(oldhandler)
                else:
                    signal.disconnect()
            except TypeError:
                break
        if newhandler is not None:
            signal.connect(newhandler)

    # пустая функция чтобы реализовать аналог setEnabled(False)
    def nothing(self):
        pass

    def addWinWindow(self, winWindow):
        self.winWindow = winWindow

    # перемешивание картинок
    def randomPic(self):
        random.shuffle(self.pics)

    # замена всех picLabel на работающую функцию
    def makeAllOn(self):
        for el in self.labels:
            self.reconnect(el.clicked, self.picClicked)

    # замена всех picLabel на пустую функцию
    def makeAllOff(self):
        for el in self.labels:
            self.reconnect(el.clicked, self.nothing)

    # замена всех картинок picLabel на дефолтную
    def makeAllDefault(self):
        for el in self.labels:
            el.setPixmap(QPixmap("resources/pics/default.jpeg"))

    # замена всех picLabel на их картинки
    def showAll(self):
        for el in self.labels:
            el.setPixmap(QPixmap(self.pics[int(el.getName()) - 1]))

    # проверка все ли картинки были найдены
    def checkAll(self):
        for el in self.labels:
            if not el.outOfGame:
                return False
        return True

    # показ 2 нажатых картинок и смена их на дефолтные
    def make2Default(self, el1, el2):
        def func():
            for el in self.labels:
                self.reconnect(el.clicked, self.picClicked)
                if el.outOfGame:
                    self.reconnect(el.clicked, self.nothing)
                    el.setPixmap(QPixmap("resources/pics/outofgame.jpeg"))
            if not el1.outOfGame:
                el1.setPixmap(QPixmap("resources/pics/default.jpeg"))
            if not el2.outOfGame:
                el2.setPixmap(QPixmap("resources/pics/default.jpeg"))
        return func

    # функция выполняется если нажата picLabel(картинка)
    def picClicked(self):
        sender = self.sender()
        if sender.wasClicked:
            return
        sender.wasClicked = True
        sender.setPixmap(QPixmap(self.pics[int(sender.getName()) - 1]))
        for el in self.labels:
            if sender == el:
                continue
            if el.wasClicked:
                if self.pics[int(sender.getName()) - 1] == self.pics[int(el.getName()) - 1]:
                    self.makeAllOff()
                    self.timerScreen = QTimer()
                    self.timerScreen.setSingleShot(True)
                    self.timerScreen.timeout.connect(
                        self.make2Default(el, sender))
                    self.timerScreen.start(1500)
                    sender.wasClicked = False
                    el.wasClicked = False
                    sender.outOfGame = True
                    el.outOfGame = True
                else:
                    self.makeAllOff()
                    self.timerScreen = QTimer()
                    self.timerScreen.setSingleShot(True)
                    self.timerScreen.timeout.connect(
                        self.make2Default(el, sender))
                    self.timerScreen.start(1500)
                    sender.wasClicked = False
                    el.wasClicked = False
                    self.errors += 1
                    self.wrongsNumber.display(self.errors)

        # если все пары были найдены
        if self.checkAll():
            self.userName = self.mainMenu.autorization.getUserName()
            self.winWindow.show()
            self.setEnabled(False)
            hour = self.sec / 3600
            minut = (self.sec % 3600) / 60
            sec = (self.sec % 3600) % 60
            self.winWindow.timeLabel.setText(
                "%02d:%02d:%02d" % (hour, minut, sec))
            self.winWindow.errorsLabel.setText(str(self.errors))

            db = sqlite3.connect('MemoryTrainingDB.db')
            sql = db.cursor()
            sql.execute(
                f"SELECT time FROM users WHERE login = '{self.userName}'")
            bestTime = sql.fetchone()
            bestTime = int(list(bestTime)[0])
            sql.execute(
                f"SELECT mistakes FROM users WHERE login = '{self.userName}'")
            bestErrors = sql.fetchone()
            bestErrors = int(list(bestErrors)[0])
            if 1000 - bestTime - bestErrors * 5 < 1000 - self.sec - self.errors * 5:
                sql.execute(
                    f"UPDATE users SET time = {self.sec} WHERE login = '{self.userName}'")
                db.commit()
                sql.execute(
                    f"UPDATE users SET mistakes = {self.errors} WHERE login = '{self.userName}'")
                db.commit()
            self.stop()

    # кнопка старта
    def start(self):
        # если кнопка была нажата впервый раз
        if self.firstTime:
            self.firstTime = False
            for el in self.labels:
                el.show()
            self.timerScreen = QTimer()
            self.timerScreen.setSingleShot(True)
            self.timerScreen.timeout.connect(self.makeAllDefault)
            self.timerScreen.start(5000)
            self.timerScreen1 = QTimer()
            self.timerScreen1.setSingleShot(True)
            self.timerScreen1.timeout.connect(self.makeAllOn)
            self.timerScreen1.start(5000)
            self.wrongsNumber.display(self.errors)
            self.showAll()
        else:
            self.makeAllOn()
            for el in self.labels:
                if el.outOfGame:
                    self.reconnect(el.clicked, self.nothing)
                    el.setPixmap(QPixmap("resources/pics/outofgame.jpeg"))
        self.timer.start(1000)

    def stop(self):
        for el in self.labels:
            el.wasClicked = False
        self.timer.stop()
        self.makeAllDefault()
        self.makeAllOff()

    def counter(self):
        self.sec += 1
        self.setTime()

    def setTime(self):
        hour = self.sec / 3600
        minut = (self.sec % 3600) / 60
        sec = (self.sec % 3600) % 60
        self.timeLabel.setText("%02d:%02d:%02d" % (hour, minut, sec))

    def exit(self):
        self.stop()
        for el in self.labels:
            el.hide()
            el.outOfGame = False
            el.wasClicked = False
        self.firstTime = True
        self.randomPic()
        self.mainMenu.show()
        self.timer.stop()
        self.sec = 0
        self.errors = 0
        self.setTime()
        self.randomPic()
        self.makeAllDefault()
        self.wrongsNumber.display(self.errors)
        self.makeAllOff()
        self.hide()

    def addMenu(self, mainMenu):
        self.mainMenu = mainMenu


#!/usr/bin/env python

##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Sardana is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with Sardana.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

"""
scanplotter.py:
    module containing the widget: scanplotter,
    to be used in the Taurus app "scanner.py"
"""

import taurus.core

from taurus.external.qt import QtGui, Qwt5
#from taurus.qt.Qt import *

from taurus.core.util import dictFromSequence
from taurus.core.util.containers import CaselessDict
from taurus.core.util import eventfilters
from taurus.qt.qtgui.plot import TaurusTrend

class ScanPlotter(TaurusTrend):

    def __init__(self, parent=None, designMode=False):

        TaurusTrend.__init__(self, parent, designMode)
        self.setUseParentModel(False)
        self._plotables = CaselessDict()
        self._movingMotors = []
        self._macroNames = []
        self._doorName = None

        self.setMinimumSize(300, 200)
        self.setXIsTime(True)
        self.setAxisScale(Qwt5.QwtPlot.xBottom, 0, 60)
        self.setXDynScale(True)

    def onSequenceCleared(self):
        self._movingMotors = []
        self._macroNames = []
        self.populatePlotables()

    def onMacrosAdded(self, macroNames, motors):
        for macro in macroNames:
            self._macroNames.append(macro)
        self._movingMotors += motors
        self.populatePlotables()

    def onMacroEdited(self, oldMotors, newMotors):
        for motor in oldMotors:
            self._movingMotors.remove(motor)
        self._movingMotors += newMotors
        self.populatePlotables()

    def onMacrosDeleted(self, macroNames, motors):
        for macro in macroNames:
            self._macroNames.remove(macro)
        for motor in motors:
            self._movingMotors.remove(motor)
        self.populatePlotables()

    def onMacroStarted(self, macroName, motors):
        self._macroNames = [macroName]
        self._movingMotors = motors
        self.populatePlotables()

    def onMotorChanged(self, oldMotor, newMotor):
        if oldMotor in self._movingMotors:
            self._movingMotors.remove(oldMotor)
        self._movingMotors.append(newMotor)
        self.populatePlotables()

    def onMacroChanged(self, macroNode):
        if macroNode is None:
            self._macroNames = []
            self._movingMotors = []
#            return
        else:
            self._macroNames = [macroNode.name()]
            self._movingMotors = macroNode.allMotors()
        self.populatePlotables()

    def onDoorChanged(self, doorName):
        self._doorName = doorName
        self._movingMotors = []
        self.populatePlotables()

    def getPlotables(self, macronames=None, doorname=None, movingmotors=None):
        """returns a list of plotables for this scan given macro (channels and moving motors)"""
        plotables = []
        if macronames is None: macronames = list(set(self._macroNames))
        if doorname is None: doorname = self._doorName
        if movingmotors is None: movingmotors = list(set(self._movingMotors))
        if doorname is None or not len(macronames):
            return plotables
        door = taurus.Device(doorname)

        for macroname in macronames:
            env = dictFromSequence(door.getMacroEnv([macroname]))
            mntgrp_name = env.get("ActiveMntGrp")
            if mntgrp_name is None:
                continue
            mntgrp = taurus.Device(mntgrp_name)
            channels = mntgrp.getAttribute('Channels').read()
            channelsList = channels.value
            timer_name = mntgrp.getAttribute('Timer').read().value.lower()
            plotables += [('%s/%s_value' % (mntgrp_name, ch)).lower() for ch in channelsList if ch.lower() != timer_name]

        for m in movingmotors:
            if not (m is None or m == "" or m == "None"):
                plotables += ["%s/position" % m]
        return plotables

    def populatePlotables(self, plotables=None):
        ##@TODO: The name in the legend should be more descriptive: i.e. "dev/attr" instead of "attr" (this probably has to be changed for taurusplot in general  )
        if plotables is None: plotables = self.getPlotables()
        self.setModel(plotables)
        self.curves_lock.acquire()
        try:
            for name in self.getTrendSetNames():
                ts = self.getTrendSet(name)
                ts.fireEvent(None, taurus.core.taurusbasetypes.TaurusEventType.Change, None)
        finally:
            self.curves_lock.release()
        self.setEventFilters([eventfilters.ONLY_VALID], plotables)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    form = ScanPlotter()
    if len(sys.argv) < 4: raise ValueError('Syntax: ' + sys.argv[0] + ' macroname doorname plotable [anotherplotable...]')
    form._macroName = sys.argv[1]
    form._doorName = sys.argv[2]
    form.populatePlotables(sys.argv[3:])
    form.show()
    sys.exit(app.exec_())


#! /usr/bin/env python3
################################################################################
#   currency.py
#
#   Currency game
#
#   08.12.2016  Created by: Rada Telyukova
################################################################################

import random

currency = {
    'США':       'доллар', 'Россия':   'рубль',  'Азербайджан': 'манат',
    'Албания':   'лек',    'Монголия': 'тугрик', 'Молдавия':     'лей',
    'Германия':  'евро',   'Индия':    'рупия',  'Канада':       'доллар',
    'Израиль':   'шекель', 'Ирак':     'динар',  'Казахстан':    'тенге',
    'Аргентина': 'песо',   'Польша':   'злотый', 'Грузия':       'лари',
    'Китай':     'юань',   'Армения':  'драм',   'Корея':        'вона',
    'Швейцария': 'франк',  'Япония':   'йена',   'ЮАР':          'рэнд',
    'Египет':    'фунт',   'Швеция':   'крона'
}

keys    = list(currency.keys())
random.shuffle(keys)
total   = 10
correct = 0

print('Введите валюту страны')

for i in range(0, total):
    key = keys[i]
    answer = input(key + ': ').strip().lower()
    if (answer == currency[key]):
        correct = correct + 1
        print('Правильно!')
    else:
        print('Неверно! Правильный ответ: ', currency[key])

if   (correct <  3): print ('\n"Молодец!" 2')
elif (correct <  5): print ('\n"Молодец!" 3')
elif (correct <  8): print ('\nХорошо! 4')
elif (correct < 10): print ('\nТы крут! 5')
else:                print ('\nТЫ ГЕНИЙ!!! 5+')


from sqlalchemy import Column
from db.cm_session import cm_session, Base
from sqlalchemy.dialects.mssql import BIGINT, CHAR, DATETIME, INTEGER, NVARCHAR, SMALLINT, TINYINT, VARCHAR

class TbSuspiciousLogI(Base):
    __tablename__ = 'tb_SuspiciousLog_I'
    id = Column(BIGINT, primary_key=True, nullable=False)
    LogNativeID = Column(BIGINT)
    LogType = Column(SMALLINT)
    LogGenUTCDatetime = Column(DATETIME)
    ProductGUID = Column(CHAR(36))
    DetectionName = Column(VARCHAR(64))
    ThreatType = Column(SMALLINT)
    SourceIP = Column(VARCHAR(15))
    DestIP = Column(VARCHAR(15))
    Protocol = Column(INTEGER)
    FileName = Column(NVARCHAR(512))
    RuleID = Column(INTEGER)
    InterestedIP = Column(VARCHAR(15))
    HostName = Column(VARCHAR(256))
    Group = Column(NVARCHAR(128))
    ECE_SeverityCode = Column(SMALLINT)
    Remarks = Column(NVARCHAR(2176))
    CC_Server = Column(NVARCHAR(2138))
    CC_ServerType = Column(SMALLINT)
    SLF_CCCA_DetectionSource = Column(INTEGER)
    SLF_PeerIP = Column(VARCHAR(256))
    Description = Column(VARCHAR(256))
    SHA1 = Column(VARCHAR(40))
    MalwareType = Column(VARCHAR(256))
    DetectedByVA = Column(TINYINT)
    HeurFlag = Column(SMALLINT)
    AttackPhase = Column(SMALLINT)


# File: C (Python 2.4)

from pandac.PandaModules import *
from direct.gui.DirectGui import *
from direct.interval.IntervalGlobal import *
from pirates.piratesgui import GuiTray, QuestPage
from pirates.piratesbase import PLocalizer
from pirates.piratesgui import PiratesGuiGlobals
from pirates.reputation import ReputationGlobals
from pirates.piratesbase import PiratesGlobals
from pirates.piratesgui.GuiButton import GuiButton
from pirates.uberdog.UberDogGlobals import InventoryType
from pirates.audio import SoundGlobals
from pirates.audio.SoundGlobals import loadSfx

class ChestTray(GuiTray.GuiTray):
    WantClothingPage = base.config.GetBool('want-clothing-page', 0)
    if not base.config.GetBool('want-land-infamy', 0):
        pass
    WantTitlesPage = base.config.GetBool('want-sea-infamy', 0)

    def __init__(self, parent, parentMgr, **kw):
        GuiTray.GuiTray.__init__(self, parent, 0.6, 0.12)
        self.initialiseoptions(ChestTray)
        self.setBin('gui-fixed', 1)
        self.state = 0
        self.buttonsParent = self.attachNewNode(ModelNode('ChestTray.buttonsParent'), sort = 1)
        self.stickyButtonsParent = self.attachNewNode(ModelNode('ChestTray.stickyButtonsParent'), sort = 1)
        self.stickyButtonsParent.setPos(0, 0, 0.02)
        self.buttons = { }
        self.buildShowHideButtonsIvals()
        self.openSfx = loadSfx(SoundGlobals.SFX_GUI_OPEN_SEACHEST)
        self.openSfx.setVolume(0.4)
        self.closeSfx = loadSfx(SoundGlobals.SFX_GUI_CLOSE_SEACHEST)
        self.closeSfx.setVolume(0.4)
        gui = loader.loadModel('models/gui/toplevel_gui')
        gui_main = loader.loadModel('models/gui/gui_main')
        helpPos = (-0.26, 0, 0.06)
        helpDelay = 0
        self.buttonImage = gui.find('**/topgui_icon_box')
        self.buttonImageIn = gui.find('**/topgui_icon_box_in')
        self.buttonColors = (VBase4(0.7, 0.7, 0.7, 1), VBase4(0.8, 0.8, 0.8, 1), VBase4(1.0, 1.0, 1.0, 1), VBase4(0.6, 0.6, 0.6, 1))
        self.currentButtonIn = None
        self.highlightButtons = [
            'guiMgrToggleMap',
            'guiMgrToggleInventory',
            'guiMgrToggleWeapons',
            'guiMgrToggleLevels',
            'guiMgrToggleTreasures',
            'guiMgrToggleTitles',
            'guiMgrToggleShips',
            'guiMgrToggleQuest',
            'guiMgrToggleLookout',
            'guiMgrToggleMainMenu']
        buttonOptions = {
            'image': self.buttonImage,
            'geom': None,
            'relief': None,
            'frameSize': (0, 0.12, 0, 0.12),
            'image_scale': 0.47,
            'image_pos': (0.06, 0, 0.06),
            'image0_color': self.buttonColors[0],
            'image1_color': self.buttonColors[1],
            'image2_color': self.buttonColors[2],
            'image3_color': self.buttonColors[3],
            'geom_scale': 0.12,
            'geom_pos': (0.06, 0, 0.06),
            'command': self.togglePanel }
        extraHeight = 0
        if self.WantTitlesPage:
            extraHeight = 0.12

        self.friendButtonLight = gui.find('**/friend_button_over')
        buttonOptions['geom'] = None
        self.socialButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'f',
            'shift-f'], hotkeyLabel = 'F', helpText = PLocalizer.SocialButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleSocial'], pos = (-0.069, 0, 1.525 + extraHeight))
        self.buttons['guiMgrToggleSocial'] = self.socialButton
        self.highlightButton('guiMgrToggleSocial')
        self.friendButtonLightImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.friendButtonLight, scale = 0.135, pos = (-0.069, 0, 1.645))
        self.friendButtonLightImage.sourceImage = self.friendButtonLight

        self.compassSmallButtonLight = gui.find('**/compass_small_button_open_over')
        buttonOptions['geom'] = None
        self.radarButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'c',
            'shift-c'], hotkeyLabel = 'C', helpText = PLocalizer.RadarButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleRadar'], pos = (-0.069, 0, 1.392 + extraHeight))
        self.buttons['guiMgrToggleRadar'] = self.radarButton
        self.highlightButton('guiMgrToggleRadar')
        self.compassSmallButtonLightImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.compassSmallButtonLight, scale = 0.093, pos = (-0.069, 0, 1.510))
        self.compassSmallButtonLightImage.sourceImage = self.compassSmallButtonLight
        buttonPosZ = 0.48
        buttonHeight = 0.12
        if self.WantTitlesPage:
            buttonPosZ += buttonHeight

        self.worldMapButton = gui_main.find('**/world_map_icon')
        buttonOptions['geom'] = None
        self.mapButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'm',
            'shift-m'], hotkeyLabel = 'M', helpText = PLocalizer.MapButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleMap'], pos = (-0.07, 0, 1.325))
        self.buttons['guiMgrToggleMap'] = self.mapButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleMap')
        self.worldMapButtonImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.worldMapButton, scale = 0.107, pos = (-0.069, 0, 1.320))
        self.worldMapButtonImage.sourceImage = self.worldMapButton

        self.chestClosedLight = gui.find('**/treasure_chest_closed_over')
        buttonOptions['geom'] = None
        self.bagButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'i',
            'shift-i'], hotkeyLabel = 'I', helpText = PLocalizer.InventoryButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleInventory'], pos = (-0.07, 0, 1.192))
        self.buttons['guiMgrToggleInventory'] = self.bagButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleInventory')
        self.chestClosedLightImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.chestClosedLight, scale = 0.137, pos = (-0.069, 0, 1.190))
        self.chestClosedLightImage.sourceImage = self.chestClosedLight

        self.weaponIcon = gui.find('**/topgui_icon_weapons')
        buttonOptions['geom'] = None
        self.weaponButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'y',
            'shift-y'], hotkeyLabel = 'Y', helpText = PLocalizer.WeaponButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleWeapons'], pos = (-0.07, 0, 1.059))
        self.buttons['guiMgrToggleWeapons'] = self.weaponButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleWeapons')
        self.weaponIconImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.weaponIcon, scale = 0.140, pos = (-0.069, 0, 1.07))
        self.weaponIconImage.sourceImage = self.weaponIcon

        self.skillIcon = gui.find('**/topgui_icon_skills')
        buttonOptions['geom'] = None
        self.levelButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'k',
            'shift-k'], hotkeyLabel = 'K', helpText = PLocalizer.SkillButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleLevels'], pos = (-0.07, 0, 0.926))
        self.buttons['guiMgrToggleLevels'] = self.levelButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleLevels')
        self.skillIconImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.skillIcon, scale = 0.180, pos = (-0.069, 0, 0.925))
        self.skillIconImage.sourceImage = self.skillIcon

        if self.WantClothingPage:

            self.clothingIcon = gui.find('**/topgui_icon_clothing')
            buttonOptions['geom'] = None
            self.clothingButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeyLabel = '', helpText = PLocalizer.ClothingButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
                'guiMgrToggleClothing'], pos = (-0.07, 0, 0.793))
            self.buttons['guiMgrToggleClothing'] = self.clothingButton
            buttonPosZ -= buttonHeight
            self.highlightButton('guiMgrToggleClothing')
            self.clothingIconImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.clothingIcon, scale = 0.200, pos = (-0.069, 0, 0.790))
            self.clothingIconImage.sourceImage = self.clothingIcon

        if self.WantTitlesPage:
            self.infamyButton = gui.find('**/topgui_infamy_frame')
            buttonOptions['geom'] = None
            self.titlesButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
                'b',
                'shift-b'], hotkeyLabel = 'B', helpText = PLocalizer.TitlesButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
                'guiMgrToggleTitles'], pos = (-0.07, 0, 0.660))
            self.buttons['guiMgrToggleTitles'] = self.titlesButton
            buttonPosZ -= buttonHeight
            self.highlightButton('guiMgrToggleTitles')
            self.infamyButtonImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.infamyButton, scale = 0.190, pos = (-0.069, 0, 0.660))
            self.infamyButtonImage.sourceImage = self.infamyButton

        self.shipButton = gui.find('**/topgui_icon_ship')
        buttonOptions['geom'] = None
        self.shipsButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'h',
            'shift-h'], hotkeyLabel = 'H', helpText = PLocalizer.ShipsButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleShips'], pos = (-0.07, 0, 0.527))
        self.buttons['guiMgrToggleShips'] = self.shipsButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleShips')
        self.shipButtonImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.shipButton, scale = 0.170, pos = (-0.069, 0, 0.530))
        self.shipButtonImage.sourceImage = self.shipButton

        self.journalIcon = gui.find('**/topgui_icon_journal')
        buttonOptions['geom'] = None
        self.questButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'j',
            'shift-j'], hotkeyLabel = 'J', helpText = PLocalizer.QuestButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleQuest'], pos = (-0.07, 0, 0.394))
        self.buttons['guiMgrToggleQuest'] = self.questButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleQuest')
        self.journalIconImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.journalIcon, scale = 0.200, pos = (-0.071, 0, 0.400))
        self.journalIconImage.sourceImage = self.journalIcon

        self.lookoutButtonLight = gui.find('**/telescope_button_over')
        buttonOptions['geom'] = None
        self.lookoutButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'l',
            'shift-l'], hotkeyLabel = 'L', helpText = PLocalizer.LookoutButtonHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleLookout'], pos = (-0.07, 0, 0.261))
        self.buttons['guiMgrToggleLookout'] = self.lookoutButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleLookout')
        self.lookoutButtonLightImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.lookoutButtonLight, scale = 0.350, pos = (-0.069, 0.0, 0.256))
        self.lookoutButtonLightImage.sourceImage = self.lookoutButtonLight

        self.mainMenuIcon = gui.find('**/topgui_icon_main_menu')
        buttonOptions['geom'] = None
        self.mainMenuButton = GuiButton(command = self.togglePanel, parent = self.buttonsParent, hotkeys = [
            'f7',
            'escape'], hotkeyLabel = 'F7', helpText = PLocalizer.MainMenuIconHelp, helpPos = helpPos, helpDelay = helpDelay, extraArgs = [
            'guiMgrToggleMainMenu'], pos = (-0.07, 0, 0.128))
        self.buttons['guiMgrToggleMainMenu'] = self.mainMenuButton
        buttonPosZ -= buttonHeight
        self.highlightButton('guiMgrToggleMainMenu')
        self.mainMenuIconImage = OnscreenImage(parent = self.stickyButtonsParent, image = self.mainMenuIcon, scale = 0.170, pos = (-0.069, 0, 0.130))
        self.mainMenuIconImage.sourceImage = self.mainMenuIcon

        self.highlightButton('guiMgrToggleInventory')

        self.chestButtonClosed = (gui.find('**/treasure_chest_closed'), gui.find('**/treasure_chest_closed'), gui.find('**/treasure_chest_closed_over'))
        self.chestButtonOpen = gui.find('**/treasure_chest_open_over')
        self.chestButton = GuiButton(command = self.toggle, parent = self, relief = None, image = self.chestButtonClosed, image_scale = 0.15, image_pos = (0.065, 0, 0.06), scale = 1.2)
        self.chestHotkeyText = DirectLabel(parent = self.chestButton, relief = None, text = 'Tab', text_align = TextNode.ARight, text_scale = PiratesGuiGlobals.TextScaleSmall, text_pos = (0.125, 0.0), text_fg = PiratesGuiGlobals.TextFG2, text_shadow = PiratesGuiGlobals.TextShadow, text_font = PiratesGlobals.getPirateBoldOutlineFont(), textMayChange = 1)
        self.buttonsParent.hide()
        self.socialButton.setScale(2.28)
        self.radarButton.setScale(2.26)
        self.mapButton.setScale(2.3)
        self.bagButton.setScale(2.3)
        self.weaponButton.setScale(2.3)
        self.levelButton.setScale(2.3)
        if self.WantClothingPage:
            self.clothingButton.setScale(2.3)
        self.titlesButton.setScale(2.3)
        self.shipsButton.setScale(2.3)
        self.questButton.setScale(2.3)
        self.lookoutButton.setScale(2.3)
        self.mainMenuButton.setScale(2.3)
        self.buttonsParent.setPos(0.2, 0, 0.14)
        self.chestButton.setPos(-.147, 0, .02)
        self.stickyButtonsParent.hide()
        self.stickyButtonsParent.setPos(0.2, 0, 0.14)
        gui.remove_node()

    def destroy(self):
        self.showButtonsIval.pause()
        del self.showButtonsIval
        self.hideButtonsIval.pause()
        del self.hideButtonsIval
        self.buttonsParent.remove_node()
        del self.buttonsParent
        self.stickyButtonsParent.remove_node()
        del self.stickyButtonsParent
        for button in self.buttons:
            self.buttons[button].destroy()

        del self.buttons
        loader.unloadSfx(self.openSfx)
        loader.unloadSfx(self.closeSfx)
        del self.openSfx
        del self.closeSfx
        GuiTray.GuiTray.destroy(self)

    def highlightButton(self, button):

        def changeButtonImage(button, image):
            button['image'] = image
            button['image0_color'] = self.buttonColors[0]
            button['image1_color'] = self.buttonColors[1]
            button['image2_color'] = self.buttonColors[2]
            button['image3_color'] = self.buttonColors[3]

        if self.currentButtonIn:
            changeButtonImage(self.buttons[self.currentButtonIn], self.buttonImage)

        self.currentButtonIn = button
        changeButtonImage(self.buttons[self.currentButtonIn], self.buttonImageIn)

    def togglePanel(self, message, args = None):
        if localAvatar.getInventory() == None:
            return None

        if message in self.highlightButtons:
            self.highlightButton(message)

        messenger.send(message, [
            args])

    def toggle(self):
        if not self.isHidden():
            messenger.send(PiratesGlobals.SeaChestHotkey)
            if localAvatar.guiMgr.questPage:
                chestPanel = localAvatar.guiMgr.chestPanel
                if chestPanel.currPageIndex:
                    currPage = chestPanel.pages[chestPanel.currPageIndex]

    def isOpen(self):
        return self.state

    def showButtons(self):
        if self.hideButtonsIval.isPlaying():
            self.hideButtonsIval.finish()

        self.showButtonsIval.start()

    def hideButtons(self):
        if self.showButtonsIval.isPlaying():
            self.showButtonsIval.finish()

        for button in self.buttons:
            self.buttons[button].hideDetails()

        self.hideButtonsIval.start()

    def slideOpen(self):
        if not self.state:
            self.openSfx.play()

        self.state = 1
        self.chestButton['image'] = self.chestButtonOpen
        self.showButtons()
        if localAvatar.guiMgr.questPage:
            chestPanel = localAvatar.guiMgr.chestPanel
            if chestPanel.currPageIndex:
                currPage = chestPanel.pages[chestPanel.currPageIndex]

    def slideClose(self):
        if self.state:
            self.closeSfx.play()

        self.state = 0
        self.chestButton['image'] = self.chestButtonClosed
        self.hideButtons()

    def buildShowHideButtonsIvals(self, includeSticky = True):
        showSequence = Sequence(Func(self.buttonsParent.show))
        showParallel = Parallel(LerpPosInterval(self.buttonsParent, 0.2, pos = Point3(0, 0, 0.14), startPos = self.buttonsParent.getPos, blendType = 'easeOut'))
        if includeSticky:
            showSequence.append(Func(self.stickyButtonsParent.show))
            showParallel.append(LerpPosInterval(self.stickyButtonsParent, 0.2, pos = Point3(0, 0, 0.14), startPos = self.stickyButtonsParent.getPos, blendType = 'easeOut'))

        showSequence.append(showParallel)
        self.showButtonsIval = showSequence
        hideParallel = Parallel(LerpPosInterval(self.buttonsParent, 0.2, pos = Point3(0.2, 0, 0.14), startPos = self.buttonsParent.getPos, blendType = 'easeIn'))
        hideSequence = Sequence(hideParallel, Func(self.buttonsParent.hide))
        if includeSticky:
            hideSequence.append(Func(self.stickyButtonsParent.hide))
            hideParallel.append(LerpPosInterval(self.stickyButtonsParent, 0.2, pos = Point3(0.2, 0, 0.14), startPos = self.stickyButtonsParent.getPos, blendType = 'easeIn'))

        hideSequence.append(hideParallel)
        self.hideButtonsIval = hideSequence

    def hideChestButton(self):
        self.chestButton.hide()

    def showChestButton(self):
        self.chestButton.show()


'''
Created by Samvel Khalatyan, May 23, 2013
Copyright 2013, All rights reserved
'''

from django.conf.urls import patterns, url

from authors import views

urlpatterns = patterns('',
    # get list of authors
    url(r'^$',
        views.AuthorsIndexView.as_view(),
        name='index'),

    # get author details
    url(r'^(?P<author_id>\d+)/$',
        views.AuthorDetailView.as_view(),
        name='detail'),

    # -- AJAX requests
    # get list of authors
    url(r'^ajax/$',
        views.AjaxAuthorsIndexView.as_view(),
        name='ajax-index')
)


# -*- coding: utf-8 -*-
"""
Created on Tue Feb  4 13:05:32 2020

@author: knoch
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick

plt.close('all') #closes all figures

pi = np.pi
x = np.arange(0, 2*np.pi, 2*np.pi/100.0)
ll_y = -2
ul_y = 2
y = np.sin(x)

yp= np.diff(y)/np.diff(x)
xp = x[:-1]+np.diff(x)/2

fig1 = plt.figure(1)
ax1 = fig1.gca()
ax1.set_ylim(ll_y, ul_y)
ax1.yaxis.set_major_formatter(tick.StrMethodFormatter('{x:5.1f}'))
ax1.grid(True)
ax1.plot(x, y,color='green',marker='.',linestyle='None')

ax1.plot(xp, yp,color='red',marker='.',linestyle='None')


import prism_metadata
import setup_logger
import logging

logger = logging.getLogger(setup_logger.LOGGER_NAME)

if __name__ == "__main__":
    setup_logger.setup(verbose=True)

    assay_plates = prism_metadata.read_assay_plate_from_file(
        "functional_tests/test_functional_prism_metadata_perturbagen/REP Master Plate Key_All Pools.txt", "prism_pipeline.cfg")
    replicates_det_plates = {"PREP001_P7_X1", "PREP001_P8_X1"}
    assay_plates = [x for x in assay_plates if x.det_plate in replicates_det_plates]
    logger.info("assay_plates:  {}".format(assay_plates))

    assay_plate_barcodes = set([x.assay_plate_barcode for x in assay_plates])

    perts = prism_metadata.build_perturbagens_from_file(
        "functional_tests/test_functional_prism_metadata_perturbagen/7159-03-A02-01-01_02-29-16_12.20.32.txt",
        prism_metadata.plate_map_type_CM,
        "prism_pipeline.cfg")

    replicate_perts = [x for x in perts if x.assay_plate_barcode in assay_plate_barcodes]

    well_pert_map = prism_metadata.validate_perturbagens(replicate_perts)

    logger.info("len(well_part_map):  {}".format(len(well_pert_map)))
    assert len(well_pert_map) == 384, len(well_pert_map)


from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from api.routes.todo import todo
from api.routes.user import user

app = FastAPI()
origins = ['https://localhost:3000']
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials = True,
    allow_methods=['*'],
    allow_headers=['*'],
)
app.include_router(user)
app.include_router(todo)


# Uses python3
# Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
# if n is 0 or 1 than Fibonacci number for n is n
# if n is greater than 1 than Fibonacci number is
# sum of previous two Fibonacci numbers

# In contrast to recursive solution for which
# running time grows exponentially, running time
# of this aproach grows quadratically n^2
# The list is created to hold
# Fibonacci numbers and every number is sum
# of two previous numbers in the list

def fibonacci_list(n):
	"""
	For every integer n >= 0 if n is 0 or 1 returns n, otherwise returns
	sum of previous two integers in the list
	fibonacci[n] = fibonacci[n-1] + fibonacci[n-2]
	"""
	fib = [0,1]
	for i in range(2, n + 1):
		fib.append(fib[-1] + fib[-2])
	return fib[n]

# Test Cases

i = 300000
print("Fibonacci number of " + str(i) + " is " +
	str(fibonacci_list(i)))


from SparkContext import sc
from pyspark.mllib.clustering.KMeansModel import KMeans

def main():
    data = sc.textFile('Kmeans_Data.txt')
    k = 4 #假设总共聚成4类

    model = KMeans.train( data, k, maxIterations = 60, runs = 5, initializationMode = 'random') #模型并行训练

if __name__ == '__main__':
    main()


import taichi_three as t3

scene = t3.Scene()
camera = t3.Camera()
scene.add_camera(camera)

light = t3.Light(dir=[-0.2, -0.6, 1.0])
scene.add_light(light)

obj = t3.readobj('cube.obj', scale=0.6)
model = t3.Model.from_obj(obj)
scene.add_model(model)

gui = t3.GUI('Shading Models')
while gui.running:
    gui.get_event(None)
    camera.from_mouse(gui)
    scene.render()
    gui.set_image(camera.img)
    gui.show()


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

import codecs
from collections import Counter
import pandas as pd
import time

import graph

start_time = time.time()
def find_duplicate_1(filename):

#empty set
    myset = set()
#empty list
    mylist = []

#read records.txt file
    filename = codecs.open(filename,encoding='utf-8')

    log_file = codecs.open("log.txt",'w',encoding='utf-8')
    log_file.write("Below values are duplicate" + '\n' + '\n')

#Iterate through the file
#Normalize the feature
    for rec in filename:
        rec = rec.replace('\n',"")
        if rec != "":
           myset.add(rec)
           mylist.append(rec)

    #convert set into list
    #all duplicates removed
    newlist = list(myset)

    #Start selecting features
    c1 = Counter(mylist)
    c2 = Counter(newlist)

    diff = c1 - c2
    #Print duplicate values
    print(list(diff.elements()))
    newfile=pd.DataFrame(newlist)
    newfile.to_csv('denormalization.csv')

'''Change sample.txt with your file
call find_duplicate function'''

#find_duplicate_1("sample.txt")
find_duplicate_1("Datasets/ConferenceName_non_standard-1.csv")

end_time = time.time()
GFS_time=end_time-start_time
print("Total exection time:",GFS_time)

graph.accuracy()
graph.precision()
graph.recall()
graph.time_GFS(GFS_time)


from django import forms
from django.utils.translation import ugettext_lazy as _
from djinn_forms.widgets.attachment import AttachmentWidget
from djinn_forms.fields.relate import RelateField
from djinn_forms.forms.relate import RelateMixin
from djinn_forms.forms.richtext import RichTextMixin
from djinn_forms.widgets.relate import RelateWidget
from djinn_forms.widgets.richtext import RichTextWidget
from djinn_contenttypes.forms.base import BaseContentForm
from djinn_contenttypes.models.attachment import ImgAttachment
from djinn_news.models import News

class NewsForm(BaseContentForm, RelateMixin, RichTextMixin):

    # Translators: news general help
    help = _("Add a news item. The item will be submitted for publishing")

    title = forms.CharField(label=_("Title"),
                            max_length=100,
                            widget=forms.TextInput())

    text = forms.CharField(
        # Translators: news text label
        label=_("News text"),
        required=True,
        widget=RichTextWidget(
            img_type="djinn_contenttypes.ImgAttachment",
            attrs={'class': 'extended'}
        ))

    is_global = forms.BooleanField(
        # Translators: news is_global label
        label=_("Is global"),
        required=False
        )

    documents = RelateField(
        "related_document",
        ["pgcontent.document"],
        # Translators: news documents label
        label=_("Related documents"),
        required=False,
        # Translators: news documents help
        help_text=_("Select document(s)"),
        widget=RelateWidget(
            attrs={'hint': _("Search document"),
                   # Translators: djinn_news documents link label
                   'label': _("Search documents"),
                   'searchfield': 'title_auto',
                   'template_name':
                   'djinn_forms/snippets/relatesearchwidget.html',
                   'search_url': '/document_search/',
                   'ct_searchfield': 'meta_type', },
            )
        )

    images = forms.ModelMultipleChoiceField(
        queryset=ImgAttachment.objects.all(),
        # Translators: news images label
        label=_("Images"),
        required=False,
        widget=AttachmentWidget(
            ImgAttachment,
            "djinn_forms/snippets/imageattachmentwidget.html",
            attrs={"multiple": True}
            ))

    def __init__(self, *args, **kwargs):

        super(NewsForm, self).__init__(*args, **kwargs)

        if not self.instance.get_owner():
            self.fields['owner'].initial = self.user.profile
            self.fields['owner'].widget.initial = True
        self.fields['show_images'].label = _("Show images")
        self.fields['comments_enabled'].label = _("Comments enabled")

        if not self.user.has_perm("djinn_news.manage_news", obj=self.instance):
            del self.fields['is_global']

        self.init_relation_fields()
        self.init_richtext_widgets()

    def save(self, commit=True):

        res = super(NewsForm, self).save(commit=commit)

        self.save_relations(commit=commit)

        return res

    class Meta(BaseContentForm.Meta):
        model = News
        fields = ('title', 'text', 'documents', 'images', 'parentusergroup',
                  'comments_enabled', 'owner', 'publish_from',
                  'publish_to', 'show_images', 'is_global')


import wiringpi as GPIO
import spidev

SPI_HZ = 1000000
SPI_MODE = 0b00

print("SPI-MPU6050测试程序")

spi = spidev.SpiDev()
print("打开SPI设备")
spi.open(1,0)
print('{}{}{}{}{}'.format('设置spi设备的时钟和模式:','时钟频率为:',SPI_HZ,'SPI模式:',SPI_MODE))
spi.max_speed_hz = 1000000
spi.mode = 0b00

print("初始化MPU6050")
spi.writebytes([0x6B,0x80])
GPIO.delay(100)
spi.writebytes([0x68,0x05])
GPIO.delay(100)
spi.writebytes([0x6A,0x1D])
GPIO.delay(1000)
print("读取MPU6050的设备ID")
ret = spi.xfer([0xf5,0x00])
print('{}{}'.format('SPI设备的设备ID是',ret[1]))


T = int(input())

for _ in range(T):
    N = int(input())
    if N == 0:
        print(1, 0)
    else:
        dp = [0] * 41
        dp[0] = 0
        dp[1] = 1
        for i in range(2, 41):
            dp[i] = dp[i-1] + dp[i-2]
        print(dp[N-1], dp[N])


#!/usr/bin/env python
'''
Export wirecell.sigproc functionality to a main Click program.
'''

import sys
import click

from wirecell import units

@click.group("sigproc")
@click.pass_context
def cli(ctx):
    '''
    Wire Cell Signal Processing Features
    '''

@cli.command("response-info")
@click.argument("json-file")
@click.pass_context
def response_info(ctx, json_file):
    '''
    Show some info about a field response file (.json or .json.bz2).
    '''
    import response.persist as per
    fr = per.load(json_file)
    print ("origin:%.2f cm, period:%.2f us, tstart:%.2f us, speed:%.2f mm/us, axis:(%.2f,%.2f,%.2f)" % \
           (fr.origin/units.cm, fr.period/units.us, fr.tstart/units.us, fr.speed/(units.mm/units.us), fr.axis[0],fr.axis[1],fr.axis[2]))
    for pr in fr.planes:
        print ("\tplane:%d, location:%.4fmm, pitch:%.4fmm" % \
               (pr.planeid, pr.location/units.mm, pr.pitch/units.mm))

@cli.command("convert-garfield")
@click.option("-o", "--origin", default="10.0*cm",
              help="Set drift origin (give units, eg '10*cm').")
@click.option("-s", "--speed", default="1.114*mm/us",
              help="Set nominal drift speed (give untis, eg '1.114*mm/us').")
@click.option("-n", "--normalization", default=0.0,
              help="Set normalization: 0:none, <0:electrons, >0:multiplicative scale.  def=0")
@click.option("-z", "--zero-wire-locs", default=[0.0,0.0,0.0], nargs=3, type=float,
              help="Set location of zero wires.  def: 0 0 0")
@click.argument("garfield-fileset")
@click.argument("wirecell-field-response-file")
@click.pass_context
def convert_garfield(ctx, origin, speed, normalization, zero_wire_locs,
                         garfield_fileset, wirecell_field_response_file):
    '''
    Convert an archive of a Garfield fileset (zip, tar, tgz) into a
    Wire Cell field response file (.json with optional .gz or .bz2
    compression).
    '''
    import garfield as gar
    import response as res
    import response.persist as per

    origin = eval(origin, units.__dict__)
    speed = eval(speed, units.__dict__)
    rflist = gar.load(garfield_fileset, normalization, zero_wire_locs)
    fr = res.rf1dtoschema(rflist, origin, speed)
    per.dump(wirecell_field_response_file, fr)

@cli.command("plot-garfield-exhaustive")
@click.option("-n", "--normalization", default=0.0,
              help="Set normalization: 0:none, <0:electrons, >0:multiplicative scale.  def=0")
@click.option("-z", "--zero-wire-locs", default=[0.0,0.0,0.0], nargs=3, type=float,
              help="Set location of zero wires.  def: 0 0 0")
@click.argument("garfield-fileset")
@click.argument("pdffile")
@click.pass_context
def plot_garfield_exhaustive(ctx, normalization, zero_wire_locs,
                                 garfield_fileset, pdffile):
    '''
    Plot all the Garfield current responses.
    '''
    import wirecell.sigproc.garfield as gar
    dat = gar.load(garfield_fileset, normalization, zero_wire_locs)
    import wirecell.sigproc.plots as plots
    plots.garfield_exhaustive(dat, pdffile)

@cli.command("plot-garfield-track-response")
@click.option("-g", "--gain", default=-14.0,
                  help="Set gain in mV/fC.")
@click.option("-s", "--shaping", default=2.0,
                  help="Set shaping time in us.")
@click.option("-t", "--tick", default=0.5,
                  help="Set tick time in us (0.1 is good for no shaping).")
@click.option("-p", "--tick-padding", default=0,
                  help="Number of ticks of zero ADC to pre-pad the plots.")
@click.option("-e", "--electrons", default=13300,
                help="Set normalization in units of electron charge.")
@click.option("-a", "--adc-gain", default=1.2,
                  help="Set ADC gain (unitless).")
@click.option("--adc-voltage", default=2.0,
                  help="Set ADC voltage range in Volt.")
@click.option("--adc-resolution", default=12,
                  help="Set ADC resolution in bits.")
@click.option("-n", "--normalization", default=-1,
                  help="Set normalization: 0:none, <0:electrons, >0:multiplicative scale.  def=-1")
@click.option("-z", "--zero-wire-locs", default=[0.0, 0.0, 0.0], nargs=3, type=float,
              help="Set location of zero wires.  def: 0 0 0")
@click.option("--ymin", default=-40.0,
                  help="Set Y min")
@click.option("--ymax", default=60.0,
                  help="Set Y max")
@click.option("--regions", default=0, type=int,
                  help="Set how many wire regions to use, default to all")
@click.option("--dump-data", default="", type=str,
                  help="Dump the plotted data in format given by extension (.json, .txt or .npz/.npy)")
@click.argument("garfield-fileset")
@click.argument("pdffile")
@click.pass_context
def plot_garfield_track_response(ctx, gain, shaping, tick, tick_padding, electrons,
                                     adc_gain, adc_voltage, adc_resolution,
                                     normalization, zero_wire_locs,
                                     ymin, ymax, regions,
                                     dump_data,
                                     garfield_fileset, pdffile):
    '''
    Plot Garfield response assuming a perpendicular track.

    Note, defaults are chosen to reproduce the "ADC Waveform with 2D
    MicroBooNE Wire Plane Model" plot for the MicroBooNE noise paper.
    '''
    import wirecell.sigproc.garfield as gar
    import wirecell.sigproc.response as res
    import wirecell.sigproc.plots as plots

    gain *= units.mV/units.fC
    shaping *= units.us
    tick *= units.us
    electrons *= units.eplus

    adc_gain *= 1.0                       # unitless
    adc_voltage *= units.volt
    adc_resolution = 1<<adc_resolution
    adc_per_voltage = adc_gain*adc_resolution/adc_voltage

    dat = gar.load(garfield_fileset, normalization, zero_wire_locs)

    if regions:
        print ("Limiting to %d regions" % regions)
        dat = [r for r in dat if abs(r.region) in range(regions)]

    uvw = res.line(dat, electrons)

    detector = ""
    if "ub_" in garfield_fileset:
        detector = "MicroBooNE"
    if "dune_" in garfield_fileset:
        detector = "DUNE"
    print ('Using detector hints: "%s"' % detector)

    nwires = len(set([abs(r.region) for r in dat])) - 1
    #msg = "%d electrons, +/- %d wires" % (electrons, nwires)
    msg=""

    fig,data = plots.plot_digitized_line(uvw, gain, shaping,
                                         adc_per_voltage = adc_per_voltage,
                                         detector = detector,
                                         ymin=ymin, ymax=ymax, msg=msg,
                                         tick_padding=tick_padding)
    print ("plotting to %s" % pdffile)
    fig.savefig(pdffile)

    if dump_data:
        print ("dumping data to %s" % dump_data)

        if dump_data.endswith(".npz"):
            import numpy
            numpy.savez(dump_data, data);
        if dump_data.endswith(".npy"):
            import numpy
            numpy.save(dump_data, data);
        if dump_data.endswith(".txt"):
            with open(dump_data,"wt") as fp:
                for line in data:
                    line = '\t'.join(map(str, line))
                    fp.write(line+'\n')
        if dump_data.endswith(".json"):
            import json
            open(dump_data,"wt").write(json.dumps(data.tolist(), indent=4))

@cli.command("plot-response")
@click.argument("responsefile")
@click.argument("pdffile")
@click.pass_context
def plot_response(ctx, responsefile, pdffile):
    import response.persist as per
    import response.plots as plots

    fr = per.load(responsefile)
    plots.plot_planes(fr, pdffile)

@cli.command("plot-electronics-response")
@click.option("-g", "--gain", default=14.0,
              help="Set gain in mV/fC.")
@click.option("-s", "--shaping", default=2.0,
              help="Set shaping time in us.")
@click.option("-t", "--tick", default=0.5,
              help="Set tick time in us (0.1 is good for no shaping).")
@click.argument("plotfile")
@click.pass_context
def plot_electronics_response(ctx, gain, shaping, tick, plotfile):
    '''
    Plot the electronics response function.
    '''
    gain *= units.mV/units.fC
    shaping *= units.us
    tick *= units.us
    import wirecell.sigproc.plots as plots
    fig = plots.one_electronics(gain, shaping, tick)
    fig.savefig(plotfile)

@cli.command("convert-noise-spectra")
@click.option("-f","--format", default="microboonev1",
                  help="Format of input file")
@click.argument("inputfile")
@click.argument("outputfile")
@click.pass_context
def convert_noise_spectra(ctx, format, inputfile, outputfile):
    '''
    Convert an file of noise spectra in some external format into WCT format.
    '''
    loader = None
    if format == "microboonev1":
        from wirecell.sigproc.noise.microboone import load_noise_spectra_v1
        loader = load_noise_spectra_v1
    #elif:...

    if not loader:
        click.echo('Unknown format: "%s"' % format)
        sys.exit(1)

    spectra = loader(inputfile)

    from wirecell.sigproc.noise import persist
    persist.dump(outputfile, spectra)

@cli.command("plot-noise-spectra")
@click.argument("spectrafile")
@click.argument("plotfile")
@click.pass_context
def plot_noise_spectra(ctx, spectrafile, plotfile):
    '''
    Plot contents of a WCT noise spectra file such as produced by
    the convert-noise-spectra subcommand.
    '''
    from wirecell.sigproc.noise import persist, plots
    spectra = persist.load(spectrafile)
    plots.plot_many(spectra, plotfile)

@cli.command("channel-responses")
@click.option("-t","--tscale", default="0.5*us", type=str,
                  help="Scale of time axis in the histogram.")
@click.option("-s","--scale", default="1e-9*0.5/1.13312", type=str,
                  help="Scale applied to the samples.")
@click.option("-n","--name", default="pResponseVsCh",
                  help="Data name (eg, the TH2D name if using 'hist' schema")
@click.argument("infile")
@click.argument("outfile")
@click.pass_context
def channel_responses(ctx, tscale, scale, name, infile, outfile):
    '''Produce the per-channel calibrated response JSON file from a TH2D
    of the given name in the input ROOT file provided by the analysis.

    - tscale :: a number to multiply to the time axis of the histogram
      in order to bring the result into the WCT system of units.  It
      may be expressed as a string of an algebraic expression which
      includes symbols, eg "0.5*us".

    - scale :: a number multiplied to all samples in the histogram in
      order to make the sample value a unitless relative measure.  It
      may be expressed as a string of an algebraic expression which
      includes symbols, eg "0.5*us". For uBoone's initial
      20171006_responseWaveforms.root the appropriate scale is
      1e-9*0.5/1.13312 = 4.41267e-10
    '''
    import json
    import ROOT
    import numpy
    from root_numpy import hist2array

    tscale = eval(tscale, units.__dict__)
    scale = eval(scale, units.__dict__)

    tf = ROOT.TFile.Open(str(infile))
    assert(tf)
    h = tf.Get(str(name))
    if not h:
        click.echo('Failed to get histogram "%s" from %s' % (name, infile))
        sys.exit(1)

    arr,edges = hist2array(h, return_edges=True)

    arr *= scale
    tedges = edges[1]
    t0,t1 = tscale*(tedges[0:2])
    tick = t1-t0

    nchans, nticks = arr.shape
    channels = list()
    for ch in range(nchans):
        # reduce down to ~32 bit float precision to save file space
        res = [float("%.6g"%x) for x in arr[ch,:].tolist()]
        one = [ch, res]
        channels.append(one)

    dat = dict(tick=tick, t0=t0, channels=channels)

    jtext = json.dumps(dat, indent=4)
    if outfile.endswith(".json.bz2"):
        import bz2
        bz2.BZ2File(outfile, 'w').write(jtext)
        return
    if outfile.endswith(".json.gz"):
        import gzip
        gzip.open(outfile, 'wb').write(jtext) # wb?
        return

    open(outfile, 'w').write(jtext)
    return

def main():
    cli(obj=dict())

if '__main__' == __name__:
    main()


# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
# pylint: disable=unused-variable

from simcore_service_api_server.models.schemas.jobs import ArgumentType, File
from simcore_service_api_server.utils.solver_job_outputs import (
    BaseFileLink,
    ResultsTypes,
)
from simcore_service_api_server.utils.typing_extra import get_types

def test_result_type_mapped():
    # I/O types returned by node-ports must be one-to-one mapped
    # with those returned as output results

    api_arg_types = list(get_types(ArgumentType))
    output_arg_types = list(get_types(ResultsTypes))

    assert File in api_arg_types
    assert BaseFileLink in output_arg_types

    api_arg_types.remove(File)
    output_arg_types.remove(BaseFileLink)

    assert set(api_arg_types) == set(output_arg_types)


# Sebastian Staszczyk

array = [15, 8, 31, 47, 2, 19]

sum_odd = 0
ammount_odd = 0

for x in array:
    if x % 2 != 0:
        sum_odd +=x
        ammount_odd += 1
output = sum_odd / ammount_odd
print(f"Średnia arytmetyczna liczb nieparzystych: {output}")

02-ControlStructures/During class/Zad 22 - Średnia arytmetyczna liczb nieparzystych.py


import time
import sys
# information functions
def commands():
        commandList = ["commands", "square", "countChars", "make a note", "show my notes", "delete my notes", "create file", "new txt file", "new python script"]
        print(commandList)

# math functions
def square():
        vartosquare = input("insert value to square: ")
        result = int(vartosquare) ** 2
        print(result)

def countChars():
        objectToCount = input("insert string to count: ")
        counter = int(0)
        for i in str(objectToCount):
            counter += 1
        print(int(counter))

# note system
def make_a_note():
        file = open("note.txt", "a")
        newEntry = input("Inster your new entry: ")
        file.write("\n" + "- " + newEntry)
        file.close()

def show_my_notes():
        file = open("note.txt", "r")
        notes = file.read()
        print(notes)
        file.close()

def delete_my_notes():
        authentification = input("Are you sure that you want to delete all your notes?[y/n]: ")
        if authentification == "y":
                file = open("note.txt", "w")
                delete = ""
                file.write(delete)
                print("Your notes have been deleted")
        else:
                print("Your notes are not deleted")

def new_txt_file():
        filename = input("insert the filename: ")
        file = open(filename + ".txt", "w")
        content = input("start writing: ")
        file.write(content)
        file.close()

def new_script_python():
        filename = input("insert the filename: ")
        file = open(filename + ".py", "w")
        content = input("start coding: ")
        file.write(content)
        file.close()

def create_file():
        print("supported file types:")
        sup_fileT = ["1 .txt", "2 .py"]
        print(sup_fileT)
        chosen_type = input("insert the number or the filetype it self: ")
        if chosen_type == "1":
                new_txt_file()

        elif chosen_type == "2":
                new_script_python()

        else:
                print("this filetype is not supported")

def load(t=5):
    t0 = time.time()
    now = t0
    while now-t0 < t:
        now = time.time()
        timestring: str = '\r%%%i\t' % (100*(now-t0)/t)
        sys.stdout.write(timestring)
        sys.stdout.flush()
        time.sleep(0.1)

def explore_truth():
        print("truth")


def nar():

    x=str(input("enter the number"))
    y=len(x)
    list=[int(i) for i in str(x)]
    list2=[]
    print(list)

    for j in range(len(list)):
        c=pow(list[j],y)
        list2.append(c)
    print(list2)
    add = sum(list2)
    print(add)

    if add == int(x):
        print("true")
    else:
        print("false")
nar()


#! /usr/bin/env python
# -*- coding: utf-8 ; mode: python -*-
# © Copyright 2010–2 ospalh@gmail.com
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

import math
import sys
from decimal import Decimal

__version__ = '1.3.0'

year = 365.2421897

if sys.platform.startswith("win32"):
    # Chicken out. use ASCII on windows.
    day_format_separators =  {-1: '.', -3: "'", -4: "'", -6: "'" }
else:
    day_format_separators =  {-1: u'.', -3: u"’", -4: u"’", -6: u"’" }

year = 365.2421897

def omag(x):
    """Return the order of magnitude of a number."""
    try:
        return int(math.floor(math.log10(abs(x))))
    except ValueError:
        return 0

def days_formated(days=0, hours=0, minutes=0, seconds=0,
                  years=0, sigfig=3, maybe_show_years=True):
    """
    Return a value formated in a specific way.

    Returns a string that represents the number of days given as an
    argument formated in a specific way that should make parsing the
    decimal part of the age easier for humans.
    """
    days = days + hours/24.0 + minutes/1440.0 + seconds/86400.0 + \
        years*year
    # Calculate how many digits to show. Show full precision of days,
    # limited for shorter times.
    show_digits = max(sigfig - omag(days) - 1, 0)
    out_string = ''
    if 0 == show_digits:
        out_string = str(int(round(days,0)))
    else:
        decimal_days = Decimal(str(days))\
            .quantize(Decimal('0.' + '0'*(show_digits-1) + '1'))
        dec_sign, dec_digits, dec_exponent = decimal_days.as_tuple()
        ndig = len(dec_digits)
        if dec_sign:
            out_string = '-'
        for pad in range(0, dec_exponent + ndig - 1, -1):
            try:
                out_string += day_format_separators[pad]
            except KeyError:
                pass
            out_string += '0'
        for ex, dg in enumerate(dec_digits):
            # Add a decorator if it is the right position
            try:
                out_string += \
                    day_format_separators[-ex + dec_exponent + ndig - 1]
            except KeyError:
                pass
            out_string += str(dg)
    if days > year and maybe_show_years:
        out_string += " ({0:.1f} years)".format(days/year)
    return out_string


import matplotlib.pyplot as plt
from osgeo import ogr
from ospybook.vectorplotter import VectorPlotter
import random

vp = VectorPlotter(False)

# Create a point geometry
points = ogr.Geometry(ogr.wkbPoint)

# Create line geometry
line0 = ogr.Geometry(ogr.wkbLineString)
line1 = ogr.Geometry(ogr.wkbLineString)
line2 = ogr.Geometry(ogr.wkbLineString)

# Create a Multiline geometry
mainLine = ogr.Geometry(ogr.wkbMultiLineString)

# Plotting the line using a for loop assuming a range of 0 to 3

for j in range(3):
    x = j
    y0 = x+1
    y1 = x+3
    y2 = x+5
    line0.AddPoint(x, y0)
    line1.AddPoint(x, y1)
    line2.AddPoint(x, y2)

mainLine.AddGeometry(line0)
mainLine.AddGeometry(line1)
mainLine.AddGeometry(line2)

vp.plot(mainLine, 'b')

for line in range(mainLine.GetGeometryCount()):
    geom = mainLine.GetGeometryRef(line)

    for pt in range(geom.GetPointCount()):
        geom.SetPoint(pt, geom.GetX(pt) - 5, geom.GetY(pt))

vp.plot(mainLine, 'g')

plt.legend(('Initial Line','Final Line'), loc='lower right')
plt.title('ECG 33KV MULTI LINES')
plt.show()


# print ('Hello World')
# print ('Welcometo Python')
# name = raw_input('What is your name?')
# print ('Hello ' + name)

#num1 = int(input('enter first number: '))
#num2 = int(input('enter second number: '))
#sum = num1 + num2

#print(sum)

#s= 'Hello'
#str=""
#for i in s:
    #str = i + str
    #print(str)

num1 = int(input('enter number here : '))
if num1 <=10:
    print ("small")
else:
    print ("Big")


import os
import zipfile
import rarfile

def decompress(name, select=lambda file_name, extension: True):
    # get file path and extension name
    path_name, f_n = os.path.split(name)
    _, ext = os.path.splitext(f_n)

    # create compressed file object
    if ext == '.zip':
        sub_file = zipfile.ZipFile(name)
    elif ext == '.rar':
        sub_file = rarfile.RarFile(name)
    else:
        return

    # recode GBK as UTF-8
    for component in sub_file.namelist():
        try:
            utf8_name = component.decode('utf-8')
        except UnicodeDecodeError:
            utf8_name = component.decode('gbk').encode('utf-8')

        # filter files
        _, extension = os.path.splitext(utf8_name)
        if extension in ['.zip', '.rar'] or select(utf8_name, extension):
            utf8_name = path_name + '/' + utf8_name
            pathname = os.path.dirname(utf8_name)
            if not os.path.exists(pathname) and pathname != '':
                os.makedirs(pathname)
            data = sub_file.read(component)
            if not os.path.exists(utf8_name):
                fo = open(utf8_name, "w")
                fo.write(data)
                fo.close()

            # decompress recursively
            decompress(utf8_name, select)
    sub_file.close()
    os.remove(name)


# Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import (
    absolute_import, division, print_function, unicode_literals
)

from sqlalchemy import (
    Table, Column, UnicodeText, Text, Enum, DateTime
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func

from linehaul import db

downloads = Table(
    "downloads", db.metadata,
    Column(
        "id",
        UUID(),
        primary_key=True,
        nullable=False,
        server_default=func.uuid_generate_v4()
    ),

    Column("package_name", UnicodeText(), nullable=False),
    Column("package_version", UnicodeText()),
    Column(
        "distribution_type",
        Enum("sdist", "wheel", "exe", "egg", "msi", name="distribution_type")
    ),

    Column(
        "python_type",
        Enum("cpython", "pypy", "jython", "ironpython", name="python_type")
    ),
    Column("python_release", Text()),
    Column("python_version", Text()),

    Column(
        "installer_type",
        Enum(
            "browser",
            "pip",
            "setuptools",
            "distribute",
            "bandersnatch",
            "z3c.pypimirror",
            "pep381client",
            "devpi",
            name="installer_type"
        )
    ),
    Column("installer_version", Text()),

    Column("operating_system", Text()),
    Column("operating_system_version", Text()),

    Column("download_time", DateTime(), nullable=False),
    Column("raw_user_agent", Text(), nullable=False),
)


#!/usr/bin/python3
import sys
import os

def progress(blockNum, blockSize, totalSize):
    read = blockNum * blockSize
    if totalSize > 0:
        percent = read * 100 / totalSize
        s = "\r%5.0f%% " % (percent)
        sys.stderr.write(s)
        if read >= totalSize:
            sys.stderr.write("\n")
    else:
        sys.stderr.write("read %d\n" % (read,))

urls = ['https://raw.githubusercontent.com/intel-iot-devkit/sample-videos/master/one-by-one-person-detection.mp4',
        'https://raw.githubusercontent.com/intel-iot-devkit/sample-videos/master/people-detection.mp4',
        'https://raw.githubusercontent.com/intel-iot-devkit/sample-videos/master/bottle-detection.mp4']

for url in urls:
    filename = url[url.rfind("/") + 1: ]
    print ('Downloading ' + filename)
    if sys.version_info.major > 2:
        import urllib.request
        urllib.request.urlretrieve(url, os.path.join("application", "resources", filename), progress)
    else:
        import urllib
        urllib.urlretrieve(url, os.path.join("application", "resources", filename), progress)


''' Author : Susha Pozhampallan Suresh

The program takes as input the data, trains an apriori algorithm, and fp tree algorithm to find frequent dataset.

The program then creates an association rule to predict the next possible city to be searched.

'''

# Import all the libraries required

import pandas as pd
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import fpgrowth
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import association_rules

class association_mining():

    ''' Define a model that will take in the training data of sequence
        of search and predict the next possible searches given 0 to n list of searches
    '''

    def __init__(self):
        self.city = {'Chicago IL'} # the list of cities searched

    def load_data(self):

        '''
        Load the json file to a dataframe
        '''

        # path of the data here
        self.data = pd.read_json('./city_search.json')

    def sparse_transaction_encoder(self):

        '''
        Convert the training data to format that is suitable for Machine Learning models
        encode the data using transaction encoder
        '''

        # obtain list of cities from data frame
        self.data_cities = self.data['cities'].values.tolist()
        self.data_cities_list = [i[0].split(', ') for i in self.data_cities]

        # initialize the tansaction encoder
        transactionencoder = TransactionEncoder()

        #  encode the into an array format suitable for typical machine learning
        transaction = transactionencoder.fit(
            self.data_cities_list).transform(self.data_cities_list, sparse=True)

        # convert to a sparse data frame
        self.data_transaction = pd.SparseDataFrame(
            transaction, columns=transactionencoder.columns_, default_fill_value=False)

    def association_rule(self):

        '''
        Grow an fptree or use apriori algorithm to find the frequent dataset
        '''
        # self.data_itemset = apriori(self.data_transaction, min_support=0.001, use_colnames = True)
        self.data_itemset = fpgrowth(self.data_transaction, min_support=0.001, use_colnames = True)
        # create association rules for the frequent item set
        self.data_rule = association_rules(self.data_itemset, metric="confidence", min_threshold=0.01)

    def prediction_cities(self, city):

        '''
        Takes a list of cities and cities searched as input and returns the next possible city
        likely to be searched
        '''

        # Math the antecedents to the list of cities
        self.match = self.data_rule[self.data_rule['antecedents'] == city]

        #Print the consequent or list of consequents corresponding to the antecedent with highest confidece value
        self.prediction = self.data_rule.loc[self.match['confidence'].idxmax()]['consequents']

        return self.prediction

    def run(self):

        '''
        Train and predicts the next search
        '''

        data = self.load_data()
        data_transaction = self.sparse_transaction_encoder()
        data_rules = self.association_rule()
        prediction = self.prediction_cities(self.city)
        print("Cities most likely to be searched next:" , prediction)

def main():

    '''
    Function that predicts next possible search

    '''
    association_mining().run()

if __name__ == '__main__':
    main()