import argparse
import os
import time
from typing import Callable, Tuple

import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg as spla
import scipy.stats as spst
import tqdm

import hmc

parser = argparse.ArgumentParser(description='Comparison of implicit midpoint and generalized leapfrog on Bayesian logistic regression')
parser.add_argument('--dataset', type=str, default='banana', help='Logistic regression dataset')
parser.add_argument('--step-size', type=float, default=0.1, help='Integration step-size')
parser.add_argument('--num-steps', type=int, default=10, help='Number of integration steps')
parser.add_argument('--num-samples', type=int, default=1000, help='Number of samples to generate')
parser.add_argument('--thresh', type=float, default=1e-6, help='Convergence tolerance for fixed-point iterations')
parser.add_argument('--integrator', type=str, default='glf', help='Select which integrator to use; can be `glf`, `sglf`, or `imp`')
parser.add_argument('--randomize-steps', default=True, action='store_true', help='Randomize the number of integration steps')
parser.add_argument('--no-randomize-steps', action='store_false', dest='randomize_steps')
args = parser.parse_args()

# Construct posterior distribution.
distr = hmc.applications.logistic_regression
(x, y), (_, _) = distr.load_dataset(args.dataset)
alpha = 1.0
(
    log_posterior, grad_log_posterior, _,
    metric, grad_metric, _,
    grad_log_posterior_and_metric_and_grad_metric
) = distr.posterior_factory(x, y, alpha)
(
    hamiltonian, grad_pos_hamiltonian, grad_mom_hamiltonian,
    vector_field, sample_momentum
) = hmc.integrators.riemannian_hamiltonian_vector_field(
    log_posterior, grad_log_posterior, metric, grad_metric,
    grad_log_posterior_and_metric_and_grad_metric)

qmap = hmc.applications.newton_raphson(np.zeros(x.shape[-1]), grad_log_posterior, metric)
num_dims = len(qmap)
coef = ['beta-{}'.format(i+1) for i in range(num_dims)]

def experiment(method: str, step_size: float, num_steps: int, num_samples: int, proposal: Callable, randomize_steps: bool):
    """Experiment to examine the use of different integrators for sampling from the
    posterior distribution of a Bayesian logistic regression model. Given a
    proposal operator, attempts to draw samples and computes performance
    metrics for the sampler.

    Args:
        step_size: Integration step-size.
        num_steps: Number of integration steps.
        num_samples: Number of samples to generate.
        proposal: Proposal function that will yield the next state of the Markov
            chain.
        randomize_steps: Randomize the number of integration steps.

    Returns:
        samples: Samples from the Markov chain generated using the proposal
            operator.

    """
    sampler = hmc.sample(qmap, step_size, num_steps, hamiltonian, proposal, sample_momentum, randomize_sign=False, randomize_steps=randomize_steps)
    _ = next(sampler)
    samples = np.zeros((num_samples, num_dims))
    acc = 0
    pbar = tqdm.tqdm(total=num_samples, position=0, leave=True)
    start = time.time()
    for i in range(num_samples):
        samples[i], isacc = next(sampler)
        acc += isacc
        pbar.set_postfix({'accprob': acc / (i + 1)})
        pbar.update(1)

    elapsed = time.time() - start
    accprob = acc / num_samples
    print('{} - time elapsed: {:.5f} - acceptance prob.: {:.5f}'.format(method, elapsed, accprob))
    metrics = hmc.summarize(samples, coef)
    mean_ess = metrics['ess'].mean()
    mean_ess_sec = mean_ess / elapsed
    min_ess = metrics['ess'].min()
    min_ess_sec = min_ess / elapsed
    print('mean ess: {:.3f} - mean ess / sec: {:.3f} - min ess: {:.3f} - min ess / sec: {:.3f}'.format(mean_ess, mean_ess_sec, min_ess, min_ess_sec))
    return samples

def display_results(res: np.ndarray, check: str, method: str):
    """Compare the volume-preservation and reversibility properties of the two
    integrators.

    """
    res = res[~np.isnan(res) & ~np.isinf(res)]
    print('{} - {} - min.: {:.2e} - max.: {:.2e} - median: {:.2e} - 10%: {:.2e} - 90%: {:.2e}'.format(
        check, method, np.min(res), np.max(res), np.median(res), np.percentile(res, 10), np.percentile(res, 90)))

print('dataset: {} - step-size: {} - num. steps: {} - randomize steps: {}'.format(args.dataset, args.step_size, args.num_steps, args.randomize_steps))

proposal_generalized_leapfrog = hmc.proposals.generalized_leapfrog_proposal_factory(grad_pos_hamiltonian, grad_mom_hamiltonian, args.thresh)
proposal_smart_generalized_leapfrog = hmc.proposals.smart_generalized_leapfrog_proposal_factory(grad_log_posterior, metric, grad_metric, grad_log_posterior_and_metric_and_grad_metric, args.thresh)
proposal_implicit_midpoint = hmc.proposals.implicit_midpoint_proposal_factory(vector_field, args.thresh)
proposal_lagrange_implicit_midpoint = hmc.proposals.lagrange_implicit_midpoint_proposal_factory(grad_log_posterior_and_metric_and_grad_metric, args.thresh)
proposal_smart_implicit_midpoint = hmc.proposals.smart_implicit_midpoint_proposal_factory(vector_field, args.thresh)

name, proposal = {
    'limp': ('lagrange implicit midpoint', proposal_lagrange_implicit_midpoint),
    'imp': ('implicit midpoint', proposal_implicit_midpoint),
    'simp': ('smart implicit midpoint', proposal_smart_implicit_midpoint),
    'sglf': ('smart generalized leapfrog', proposal_smart_generalized_leapfrog),
    'glf': ('naive generalized leapfrog', proposal_generalized_leapfrog),
}[args.integrator]

samples = experiment(name, args.step_size, args.num_steps, args.num_samples, proposal, args.randomize_steps)
vp = hmc.checks.jacobian_determinant(samples, args.step_size, args.num_steps, proposal, sample_momentum)
rev = hmc.checks.reversibility(samples, args.step_size, args.num_steps, proposal, sample_momentum)
display_results(vp, 'volume', name)
display_results(rev, 'reverse', name)


#!/usr/bin/env python

import json
from mimetypes import guess_type
import os
from re import findall
import subprocess

from flask import abort, make_response
from werkzeug.datastructures import Headers

import app_config
import copytext
from flask import Blueprint
from render_utils import BetterJSONEncoder, flatten_app_config

static = Blueprint('static', __name__)

# Render JST templates on-demand
@static.route('/js/templates.js')
def _templates_js():
    r = subprocess.check_output(["node_modules/universal-jst/bin/jst.js", "--template", "underscore", "jst"])

    return make_response(r, 200, { 'Content-Type': 'application/javascript' })

# Render LESS files on-demand
@static.route('/less/<string:filename>')
def _less(filename):
    if not os.path.exists('less/%s' % filename):
        abort(404)

    r = subprocess.check_output(["node_modules/less/bin/lessc", "less/%s" % filename])

    return make_response(r, 200, { 'Content-Type': 'text/css' })

# Render application configuration
@static.route('/js/app_config.js')
def _app_config_js():
    config = flatten_app_config()
    js = 'window.APP_CONFIG = ' + json.dumps(config, cls=BetterJSONEncoder)

    return make_response(js, 200, { 'Content-Type': 'application/javascript' })

# Render copytext
@static.route('/js/copy.js')
def _copy_js():
    copy = 'window.COPY = ' + copytext.Copy(app_config.COPY_PATH).json()

    return make_response(copy, 200, { 'Content-Type': 'application/javascript' })

# Audio route to serve range headers for Safari.
@static.route('/assets/audio/<string:filename>')
def audio(filename):
    from flask import Response, request

    path = 'www/assets/audio/%s' % filename
    with open(path) as f:
        headers = Headers()
        headers.add('Content-Disposition', 'attachment', filename=filename)
        headers.add('Content-Transfer-Encoding','binary')

        status = 200
        size = os.path.getsize(path)
        begin = 0
        end = size - 1

        if request.headers.has_key('Range'):
            ranges = findall(r'\d+', request.headers['Range'])
            begin = int(ranges[0])
            if len(ranges) > 1:
                end = int(ranges[1])

            if begin != 0 or end != size - 1:
                status = 206
                headers.add('Accept-Ranges', 'bytes')
                headers.add('Content-Range', 'bytes %i-%i/%i' % (begin, end, end - begin) )

        headers.add('Content-Length', str( (end - begin) + 1) )

        response = Response(
            file(path),
            status = status,
            mimetype = 'application/octet-stream',
            headers = headers,
            direct_passthrough = True
        )

        return response

# Server arbitrary static files on-demand
@static.route('/<path:path>')
def _static(path):
    try:
        with open('www/%s' % path) as f:
            return make_response(f.read(), 200, { 'Content-Type': guess_type(path)[0] })
    except IOError:
        abort(404)


from im2dhist import  im2dhist
import cv2
import numpy as np
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt

def plot2DHistogram(Hist2D, title):
    # plot 2D-Histogram
    [K, _] = Hist2D.shape
    x = np.outer(np.arange(0, K), np.ones(K))
    y = x.copy().T
    # ln-ing Hist2D makes its details more prominent.
    Hist2D_ln = Hist2D.copy()
    Hist2D_ln[np.where(Hist2D_ln<=0)] = 1e-15
    z = np.log(Hist2D_ln)
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.plot_surface(x, y, z,cmap='viridis', edgecolor='none')
    ax.set_title(title)
    plt.show()

def main():
    image_name = 'assets/Plane.jpg'
    image = cv2.imread(image_name)
    # convert rgb image to gray
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 2*w_neighboring+1 is width of the square window around each pixel, when counting neiboring pixels
    # calculate 2 dimensional histogram of gray_image
    v_image_2DHisteq = im2dhist(gray_image, w_neighboring=6)
    #np.save(f'{image_name}-2D-Histogram', v_image_2DHisteq)
    # v_image_2DHisteq_cmpr = np.load(f'{image_name}-2D-Histogram.npy')
    plot2DHistogram(v_image_2DHisteq, title="2D Histogram of Plane.jpg")

if __name__ == '__main__': main()


#!/usr/bin/python
import smbus
import numpy as np
import helpers as helpers
import time
# source: https://tutorials-raspberrypi.com/measuring-rotation-and-acceleration-raspberry-pi/

# Register
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c

def read_byte(reg):
    return bus.read_byte_data(address, reg)

def read_word(reg):
    h = bus.read_byte_data(address, reg)
    l = bus.read_byte_data(address, reg + 1)
    value = (h << 8) + l
    return value

def read_word_2c(reg):
    val = read_word(reg)
    if val >= 0x8000:
        return -((65535 - val) + 1)
    else:
        return val

bus = smbus.SMBus(1)  # bus = smbus.SMBus(0) fuer Revision 1
address = 0x68  # via i2cdetect

# Activate to be able to address the module
bus.write_byte_data(address, power_mgmt_1, 0)
while True:
    gyro_x = read_word_2c(0x43) / 131
    gyro_y = read_word_2c(0x45) / 131
    gyro_z = read_word_2c(0x47) / 131

    acc_x = read_word_2c(0x3b) / 16384.0
    acc_y = read_word_2c(0x3d) / 16384.0
    acc_z = read_word_2c(0x3f) / 16384.0

    # convert to Angles and Angular Velocities:
    factor = 180/np.pi  # set to 1 if output in radians.
    roll, pitch, yaw = helpers.get_roll_pitch_yaw(acc_x, acc_y, acc_z, factor=factor)

    # log incoming data:
    print('-- Raw data:')
    print("gyro [deg/sec] wx,wy,wz: {0:.2f},{1:.2f},{2:.2f}".format(gyro_x, gyro_y, gyro_z))
    print("acc  [       ] ax,ay,az: {0:.2f},{1:.2f},{2:.2f}".format(acc_x, acc_y, acc_z))
    print('-- angles acc only: factor=1 (radians), factor=180/pi (degrees)')
    print("roll,pitch,yaw: {0:.2f},{1:.2f},{2:.2f}".format(roll, pitch, yaw))
    time.sleep(1)


writing = 'Ala ma <kota>, a kot ma Alę'
startPosition = None
endPosition = None

for position, letter in enumerate(writing):
    if letter == '<':
        startPosition = position
    elif letter == '>':
        endPosition = position - 1
        break

print(f'Between <> are {endPosition - startPosition} signs')


"""
5978. 统计追加字母可以获得的单词数
给你两个下标从 0 开始的字符串数组 startWords 和 targetWords 。每个字符串都仅由 小写英文字母 组成。
对于 targetWords 中的每个字符串，检查是否能够从 startWords 中选出一个字符串，执行一次 转换操作 ，得到的结果与当前 targetWords 字符串相等。
转换操作 如下面两步所述：
追加 任何 不存在 于当前字符串的任一小写字母到当前字符串的末尾。
例如，如果字符串为 "abc" ，那么字母 'd'、'e' 或 'y' 都可以加到该字符串末尾，但 'a' 就不行。如果追加的是 'd' ，那么结果字符串为 "abcd" 。
重排 新字符串中的字母，可以按 任意 顺序重新排布字母。
例如，"abcd" 可以重排为 "acbd"、"bacd"、"cbda"，以此类推。注意，它也可以重排为 "abcd" 自身。
找出 targetWords 中有多少字符串能够由 startWords 中的 任一 字符串执行上述转换操作获得。返回 targetWords 中这类 字符串的数目 。
注意：你仅能验证 targetWords 中的字符串是否可以由 startWords 中的某个字符串经执行操作获得。startWords  中的字符串在这一过程中 不 发生实际变更。
"""
import collections
from typing import List

def wordCount(startWords: List[str], targetWords: List[str]) -> int:
    def calculateHash(word):
        hashCode = 0
        for ch in word:
            hashCode = hashCode * 26
            hashCode += ord(ch) - ord('a')
        return hashCode

    dictionary = collections.defaultdict(set)
    for word in startWords:
        dictionary[len(word)].add(calculateHash(sorted(word)))
    result = 0
    for word in targetWords:
        currentCounter = collections.Counter(word)
        if len(word) - 1 not in dictionary:
            continue
        currentWord = sorted(word)
        for i in range(len(word)):
            if currentCounter[currentWord[i]] == 1:
                testWord = currentWord[:i] + currentWord[i + 1:]
                if calculateHash(testWord) in dictionary[len(word) - 1]:
                    result += 1
                    break
    return result

def wordCountVersion2(startWords: List[str], targetWords: List[str]) -> int:
    def toNumber(word: str):
        hashNumber = 0
        for i in range(len(word)):
            hashNumber += 1 << (ord(word[i]) - ord('a'))
        return hashNumber

    wordSet = set()
    for word in startWords:
        wordSet.add(toNumber(word))
    result = 0
    for word in targetWords:
        totalCode = toNumber(word)
        for ch in word:
            if totalCode - (1 << (ord(ch) - ord('a'))) in wordSet:
                result += 1
                break
    return result

5978. 统计追加字母可以获得的单词数.py


import wx
from common import utils

class PreviewPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent, style=wx.BORDER_RAISED)
        # hbox_header = wx.GridBagSizer(hgap=10, vgap=0)
        hbox_header = wx.BoxSizer(wx.HORIZONTAL)
        lbl_header = wx.StaticText(self, -1, "Preview of data to be generated")
        # lbl_header.SetFont(wx.Font(9, wx.DECORATIVE, wx.NORMAL, wx.NORMAL))
        refresh_icon = utils.resize_images(r'.\icons\refresh-icon_1.png', 10, 10)
        btn_refresh = wx.BitmapButton(self, wx.ID_ANY, wx.Bitmap(refresh_icon))#, style=wx.NO_BORDER)
        hbox_header.Add(lbl_header, flag=wx.ALIGN_LEFT | wx.EXPAND)
        hbox_header.Add(btn_refresh, flag=wx.ALIGN_RIGHT | wx.EXPAND)
        header_line = wx.StaticLine(self, wx.ID_ANY)
        config_box = wx.BoxSizer(wx.VERTICAL)
        # self.SetMinSize((800,400))

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(hbox_header, 0, wx.ALIGN_TOP | wx.TOP | wx.EXPAND, 5)
        sizer.Add(header_line, 0, wx.ALIGN_TOP | wx.TOP | wx.EXPAND, 5)
        self.SetSizer(sizer)


#import OpenGL
#OpenGL.ERROR_CHECKING = False
#from OpenGL.GL import *
#from OpenGL.GLU import *
#import math

from OpenVG import VG
from OpenVG import VGU
from OpenVG.constants import *
from random import random
import math

from parameters import pe

class TestSprite(object):

    def __init__(self):
        VG.create_context((2048,2048))

        self.x = 0
        self.y = -.99
        self.vr = 10
        self.vt = math.pi/2
        self.at = 0

    def render(self):
        if (pe.square_a != 0.0 and pe.vg_mode == 3):
            VG.set(VG_STROKE_LINE_WIDTH, 15.0)

            fill_paint = VG.ColorPaint((pe.square_r, pe.square_g, pe.square_b, pe.square_a))
            stroke_paint = VG.ColorPaint((  0.65 + 0.350*( 0.60*math.sin(0.742*pe.time) +
                                                           0.40*math.sin(1.021*pe.time) ),
                                            0.65 + 0.350*( 0.60*math.sin(0.703*pe.time) +
                                                           0.40*math.sin(0.969*pe.time) ),
                                            0.65 + 0.350*( 0.60*math.sin(1.090*pe.time) +
                                                           0.40*math.sin(0.963*pe.time) ),
                                            pe.square_a))
            VG.set_paint(fill_paint, VG_FILL_PATH)
            VG.set_paint(stroke_paint, VG_STROKE_PATH)

            p = VG.Path(capabilities=VG_PATH_CAPABILITY_APPEND_TO)

            vx=self.vr*math.cos(self.vt)
            vy=self.vr*math.sin(self.vt)

            p.move_to((self.x,self.y))
            self.x+=vx
            self.y+=vy
            p.line_to((self.x,self.y))

            VG.set(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE)
            VG.load_identity()
            VG.scale(0.001, 0.001)
            p.draw(VG_STROKE_PATH);

            if random()<.01:
                self.at = 0

            if self.x<-1000 or self.x>1000 or self.y<-1000 or self.y>1000:
                self.x=0
                self.y=0

            self.vt += (random()-.5)*.1
            self.vt += self.at
            self.at += (random()-.5)*.1


#!/usr/bin/python3

""" This is a decription of this module .

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
"""

class Node:
    """A class Node that defines a node of a singly linked list by:
    """
    def __init__(self, data=0, next_node=None):
        """
         The __init__ method may be documented in either the class level
        docstring, or as a docstring on the __init__ method itself.
        Args:
            data (int): integer var.
            next (Node): the node
        """
        if not isinstance(data, int):
            raise TypeError("data must be an integer")
        self.__data = data
        if next_node is not None and not isinstance(next_node, Node):
            raise TypeError("next_node must be a Node object")
        self.__next_node = next_node
    """  Attributes:
        __data:  must be an integer, otherwise raise a TypeError exception
        with the message data must be an integer
        __next_node:next_node can be None or must be a Node, otherwise raise
        a TypeError exception with the message
        next_node must be a Node object"""

    @property
    def data(self):
        """property def data(self): to retrieve it"""
        return self.__data

    @data.setter
    def data(self, value):
        """property setter def data(self, value): to set it
        Args:
            value (int): set the __data to value.
        If the setter method contains notable behavior, it should be
        mentioned here.
        """
        if not isinstance(value, int):
            raise TypeError("data must be an integer")
        self.__data = value

    @property
    def next_node(self):
        """property def next_node(self): to retrieve it
        """
        return self.__next_node

    @next_node.setter
    def next_node(self, value):
        """property setter def next_node(self, value): to set it
        Args:
            value (int): set the __postion to value.
        If the setter method contains notable behavior, it should be
        mentioned here.
        """
        if value is not None and not isinstance(value, Node):
            raise TypeError("next_node must be a Node object")
        self.__next_node = value
        return self.__next_node

class SinglyLinkedList:
    """a class SinglyLinkedList that defines a singly linked list"""
    def __init__(self, head=None) -> None:
        """Simple instantiation: def __init__(self):"""
        self.__head = head
        """ Attributes:
        __head: Private instance attribute: head (no setter or getter)"""
    def sorted_insert(self, value):
        """Public instance method: def sorted_insert(self, value):
        that inserts a new Node into the correct sorted position in
        the list (increasing order)"""
        node = Node(value, None)
        tmp = self.__head
        prev = self.__head
        if self.__head is None:
            node.next_node = None
            self.__head = node
            return self.__head
        if self.__head.data >= node.data:
            node.next_node = self.__head
            self.__head = node
            return self.__head
        while (tmp is not None):
            if node.data <= tmp.data:
                node.next_node = tmp
                prev.next_node = node
                break
            elif node.data > tmp.data and tmp.next_node is None:
                tmp.next_node = node
                node.next_node = None
                break
            prev = tmp
            tmp = tmp.next_node
        return self.__head

    def __str__(self) -> None:
        """_str__ make the singly_linked_list printable:
        =>print the entire list in stdout
        =>one node number by line"""
        tmpnode = self.__head
        flag = False
        while tmpnode is not None:
            if not tmpnode.next_node:
                flag = True
                break
            print(f"{tmpnode.data}")
            tmpnode = tmpnode.next_node
        if flag:
            print(f"{tmpnode.data}", end='')
        return ''


import sys

from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QFileDialog, QFontDialog
from PyQt5.QtCore import Qt
import sqlite3
import datetime as dt
import os

class Notepad2(QMainWindow):
    def __init__(self):
        super().__init__()
        self.count = 0
        self.idofnote = 0
        uic.loadUi('notepad.ui', self)
        self.initUI()

    def initUI(self):
        self.setStyleSheet("background-color: white;")
        self.label_2.hide()
        self.lineEdit_2.hide()
        self.pushButton_4.hide()
        self.checkBox.stateChanged.connect(self.check)
        self.pushButton.clicked.connect(self.save)
        self.pushButton_2.clicked.connect(self.open)
        self.pushButton_4.clicked.connect(self.search)
        self.pushButton_5.clicked.connect(self.themes)
        self.pushButton_6.clicked.connect(self.font_change)
        self.pushButton_7.clicked.connect(self.delete_file)
        self.create()

    def create(self):
        self.con = sqlite3.connect("notes.db")
        create = self.con.cursor()
        create.execute("""CREATE TABLE IF NOT EXISTS Notes(
                       title TEXT NOT NULL,
                       id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                       date TEXT NOT NULL,
                       time TEXT NOT NULL);
                       """)
        self.con.commit()

    def save(self):
        text = self.textEdit.toPlainText()
        text = text.split("\n")
        self.title = self.lineEdit.text()
        if len(self.title) != 0:
            self.add_in_bd(self.title)
            file = open(f"{self.title}.txt", "w", encoding="utf-8")
            for line in text:
                print(line, file=file)
            QMessageBox.about(self, "Сохранение", f"Файл сохранён. Ему присвоен id {self.currentid}")
            file.close()

        else:
            self.title = "Безымянный"
            self.add_in_bd(self.title)
            file = open(f"{self.title}.txt", 'w', encoding="utf-8")
            for line in text:
                print(line, file=file)
            QMessageBox.about(self, "Сохранение", f"Файл сохранён. Ему присвоен id {self.currentid}")
            file.close()

    def add_in_bd(self, title, saving=False):
        self.title = title
        self.added_in_bd = False
        date = str(dt.datetime.now()).split()
        dat = date[0].split(":")
        dat = dat[0].split("-")
        dat = f"{dat[2]}-{dat[1]}-{dat[0]}"
        time = date[1]
        time = time.split(":")
        time = f"{time[0]}:{time[1]}"
        curs = self.con.cursor()
        curs2 = self.con.cursor()
        cursor = self.con.cursor()
        all_id = curs.execute("""SELECT id from Notes""").fetchall()
        titles = curs2.execute("""SELECT title from Notes""").fetchall()
        titles = [str(i[0]) for i in titles]
        all_id = [int(i[0]) for i in all_id]
        if all_id:
            self.idofnote = max(all_id)

        if all_id and self.title not in titles:
            self.idofnote += + 1
            self.currentid = self.idofnote
            cursor.execute("""INSERT INTO notes(title, date, time)
                        VALUES (?, ?, ?)""", (self.title, dat, time))
            if saving:
                self.added_in_bd = True
            self.con.commit()

        elif all_id and self.title in titles and saving is False:
            rewrite = QMessageBox.question(self, "Перезапись", "Файл с таким названием найден. Перезаписать?",
                                           QMessageBox.Yes, QMessageBox.No)
            if rewrite == QMessageBox.Yes:
                new_id = self.idofnote + 1
                self.currentid = new_id
                cursor.execute("""UPDATE Notes
                            SET id = ?
                            WHERE title = ?""", (new_id, self.title))
                self.con.commit()

            elif rewrite == QMessageBox.No:
                curs4 = self.con.cursor()
                alltitles = curs4.execute("""SELECT title from Notes
                                       WHERE title like ?""", ('{}(_)'.format(self.title),)).fetchall()
                lentitles = len(alltitles)
                if lentitles == 0:
                    lentitles += 1
                self.idofnote += 1
                self.currentid = self.idofnote
                self.title = f"{self.title}({lentitles})"
                cursor.execute("""INSERT INTO notes(title, date, time)
                                                    VALUES (?, ?, ?)""", (self.title, dat, time))
                self.con.commit()

        elif len(all_id) == 0:
            cursor.execute("""INSERT INTO notes(title, date, time)
                                    VALUES (?, ?, ?)""", (self.title, dat, time))
            self.currentid = cursor.execute("""SELECT id from notes WHERE title = ?""", (self.title,)).fetchone()[0]
            if saving:
                self.added_in_bd = True
            self.con.commit()

    def open(self):
        self.textEdit.clear()
        filename = QFileDialog.getOpenFileName(
            self, 'Выбрать файл', '',
            'Текстовый файл (*.txt)')[0]
        if filename:
            file = open(filename, encoding="utf-8")
            lines = file.readlines()
            lines = [line.rstrip() for line in lines]
            self.lineEdit.setText("")
            path = filename.split("/")
            name = path[-1].split(".txt")
            name = name[0]
            self.lineEdit.setText(name)
            for line in lines:
                self.textEdit.append(line)
            file.close()
            self.add_in_bd(name, True)
            if self.added_in_bd:
                QMessageBox.about(self, "Загрузка", f"Файл загружен. Его id {self.currentid}")

    def check(self, state):
        if state == Qt.Checked:
            self.label_2.show()
            self.lineEdit_2.show()
            self.pushButton_4.show()

        else:
            self.label_2.hide()
            self.lineEdit_2.hide()
            self.pushButton_4.hide()
            self.lineEdit_2.setText("")

    def font_change(self):
        font, ok_pressed = QFontDialog.getFont()
        if ok_pressed:
            self.textEdit.setFont(font)
            self.lineEdit.setFont(font)
            self.lineEdit_2.setFont(font)

    def search(self):
        search_text = self.lineEdit_2.text()
        con = sqlite3.connect("notes.db")
        curs5 = con.cursor()
        if search_text.isdigit():
            result_of_search = curs5.execute("""SELECT title from Notes
                                          WHERE id = ?""", (search_text,)).fetchall()
            if result_of_search:
                result_of_search = result_of_search[0][0]
                request = QMessageBox.question(self, "Поиск", f"Файл с id {search_text} найден. Загрузить?",
                                               QMessageBox.Yes, QMessageBox.No)
                if request == QMessageBox.Yes:
                    self.load(result_of_search)
            else:
                QMessageBox.about(self, "Поиск",
                                  "Файл не найден. Возможно его нет в базе данных или введён неверный id.")
        elif len(search_text) != 0:
            result_of_search = curs5.execute("""SELECT title from Notes
                                          WHERE title = ?""", (search_text,)).fetchall()
            if result_of_search:
                request = QMessageBox.question(self, "Поиск",
                                               f'Файл с названием "{result_of_search[0][0]}" найден. Загрузить?',
                                               QMessageBox.Yes, QMessageBox.No)
                if request == QMessageBox.Yes:
                    self.load(search_text)
            else:
                QMessageBox.about(self, "Поиск",
                                  "Файл не найден. Возможно его нет в базе данных или введено неверное название.")
        elif len(search_text) == 0:
            QMessageBox.about(self, "Поиск", "Введён неверный запрос.")

    def load(self, title):
        self.textEdit.clear()
        file = open(f"{title}.txt", encoding="utf-8")
        lines = file.readlines()
        lines = [line.rstrip() for line in lines]
        self.lineEdit.setText("")
        self.lineEdit.setText(title)
        for line in lines:
            self.textEdit.append(line)

    def themes(self):
        if self.count == 0:
            self.pushButton_5.setText(f"Светлая тема")
            self.setStyleSheet("background-color: black; color: white;")
            self.pushButton.setStyleSheet("background-color: grey")
            self.pushButton_2.setStyleSheet("background-color: grey")
            self.pushButton_4.setStyleSheet("background-color: grey")
            self.pushButton_5.setStyleSheet("background-color: grey")
            self.pushButton_6.setStyleSheet("background-color: grey")
            self.pushButton_7.setStyleSheet("background-color: grey")
            self.textEdit.setStyleSheet("background-color: rgb(190, 190, 190, 255)")
            self.lineEdit.setStyleSheet("background-color: rgb(190, 190, 190, 255)")
            self.lineEdit_2.setStyleSheet("background-color: rgb(190, 190, 190, 255)")
            self.count = 1

        else:
            self.pushButton_5.setText(f"Тёмная тема")
            self.setStyleSheet("background-color: white;")
            self.pushButton.setStyleSheet("background-color: white;")
            self.pushButton_2.setStyleSheet("background-color: white;")
            self.pushButton_4.setStyleSheet("background-color: white;")
            self.pushButton_5.setStyleSheet("background-color: white;")
            self.pushButton_6.setStyleSheet("background-color: white")
            self.pushButton_7.setStyleSheet("background-color: white")
            self.textEdit.setStyleSheet("background-color: white;")
            self.lineEdit.setStyleSheet("background-color: white")
            self.lineEdit_2.setStyleSheet("background-color: white")
            self.count = 0

    def delete_file(self):
        filename = QFileDialog.getOpenFileName(
            self, 'Выбрать файл для удаления', '',
            'Текстовый файл (*.txt)')[0]
        if filename:
            path = filename.split("/")
            name = path[-1].split(".txt")
            name = name[0]
            self.check_in_db(name)
            if self.check_in_db:
                delete_yes = QMessageBox.question(self, "Удаление",
                                               f'Удалить файл {name} ?',
                                               QMessageBox.Yes, QMessageBox.No)
                if delete_yes:
                    cursor = self.con.cursor()
                    cursor.execute("DELETE FROM notes WHERE title = ?", (name,))
                    self.con.commit()
                    os.remove(filename)
                    if self.lineEdit.text() == name:
                        self.lineEdit.setText("")
                        self.textEdit.clear()
                    QMessageBox.about(self, "Удаление", "Файл удалён.")
            else:
                delete_yes = QMessageBox.question(self, "Удаление",
                                                  f'Удалить файл {name} ?',
                                                  QMessageBox.Yes, QMessageBox.No)
                if delete_yes:
                    os.remove(filename)
                    if self.lineEdit.text() == name:
                        self.lineEdit.setText("")
                        self.textEdit.clear()
                    QMessageBox.about(self, "Удаление", "Файл удалён.")
        else:
            QMessageBox.about(self, "Удаление", "Файл не выбран.")

    def check_in_db(self, title):
        self.file_in_db = False
        cursor = self.con.cursor()
        titles = cursor.execute("""SELECT title from notes""")
        if title in titles:
            self.file_in_db = True

def except_hook(cls, exception, traceback):
    sys.__excepthook__(cls, exception, traceback)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Notepad2()
    ex.show()
    sys.exit(app.exec_())


from dummy_equation_solver import *

import sys
sys.path.append("../../CodeObserver")

from graphic_smoother import *
from dummy_equation_solver import *
from matplotlib import pyplot as plt
import statistics

median = statistics.mean(all_resistance_values)
sigma = statistics.stdev(all_resistance_values)

print("____________________________________________")
print("Mean value is:", median)
print("Standard deviation is:", sigma)

range_min_value = median - sigma
range_max_value = median + sigma

satisfies_range = lambda x: range_min_value <= x <= range_max_value

used_resistances = [value for value in all_resistance_values if satisfies_range(value)]
used_resistance_indexes = [index for (index, value) in enumerate(all_resistance_values) if satisfies_range(value)]

used_dispersion_sum = 0
for r_index in used_resistance_indexes:
	used_dispersion_sum += all_resistance_dispersions[r_index]

resistance_dispersion_average = used_dispersion_sum / len(used_resistance_indexes)
resultant_resistance_dispersion = resistance_dispersion_average / (len(used_resistance_indexes) / 2)
print("Resultant resistance dispersion:", resultant_resistance_dispersion)

print("Resistances left after dropping out: ", used_resistances)

if __name__ == '__main__':
	from equation_solving_optimization import optimal_r
	print("Optimal R is:", optimal_r)

	distribution_density = count_density(all_resistance_values, 0.1, 1000, smoothing_normal)
	# print(distribution_density)

	# Distribution:
	plt.plot([i[0] for i in distribution_density], [i[1] for i in distribution_density])

	# Points
	plt.scatter(all_resistance_values, [0] * len(all_resistance_values), color="red", edgecolors = "darkred", s=[200]*len(all_resistance_values))

	# Median:
	max_density_value = max([i[1] for i in distribution_density])
	print(f"Max density value is {max([i[1] for i in distribution_density])}")
	plt.plot([median, median], [0, max_density_value], linestyle = ":", label = "Median", color = "#0FD00F")

	# Median - sigma:
	plt.plot([range_min_value, range_min_value], [0, max_density_value], linestyle = "-.", color = "#FF1111", label = "Range start")

	# Median + sigma:
	plt.plot([range_max_value, range_max_value], [0, max_density_value], linestyle = "--", color = "#FF1111", label = "Range end")

	# Optimal R value:
	plt.plot([optimal_r, optimal_r], [0, max_density_value], linestyle = "-.", color = "cyan", label = "Optimal resistance", linewidth = 5)

	plt.legend()
	plt.show()


from copy import copy
from typing import List

class Triangulo:
    def __init__(self, lado1: float, lado2: float, lado3: float):
        self.lado3: float = lado3
        self.lado2: float = lado2
        self.lado1: float = lado1

    def is_triangulo(self):
        lados: List[float] = [self.lado1, self.lado2, self.lado3]

        for pos, lado in enumerate(lados):
            lados_copy = copy(lados)
            lados_copy.pop(pos)
            if not (abs(lados_copy[0] - lados_copy[1]) < lado < sum(lados_copy)):
                return False
        return True

    def print_lados(self):
        for pos, lado in enumerate([self.lado1, self.lado2, self.lado3]):
            print(f'lado{pos}: {lado}')

class TrianguloRetangulo(Triangulo):

    def __init__(self, cateto1: float = None, cateto2: float = None, hipotenusa: float = None):
        cateto1, cateto2, hipotenusa = self.validacao_inicial_dos_lados_informados(cateto1, cateto2, hipotenusa)
        super().__init__(cateto1, cateto2, hipotenusa)

    def validacao_inicial_dos_lados_informados(self, cateto1, cateto2, hipotenusa):
        if self.has_mais_de_dois_nulos([cateto1, cateto2, hipotenusa]):
            raise ValueError('É necessário ter pelo menos 2 valores não nulos')
        elif not hipotenusa:
            hipotenusa = self.calcular_hipotenusa(cateto1, cateto2)
        elif not cateto1:
            cateto1 = self.calcular_cateto(cateto2, hipotenusa)
        elif not cateto2:
            cateto1 = self.calcular_cateto(cateto1, hipotenusa)
        else:
            if not (hipotenusa == self.calcular_hipotenusa(cateto1, cateto2)):
                raise ValueError('Valor de hipotenuas inválido')
        return cateto1, cateto2, hipotenusa

    def has_mais_de_dois_nulos(self, lados: list) -> bool:
        contador_nulos = 0
        for lado in lados:
            if lado == None:
                contador_nulos += 1

            if contador_nulos >= 2:
                return True

        return False

    def calcular_hipotenusa(self, cateto1: float, cateto2: float) -> float:
        return round((cateto1 ** 2 + cateto2 ** 2) ** 0.5, 2)

    def calcular_cateto(self, cateto: float, hipotenusa: float) -> float:
        if cateto >= hipotenusa:
            raise ValueError('Cateto maior ou igual a Hipotenusa')

        return round((hipotenusa ** 2 - cateto ** 2) ** 0.5, 2)

    def is_triangulo_retangulo(self) -> bool:
        if not self.is_triangulo():
            return False

        lados: set = {self.lado1, self.lado2, self.lado3}
        cateto1 = lados.pop()
        cateto2 = lados.pop()
        hipotenusa = lados.pop()

        return hipotenusa == self.calcular_hipotenusa(cateto1, cateto2)

    def get_hipotenusa(self) -> float:
        lados: set = {self.lado1, self.lado2, self.lado3}
        return max(lados)

    def get_menor_cateto(self) -> float:
        lados: set = {self.lado1, self.lado2, self.lado3}
        return min(lados)

    def get_maior_cateto(self) -> float:
        lados = {self.lado1, self.lado2, self.lado3}
        lados.pop()
        return min(lados)

    def get_catetos(self) -> List[float]:
        return list({self.get_menor_cateto(), self.get_maior_cateto()})

    def print_lados(self):
        print(f'cateto_menor: {self.get_menor_cateto()}')
        print(f'cateto_maior: {self.get_maior_cateto()}')
        print(f'hipotenusa: {self.get_hipotenusa()}')


#!/usr/bin/env python3

from nucleus.constants import NETS, DATASETS
import argparse
import sys
import numpy as np
import os

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

def get_args():
    parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
    parser.add_argument("--net")
    parser.add_argument("--dataset")
    parser.add_argument("--test_root")
    parser.add_argument("--train_root")
    parser.add_argument("--model_dir")
    parser.add_argument("--epoch", type=int)
    parser.add_argument("--learning_rate", type=float)
    parser.add_argument("--solution_dir", default="")
    parser.add_argument("--batch_size", type=int, default=2)
    parser.add_argument("--input_height", type=int)
    parser.add_argument("--input_width", type=int)
    return parser.parse_args()

def print_train_info(net, dataset, test_root, train_root, model_dir, solution_dir, batch_size,
                     input_height, input_width, learning_rate,
                     train_data_count, test_data_count):
    msg_info = "+------------+\n"
    msg_info += "| Train Info |\n"
    msg_info += "+------------+\n"
    msg_info += "-- net: {}\n".format(net)
    msg_info += "-- dataset: {}\n".format(dataset)
    msg_info += "-- model directory: {}\n".format(model_dir)
    msg_info += "-- solution directory: {}\n".format(solution_dir)
    msg_info += "-- batch size: {}\n".format(batch_size)
    msg_info += "-- learning rate: {}\n".format(learning_rate)
    msg_info += "+-----------+\n"
    msg_info += "| Data Info |\n"
    msg_info += "+-----------+\n"
    msg_info += "-- test root: {}\n".format(test_root)
    msg_info += "-- train root: {}\n".format(train_root)
    msg_info += "-- input height: {}\n".format(input_height)
    msg_info += "-- input width: {}\n".format(input_width)
    msg_info += "-- train data count: {}\n".format(train_data_count)
    msg_info += "-- test data count: {}\n\n".format(test_data_count)
    print(msg_info)
    with open("{}.info".format(model_dir.rstrip("/")), mode="a") as f_info:
        f_info.write(msg_info)

def train(net_name, dataset, test_root, train_root, model_dir, epoch,
          solution_dir, batch_size, input_height, input_width, learning_rate):

    data = DATASETS[dataset]((input_height, input_width), test_root, train_root)
    input_height, input_width = data.img_size

    if os.path.exists(model_dir):
        net = NETS[net_name](input_height, input_width, learning_rate, init_vars=False)
        net.restore_model(model_dir, epoch)
    else:
        net = NETS[net_name](input_height, input_width, learning_rate)

    print_train_info(net_name, dataset, test_root, train_root, model_dir, solution_dir, batch_size,
                     input_height, input_width, learning_rate,
                     data.train_data_count, data.test_data_count)

    epoch_count = 0
    epoch_step = 0
    all_steps = 0
    while True:
        batch_xs, batch_ys = data.get_next_train_batch(batch_size,
                                                       solution_dir=solution_dir)

        net.session.run(net.train_step, feed_dict={net.x: batch_xs, net.y_: batch_ys})

        epoch_step += 1
        if epoch_step == (data.train_data_count // batch_size) or all_steps == 0:

            net.save_model(model_dir, epoch_count)

            train_cost = net.cost.eval(feed_dict={net.x: batch_xs, net.y_: batch_ys})
            train_accuracy = net.accuracy.eval(feed_dict={net.x: batch_xs, net.y_: batch_ys})

            test_cost = 0
            test_accuracy = 0
            for test_img in data.test_data:
                test_x, test_y = data.get_test_imgs(test_img, solution_dir)
                test_x = np.array([test_x])
                test_y = np.array([test_y])

                test_accuracy += net.accuracy.eval(feed_dict={net.x: test_x, net.y_: test_y})
                test_cost += net.cost.eval(feed_dict={net.x: test_x, net.y_: test_y})

            test_cost = test_cost / data.test_data_count
            test_accuracy = test_accuracy / data.test_data_count

            all_steps += epoch_step
            epoch_step = 0
            epoch_count += 1

            print("----------------------------------")
            print("Epoch {}\nStep: {}\n-- "
                  "Cost\n----> Train: {}\n----> Test: {}".format(epoch_count, all_steps, train_cost, test_cost))
            print("-- Accuracy\n----> Train {}\n----> Test: {}".format(train_accuracy, test_accuracy))
            print("----------------------------------")
            with open("{}.log".format(model_dir.rstrip("/")), mode="a") as log:
                log.write("{},{},{},{}\n".format(test_cost, train_cost, test_accuracy, train_accuracy))
        else:
            msg = "Current step: {}".format(epoch_step)
            sys.stdout.write(msg + len(msg) * "\r")

if __name__ == "__main__":
    args = get_args()
    train(args.net,
          args.dataset,
          args.test_root,
          args.train_root,
          args.model_dir,
          args.epoch,
          args.solution_dir,
          args.batch_size,
          args.input_height,
          args.input_width,
          args.learning_rate)


import cjson
from operator import itemgetter
infile = '/spare/wei/tag_user_dict_sift'
taglist=[]
for line in open(infile,'r'):
    line=cjson.decode(line)
    taglist.append(line)
aaa=sorted(taglist,key=itemgetter(2),reverse=1)
tag_user_coverage=[]
tag_user_cnt=[]
users=[]
last_tag_sum=0
for ls in aaa:
    tag_user_cnt.append([ls[0],len(ls[1])])
    num_new=0
    for key,value in ls[1].iteritems():
        if key not in users:
            num_new+=1
            users.append(key)
    tag_user_coverage.append([ls[0],num_new,num_new+last_tag_sum])
    last_tag_sum=num_new+last_tag_sum
outfile=open('/spare/wei/tag_user_coverage','w')
outfile.write(cjson.encode(tag_user_coverage)+'\n')
outfile.write(cjson.encode(tag_user_cnt)+'\n')


"""
Classes that provide files and classes to the ImgDataset.
"""
__authors__ = "Nicu Tofan"
__copyright__ = "Copyright 2015, Nicu Tofan"
__credits__ = ["Nicu Tofan"]
__license__ = "3-clause BSD"
__maintainer__ = "Nicu Tofan"
__email__ = "nicu.tofan@gmail.com"

import csv
import functools
import Image
import logging
import numpy
import os
from pylearn2.utils import as_floatX
from pylearn2.utils.string_utils import preprocess
from pylearn2.utils.rng import make_np_rng

class Provider(object):
    """
    Abstract class providing the interface for data providers.

    If implementations below are not suited for your needs implement a
    subclass of this class. The methods to be implemented are ``next()``
    and ``category()``.

    Parameters
    ----------
    categories : list, optional
        A list of categories; if empty the provider will use `get_categs()`.
    """
    def __init__(self, categs=None):
        if not categs is None:
            if isinstance(categs, Provider):
                self.categs = categs.categories()
            else:
                self.categs = categs
        super(Provider, self).__init__()

    def next(self):
        """
        Either gets the name of next file or throws StopIteration.

        Returns
        -------
        fpath : str
            Path for next file to be considered.
        """
        raise NotImplementedError()

    def __next__(self):
        """
        Get next file.

        Returns
        -------
        fpath : str
            Path for next file to be considered.
        """
        return self.next()

    def cnext(self):
        """
        Gets next file; if the end is reached first file is returned
        """
        raise NotImplementedError()

    def __len__(self):
        """
        Number of files stored inside.

        Returns
        -------
        len : int
            A non-negative integer.
        """
        return len(self.everything())

    def __iter__(self):
        """
        Standard interface for iterators.
        """
        return self

    def setup(self, dataset):
        """
        Called by the dataset once it initialized itself.
        """
        pass
        #assert isinstance(dataset, ImgDataset)

    def tear_down(self):
        """
        Called by the dataset fromits tear_down() method.
        """
        pass

    @staticmethod
    def normalize_image(img):
        """
        Converts an image into the format used by ``read()``.
        """
        if img.mode == 'LAB' or img.mode == 'HSV':
            raise ValueError('%s image mode is not supported' % img.mode)
        img = img.convert('RGBA')
        imarray = as_floatX(numpy.array(img)) / 255.0
        assert numpy.all(imarray >= 0.0) and numpy.all(imarray <= 1.0)
        assert len(imarray.shape) == 3
        assert imarray.shape[2] == 4
        return imarray

    def read(self, f_path):
        """
        Read a file and return an image and its category as a tuple.

        This method only reads internal images. For a more general method
        see `read_image()`.

        The returned array has (0, 1, 'c') shape, with c always 4
        (r, g, b, a) and datatype being floatX.

        Parameters
        ----------
        f_path : str
            The path as returned by a previous ``next()`` call.

        Returns
        -------
        result : tuple
            First member is the image as an numpy array,
            second is the category.
        """
        categ = self.category(f_path)
        logging.debug('generator reading [%s] from %s', categ, f_path)
        img = Image.open(f_path)
        return Provider.normalize_image(img), categ

    def read_image(self, image, internal=True):
        """
        Read an image and convert it in the format used by Provider.

        Parameters
        ----------
        image : str or Image.Image or numpy.ndarray
            The path for the image or the image itself.
        internal : bool
            Interpretation of the ``image`` parameter if it is a string:
            - If ``internal`` is True the image is read
              using `Provider.read()` (it is  assumed it is
              one of dataset's own image).
            - If False it is interpreted as being a
              path and is read using Image.

        The returned array is normalized to (0, 1, 'c') shape, with c always 4
        (r, g, b, a) and datatype being floatX.

        Returns
        -------
        result : numpy.ndarray
            The resulted image.
        """
        if isinstance(image, basestring):
            if internal:
                image = self.read(image)[0]
            else:
                image = Image.open(image)
                image = Provider.normalize_image(image)
        elif isinstance(image, numpy.ndarray):
            assert len(image.shape) == 3
            image = as_floatX(image)
        else:
            assert isinstance(image, Image.Image)
            image = Provider.normalize_image(image)
        # image is an array
        if image.shape[2] == 3:
            app = numpy.ones(shape=(image.shape[0], image.shape[1], 1),
                             dtype=image.dtype) * 255
            numpy.append(image, app, axis=2)
        assert numpy.all(image >= 0.0) and numpy.all(image <= 1.0)
        return image

    def category(self, f_path):
        """
        Given a file name returned by next finds the category for that file.

        Parameters
        ----------
        iterator_cls : class
            An iterator class that inherits from SubsetIterator

        Returns
        -------
        categ : str
            A string indicating the category.
        """
        raise NotImplementedError()

    def categ_len(self):
        """
        Number of categories for this Provider.
        """
        return len(self.categories())

    def categories(self):
        """
        Get the list of categories.

        The list should always be the same for the lifetime of the instance
        as the indices are used to identify the class.

        Returns
        -------
        categs : list of str
            A string indicating the category.
        """
        if hasattr(self, 'categs'):
            return self.categs
        else:
            return self.get_categs()

    def get_categs(self):
        """
        Get a list of all categories in this provider.

        The implementation in the base class caches the result so, in you
        later want to insert images make sure to update the category
        yourself.
        """
        self.categs = []
        for key in self:
            ctg = self.category(key)
            if not ctg in self.categs:
                logging.warning('category %d: %s', len(self.categs), str(ctg))
                self.categs.append(ctg)

        return self.categs

    def categ2int(self, categ):
        """
        Converts a string representing a category name into an integer.

        Parameters
        ----------
        categ : str
            A category name.

        Returns
        -------
        idx : int
            The index of this category in the list of categories.
        """
        idx = self.categories().index(categ)
        if idx == -1:
            raise ValueError('%s is not among the '
                             'categories of the Provider' % categ)
        return idx

    def int2categ(self, idx):
        """
        Converts a string representing a category name into an integer.

        Parameters
        ----------
        idx : int
            The numeric id of the catgory.

        Returns
        -------
        categ : str
            The category coresponding to provided integer..
        """

        ctgs = self.categories()
        if idx < 0 or idx >= len(ctgs):
            raise ValueError('%d is outside the valid range '
                             'for categories of the Provider' % idx)
        return ctgs[idx]

    def everything(self):
        """
        The whole set of files and categories as a dictionary.

        Returns
        -------
        retdict : dict
            A dictionary where keys are files and values are categories.
        """
        retdict = {}
        for key in self:
            retdict[key] = self.category(key)
        return retdict

    def __hash__(self):
        """
        Called by built-in function hash() and for operations on members
        of hashed collections including set, frozenset, and dict.
        """
        hdict = hash(self.__class__.__name__)
        evr = self.everything()
        for k in evr:
            hdict = hdict ^ (hash(k) << 1) ^ (hash(evr[k]) << 2)
        return  hdict

    def get(self, offset, count):
        """
        Get the files in a given range.

        The method does not throw errors if the range is outside allowed
        range. instead, the list of files is treated as a ring.

        Parameters
        ----------
        offset : int
            Zero-based indes of the first file to retreive.
        count : int
            Number of files to retreive.
        """
        assert offset >= 0
        assert count > 0
        evrt = self.everything()
        evrt_len = len(evrt)
        keys = evrt.keys()

        result = []
        while count > 0:
            # bring offset in valid range
            offset = offset % evrt_len
            # max number of items
            valid_range = evrt_len - offset
            # how many are we going to get on this round
            this_round = min(valid_range, count)
            result.extend(keys[offset:offset+this_round])

            offset = offset + this_round
            count = count - this_round

        return result

class DictProvider(Provider):
    """
    A provider based on a dictionary.

    Parameters
    ----------
    data : dict of strings
        A dictionary with the keys being file paths and values being
        the category.
    categs : list, optional
        A list of categories; if empty the provider will use `get_categs()`.
    """
    def __init__(self, data, categs=None):
        super(DictProvider, self).__init__(categs)

        #: The dictionary that maps paths to classes.
        self.data = data

        #: The list of paths used for iteration purposes.
        self.keys_iter = data.keys().__iter__()

    @functools.wraps(Provider.__iter__)
    def __iter__(self):
        return self.data.keys().__iter__()

    @functools.wraps(Provider.__iter__)
    def __len__(self):
        return len(self.data)

    @functools.wraps(Provider.next)
    def next(self):
        return self.keys_iter.next()

    @functools.wraps(Provider.category)
    def category(self, f_path):
        return self.data[f_path]

    @functools.wraps(Provider.everything)
    def everything(self):
        return self.data

    @functools.wraps(Provider.cnext)
    def cnext(self):
        try:
            return self.next()
        except StopIteration:
            self.keys_iter = self.data.keys().__iter__()
            return self.next()

    def __getstate__(self):
        """
        Help pickle this instance.
        """
        if not hasattr(self, 'categs'):
            self.get_categs()
            assert hasattr(self, 'categs')

        return {'data': self.data, 'categs': self.categs}

    def __setstate__(self, state):
        """
        Help un-pickle this instance.
        """
        self.data = state['data']
        self.categs = state['categs']

        #: The list of paths used for iteration purposes.
        self.keys_iter = self.data.keys().__iter__()

class CsvProvider(DictProvider):
    """
    A provider based on a comma separated values file.

    The constructor will read the file and construct a dictionary that is
    later used by the DictProvider superclass.

    Parameters
    ----------
    csv_path : str
        The path where the csv file can be found.
    has_header : bool
        Skip first row if true. ``has_header`` must be True if ``col_path``
        or ``col_class`` are strings.
    col_path : str or int, optional
        If this is an integer, it represents the zero based index of the column
        that contains image paths.
        If this is a string, it represents the name of the column; the name
        will be searched in the header (so it is asserted the ``has_header``
        is true).
    col_class : str or int, optional
        If this is an integer, it represents the zero based index of the column
        that contains image paths.
        If this is a string, it represents the name of the column; the name
        will be searched in the header (so it is asserted the ``has_header``
        is true).
    delimiter : str, optional
        A one-character string used to separate fields. It defaults to ``,``.
    quotechar : str, optional
        A one-character string used to quote fields containing special
        characters, such as the delimiter or quotechar,
        or which contain new-line characters. It defaults to ``"``.
    skip_first : int, optional
        Skip this many rows at the beginning of the file; this does
        not include the header row that is managed separatelly.
    skip_last : int, optional
        Skip this many rows at the end of the file.
    categs : list, optional
        A list of categories; if empty the provider will use `get_categs()`.

    Notes
    -----
    The class is only interested in two columns: the class and the path.
    Both results are passed through pylearn2.utils.string_utils.preprocess
    so you can use environment variables to customize their final value.

    The paths inside csv file, if relative, are considered relative to
    the path of the .csv file.

    For the last entries to be removed the entries are parsed
    and added to a list. They are later removed from the result.
    This is in order to avoid reading the csv file twice but
    it has the downside that the entries to be skipped stil
    have to be valid (enough columns).
    """
    def __init__(self, csv_path, col_path=1, col_class=0, has_header=False,
                 delimiter=',', quotechar='"',
                 skip_first=0, skip_last=0, categs=None):

        assert skip_first >= 0
        assert skip_last >= 0

        if (isinstance(col_class, basestring) or
                isinstance(col_path, basestring)):
            # we will need to locate the indices so we need a header
            assert has_header
        else:
            col_min = max(col_path, col_class)

        # make the path absolute and extract base directory
        csv_path = os.path.abspath(csv_path)
        csv_base = os.path.split(csv_path)[0]

        # collect data in a dictionary
        data = {}
        file_list = []
        with open(csv_path, 'rt') as fhand:
            csvr = csv.reader(fhand,
                              delimiter=delimiter,
                              quotechar=quotechar)

            # collect all rows
            for i, row in enumerate(csvr):
                if len(row) == 0:
                    continue
                if has_header:
                    # find the actual indices for columns of interest
                    if isinstance(col_class, basestring):
                        col_class = row.index(col_class)
                    if isinstance(col_path, basestring):
                        col_path = row.index(col_path)
                    has_header = False
                    col_min = max(col_path, col_class)
                    skip_first = skip_first + 1
                    continue

                if i < skip_first:
                    continue

                if len(row) <= col_min:
                    err = '%s[%d] should have at least %d ' + \
                          'columns but it only has %d'
                    raise ValueError(err % (csv_path, i, col_min, len(row)))
                else:
                    class_name = preprocess(row[col_class]).strip().lower()
                    fpath = preprocess(row[col_path])
                    if len(fpath) > 0:
                        if not os.path.isabs(fpath):
                            fpath = os.path.join(csv_base, fpath)
                    data[fpath] = class_name
                    if skip_last > 0:
                        file_list.append(fpath)

        # remove last entries
        if skip_last > 0:
            if len(file_list) <= skip_last:
                data = {}
            else:
                for f2rem in file_list[-skip_last:]:
                    data.pop(f2rem, None)

        # everything else is provided by DictProvider
        super(CsvProvider, self).__init__(data, categs)

class RandomProvider(DictProvider):
    """
    A provider that has 100 random images labelled 1 to 100

    The constructor will create the random images and will construct
    a dictionary that is used by the DictProvider superclass.

    Parameters
    ----------
    rng : `numpy.random.RandomState` or seed, optional
        Seed for random number generator or an actual RNG.
    """
    def __init__(self, rng=None, count=100, alpha=False, size=(128, 128)):
        self.rng = make_np_rng(rng)
        self.content = {}
        self.rng = rng
        self.count = count
        self.alpha = alpha
        self.size = size
        data = self.prepare()

        # everything else is provided by DictProvider
        super(RandomProvider, self).__init__(data)

    @functools.wraps(Provider.__iter__)
    def __len__(self):
        return self.count

    @functools.wraps(Provider.read)
    def read(self, f_path):
        logging.debug('generator reading file %s', f_path)
        categ = f_path
        img = self.content[f_path]
        return Provider.normalize_image(img), categ

    def __getstate__(self):
        """
        Help pickle this instance.
        """
        state = {}
        state['count'] = self.count
        state['alpha'] = self.alpha
        state['size'] = self.size
        return state

    def __setstate__(self, state):
        """
        Help un-pickle this instance.
        """
        self.count = state['count']
        self.alpha = state['alpha']
        self.size = state['size']
        self.data = self.prepare()
        self.keys_iter = self.data.keys().__iter__()

    def prepare(self):
        """
        Initializes the instance according to internal attributes.
        """
        self.content = {}
        data = {}
        modes = ['RGBA', 'RGB', '1', 'L', 'P', 'CMYK', 'I', 'F']
        channels = 4 if self.alpha else 3
        for i in range(self.count):
            file_name = str(i+1)
            imarray = numpy.random.rand(self.size[0],
                                        self.size[1],
                                        channels) * 255
            img = Image.fromarray(imarray.astype('uint8'))
            self.content[file_name] = img.convert(modes[i % len(modes)])
            data[file_name] = file_name
        return data

class DeDeMaProvider(Provider):
    """
    A provider based on a DenseDesignMatrix.

    Parameters
    ----------
    data : dict of strings
        A dictionary with the keys being file paths and values being
        the category.
    """
    def __init__(self, dedema):
        self.dedema = dedema
        self.dataset_iter = range(dedema.get_num_examples()).__iter__()
        super(DeDeMaProvider, self).__init__()

    @functools.wraps(Provider.__iter__)
    def __iter__(self):
        return self.dataset_iter

    @functools.wraps(Provider.__iter__)
    def __len__(self):
        return self.dedema.get_num_examples()

    @functools.wraps(Provider.next)
    def next(self):
        return self.dataset_iter.next()

    @functools.wraps(Provider.category)
    def category(self, f_path):
        f_path = int(f_path)
        assert not self.dedema.y is None
        return self.dedema.y[f_path]

    @functools.wraps(Provider.everything)
    def everything(self):
        rang = range(self.dedema.get_num_examples())
        data = {}
        for i in rang:
            data[i] = self.dedema.y[i]
        return data

    @functools.wraps(Provider.cnext)
    def cnext(self):
        try:
            return self.next()
        except StopIteration:
            rang = range(self.dedema.get_num_examples())
            self.dataset_iter = rang.__iter__()
            return self.next()

    def __getstate__(self):
        """
        Help pickle this instance.
        """
        return {'data': self.dedema}

    def __setstate__(self, state):
        """
        Help un-pickle this instance.
        """
        self.dedema = state['data']
        self.dataset_iter = self.dedema.iterator()

    @functools.wraps(Provider.read)
    def read(self, f_path):
        f_path = int(f_path)
        categ = self.category(f_path)
        ddm = self.dedema.get_design_matrix()
        view_conv = self.dedema.view_converter.design_mat_to_topo_view
        exm = view_conv(ddm[f_path].reshape(1, ddm.shape[1]))
        return exm[0], categ


import scrapy
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from logzero import logfile, logger

class QuotesSpider(scrapy.Spider):
    name = "shopee"

    def start_requests(self):
        urls = [
            'https://shopee.tw/flash_sale'
        ]

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # to handle url array
        page = response.url.split("/")[-2]

        filename = f'shopee-{page}.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log(f'Saved file {filename}')

        # driver = webdriver.Chrome()  # To open a new browser window and navigate it

        # Use headless option to not open a new browser window
        options = webdriver.ChromeOptions()
        options.add_argument("headless")
        desired_capabilities = options.to_capabilities()
        driver = webdriver.Chrome(desired_capabilities=desired_capabilities)

        # Getting list of Countries
        driver.get(response.url)

        # Implicit wait
        driver.implicitly_wait(10)

        # Explicit wait
        wait = WebDriverWait(driver, 5)
        wait.until(EC.presence_of_element_located(
            (By.CLASS_NAME, "flash-sale-items")))

        # Extracting country names
        countries = driver.find_elements_by_class_name("flash-sale-items")
        countries_count = 0
        # Using Scrapy's yield to store output instead of explicitly writing to a JSON file
        for country in countries:
            yield {
                "country": country.text,
            }
            countries_count += 1

        driver.quit()
        logger.info(
            f"Total number of Countries in openaq.org: {countries_count}")


# -*-coding:utf-8-*-
# @Author: Damon0626
# @Time  : 19-1-16 下午10:03
# @Email : wwymsn@163.com
# @Software: PyCharm

import cv2
import numpy as np
from collections import Counter

def detec_weiqi_color(img):
	txt = 'black'
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
	ret, threshold = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)  # 高于100的都设置为255

	c = Counter(list(threshold.flatten()))  # 对边缘像素数量进行计数
	print(c.most_common())  # 黑色:num, 白色:num

	if c.most_common()[0][0] != 0:  # 不存在0,即不存在黑色
		txt = 'white'
	return txt, threshold

img = cv2.imread('weiqi.png')
img = cv2.medianBlur(img, 5)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', gray)

circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=100, param2=30, minRadius=10, maxRadius=50)

if circles is None:
	exit(-1)

circles = np.uint16(np.around(circles))

cv2.waitKey(0)
font = cv2.FONT_HERSHEY_SIMPLEX

for i in circles[0, :]:
	cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)
	cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3)

	x, y, r = i
	crop_img = img[y-r:y+r, x-r:x+r]  # 棋子方图

	# 检测颜色
	txt, threshold = detec_weiqi_color(crop_img)
	print("颜色：", '黑色' if txt == 'black' else '白色')

	cv2.putText(threshold, txt, (0, 0), font, 0.5, (0, 255, 0), 2)
	cv2.imshow('threshold', threshold)

	cv2.imshow('crop_img', crop_img)
	cv2.moveWindow('crop_img', x=0, y=img.shape[0])

	cv2.imshow('detectd chess', img)
	cv2.moveWindow('detected chess', y=0, x=img.shape[1])

	cv2.waitKey(1500)

cv2.waitKey(0)
cv2.destroyAllWindows()


# calculating area depending on the type of shape the user wants

shape = input("chose your shape:\n{circle,rectangle,square}: \n")
if shape=="circle":
    r = float(input("entre radius: "))
    pi = 3.14
    area = pi*r**2
    print(f"the area of a circle with radius {r} is",area)
elif shape=="rectangle":
    length = float(input(" enter length: "))
    width = float(input(" enter width: "))
    area = length*width
    print(f"the area of rectangle with length {length} and width {width} is",area)
elif shape=="square":
    sq = float(input("square: "))
    area = sq*sq
    print(f"the area of square {sq} is ",area)
else:
    print("please go back and chose an option")


import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.actions.action_builder import ActionBuilder

from iOS.IBS.functions_iRD import *

dc = {
    "platformName": "iOS",
    "xcodeOrgId": "5K7J2838R5",
    "xcodeSigningId": "iPhone Developer",
    "deviceName": "Cara's iPhone",
    "automationName": "XCUITest",
    "bundleId": "com.gohidoc.caraeu",
    "udid": "cebfcd519bbf550c384f2fa30c201c86926ab935",
    "platformVersion": "15.3",
    "noReset": "false",
    "newCommandTimeout": 3000
}
# count = 0
driver = webdriver.Remote("http://localhost:4723", dc)
time.sleep(5)

dimension = driver.get_window_size()
print(dimension['width'])
print(dimension['height'])
x = int(dimension['width'] * 0.08533333333)
y = int(dimension['height'] * 0.36206896551)

print(x, y)
action = ActionBuilder(driver)
action.pointer_action.move_to_location(x, y)
action.pointer_action.click()
action.perform()

# el = driver.find_elements(AppiumBy.CLASS_NAME, "XCUIElementTypeOther")
# print(len(el))
# for check in range(10):
#     print(check)
# swipe_up(driver)
# swipe_down(driver)
# click_element(driver, index=0, path="studyConfirmationScreen_informedCheckBox")
# for p in range(len(el)):
#     time.sleep(1)
#     print(el[p])
#     actions = TouchAction(driver)
#     actions.tap(el[p])
#     actions.perform()
#     count = count + 1
#     print(count)
#


#!/bin/python

import math
import os
import random
import re
import sys

# Complete the countTriplets function below.
def countTriplets(arr, r):
    former, latter = {}, {}
    for a in arr:
        if a not in former:
            former[a] = 0

        if a not in latter:
            latter[a] = 0
        latter[a] += 1

    s = 0
    for a in arr:
        latter[a] -= 1

        f = a // r
        l = a * r
        if a % r == 0 and f in former and l in latter:
            s += former[f] * latter[l]

        former[a] += 1

    return s

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nr = raw_input().rstrip().split()

    n = int(nr[0])

    r = int(nr[1])

    arr = map(long, raw_input().rstrip().split())

    ans = countTriplets(arr, r)

    fptr.write(str(ans) + '\n')

    fptr.close()


import sys
import pigpio
import time
from colorama import Fore, Back, Style

def set_speed(lspeed, rspeed):
    pi.hardware_PWM(left_servo_pin, 800, int(lspeed)*10000)
    pi.hardware_PWM(right_servo_pin, 800, int(rspeed)*10000)

pi = pigpio.pi()
left_servo_pin = 13
right_servo_pin = 12
dead_pin = 17
die_distance = 8
ls = 100
rs = 100
print("start")

try:
    while True:
        set_speed(ls, rs)
        if pi.read(dead_pin) == pigpio.LOW:
            set_speed(0, 0)

except :
    set_speed(0, 0)
    sys.exit(0)


from datetime import datetime
import matplotlib.pyplot as plt

'''

    TIPO DE TEXTO:

    Weekdays 1:
    ('2017-12-01T06', 1) Users: 1
    ('2017-12-01T07', 1) Users: 21

'''

data_list_weekdays = []
data_list_weekends = []

histogramas = []
with open("sample_spark.txt", 'r') as file:
    histograma = []
    for line in file:
        line = line.strip() # suprimir \n
        if line.startswith('Week'):
            if histograma != []:
                histogramas.append(histograma)
            histograma = [line,[]]
        #if not (line.startswith('Week')): # pasar los titulos
        else:
            #encuentro los indices de los str para extraer los datos que quiero

            time_start_index = line.find('T') + 1
            time_end_index = line.find("'", time_start_index)

            time = line[time_start_index:time_end_index]

            user_type_start_index = line.find(", ") + 1
            user_type_end_index = line.find(")", user_type_start_index)

            user_type = line[user_type_start_index:user_type_end_index]

            users_start_index = line.find('U') + 6

            users = line[users_start_index:]
            histograma[1].append([int(time), int(users)])
            #separar entresemana y fin de semana
            #if datetime.strptime(line[2:12], "%Y-%m-%d").weekday() < 5:
            #hago una lista con los datos
            #    data_list_weekdays.append([int(time), int(users)])
            #else:
            #    data_list_weekends.append([int(time), int(users)])

#print(data_list_weekdays)
#print(data_list_weekends)

for histograma in histogramas:
        #Hago lista con sublistas[tiempo, usuarios] para las 24 horas
        suma_week = 24*[0]

        for sublist in histograma[1]:
            index = sublist[0]
            value = sublist[1]
            suma_week[index] += value  #sumo los usuarios en las mismas horas

        suma_list_week = [[i,suma_week[i]] for i in range(24)]
        #print(suma_weekdays)
        #print(f"SUMA {suma_list_weekdays}")

        x = [sublist[0] for sublist in suma_list_week] #TIEMPO  X - AXIS
        y = [sublist[1] for sublist in suma_list_week] #USUARIOS Y - AXIS

        if 'day' in histograma[0]:
            plt.bar(x, y, color = "green")
            plt.xlabel('Time')
            plt.ylabel('Usuarios')
            plt.title(f'Histograma {histograma[0]}')
            plt.savefig(f'Histograma {histograma[0]}')
            plt.show()
        else:
            plt.bar(x, y, color = "purple")
            plt.xlabel('Time')
            plt.ylabel('Usuarios')
            plt.title(f'Histograma {histograma[0]}')
            plt.savefig(f'Histograma {histograma[0]}')
            plt.show()


import earth_distance as ed
import random

def read_cities(file_name): #Reads in list of cities
    with open(file_name, 'r') as f:
        data = f.readlines()
        data = [x.strip() for x in data]
        data = [x.split('\t') for x in data]
        t = []
        for i in data:
            t.append(tuple(i))
        return t

    """
    Read in the cities from the given `file_name`, and return
    them as a list of four-tuples:

      [(state, city, latitude, longitude), ...]

    Use this as your initial `road_map`, that is, the cycle

      Alabama -> Alaska -> Arizona -> ... -> Wyoming -> Alabama.
    """

def print_cities(road_map):#Prints cycle to two decimal places
    for i in range(len(road_map)):
        for y in range(len(road_map[i])):
            try:
                print(round(float(road_map[i][y]),2), end = ' ')
            except ValueError:
                print(road_map[i][y], end = ' ')
        print()

def compute_total_distance(road_map): #Returns total sum of all distances in the cycle. Distance is shown in Miles
    distcnt = 0.00
    for i in range(len(road_map)):
        for y in range(1):
            if i+1 == len(road_map):
                distcnt += ed.distance(float(road_map[i][2]), float(road_map[i][3]), float(road_map[0][2]), float(road_map[0][3]))
                break
            else:
                distcnt += ed.distance(float(road_map[i][2]), float(road_map[i][3]), float(road_map[i+1][2]), float(road_map[i+1][3]))
    return distcnt

    """
    Returns, as a floating point number, the sum of the distances of all
    the connections in the `road_map`. Remember that it's a cycle, so that
    (for example) in the initial `road_map`, Wyoming connects to Alabama...
    """

def swap_adjacent_cities(road_map, index): #Swaps two Adjacent Cities or first and last of cycle
    new1 = road_map
    tempi = new1[index]
    if index + 1 == len(road_map):
        new1[index] = new1[0]
        new1[0] = tempi
    else:
        new1[index] = new1[index+1]
        new1[index +1] = tempi
    newroad_map = (new1, compute_total_distance(new1))
    return newroad_map

    """
    Take the city at location `index` in the `road_map`, and the city at
    location `index+1` (or at `0`, if `index` refers to the last element
    in the list), swap their positions in the `road_map`, compute the
    new total distance, and return the tuple

        (new_road_map, new_total_distance)
    """

def swap_cities(road_map, index1, index2):
    if index1 == index2:
        return swap_adjacent_cities(road_map, index1)
    else:
        new2 = road_map
        tempi = new2[index1]
        new2[index1] = new2[index2]
        new2[index2] = tempi
        newroad_map2 = (new2, compute_total_distance(new2))
        return newroad_map2

    """
    Take the city at location `index` in the `road_map`, and the
    city at location `index2`, swap their positions in the `road_map`,
    compute the new total distance, and return the tuple

        (new_road_map, new_total_distance)

    Allow for the possibility that `index1=index2`,
    and handle this case correctly.
    """

def find_best_cycle(road_map):
    dist = compute_total_distance(road_map)

    count = 0
    bestroad_map = 0
    print('Finding Best Cycle')
    for i in range(100):
        count += 1
        print(count)
        t_road_map = swap_cities(road_map, random.randint(0, len(road_map)-1), random.randint(0, len(road_map)-1))
        if t_road_map[1] < dist:
            dist = t_road_map[1]
            road_map = t_road_map[0]
            bestroad_map = tuple()
            bestroad_map = t_road_map
            print('Best Distance Is:', dist)
            print('FOUND BEST!')
            print(bestroad_map[1])
        else:
            road_map = t_road_map[0]
            print(compute_total_distance(road_map))
    print('Printing first index')
    print(bestroad_map[0])
    print('printing second index')
    print(bestroad_map[1])
    optcycle = bestroad_map[0]
    print(optcycle)
    return optcycle

    """Using a combination of `swap_cities` and `swap_adjacent_cities`,
    try `10000` swaps, and each time keep the best cycle found so far.
    After `1000   0` swaps, return the best cycle found so far. """

def print_map(road_map):
    print('Please find your calculated optimum journey as follows:')
    for i in range(len(road_map)):
        if i+1 == len(road_map):
            print('Journey', i+1,':')
            print(road_map[i][1], ' -> ' , road_map[0][1])
            print(round(ed.distance(float(road_map[i][2]), float(road_map[i][3]), float(road_map[0][2]), float(road_map[0][3]))),"Miles")
        else:
            print('Journey', i+1,':')
            print(road_map[i][1], ' -> ' , road_map[i+1][1])
            print('Distance is:', round(ed.distance(float(road_map[i][2]), float(road_map[i][3]), float(road_map[i+1][2]), float(road_map[i+1][3]))),"Miles")
    print('Total Travel Distance is', round(compute_total_distance(road_map), ),'Miles')

    """
    Prints, in an easily understandable format, the cities and
    their connections, along with the cost for each connection
    and the total cost.
    """

def main():
    road_map = read_cities('city-data.txt')
    print('Please find the list of cities you need to travel to:')
    print_cities(road_map)
    bestcycle = find_best_cycle(road_map)
    print(compute_total_distance(bestcycle))
    print_map

    """
    Reads in, and prints out, the city data, then creates the "best"
    cycle and prints it out.
    """

if __name__ == "__main__":
    main()


# 백준 1037 약수

n = int(input())
arr = list(map(int,input().split()))

arr.sort()
result = arr[0] * arr[-1]

print(result)
# 가장 작은 약수랑 가장 큰 약수를 곱하면 해당 숫자가 됨


import time
import traceback
from datetime import timedelta, datetime
from multiprocessing import Process
from library.logger import getLogger
import requests
from constants.config import config
from azure.storage.blob import BlobServiceClient
from azure.storage.queue import QueueServiceClient
from azure.core import exceptions as AzureExceptions
import library.db as db
import json
import library.utils as utils

logger = getLogger("validate")

def process_hash_list(document_datasets):

    conn = db.getDirectConnection()
    now = datetime.now()

    for file_data in document_datasets:
        try:
            file_hash = file_data[0]
            downloaded = file_data[1]
            file_id = file_data[2]
            file_url = file_data[3]
            publisher = file_data[4]
            publisher_name = file_data[5]
            file_schema_valid = file_data[6]
            publisher_black_flag = file_data[7] is not None

            if file_schema_valid == False and downloaded > (now - timedelta(hours=config['VALIDATION']['SAFETY_CHECK_PERIOD'])):
                logger.info(
                    f"Skipping Schema Invalid file for Full Validation until {config['VALIDATION']['SAFETY_CHECK_PERIOD']}hrs after download: {downloaded.isoformat()} for hash: {file_hash} and id: {file_id}")
                continue

            if file_schema_valid == False and publisher_black_flag == True:
                logger.info(
                    f"Skipping Schema Invalid file for Full Validation since publisher: {publisher} is black flagged for hash: {file_hash} and id: {file_id}")
                continue

            blob_name = file_hash + '.xml'

            blob_service_client = BlobServiceClient.from_connection_string(
                config['STORAGE_CONNECTION_STR'])
            blob_client = blob_service_client.get_blob_client(
                container=config['SOURCE_CONTAINER_NAME'], blob=blob_name)

            downloader = blob_client.download_blob()

            try:
                payload = utils.get_text_from_blob(downloader, file_hash)
            except:
                logger.warning(
                    f"Could not identify charset for hash: {file_hash} and id: {file_id}")
                continue

            if file_schema_valid is None:
                logger.info(
                    f"Schema Validating file hash: {file_hash} and id: {file_id}")
                schema_headers = {config['VALIDATION']['SCHEMA_VALIDATION_KEY_NAME']: config['VALIDATION']['SCHEMA_VALIDATION_KEY_VALUE']}
                schema_response = requests.post(
                    config['VALIDATION']['SCHEMA_VALIDATION_URL'], data=payload.encode('utf-8'), headers=schema_headers)
                db.updateValidationRequestDate(conn, file_id)

                if schema_response.status_code != 200:
                    if schema_response.status_code >= 400 and schema_response.status_code < 500:  # client errors
                        # log in db and 'continue' to break out of for loop for this file
                        db.updateValidationError(
                            conn, file_id, schema_response.status_code)
                        logger.warning(
                            f"Schema Validator reports Client Error HTTP {schema_response.status_code} for hash: {file_hash} and id: {file_id}")
                        continue
                    elif schema_response.status_code >= 500:  # server errors
                        # log in db and 'continue' to break out of for loop for this file
                        db.updateValidationError(
                            conn, file_id, schema_response.status_code)
                        logger.warning(
                            f"Schema Validator reports Server Error HTTP {schema_response.status_code} for hash: {file_hash} and id: {file_id}")
                        continue
                    else:
                        logger.error(
                            f"Schema Validator reports HTTP {schema_response.status_code} for hash: {file_hash} and id: {file_id}")
                try:
                    body = schema_response.json()
                    if body['valid'] == True or body['valid'] == False:
                        db.updateDocumentSchemaValidationStatus(
                            conn, file_id, body['valid'])
                        file_schema_valid = body['valid']
                    else:
                        raise
                except:
                    logger.error(
                        f"Unexpected response body from Schema validator for hash: {file_hash} and id: {file_id}")
                    continue

            if file_schema_valid == False and downloaded > (now - timedelta(hours=config['VALIDATION']['SAFETY_CHECK_PERIOD'])):
                logger.info(
                    f"Skipping Schema Invalid file for Full Validation until {config['VALIDATION']['SAFETY_CHECK_PERIOD']}hrs after download: {downloaded.isoformat()} for hash: {file_hash} and id: {file_id}")
                continue

            if file_schema_valid == False and publisher_black_flag == True:
                logger.info(
                    f"Skipping Schema Invalid file for Full Validation since publisher: {publisher} is black flagged for hash: {file_hash} and id: {file_id}")
                continue

            logger.info(
                f"Full Validating file hash: {file_hash} and id: {file_id}")

            full_headers = {config['VALIDATION']['FULL_VALIDATION_KEY_NAME']: config['VALIDATION']['FULL_VALIDATION_KEY_VALUE']}

            full_url = config['VALIDATION']['FULL_VALIDATION_URL']

            # only need meta=true for invalid files to "clean" them later
            if file_schema_valid == False:
                full_url += '?meta=true'
            full_response = requests.post(
                full_url, data=payload.encode('utf-8'), headers=full_headers)
            db.updateValidationRequestDate(conn, file_id)

            if full_response.status_code != 200:
                # 'expected' error codes returned from Validator
                if full_response.status_code == 400 or full_response.status_code == 413 or full_response.status_code == 422:
                    # log db and move on to save the validation report
                    db.updateValidationError(
                        conn, file_id, full_response.status_code)
                elif full_response.status_code >= 400 and full_response.status_code < 500:  # unexpected client errors
                    # log in db and 'continue' to break out of for loop for this file
                    db.updateValidationError(
                        conn, file_id, full_response.status_code)
                    logger.warning(
                        f"Full Validator reports Client Error HTTP {full_response.status_code} for hash: {file_hash} and id: {file_id}")
                    continue
                elif full_response.status_code >= 500:  # server errors
                    # log in db and 'continue' to break out of for loop for this file
                    db.updateValidationError(
                        conn, file_id, full_response.status_code)
                    logger.warning(
                        f"Full Validator reports Server Error HTTP {full_response.status_code} for hash: {file_hash} and id: {file_id}")
                    continue
                else:
                    logger.error(
                        f"Full Validator reports HTTP {full_response.status_code} for hash: {file_hash} and id: {file_id}")

            report = full_response.json()

            state = report.get('valid', None)

            db.updateValidationState(
                conn, file_id, file_hash, file_url, publisher, state, json.dumps(report), publisher_name)

        except (AzureExceptions.ResourceNotFoundError) as e:
            logger.warning(
                f"Blob not found for hash: {file_hash} and id: {file_id} updating as Not Downloaded for the refresher to pick up.")
            db.updateFileAsNotDownloaded(conn, file_id)
        except Exception as e:
            logger.error(f"ERROR with validating {file_hash}")
            print(traceback.format_exc())
            if hasattr(e, 'message'):
                logger.error(e.message)
            if hasattr(e, 'msg'):
                logger.error(e.msg)
            try:
                logger.warning(e.args[0])
            except:
                pass

    conn.close()

def validate():
    logger.info("Starting validation...")

    conn = db.getDirectConnection()

    file_hashes = db.getUnvalidatedDatasets(conn)

    if config['VALIDATION']['PARALLEL_PROCESSES'] == 1:
        logger.info(
            f"Processing {len(file_hashes)} IATI files in a single process for validation")
        process_hash_list(file_hashes)
    else:
        chunked_hash_lists = list(utils.chunk_list(
            file_hashes, config['VALIDATION']['PARALLEL_PROCESSES']))

        processes = []

        logger.info(
            f"Processing {len(file_hashes)} IATI files in a maximum of {config['VALIDATION']['PARALLEL_PROCESSES']} parallel processes for validation")

        for chunk in chunked_hash_lists:
            if len(chunk) == 0:
                continue
            process = Process(target=process_hash_list, args=(chunk,))
            process.start()
            processes.append(process)

        for process in processes:
            process.join()

    conn.close()
    logger.info("Finished validation.")

def safety_check():
    conn = db.getDirectConnection()

    logger.info(f"Starting validation safety check / publisher black flag check")

    try:
        queue_service_client = QueueServiceClient.from_connection_string(
            config['STORAGE_CONNECTION_STR'])
        queue_client = queue_service_client.get_queue_client(
            "publisher-black-flag-remove")

        messages = queue_client.receive_messages()

        for message in messages:
            try:
                logger.info(
                    f"Received message to remove black flag for publisher id: {message.content}")
                db.removeBlackFlag(conn, message.content)
                logger.info(f"Dequeueing message: {message.content}")
                queue_client.delete_message(message.id, message.pop_receipt)
            except Exception as e:
                logger.warning(
                    f"Could not process message with id: {message.id} for publisher id: {message.content}")
                continue
    except Exception as e:
        logger.warning(f"Failed to process removal of publisher black flags")

    db.blackFlagDubiousPublishers(
        conn, config['VALIDATION']['SAFETY_CHECK_THRESHOLD'], config['VALIDATION']['SAFETY_CHECK_PERIOD'])

    black_flags = db.getUnnotifiedBlackFlags(conn)

    for black_flag in black_flags:
        org_id = black_flag[0]

        notification = {
            "type": "NEW_BLACK_FLAG",
            "data": {
                "publisherId": org_id,
                "reason": f"Over {config['VALIDATION']['SAFETY_CHECK_THRESHOLD']} critical documents in the last {config['VALIDATION']['SAFETY_CHECK_PERIOD']}) hours."
            }
        }
        headers = {
            config['NOTIFICATION_KEY_NAME']: config['NOTIFICATION_KEY_VALUE'],
            'Content-Type': 'application/json'
        }

        try:
            response = requests.post(
                config['NOTIFICATION_URL'], data=json.dumps(notification), headers=headers)
        except Exception as e:
            logger.warning(
                f"Could not notify Black Flag for publisher id: {org_id}")
            continue

        if response.status_code != 200:
            logger.warning(
                f"Could not notify Black Flag for publisher id: {org_id}, Comms Hub Responded HTTP {response.status_code}")
            continue

        db.updateBlackFlagNotified(conn, org_id)

    conn.close()
    logger.info("Finished safety check.")

def service_loop():
    logger.info("Start service loop")

    while True:
        safety_check()
        validate()
        time.sleep(60)


import json, branca

geo_data = None
with open('./blocks.geojson') as geojson_file:
    geo_data = json.load(geojson_file)

data = {datum['id']: datum['properties'] for datum in geo_data['features']}

low_color_scale = branca.colormap.linear.Greens_05.scale(0, 150)
low_color_scale.caption = 'Land Value Per Square Foot'
mid_color_scale = branca.colormap.linear.Blues_05.scale(150, 1000)
mid_color_scale.caption = 'Land Value Per Square Foot'
high_color_scale = branca.colormap.linear.Reds_05.scale(1000, 10000)
high_color_scale.caption = 'Land Value Per Square Foot'

def style_function(feature):
    datum = data[feature['id']]
    value = datum['avg_per_sqft_extrapolated_land_value']
    min_val, max_val = 150, 1000
    fillColor = '#black'
    if value < min_val:
        fillColor = low_color_scale(value)
    elif value > max_val:
        fillColor = high_color_scale(value)
    else:
        fillColor = mid_color_scale(value)
    return {
        'fillOpacity': 0.7,
        'weight': 2,
        'color': fillColor,
        'fillColor': fillColor,
    }

sf_coords = (37.76, -122.43)
m =  folium.Map(sf_coords, zoom_start=12, tiles='cartodbpositron')

folium.GeoJson(
    geo_data,
    style_function=style_function,
    name='Extrapolated Land Value',
).add_to(m)

folium.LayerControl().add_to(m)
m.add_child(low_color_scale)
m.add_child(mid_color_scale)
m.add_child(high_color_scale)
m.save('sf_blocks.html')


# coding: utf8
import pygame, sys
from pygame.locals import *
import random
from tiro import Tiro
class Inimigo(object):
	def __init__(self,DISPLAYSURF):
		self.DISPLAYSURF=DISPLAYSURF
		self.x=random.randint(1, 450);
		self.y=1
		self.posicao="DIREITA";
		self.bala=list()
		self.cont=1

	def controleDeMovimento(self):
		self.cont+=1
		if(self.cont>=1000):
			self.cont=1

		if(self.x>=450):
			self.x-=1
			self.posicao="CIMA";
		if(self.x<=10):
			self.x+=1
			self.posicao="BAIXO";
		if(self.y>=450):
			self.y-=1
			self.posicao="DIREITA";
		if(self.y<10):
			self.y+=1
			self.posicao="ESQUERDA";

		if(float(random.randint(1, 1000)) % 100 ==0):
			self.posicao="CIMA";
			self.bala.append(Tiro(self.x,self.y,self.posicao,(255,0,0)))
		if(float(random.randint(1, 1000)) % 200 ==0):
			self.posicao="BAIXO";
			self.bala.append(Tiro(self.x,self.y,self.posicao,(255,0,0)))
		if(float(random.randint(1, 1000)) % 300 ==0):
			self.posicao="DIREITA";
			self.bala.append(Tiro(self.x,self.y,self.posicao,(255,0,0)))
		if(float(random.randint(1, 1000)) % 400 ==0):
			self.posicao="ESQUERDA";
			self.bala.append(Tiro(self.x,self.y,self.posicao,(255,0,0)))

		if(self.cont % 20 ==0):
			self.bala.append(Tiro(self.x,self.y,self.posicao,(255,0,0)))

		for i in range(len(self.bala)):
			self.bala[i].atira()
			self.bala[i].drawBala(self.DISPLAYSURF)
			if(self.bala[i].x > 550 or self.bala[i].x < -50):
				del self.bala[i]
				break
			if(self.bala[i].y > 550 or self.bala[i].y < -50):
				del self.bala[i]
				break

		if(self.posicao=="DIREITA"):
			self.x+=3
		if(self.posicao=="ESQUERDA"):
			self.x-=3
		if(self.posicao=="CIMA"):
			self.y-=3
		if(self.posicao=="BAIXO"):
			self.y+=3

	def draw(self,tamanho):
		pygame.draw.rect(self.DISPLAYSURF,  (255, 0, 0), (self.x, self.y, tamanho, tamanho))
		if(self.posicao=="BAIXO"):
			pygame.draw.rect(self.DISPLAYSURF,  (255, 0, 0), (self.x+(tamanho/3), self.y+tamanho, tamanho/3, tamanho/3))
		elif(self.posicao=="CIMA"):
			pygame.draw.rect(self.DISPLAYSURF,  (255, 0, 0), (self.x+(tamanho/3), self.y-(tamanho/3), tamanho/3, tamanho/3))
		elif(self.posicao=="DIREITA"):
			pygame.draw.rect(self.DISPLAYSURF,  (255, 0, 0), (self.x+tamanho, self.y+(tamanho/3), tamanho/3, tamanho/3))
		elif(self.posicao=="ESQUERDA"):
			pygame.draw.rect(self.DISPLAYSURF,  (255, 0, 0), (self.x-(tamanho/3), self.y+(tamanho/3), tamanho/3, tamanho/3))


#!/usr/bin/python3

import sys

counties = ["Clinton","Eaton","Ingham","Kent","Macomb","Shiawassee","Wayne"]

for line in sys.stdin:
    values = line.split(',')
    for i in range(1, len(values)):
        key = counties[i-1]
        num = ''
        for char in values[i]:
            if char.isdigit():
                num += char
        print(key + ', ' + num)


import os
import win32com.client as win32
olApp = win32.Dispatch('Outlook.Application')
olNS = olApp.GetNameSpace('MAPI')

# construct the mail item object

mailItem = olApp.createItem(0)
mailItem.Subject = 'Jio dhan dhana dhan'

mailItem.BodyFormat = 1
mailItem.To = "<sendermail@>"
mailItem.Attachments.Add(os.path.join(os.getcwd(),"mk.txt"))
mailItem.Body="this is sample mail"

mailItem.Display()
mailItem.Save()
mailItem.Send()


import click as _click
import cv2
import base64
from io import BytesIO
import json

f = open('config.json')
data = json.load(f)
frame_width = int(data['width'])
frame_height = int(data['height'])
f.close()

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)
cap.set(cv2.CAP_PROP_FPS, 15)

def get_frames(image_name):

    # using click package to make sure that path is interpreted correctly
    _click.command()
    _click.argument('image_name',type=_click.Path(exists=True,
                                dir_okay=True, readable=True))

    retval, image = cap.read()

    retval, buffer = cv2.imencode('.jpg', image)
    jpg_as_text = base64.b64encode(buffer)

    return(jpg_as_text)