from collections import deque
from threading import Lock
from time import perf_counter
import asyncio
from typing import Optional, Tuple

# Third-party modules
import orjson
from typing import Union, Iterable, List, Dict, Any

# NOC modules
from noc.config import config
from noc.core.comp import smart_text

class TopicQueue(object):
    def __init__(self, topic: str, loop: Optional[asyncio.BaseEventLoop] = None) -> None:
        self.topic = topic
        self.lock = Lock()
        self.waiter: Optional[asyncio.Event] = None
        self.shutdown_waiter: Optional[asyncio.Event] = None
        self.queue: deque = deque()
        self.queue_size = 0
        self.to_shutdown = False
        self.last_get: Optional[float] = None
        self.loop = loop
        # Metrics
        self.msg_put = 0
        self.msg_get = 0
        self.msg_put_size = 0
        self.msg_get_size = 0
        self.msg_requeued = 0
        self.msg_requeued_size = 0

    @staticmethod
    def iter_encode_chunks(
        message: Union[str, object], limit: int = config.nsqd.mpub_size - 8
    ) -> Iterable[str]:
        """
        Encode data to iterable atomic chunks of up to limit size

        :param message: Input data
        :param limit: Chunk limit
        :return: Yields JSON-encoded chunks
        :raises ValueError: If message cannot be encoded or too big
        """
        if isinstance(message, str):
            if len(message) > limit:
                raise ValueError("Message too big")
            yield message
        else:
            data = smart_text(orjson.dumps(message))
            if len(data) <= limit:
                yield data
            elif isinstance(message, (list, tuple)):
                # Try to split in parts
                n_chunks = len(data) // limit + 1
                chunk_size = len(message) // n_chunks
                while message:
                    chunk, message = message[:chunk_size], message[chunk_size:]
                    chunk_data = smart_text(orjson.dumps(chunk))
                    if len(chunk_data) > limit:
                        raise ValueError("Message too big")
                    yield chunk_data
            else:
                raise ValueError("Message too big")

    def put(self, message: object, fifo: bool = True) -> None:
        """
        Put message into queue. Block if queue is full

        :param message: Message of any json-serializable type
        :param fifo: Boolean. Append message to the start of queue (LIFO) if False.
            Append message to the end of queue (FIFO) if True.
        :return:
        """
        if not isinstance(message, str):
            message = smart_text(orjson.dumps(message))
        with self.lock:
            if self.to_shutdown:
                raise RuntimeError("put() after shutdown")
            if fifo:
                self.queue.append(message)
            else:
                self.queue.appendleft(message)
            m_size = len(message)
            self.queue_size += m_size
            self.msg_put += 1
            self.msg_put_size += m_size
            self._notify_waiters()

    def _notify_waiters(self):
        """
        Notify waiting coroutine.
        Must be called within lock
        :return:
        """
        if not self.waiter:
            return
        waiter = self.waiter
        if self.loop:
            self.loop.call_soon_threadsafe(waiter.set)
        else:
            waiter.set()

    async def _wait_for_data(self, timeout: Optional[float] = None):
        if self.waiter:
            raise RuntimeError("Incomplete wait")
        with self.lock:
            self.waiter = asyncio.Event()
        try:
            if timeout:
                await asyncio.wait_for(self.waiter.wait(), timeout)
            else:
                await self.waiter.wait()
        except asyncio.TimeoutError:
            pass
        finally:
            with self.lock:
                self.waiter = None

    def return_messages(self, messages: List[str]) -> None:
        """
        Return messages to the start of the queue

        :param messages: List of messages
        :return:
        """
        with self.lock:
            if self.to_shutdown:
                raise RuntimeError("return_messages() after shutdown")
            for msg in reversed(messages):
                self.queue.appendleft(msg)
                self.msg_requeued += 1
                self.msg_requeued_size += len(msg)
            self._notify_waiters()

    def iter_get(
        self, n: int = 1, size: int = None, total_overhead: int = 0, message_overhead: int = 0
    ) -> Iterable[str]:
        """
        Get up to `n` items up to `size` size.

        Warning queue will be locked until the end of function call.

        :param n: Amount of items returned
        :param size: None - unlimited, integer - upper size limit
        :param total_overhead: Adjust total size to `total_overhead` octets.
        :param message_overhead: Adjust total size to `message_overhead` per each returned message.
        :return: Yields items
        """
        total = 0
        if size and total_overhead:
            total += total_overhead
        with self.lock:
            for _i in range(n):
                try:
                    msg = self.queue.popleft()
                    m_size = len(msg)
                    total += m_size
                    if size and message_overhead:
                        total += message_overhead
                    if size and total > size:
                        # Size limit exceeded. Return message to queue
                        self.queue.appendleft(msg)
                        break
                    self.queue_size -= m_size
                    self.msg_get += 1
                    self.msg_get_size += m_size
                    yield msg
                except IndexError:
                    break
            self.last_get = perf_counter()

    def is_empty(self) -> bool:
        """
        Check if queue is empty

        :return: True if queue is empty, False otherwise
        """
        return not self.queue_size

    def qsize(self) -> Tuple[int, int]:
        """
        Returns amount of messages and size of queue

        :return: messages, total size
        """
        with self.lock:
            return len(self.queue), self.queue_size

    def shutdown(self) -> None:
        """
        Begin shutdown sequence. Disable queue writes

        :return:
        """
        if self.to_shutdown:
            raise RuntimeError("Already in shutdown")
        self.to_shutdown = True
        self.shutdown_waiter = asyncio.Event()
        with self.lock:
            self._notify_waiters()  # Leave publisher waiting state

    async def wait_for_shutdown(self, timeout: Optional[float] = None) -> None:
        """
        Get publisher a chance to drain collected items
        :param timeout:
        :return:
        """
        if not self.shutdown_waiter:
            return
        try:
            await asyncio.wait_for(self.shutdown_waiter.wait(), timeout)
        except asyncio.TimeoutError:
            pass

    def notify_shutdown(self):
        if self.shutdown_waiter:
            self.shutdown_waiter.set()

    async def wait(self, timeout: Optional[float] = None, rate: Optional[int] = None):
        """
        Block and wait up to `timeout`
        :param timeout: Max. wait in seconds
        :param rate: Max. rate of publishing in messages per second
        :return:
        """
        # Sleep to throttle rate
        if rate and self.last_get and not self.to_shutdown:
            now = perf_counter()
            delta = max(self.last_get + 1.0 / rate - now, 0)
            if delta > 0:
                await asyncio.sleep(delta)
                # Adjust remaining timeout
                if timeout:
                    # Adjust timeout
                    timeout -= delta
                    if timeout <= 0:
                        # Timeout expired
                        return
        # Check if queue already contains messages
        if not self.queue_size and not self.to_shutdown:
            # No messages, wait
            await self._wait_for_data(timeout)

    def apply_metrics(self, data: Dict[str, Any]) -> None:
        data.update(
            {
                ("nsq_msg_put", ("topic", self.topic)): self.msg_put,
                ("nsq_msg_put_size", ("topic", self.topic)): self.msg_put_size,
                ("nsq_msg_get", ("topic", self.topic)): self.msg_get,
                ("nsq_msg_get_size", ("topic", self.topic)): self.msg_get_size,
                ("nsq_msg_requeued", ("topic", self.topic)): self.msg_requeued,
                ("nsq_msg_requeued_size", ("topic", self.topic)): self.msg_requeued_size,
            }
        )


'''
Написати функцію, яка приймає на вхід список і підраховує кількість однакових елементів у ньому.
'''

def my_func(my_list):
    my_dict = {i: my_list.count(i) for i in my_list}
    return my_dict
my_list = [1, 1, 3, 3, 'a']

print(my_func(my_list))


from odoo import api, fields, models

class EventSession(models.Model):
    _inherit = "event.event"

    order_line_ids = fields.One2many(
        comodel_name="sale.order.line",
        inverse_name="event_id",
        string="Sales Order Lines",
    )
    unconfirmed_qty = fields.Integer(
        string="Unconfirmed Qty",
        compute="_compute_unconfirmed_qty",
        store=True,
    )

    @api.depends(
        "order_line_ids",
        "order_line_ids.product_uom_qty",
        "order_line_ids.order_id.state",
    )
    def _compute_unconfirmed_qty(self):
        for event in self:
            event.unconfirmed_qty = int(
                sum(
                    event.order_line_ids.filtered(
                        lambda x: x.order_id.state in ("draft", "sent")
                    ).mapped("product_uom_qty")
                )
            )

    def button_open_unconfirmed_event_order(self):
        action = self.env["ir.actions.act_window"]._for_xml_id("sale.action_quotations")
        sales = (
            self.env["sale.order.line"]
            .search([("event_id", "in", self.ids)])
            .mapped("order_id")
            .ids
        )
        action["domain"] = [("id", "in", sales), ("state", "in", ("draft", "sent"))]
        action["context"] = {}
        return action


import sys
import os
import glob
import cv2
import argparse
import json
import numpy as np
import pprint
import traceback

# classes_file is a text file which contains all classes(labels)
# Example classes.txt
"""
Bicycles_Only
Bumpy_Road
Buses_Priority
Centre_Line
Closed_To_Pedestrians
Crossroads
Dangerous_Wind _Gusts
Directions_Indicator
Falling_Rocks
Keep_Left
...
"""

class YOLO2COCOConverter:

  def __init__(self, classes_file):
    self.classes = []
    with open(classes_file, "r") as f:
      all_class_names = f.readlines()
      for class_name in all_class_names:
        class_name = class_name.strip()
        if class_name.startswith("#") ==False:
          self.classes.append(class_name)
    print("==== classes {}".format(self.classes))

  def run(self, dataset_dir, coco_json):
    print("=== YOLO2COCOConverter.run() start")
    NL = "\n"
    coco_annotation = {}
    info = {
      "description": "COCO 2022 Dataset",
      "url": "http://cocodataset.org",
      "version": 1.0,
      "year": 2022,
      "contributor": "antillia.com",
      "date_created": "2022/04/05"
    }
    license = [
        {
          "url": "http://creativecommons.org/licenses/by-nc-sa/2.0/",
          "id":  1,
          "name": "Attribution-NonCommercial-ShareAlike License"
        },
    ]
    coco_annotation["info"]        = info
    coco_annotation["license"]     = license

    images, annotations = self.create_images_and_annotations_sections(dataset_dir)

    coco_annotation['images']      = images
    coco_annotation['annotations'] = annotations
    coco_annotation['categories']  = []

    for index, label in enumerate(self.classes):
      category = {
        "supercategory": "None",
        "id": index + 1,
        "name": label
      }
      coco_annotation['categories'].append(category)

    with open(coco_json, 'w') as outfile:
      json.dump(coco_annotation, outfile, indent=4)

    print("=== YOLO2COCOConverter.run() end")

  def create_images_and_annotations_sections(self, dataset_dir):
    # The dataset_dir(train, valid, or test) contains both something_image.jpg and something_image.txt , and so on.

    # We assume the following folder structure:
    # dataset_dir/train/
    #  +- image1.jpg
    #  +- image1.txt  (YOLO format annotation file to image1.jpg)
    #  ...
    #  ...
    #  +- imageN.jpg
    #  +- imageN.txt  (YOLO format annotation file to imageN.jpg)
    #
    annotations = []
    images      = []
    pattern     = dataset_dir + "/*.jpg"
    all_jpg_files   = glob.glob(pattern)

    image_id      = 0
    annotation_id = 1   # In COCO dataset format, you must start annotation id with '1'

    for jpg_file in all_jpg_files:
        # Check how many items have progressed
        print("==== YOLOtoCOCOConverter.run() processing  annotation_id {} filename {}".format(annotation_id, jpg_file))

        image = cv2.imread(jpg_file)

        annotation_file = jpg_file.replace(".jpg", ".txt")
        if os.path.exists(annotation_file) == False:
          raise Exception("Not found annotation file {}".format(annotation_file))

        annotation_f = open(annotation_file, "r")
        all_annotations  = annotation_f.readlines()
        annotation_f.close()

        image_height, image_width, _ = image.shape

        jpg_base_filename = os.path.basename(jpg_file)

        image = self.create_image_section(jpg_base_filename, image_width, image_height, image_id)
        images.append(image)

        image_height = float(image_height)
        image_width  = float(image_width)

        # YOLO format - (class_id, x_center, y_center, width, height)
        # where class_id starts from 0, and x_center, y_center, width, height are float, and in range [0.0, 1.0]

        # COCO format - (annotation_id, x_upper_left, y_upper_left, width, height)
        # where annotation_id starts from 1, and x_upper_left, y_upper_left, width, height are integer, and real coordinates of the bbox rectangle.

        for annotation in all_annotations:

            class_id, x_center, y_center, width, height = annotation.split(" ")

            category_id   = int(class_id) + 1
            x_center      = float(x_center)
            y_center      = float(y_center)
            width         = float(width)
            height        = float(height)

            real_x_center = int(x_center * image_width)
            real_y_center = int(y_center * image_height)
            real_width    = int(width    * image_width)
            real_height   = int(height   * image_height)

            real_x        = real_x_center - real_width/2
            real_y        = real_y_center - real_height/2

            annotation    = self.create_annotation_section(real_x, real_y, real_width, real_height, image_id, category_id, annotation_id)
            annotations.append(annotation)
            annotation_id += 1

        image_id += 1

    return images, annotations

  def create_image_section(self, file_name, width, height, image_id):
    image_section = {
        'file_name': file_name,
        'height':    height,
        'width':     width,
        'id':        image_id
    }
    return image_section

  def create_annotation_section(self, x, y, width, height, image_id, category_id, annotation_id):
    bbox = (x, y, width, height)
    area = width * height

    annotation_section = {
        'id': annotation_id,
        'image_id': image_id,
        'bbox': bbox,
        'area': area,
        'iscrowd': 0,
        'category_id': category_id,
        'segmentation': []
    }

    return annotation_section

# python YOLO2COCOConverter.py ./classes.txt ./train ./train/annotation.json
#
# python YOLO2COCOConverter.py ./classes.txt ./valid ./valid/annotation.json

if __name__ == '__main__':
  classes_file     = ""
  dataset_dir      = ""
  output_coco_json = ""
  try:
    if len(sys.argv) == 4:
      classes_file     = sys.argv[1]
      dataset_dir      = sys.argv[2]
      output_coco_json = sys.argv[3]
    else:
      raise Exception("Invalid argment")

    if os.path.exists(classes_file) == False:
      raise Exception("Not found classes files:{}".format(classes_file))
    if os.path.exists(dataset_dir) == False:
      raise Exception("Not found dataset_dir  :{}".format(dataset_dir))

    converter = YOLO2COCOConverter(classes_file)
    converter.run(dataset_dir, output_coco_json)

  except:
    traceback.print_exc()


# 서 : N <-> 동 :M
# 1 : 1 연결 시 가장 많이 지을 수 있는 경우의 수(겹치면 안됨)
# 서로 다른 조합을 선택한다 => 다이나믹 프로그래링

for i in range(int(input())):
    N, M = map(int, input().split())
    # 경우의 수를 구할 list를 만든다
    dp = [[0 for _ in range(M + 1)] for __ in range(N + 1)]
    # 서쪽 i번째 다리가 연결될 수 있는 경우의 수
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            # 첫 번째 i는 어디든 연결 할 수있음
            if i == 1:
                dp[i][j] = j
            # 같은 경우 해당 i가 연결될 수 있는것 부터 시작
            elif i == j:
                dp[i][j] = 1
            else:
                # 작은건 그 전에 연결됨 제외
                # 크다면 연결 된 전에 연결 될수있는 경우 + 전 i가 연결에서 연결 안됐을 경우의수를 다 가질 수 있음
                if j > i:
                    dp[i][j] = dp[i][j-1] + dp[i-1][j-1]
    print(dp[i][j])


import numpy as np
import pandas as pd
from pandas import plotting
from matplotlib import pyplot as plt

#df = pd.read_csv("HW3_result.csv")
# print data

CAM = pd.read_csv('output_camshift.txt')
CAM.columns = ['index', 'x', 'y']

Kalman = pd.read_csv('output_kalman.txt')
Kalman.columns = ['index', 'x', 'y']

particle = pd.read_csv('output_particle.txt')
particle.columns = ['index', 'x', 'y']

opticle = pd.read_csv('output_of.txt')
opticle.columns = ['index', 'x', 'y']

plt.scatter(x='x', y='y', data=CAM)
plt.scatter(x='x', y='y', data=Kalman)
plt.scatter(x='x', y='y', data=particle)
plt.scatter(x='x', y='y', data=opticle)
plt.legend(['CAM', 'Kalman', 'Particle', 'Opticle'])
#plt.legend(['CAM', 'Particle', 'Opticle'])
plt.show()


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

from __future__ import unicode_literals, print_function, division, absolute_import
from builtins import str

import os
from ..indexed_enums import Enum, EnumArray

def assert_near(value, target_value, absolute_error_margin = None, message = '', relative_error_margin = None):
    '''

      :param value: Value returned by the test
      :param target_value: Value that the test should return to pass
      :param absolute_error_margin: Absolute error margin authorized
      :param message: Error message to be displayed if the test fails
      :param relative_error_margin: Relative error margin authorized

      Limit : This function cannot be used to assert near dates or periods.

    '''

    import numpy as np

    if absolute_error_margin is None and relative_error_margin is None:
        absolute_error_margin = 0
    if isinstance(value, (list, tuple)):
        value = np.array(value)
    if isinstance(target_value, (list, tuple)):
        target_value = np.array(target_value)
    if isinstance(message, str):
        message = message.encode('utf-8')
    if isinstance(value, np.ndarray):
        if isinstance(target_value, Enum) or (isinstance(target_value, np.ndarray) and target_value.dtype == object):
            if not isinstance(value, EnumArray):
                assert False, "Expected an Enum, got {} of dtype {}".format(value, value.dtype)
            else:
                assert (target_value == value.decode()).all(), "Expected {}, got {}".format(target_value, value)
        else:
            target_value = np.array(target_value).astype(np.float32)
            value = np.array(value).astype(np.float32)
            diff = abs(target_value - value)

            if absolute_error_margin is not None:
                assert (diff <= absolute_error_margin).all(), \
                    '{}{} differs from {} with an absolute margin {} > {}'.format(message, value, target_value,
                        diff, absolute_error_margin)
            if relative_error_margin is not None:
                assert (diff <= abs(relative_error_margin * target_value)).all(), \
                    '{}{} differs from {} with a relative margin {} > {}'.format(message, value, target_value,
                        diff, abs(relative_error_margin * target_value))
    else:
        if absolute_error_margin is not None:
            assert abs(target_value - value) <= absolute_error_margin, \
                '{}{} differs from {} with an absolute margin {} > {}'.format(message, value, target_value,
                    abs(target_value - value), absolute_error_margin)
        if relative_error_margin is not None:
            assert abs(target_value - value) <= abs(relative_error_margin * target_value), \
                '{}{} differs from {} with a relative margin {} > {}'.format(message, value, target_value,
                    abs(target_value - value), abs(relative_error_margin * target_value))

def indent(text):
    return "  {}".format(text.replace(os.linesep, "{}  ".format(os.linesep)))

def get_trace_tool_link(scenario, variables, api_url, trace_tool_url):
    import json
    import urllib

    scenario_json = scenario.to_json()
    simulation_json = {
        'scenarios': [scenario_json],
        'variables': variables,
        }
    url = trace_tool_url + '?' + urllib.urlencode({
        'simulation': json.dumps(simulation_json),
        'api_url': api_url,
        })
    return url


# coding=utf-8
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation
import pandas as pd
from os import chdir, makedirs
import datetime
# my modules
import calc
import convert
import fields
import c
import info

# Make new folder for each run
name = str(datetime.datetime.now()).split('.')[0]
makedirs(c.path + name)
chdir(c.path + name)

# Constants
case = [1, -1] # directions of currents in the [shock wave, current sheet]. 1 — on us, -1 — from us. => directions of B.
num = [400, 0, 200]
min_x = -5
max_x = 5
min_z = -5
max_z = 5
x = np.linspace(min_x, max_x, num=num[0])
z = np.linspace(min_z, max_z, num=num[2])

n_steps = 200
n_part = 1000  # > 1
t_koeff = 0.5 # time of particle movement for one step. Bigger — larger trajectories and more rude results
delta = 0.245
theta = 1.0 # ion mass / proton mass
dh = 0.0423
dz = 0.489
angle = np.pi/3
x_axis = -1.0
z_axis = 0.0

# Write constants to constants.txt
info.write_constants(case=case, num=num, min_x=min_x, max_x=max_x, min_z=min_z, max_z=max_z,
                     n_steps=n_steps, n_part=n_part, t_koeff=t_koeff, delta=delta, theta=theta,
                     dh=dh, dz=dz, angle=angle, x_axis=x_axis, z_axis=z_axis)

# Calc, show and save png of total field of shock wave and rotated plasmoid
u, v, m = fields.main(x, z, case, dh, dz, angle, x_axis, z_axis)

# Calc, show and save png of trajectories
sol = calc.traces(n_steps, n_part, t_koeff, delta, theta, dh, dz,
                  angle, x_axis, z_axis, case)
xyz = convert.sol_to_xyz(sol, n_steps, n_part)

# Animation
t = np.array([np.ones(n_part)*i for i in range(n_steps)]).flatten()
df = pd.DataFrame({'time': t , 'x': xyz[:, 0], 'y': xyz[:, 1], 'z': xyz[:, 2]})

def update_graph(num):
    data = df[df['time'] == num]
    graph.set_data(data.x, data.y)
    graph.set_3d_properties(data.z)
    title.set_text('step={}'.format(num))
    return title, graph

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
title = ax.set_title('')

data = df[df['time'] == 0]
graph, = ax.plot(data.x, data.y, data.z, linestyle="", marker="o")

anim = matplotlib.animation.FuncAnimation(fig, update_graph, n_steps,
                               interval=1, blit=False)

xx, yy, zz = convert.field_to_surface(num, x, z, m)
ax.contourf(xx, yy, zz, zdir='y', offset=0, alpha=0.25, cmap=cm.coolwarm)

ax.view_init(elev=0., azim=-90)
ax.set_xlabel('X')
ax.set_xlim(-20, 20)
ax.set_ylabel('Y')
ax.set_ylim(-10, 10)
ax.set_zlabel('Z')
ax.set_zlim(-10, 10)

plt.show()


from django.contrib.auth.models import User, Group
from django.shortcuts import (get_object_or_404)
from rest_framework import serializers
from .models import (Anotacion, Oracion, Parrafo, TAG,
                     Clasificacion, ArgumentacionParrafo, TAGPersonal)
class OracionSerializer(serializers.ModelSerializer):
    clasificacion = serializers.CharField()
    texto = serializers.CharField(required=True)
    class Meta:
        model = Oracion
        fields = ('anotacion', 'parrafo', 'evaluado_por', 'tipo_anotacion', 'texto', 'clasificacion')
    def create(self, validated_data):
        print("metodo create en serializer de oracionserializer")
        print(validated_data)
        clasificacion = get_object_or_404(Clasificacion, key=validated_data['clasificacion'])
        validated_data['clasificacion'] = clasificacion
        return super(OracionSerializer, self).create(validated_data, )
class ParrafoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Parrafo
        fields = ('id', 'ha_sido_evaluado')
class TAGLeyesSerializer(serializers.ModelSerializer):
    class Meta:
        model = TAG
        fields = ('id', 'texto')
class AnotacionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Anotacion
        fields = ('is_done',)
from rest_framework.fields import CurrentUserDefault
class ArgumentacionParrafoSerializer(serializers.ModelSerializer):
    autor = serializers.HiddenField(default=serializers.CurrentUserDefault())
    class Meta:
        model = ArgumentacionParrafo
        fields = ('autor', 'parrafo', 'calificacion')
class TAGPersonalSerializer(serializers.ModelSerializer):
    creado_por = serializers.HiddenField(default=serializers.CurrentUserDefault())
    class Meta:
        model = TAGPersonal
        fields = ('creado_por', 'tag', 'alias')


import timeit
#Put the graph into a format the computer can use
def pathgraph() :
    return {
        'A': {'B':22, 'C':9, 'D':12},
        'B': {'A':22, 'C':35, 'F':36, 'H':34},
        'C': {'A':9, 'B':35, 'D':4, 'E':65, 'F':42},
        'D': {'A':12, 'C':4, 'E':33, 'I':30},
        'E': {'C':65, 'D':33, 'F': 18, 'G': 23},
        'F': {'B':36, 'C':42, 'E': 18, 'G': 39, 'H':24},
        'G':{'E': 23, 'F':39, 'H':25, 'I':19},
        'H':{'B':34, 'F':24, 'G':25, 'I':19},
        'I':{'D':30, 'G':21, 'H':19}
            }

#Bellman-Ford Algorithm
def bellmanford():
    start = 'A' #staring position
    nodedistance = {} #to hold the distance between each node
    shortestmoves = {} #shortest move from each node
    paths = pathgraph() #the graph itself

    #set nodes to infinity, and the paths that can be moved to none
    for i in paths:
        nodedistance[i] = float("inf")
        shortestmoves[i] = None
    #set the first node to 0
    nodedistance[start] = 0

    #update the distances
    for _ in range (len(paths) - 1):
        for j in paths:
            for moves in paths[j]:
                    #if distance is lower than current, correct it
                    if nodedistance[moves] > nodedistance[j] + paths[j][moves]:
                        nodedistance[moves], shortestmoves[moves] = nodedistance[j] + paths[j][moves], j

    #check for negative weight
    for i in paths:
        for moves in paths[i]:
            if nodedistance[moves] > nodedistance[i] +  paths[i][moves]:
                print('Negative weight found.')
                return None

    #create a list to put the information in
    i = 'I'
    print('The shortest route to ' + i + ' is:')
    bestpath = [i]
    i = shortestmoves[i]
    while i != None:
        bestpath.append(i)
        i = shortestmoves[i]

    while len(bestpath) != 0:
        print(bestpath.pop())

#Dijkstra's Algorithm
def dijkstra():
    start = 'A' #staring position
    nodedistance = {} #to hold the distance between each node
    shortestmoves = {} #shortest move from each node
    testpaths = [] #paths to check
    paths = pathgraph() #the graph itself

    #set nodes to infinity, and the paths that can be moved to none
    for i in paths:
        nodedistance[i] = float("inf")
        shortestmoves[i] = None
        testpaths.append(i)
    #set the first node to 0
    nodedistance[start] = 0
    #test all paths
    while len(testpaths) != 0:
        #set minroute to the shortest route
        minroute = testpaths[0]
        minvalue = nodedistance[minroute]
        for i in range(1, len(testpaths)):
            #if there is a shorter route, set minvalue to that route
            test = testpaths[i]
            if nodedistance[test] < minvalue:
                minroute = testpaths[i]
                minvalue = nodedistance[minroute]
        #when smallest route is found, remove from the test and save it
        smallnode = minroute
        testpaths.remove(smallnode)

        for i in paths[smallnode]:
            #check alternate routes, if smaller change course
            altroute = paths[smallnode][i] + nodedistance[smallnode]
            if nodedistance[i] > altroute:
                nodedistance[i] = altroute
                shortestmoves[i] = smallnode
    #create a list to put the information in
    i = 'I'
    print(shortestmoves)
    print('The shortest route to ' + i + ' is:')
    bestpath = [i]
    i = shortestmoves[i]
    while i != None:
        bestpath.append(i)
        i = shortestmoves[i]

    while len(bestpath) != 0:
        print(bestpath.pop())

#time results
bfResults = timeit.repeat(stmt=r"bellmanford()",setup="from pathfindingalgorithm import bellmanford",number=100)
print("Bellman-Ford Algorithm Results: "+str(bfResults)+ "average of "+ str(sum(bfResults)/len(bfResults)) + "milliseconds.")
dijkResults = timeit.repeat(stmt=r"dijkstra()",setup="from pathfindingalgorithm import dijkstra",number=100)
print("Dijkstra's Algorithm Results: " + str(dijkResults)+ "average of "+ str(sum(dijkResults)/len(dijkResults)) + "milliseconds.")


# 定义一个武器类
class Weapon:
    # 该武器的技能有劈砍
    def cleave(self, target):
        target.hp -= 50 # 劈砍技能对目标造成50点伤害

# 定义一个人类
class Person:
    def __init__(self, name, sex, hp, atk):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.atk = atk
        self.weapon = Weapon() # 给角色绑定一个武器

# 定义一个狗类
class Dog:
    def __init__(self, name, kind, hp, atk):
        self.name = name
        self.kind = kind
        self.hp = hp
        self.atk = atk

# 实例化一个人类角色
tiele = Person('tiele', '男', 30, 10, )
# 实例化一个狗类角色
xiaobai = Dog('小白', '金毛寻回犬', 60, 15)
# 人类装备上武器使用武器技能cleave进行攻击狗类
tiele.weapon.cleave(xiaobai) # 这种用法就叫做组合
print(xiaobai.hp)  # 显示10，表明目标的确hp-50了。


class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        x, y, dx, dy = 0, 0, 0, 1

        for i in instructions:
            if i == 'R': dx, dy = dy, -dx
            elif i == 'L': dx, dy = -dy, dx
            elif i == 'G': x, y = x + dx, y + dy

        return (x, y) == (0, 0) or (dx, dy) != (0, 1)

# 1041. Robot Bounded In Circle
# https://leetcode.com/problems/robot-bounded-in-circle/description/

# There are only two scenarios where the robot can come back to its original location:

# the robot is already back to its origin by the end of the string traversal, and
# the robot is away from the origin, but heading to a direction different from its initial direction.
# For example, if the robot is facing left by the end of the first string traversal,
# after three other traversals of left->left->left, it is back to the origin.

# A second example is that if the robot is facing down by the end of the first string traversal,
# it only takes another traversal for it to get back to the origin.

# Another tip on how to change the directions.
# You actually do not need to keep a list of all possible directions [(0,1), (-1,0), (0,-1), (1,0)].
# Just swap dx and dy and add a negative sign to one of it to rotate the direction by 90 degrees.

# The proof is that the dot product of (dx,dy) and (dy,-dx) is 0,
# meaning that these two vectors are perpendicular to each other.


import os
import cv2
from time import sleep
folder = os.listdir(r'C:\Users\islom\PycharmProjects\Hakaton\Data\dasturlash')
print(folder[0])
list_videos = fr'C:\Users\islom\PycharmProjects\Hakaton\Data\dasturlash\{folder[0]}'
cap = cv2.VideoCapture(list_videos)
counter = 0
while True:
    success, img = cap.read()
    cv2.imshow("Image", img)
    print(counter)
    counter += 1
    sleep(0.08)
    key = cv2.waitKey(1)
    if key == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()


import argparse
import logging
import os.path
import random
import re
import sys

from . import M209Error
from .converter import M209_ALPHABET_SET
from .data import KEY_WHEEL_DATA
from .keylist.generate import generate_key_list
from .keylist.key_list import valid_indicator, IndicatorIter
from .keylist.config import write as write_config, read_key_list
from .procedure import StdProcedure

DESC = "M-209 simulator and utility program"
DEFAULT_KEY_LIST = 'm209keys.cfg'
LOG_CHOICES = ['debug', 'info', 'warning', 'error', 'critical']
SYS_IND_RE = re.compile(r'^[A-Z]{1}$')
M209_ALPHABET_LOWER = set(c.lower() for c in M209_ALPHABET_SET)

def validate_key_list_indicator(s):
    """Validation/conversion function for validating the supplied starting key
    list indicator.

    Returns the string value if valid, otherwise raises an ArgumentTypeError.

    """
    if len(s) == 2:
        s = s.upper()
        if valid_indicator(s):
            return s

    raise argparse.ArgumentTypeError('must be in the range AA-ZZ')

def validate_num_key_lists(s):
    """Validation/conversion function for validating the number of key lists to
    generate.

    Returns the integer value if valid, otherwise raises an ArgumentTypeError

    """
    bounds = (1, 26 ** 2)
    msg = "value must be in range {}-{}".format(*bounds)
    try:
        val = int(s)
    except ValueError:
        raise argparse.ArgumentTypeError(msg)

    if not (bounds[0] <= val <= bounds[1]):
        raise argparse.ArgumentTypeError(msg)
    return val

def validate_ext_indicator(s):
    """Validation function for the external message indicator option.

    Returns the string value if valid, otherwise raises an ArgumentTypeError.

    """
    if len(s) == 6:
        s = s.upper()
        for n, c in enumerate(s):
            if c not in KEY_WHEEL_DATA[n][0]:
                break
        else:
            return s

    raise argparse.ArgumentTypeError(
        "{} is not a valid external message indicator".format(s))

def validate_sys_indicator(s):
    """Validation function for the system message indicator option.

    Returns the string value if valid, otherwise raises an ArgumentTypeError.

    """
    if len(s) == 1:
        s = s.upper()
        if s in M209_ALPHABET_SET:
            return s

    raise argparse.ArgumentTypeError('value must be 1 letter')

def plaintext_filter(fp):
    """Generator function to filter input plaintext.

    * upper case letters are passed as-is.
    * lower case letters are converted to upper case.
    * Whitespace characters are converted to 'Z'.
    * All other characters are dropped from the input.

    """
    for line in fp:
        for c in line:
            if c in M209_ALPHABET_SET:
                yield c
            elif c in M209_ALPHABET_LOWER:
                yield c.upper()
            elif c.isspace():
                yield 'Z'

def encrypt(args):
    """Encrypt subcommand processor"""
    logging.info("Encrypting using key file %s", args.key_file)

    if args.text and args.file:
        sys.exit("Please supply either -f/--file or -t/--text, not both\n")
    elif not args.text and not args.file:
        sys.exit("Please supply either -f/--file or -t/--text\n")

    # Get a key list from the key list file
    if not os.path.isfile(args.key_file):
        sys.exit("key list file not found: {}\n".format(args.key_file))

    key_list = read_key_list(args.key_file, args.key_list_ind)
    if not key_list:
        sys.exit("key list not found in file: {}\n".format(args.key_file))

    # Get the plaintext
    if args.text:
        plaintext = plaintext_filter(args.text)
    else:
        infile = open(args.file, 'r') if args.file != '-' else sys.stdin
        plaintext = plaintext_filter(infile)

    proc = StdProcedure(key_list=key_list)
    ct = proc.encrypt(plaintext, ext_msg_ind=args.ext_ind, sys_ind=args.sys_ind)
    print(ct)

def decrypt(args):
    """Decrypt subcommand processor"""
    logging.info("Decrypting using key file %s", args.key_file)

    if args.text and args.file:
        sys.exit("Please supply either -f/--file or -t/--text, not both\n")
    elif not args.text and not args.file:
        sys.exit("Please supply either -f/--file or -t/--text\n")

    # Check for key list file
    if not os.path.isfile(args.key_file):
        sys.exit("key list file not found: {}\n".format(args.key_file))

    # Get the ciphertext to decrypt
    if args.text:
        msg = args.text
    else:
        # Read contents of ciphertext file
        if args.file == '-':
            msg = sys.stdin.read()
        else:
            with open(args.file, 'r') as fp:
                msg = fp.read()
        msg = msg.strip()

    # Start the decrypt procedure
    proc = StdProcedure()
    params = proc.set_decrypt_message(msg)

    # Find a key list for the message
    key_list = read_key_list(args.key_file, params.key_list_ind)
    if key_list is None:
        sys.exit("Could not find key list {} in {}\n".format(
            params.key_list_ind, args.key_file))

    # Install the key list and perform the decrypt operation
    proc.set_key_list(key_list)
    plaintext = proc.decrypt()
    print(plaintext)

def keygen(args):
    """Key list generation subcommand processor"""
    logging.info("Creating key list file: %s", args.key_file)

    if not args.overwrite and os.path.exists(args.key_file):
        sys.exit("File '{}' exists. Use -o to overwrite\n".format(args.key_file))

    if args.start is None:   # random indicators
        indicators = random.sample([i for i in IndicatorIter()], args.number)
        indicators.sort()
    else:
        it = IndicatorIter(args.start)
        n = len(it)
        if n < args.number:
            sys.exit("Error: can only produce {} key lists when starting at {}\n".format(
                n, args.start))

        indicators = (next(it) for n in range(args.number))

    key_lists = (generate_key_list(indicator) for indicator in indicators)

    write_config(args.key_file, key_lists)

def main(argv=None):
    """Entry point for the m209 command-line utility."""

    # create the top-level parser
    parser = argparse.ArgumentParser(description=DESC)
    parser.add_argument('-l', '--log', choices=LOG_CHOICES, default='warning',
        help='set log level [default: %(default)s]')
    subparsers = parser.add_subparsers(title='list of commands',
        description='type %(prog)s {command} -h for help on {command}')

    # create the sub-parser for encrypt
    enc_parser = subparsers.add_parser('encrypt', aliases=['enc'],
        description='Encrypt text from a file or command-line',
        help='encrypt text from file or command-line',
        epilog='Either the -f/--file or -t/--text arguments must be supplied')
    enc_parser.add_argument('-z', '--key-file', default=DEFAULT_KEY_LIST,
        help='path to key list file [default: %(default)s]')
    enc_parser.add_argument('-f', '--file',
        help='path to plaintext file or - for stdin')
    enc_parser.add_argument('-t', '--text',
        help='text string to encrypt')
    enc_parser.add_argument('-k', '--key-list-ind', metavar='XX',
        type=validate_key_list_indicator,
        help='2-letter key list indicator; if omitted a random one is used')
    enc_parser.add_argument('-e', '--ext-ind', metavar='ABCDEF',
        type=validate_ext_indicator,
        help='6-letter external message indicator; if omitted a random one is used')
    enc_parser.add_argument('-s', '--sys-ind', metavar='S',
        type=validate_sys_indicator,
        help='1-letter system indicator; if omitted a random one is used')
    enc_parser.set_defaults(subcommand=encrypt)

    # create the sub-parser for decrypt
    dec_parser = subparsers.add_parser('decrypt', aliases=['dec'],
        description='Decrypt text from a file or command-line',
        help='decrypt text from file or command-line',
        epilog='Either the -f/--file or -t/--text arguments must be supplied')
    dec_parser.add_argument('-z', '--key-file', default=DEFAULT_KEY_LIST,
        help='path to key list file [default: %(default)s]')
    dec_parser.add_argument('-f', '--file',
        help='path to ciphertext file or - for stdin')
    dec_parser.add_argument('-t', '--text',
        help='text string to decrypt')
    dec_parser.set_defaults(subcommand=decrypt)

    # create the sub-parser for generating key lists

    kg_parser = subparsers.add_parser('keygen', aliases=['key'],
        description='Generate key list file',
        help='generate key list')
    kg_parser.add_argument('-z', '--key-file', default=DEFAULT_KEY_LIST,
        help='path to key list file [default: %(default)s]')
    kg_parser.add_argument('-o', '--overwrite', action='store_true',
        help='overwrite key list file if it exists')
    kg_parser.add_argument('-s', '--start', metavar='XX',
        type=validate_key_list_indicator,
        help='starting indicator; if omitted, random indicators are used')
    kg_parser.add_argument('-n', '--number', type=validate_num_key_lists, default=1,
        help='number of key lists to generate [default: %(default)s]')
    kg_parser.set_defaults(subcommand=keygen)

    args = parser.parse_args(args=argv)

    log_level = getattr(logging, args.log.upper())
    logging.basicConfig(level=log_level, format='%(message)s')

    try:
        args.subcommand(args)
    except EnvironmentError as ex:
        sys.exit('{}\n'.format(ex))
    except KeyboardInterrupt:
        sys.exit('Interrupted\n')
    except M209Error as ex:
        sys.exit('{}\n'.format(ex))

if __name__ == '__main__':
    main()


#!/usr/bin/python3
from __future__ import print_function
import re, itertools

class Ingredient(object):
    def __init__(self, description):
        ingredient_re = r"(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)"
        parse = re.match(ingredient_re, description).groups()
        self.name       =     parse[0]
        self.capacity   = int(parse[1])
        self.durability = int(parse[2])
        self.flavor     = int(parse[3])
        self.texture    = int(parse[4])
        self.calories   = int(parse[5])

def getCalories(ingredients_list):
    return sum(l[0]*l[1].calories for l in ingredients_list)

def getScore(ingredients_list):
    capacity    = max(0, sum(l[0]*l[1].capacity     for l in ingredients_list))
    durability  = max(0, sum(l[0]*l[1].durability   for l in ingredients_list))
    flavor      = max(0, sum(l[0]*l[1].flavor       for l in ingredients_list))
    texture     = max(0, sum(l[0]*l[1].texture      for l in ingredients_list))

    return capacity * durability * flavor * texture

# That's handy, the Advent of Code gives unittests.
def UnitTest():
    ex = """Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3"""

    print("Unit test for Part One.")
    print("Test {inp} gives {res}".format(inp=ex, res=partOne(ex.strip())))

    print("")
    print("Unit test for Part Two.")
    print("Test {inp} gives {res}".format(inp=ex, res=partTwo(ex)))

def partOne(inp):
    ingredients = list(map(Ingredient, inp.split('\n')))
    def _genScores():
        for prod in itertools.product(*([range(100)]*(len(ingredients)-1))):
            if sum(prod) > 100:
                continue
            else:
                last_qty = 100-sum(prod)
                recipe = list(zip(list(prod)+[last_qty], ingredients))
                yield getScore(recipe)
    return max(_genScores())

def partTwo(inp):
    ingredients = list(map(Ingredient, inp.split('\n')))
    def _genScores():
        for prod in itertools.product(*([range(100)]*(len(ingredients)-1))):
            if sum(prod) > 100:
                continue
            else:
                last_qty = 100-sum(prod)
                recipe = list(zip(list(prod)+[last_qty], ingredients))
                if getCalories(recipe) == 500:
                    yield getScore(recipe)
    return max(_genScores())

if __name__ == '__main__':
    from argparse import ArgumentParser, FileType

    args = ArgumentParser()
    args.add_argument("-t", "--test", help='Unit tests', action='store_true')
    args.add_argument("-i", "--input", help='Your input file', type=FileType('r'))
    options = args.parse_args()

    if options.test:
        UnitTest()
    if options.input:
        inp = options.input.read().strip()
        print("Answer for part one is : {res}".format(res=partOne(inp)))
        print("Answer for part two is : {res}".format(res=partTwo(inp)))


#!/usr/bin/python3

import argparse
import datetime
import json
import logging
import os
import sdr.scanner

def config_logger(verbose, dir):
    params = {}

    levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
    level = levels[min(len(levels) - 1, verbose)]

    params["format"] = "[%(asctime)s][%(levelname)7s][%(name)6s] %(message)s"
    params["level"] = level
    params["datefmt"] = "%Y-%m-%d %H:%M:%S"

    if dir:
        now = datetime.datetime.now()
        os.makedirs("%s/%04d-%02d-%02d" % (dir, now.year, now.month, now.day), exist_ok=True)
        filename = "%s/%04d-%02d-%02d/%02d_%02d_%02d.txt" % (dir, now.year, now.month, now.day, now.hour, now.minute, now.second)
        params["filename"] = filename
    logging.basicConfig(**params)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("config", help="path to config file", type=str, metavar="file")
    parser.add_argument("-ld", "--log_directory", help="store output log in directory", type=str, metavar="dir")
    parser.add_argument("-wd", "--wav_directory", help="store output wav in directory", type=str, metavar="dir", default="wav")
    parser.add_argument("-dr", "--disable_recording", help="disable recording, only scannig", action="store_true")
    parser.add_argument("-pbf", "--print_best_frequencies", help="print n best frequencies", type=int, default=1, metavar="n")
    parser.add_argument("-fbf", "--filter_best_frequencies", help="filter printed n best frequencies", action="store_true")
    parser.add_argument("-v", "--verbose", action="count", default=0)
    args = parser.parse_args()

    config_logger(args.verbose, args.log_directory)
    with open(args.config) as f:
        config = json.load(f)
        ignored_frequencies_ranges = []
        if "ignored_frequencies_ranges" in config:
            ignored_frequencies_ranges = config["ignored_frequencies_ranges"]
        sdr.scanner.run(
            frequencies_ranges=config["frequencies_ranges"],
            ignored_frequencies_ranges=ignored_frequencies_ranges,
            ppm_error=int(config["device"]["ppm_error"]),
            tuner_gain=config["device"]["tuner_gain"],
            squelch=config["recording"]["squelch"],
            noise_level=config["scanning"]["noise_level"],
            bandwidth=config["scanning"]["bandwidth"],
            samples=config["scanning"]["samples"],
            fft=config["scanning"]["fft"],
            min_recording_time=config["recording"]["min_recording_time"],
            max_recording_time=config["recording"]["max_recording_time"],
            max_silence_time=config["recording"]["max_silence_time"],
            samples_rate=config["recording"]["samples_rate"],
            wav_directory=args.wav_directory,
            disable_recording=args.disable_recording,
            print_best_frequencies=args.print_best_frequencies,
            filter_best_frequencies=args.filter_best_frequencies,
        )


# Créez un programme qui affiche
#  le résultat et le reste d’une division entre deux nombres.
#
# exp :
#       --> python exo.py 5 2
#           resultat : 2
#           reste : 1
#
#       --> python exo.py 10 0
#           erreur.
#
#       --> python exo.py 3 5
#           erreur.

import sys

def lenght_argument():
    if len(sys.argv[1:]) != 2:
        print ("il faut un dividende et un diviseur")
        exit()

def int_numbers_check():
    is_first_arg_digit=(sys.argv[1]).isdigit()
    is_second_arg_digit=(sys.argv[2]).isdigit()
    if not is_first_arg_digit or not is_second_arg_digit:
        print("Bien essayer mais il faut des chiffres entiers !")
        exit()

def calculation_rules():
    dividende = int(sys.argv[1])
    diviseur = int(sys.argv[2])
    if dividende < diviseur:
        print("Erreur le diviseur doit être inférieur au dividende")
        exit()
    if diviseur == 0:
        print ("Erreur le diviseur ne peut pas être nul")
        exit()

def generate_result():
    dividende = int(sys.argv[1])
    diviseur = int(sys.argv[2])
    quotient = (dividende) // (diviseur)
    print ('resultat :',quotient)
    reste = dividende % diviseur
    print ('reste :',reste)

lenght_argument()
int_numbers_check()
calculation_rules()
generate_result()


def mostrar_menu(saldo=0):

    while(True):
        print('Bienvenido al portal del Banco Amigo. Escoja una opción:')
        print('1. Consultar saldo')
        print('2. Hacer depósito')
        print('3. Realizar giro')
        print('4. Salir')
        entrada = int(input())

        if entrada == 1:
            print(getSaldo(saldo))
        elif entrada == 2:
            cantidad = int(input("Ingrese cantidad a depositar\n"))
            saldo = depositar(saldo, cantidad)
            print(getSaldo(saldo))
        elif entrada == 3:
            if saldo <= 0:
                print("No se puede girar esta cantidad. " + getSaldo(saldo))
            else:
                cantidad = int(input("Ingrese cantidad a girar\n"))
                resultado = girar(saldo, cantidad)
                if resultado is False:
                    print("No se puede girar esta cantidad. " + getSaldo(saldo))
                else:
                    saldo = resultado
                    print(getSaldo(saldo))
        elif entrada == 4:
            break

def depositar(saldo, cantidad):
    return saldo + cantidad

def girar(saldo, cantidad):
    if cantidad <= saldo:
        return saldo - cantidad
    else:
        return False

def getSaldo(saldo):
    return "Su saldo es de " + str(saldo)

mostrar_menu(1000)

1 - Introducción a la programación con Python/Desafío 05 - Ciclos y métodos/menu_banco.py


from collections import defaultdict
import re
import heapq

class Node(object):
    def __init__(self, name):
        self.name = name
        self.children = set()
        self.parents = set()

re_steps = re.compile("""Step (.+) must be finished before step (.+) can begin.""")
steps = []
nodes = dict()
with open('input.txt', 'r') as f:
    for line in f:
        m = re_steps.match(line)
        a, b = m[1], m[2]
        if a not in nodes:
            nodes[a] = Node(a)
        if b not in nodes:
            nodes[b] = Node(b)
        nodes[a].children.add(nodes[b])
        nodes[b].parents.add(nodes[a])

q = [n.name for n in nodes.values() if len(n.parents) == 0]
heapq.heapify(q)
ans = []
while len(q) > 0:
    name = heapq.heappop(q)
    ans.append(name)

    node = nodes[name]
    for child in node.children:
        child.parents.remove(node)
        if len(child.parents) == 0:
            heapq.heappush(q, child.name)

print("".join(ans))


import glob
import os, sys
import subprocess

RE ="/dors/capra_lab/projects/enhancer_ages/fantom/results/for_publication/syn/"

RepeatP = "/dors/capra_lab/projects/enhancer_ages/te/data/"
RepeatF = "%srepeatmasker_hg19.bed" % RepeatP

ShufP = "/dors/capra_lab/projects/enhancer_ages/fantom/data/shuffle/breaks/"
ShufFs = glob.glob("%s*_age_breaks.bed" % ShufP)

EnhP = "/dors/capra_lab/projects/enhancer_ages/fantom/data/"
EnhFs = glob.glob("%sFANTOM_enh_age_arch_*.tsv" % EnhP)

ShufOutP = "%sno-repeats/" % EnhP
OutP = "%sno-repeats/" % EnhP

#%% define bedtools intersection command

def bed_subtract(shufF, RepeatF, outP):

    fName = (shufF.split("/")[-1]).split(".")[0]
    outF = "%sno-repeatmasker_%s.bed" % (outP, fName)

    # use -v argument to subtract exons from shuffle file.
    cmd = "bedtools intersect -a %s -b %s -v > %s" % (shufF, RepeatF, outF)
    subprocess.call(cmd, shell = True)
    print(cmd)

#%% subtract shuffles

for ShufF in ShufFs:

    bed_subtract(ShufF, RepeatF, ShufOutP)

#%% subtract enhancers

for EnhF in EnhFs:
    fName = (EnhF.split("/")[-1]).split(".")[0]
    tempF = "%stemp_%s.bed" % (OutP, fName)
    cmd = "sed '1d' %s > %s " % (EnhF, tempF)
    print(cmd)
    subprocess.check_call(cmd, shell = True)
    bed_subtract(tempF, RepeatF, OutP)


import socket  # funkcje gniazd sieciowych
import threading  # wątki
import datetime  # czas do zapisu w logach rozmów
import signal
import sys
import time

class FORMAT:  # formatowanie tekstu
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    IDK = '\033[90m'
    BOLD = '\033[1m'
    END = '\033[0m'
    NOCOLOR = '\x1b[0m'

class SRV:  # klasa serwera z definicjami metod uzywanych przez serwer
    clients = {}  # slownik klientów
    addresses = {}  # słownik adresów
    threads = []
    kill_threads = False
    HOST = ''
    PORT = 33000
    BUFSIZ = 1024
    ADDR = (HOST, PORT)
    SERVER = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # stworzenie gniazda IPv4 z protokołem TCP
    SERVER.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # ustawienie opcji gniazda
    print(FORMAT.GREEN, "Socket created!", FORMAT.END)

    def __init__(self):  # konstruktor do bindowania gniazda
        self.SERVER.bind(self.ADDR)
        print(FORMAT.GREEN, "Socket bounded!", FORMAT.END)

    def __del__(self):
        self.SERVER.close()  # zamykanie serwera
        for client in self.clients:  # kończenie połączenia z klientami

            client.close()

    def get_clients(self):  # metoda zwracająca klientów
        return self.clients

    def add_client(self, client, name):  # metoda przypisująca klientom nazwy
        self.clients[client] = name

    def accept_conn(self):  # akceptowanie nowych połączeń
        while True:
            client, client_address = self.SERVER.accept()
            # print(FORMAT.IDK, "%s:%s joined!" % client_address, FORMAT.END)
            print(FORMAT.IDK, "'{}' joined!".format(client_address), FORMAT.END)  # rozwiazanie błędu Too few arguments
            # for format string
            client.send(bytes("!@#Enter your username: ", "utf8"))
            self.addresses[client] = client_address  # przypisanie do klienta jego adresu IP
            # threading.Thread(target=self.handle_client, args=(client,)).start()  # wystartowanie wątku wywołującego
            t = threading.Thread(target=self.handle_client, args=(client, lambda: self.kill_threads))
            self.threads.append(t)
            t.start()
            # metodę handle_client i przekazującego mu argument client

    def handle_client(self, client, stop):  # obsluga calego polaczenia z klientem
        # poniższy fragment wykonuje się tylko raz po dolączeniu klienta do serwera
        name = client.recv(self.BUFSIZ).decode("utf8")  # wpisanie swojej nazwy przez użytkownika
        welcome = '#@!Hi %s! Type !q to quit.' % name
        client.send(bytes(welcome, "utf8"))
        msg = "%s joined the chat!" % name
        f.write("%s joined the chat\n" % name)  # zapisanie do txt dołączenia klienta
        print(FORMAT.BLUE, "%s joined the chat" % name, FORMAT.END)
        self.broadcast(bytes(msg, "utf8"))
        self.clients[client] = name

        while True:
            try:
                # wykonywanie ciągle w pętli
                client.settimeout(3.0)
                msg = client.recv(self.BUFSIZ)  # odebranie wiadomości
                if not msg:
                    break
                if msg.decode("utf8")[0] == '@':  # jezeli po zdekodowaniu pierwszym znakiem jest @ to wiadomość priv
                    self.send_to_user(msg, name + ": ")
                elif msg != bytes("!q", "utf8"):
                    self.broadcast(msg, name + ": ", client)
                else:
                    # pozostaly warunek to !q czyli wyjście klienta z serwera
                    self.broadcast(bytes("%s left the chat :c" % name, "utf8"))
                    client.close()
                    print(FORMAT.BLUE, "%s left the chat" % name, FORMAT.END)
                    f.write("%s left the chat\n" % name)
                    del self.clients[client]  # kasowanie klienta ze słownika
                    break
            except socket.timeout:
                if stop():
                    break
                else:
                    continue
            except Exception as inst:
                print(FORMAT.IDK + "Connection with client lost" + FORMAT.END)
                del self.clients[client]

    def broadcast(self, msg, prefix="", poster=None):  # prefix = nazwa + :
        for sock in self.clients:
            if sock != poster:  # dla wszystkich gniazd
                sock.send(bytes(prefix, "utf8") + msg)
                tmp1 = msg.decode("utf8")
                txt = (prefix.split(':', 1)[0] + " to all: " + tmp1 + "\n")
                if txt.split(":", 2)[0] != "to all":  # żeby nie wypisywało wiadomości n razy (n liczba klientów)
                    print(" " + prefix.split(':', 1)[0] + " to all: " + tmp1)
                    f.write(txt)

    def send_to_user(self, msg, prefix=""):  # wiadomość prywatna
        tmp = msg.decode().split(" ", 1)[0]  # dzieli wiadomość po spacjach i przypisuje do tmp @nazwa
        tmp = tmp.replace('@', '')  # zastępuje @ niczym
        for client in self.clients:
            if self.clients[client] == tmp:  # szuka klienta o uzytej nazwie
                client.send(bytes(prefix, "utf8") + msg)
                tmp1 = msg.decode("utf8")
                print(" " + prefix.split(':', 1)[0] + " to " + tmp + ": " + tmp1)
                txt = (prefix.split(':', 1)[0] + " to " + tmp + ": " + tmp1 + "\n")
                f.write(txt)

    def exit(self):
        self.kill_threads = True  # ubijanie wątków
        self.broadcast(bytes("!q", "utf-8"))
        for t in self.threads:
            t.join()  # dołączanie wątków pobocznych do głównego

srv = SRV()

def signal_handler(sig, frame):
    animation = "|/-\\"
    i = 0
    while i != 7:
        print(FORMAT.YELLOW + FORMAT.BOLD + "Exiting... " + FORMAT.END + animation[i % len(animation)], end="\r"),
        i = i + 1
        time.sleep(0.2)
    global srv  # definicja zmiennej globalnej srv
    srv.exit()
    del srv  # zamykanie serwera
    sys.exit(0)

if __name__ == "__main__":  # definicja zmiennych interpretera python (plik źródłowy jako program glówny)
    signal.signal(signal.SIGINT, signal_handler)
    srv.SERVER.listen(5)  # podłączenie maksymalnie 5 użytkowników do serwera
    f = open("chat_log.txt", "w")  # utworzenie txt z prawem zapisu do pliku
    now = datetime.datetime.now()  # ustawienie czasu na chwilę obecną
    f.write(now.strftime("%Y-%m-%d %H:%M:%S\n"))
    print(FORMAT.YELLOW, "Waiting for connection...", FORMAT.END)
    srv.accept_conn()
    # ACCEPT_THREAD = threading.Thread(target=srv.accept_conn())  # akceptacja i wystartowanie wątku z accept_conn
    # ACCEPT_THREAD.start()
    while input == "!quit":
        f.close()  # zamknięcie pliku
        del srv


"""
Blackjack.py
13. June 2023

Blackjack Game

Author:
Melvin Kapferer, Maximilian Koch
"""
from PIL import Image, ImageTk
import customtkinter as ctk
from enum import Enum
import random
import sys
import os
import re
import time

# remove not-working auto-dpi awareness
ctk.deactivate_automatic_dpi_awareness()

# enumerators for players / winners
class PlayerKind(Enum):
    player = "Player"
    croupier = "Croupier"

class WinnerKind(Enum):
    player = "Player"
    croupier = "Croupier"
    draw = "Draw"

class Cards:
    """
    Cards
    """
    @staticmethod
    def function() -> list[str]:
        """
        generates a list of all available images in ./cards/
        """
        path = "cards"
        filelist = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if file == "CardBack.png":
                    continue
                filelist.append(os.path.join(root, file))
        return filelist

class BlackjackGame(ctk.CTk):
    second_card_counter: int = ...
    player_cards_x: int = ...
    player_cards_y: int = ...
    croupier_cards_x: int = ...
    croupier_cards_y: int = ...
    x_change: int = ...
    y_change: int = ...
    value_player: int = ...
    value_croupier: int = ...
    lst: list[ImageTk.PhotoImage] = ...
    filelist: list[str] = ...

    bg: ImageTk.PhotoImage = ...
    canvas1: ctk.CTkCanvas = ...
    hit_btn: ctk.CTkButton = ...
    stand_btn: ctk.CTkButton = ...
    leave_btn: ctk.CTkButton = ...

    croupier_text: int = -1
    player_text: int = -1
    hidden_card: int = -1

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.width = self.winfo_screenwidth()
        self.height = self.winfo_screenheight()
        self.playercoins = 300
        self.all_coins = [500, 250, 100, 50, 20, 10]

        # window configuration
        # check if the os is windows, and if not set fullscreen by using
        # root.attributes instead of zoomed (state won't work on linux / darwin
        if sys.platform == "win32":
            self.after(0, lambda: self.state("zoomed"))
        else:
            self.attributes("-zoomed", 1)

        self.attributes("-fullscreen", True)
        self.bg = ImageTk.PhotoImage(
            Image.open("./design/design1.png").resize(
                size=(self.width, self.height)
            )
        )
        self.delet()
        self.create_widgets()
        self.coins()

    def calculatecoins(self, coin):
        '''
        Calculate what coins the player gets
        '''
        print(self.playercoins)
        print(coin)
        print()
        z = 0
        if coin == self.playercoins:
            self.listofcoinst.append(1)
            print(self.listofcoinst)
            print()
            return "jaisNone"

        if coin > self.playercoins:
            self.listofcoinst.append(0)
            print(self.listofcoinst)
            print()
            return

        while self.playercoins > coin:
            self.playercoins -= coin
            z+=1

        self.listofcoinst.append(z)
        print(self.listofcoinst)
        print()

    def coins(self):
        """
        handles the coins and bets of the game

        Coins: 10, 20, 50, 100, 250, 500
        """
        playercoins = self.playercoins
        self.listofcoinst = []
        self.playercoins
        for i in self.all_coins:
            isNone = self.calculatecoins(i)
            if isNone == "jaisNone":
                break
        self.coincanvas.pack(anchor="sw", side="bottom", pady=200, padx=200)
        self.playercoins = playercoins
        self.coincanvas.create_image(0, 0, image=ImageTk.PhotoImage(Image.open("cards/CardBack.png")))

    def delet(self) -> None:
        """
        resets all values to game start
        """
        self.second_card_counter = 0
        self.player_cards_x = int(self.width / 2)
        self.player_cards_y = int(self.height / 1.479)
        self.croupier_cards_x = int(self.width / 2)
        self.croupier_cards_y = int(self.height / 4.695)
        self.x_change = 20
        self.y_change = 20
        self.value_player = 0
        self.value_croupier = 0
        self.lst = []
        self.filelist = Cards().function()

    def create_widgets(self) -> None:
        """
        creates all the game-widgets
        """
        self.canvas1 = ctk.CTkCanvas(self, border=0, highlightthickness=0)
        self.canvas1.pack(fill="both", expand=True)
        self.canvas1.create_image(0, 0, image=self.bg, anchor="nw")
        self.croupier_text = self.canvas1.create_text(
            self.width / 2,
            self.height / 21.6,
            text=f"croupier value: {self.value_croupier}",
            font=(
                'Times New Roman', 20,
                'bold'
            ),
            fill="white"
        )
        self.player_text = self.canvas1.create_text(
            self.width / 2,
            self.height / 2,
            text=f"croupier value: {self.value_croupier}",
            font=(
                'Times New Roman',
                20,
                'bold'
            ),
            fill="white"
        )
        self.hit_btn = ctk.CTkButton(
            self.canvas1,
            text="Hit",
            height=int(self.height / 21.6),
            width=int(self.width / 9.6),
            command=lambda: self.create_cards(PlayerKind.player),
            fg_color="#202020",
            corner_radius=0
        )
        self.hit_btn.place(
            x=self.width / 2 - self.width / 4.8,
            y=self.height - self.height / 10.8
        )
        self.stand_btn = ctk.CTkButton(
            self.canvas1,
            text="Stand",
            height=int(self.height / 21.6),
            width=int(self.width / 9.6),
            command=self.stand,
            fg_color="#202020",
            corner_radius=0
        )
        self.stand_btn.place(
            x=self.width / 2,
            y=self.height - self.height / 10.8,
            anchor="n"
        )
        self.leave_btn = ctk.CTkButton(
            self.canvas1,
            text="Hit and run",
            height=int(self.height / 21.6),
            width=int(self.width / 9.6),
            command=exit,
            fg_color="#202020",
            corner_radius=0
        )
        self.leave_btn.place(
            x=self.width / 2 + self.width / 4.8,
            y=self.height - self.height / 10.8,
            anchor="ne"
        )
        self.coincanvas = ctk.CTkCanvas(self.canvas1)

        self.create_cards(PlayerKind.player)
        self.create_cards(PlayerKind.croupier)
        self.create_cards(PlayerKind.player)
        self.create_cards(PlayerKind.croupier)

    def create_cards(self, player: PlayerKind) -> None:
        """
        creates one card and places it

        :param player: must be either Player or Croupier
        """
        if len(self.filelist) == 0:
            self.filelist = Cards().function()

        card = random.choice(self.filelist)

        self.filelist.remove(card)
        value = int(
            re.search(r'\d+', card).group()
        )  # gets integer out of a string

        if player == PlayerKind.player:
            self.player_cards_x += self.x_change
            self.player_cards_y += self.y_change
            x = self.player_cards_x - self.x_change
            y = self.player_cards_y - self.y_change
            self.value_player += value
            print(f"player value:{self.value_player}")

        elif player == PlayerKind.croupier:
            self.second_card_counter += 1
            if self.second_card_counter == 2:
                card = "cards/CardBack.png"

            else:
                self.value_croupier += value
            self.croupier_cards_x += self.x_change
            self.croupier_cards_y += self.y_change
            x = self.croupier_cards_x - self.x_change
            y = self.croupier_cards_y - self.y_change

            print(f"croupier value:{self.value_croupier}")

        else:
            raise ValueError("Invalid value for player!")

        self.canvas1.itemconfig(
            self.croupier_text,
            text=f"croupier value: {self.value_croupier}"
        )
        self.canvas1.itemconfig(
            self.player_text,
            text=f"player value: {self.value_player}"
        )
        card = ImageTk.PhotoImage(Image.open(card).resize(
            (int(self.width / 9.6), int(self.height / 3.6)))
        )
        image = self.canvas1.create_image(x, y, image=card)

        if self.second_card_counter == 2 and player == "Croupier":
            self.hidden_card = image
        self.lst.append(card)  # handles common error
        if self.value_player > 21:
            self.end(WinnerKind.croupier)

        elif self.value_croupier > 21:
            self.end(WinnerKind.player)

        if self.value_player == 21:
            self.stand()

    def stand(self) -> None:
        """
        ends the players turn
        """
        self.croupier_cards_x = self.croupier_cards_x - self.x_change
        self.croupier_cards_y = self.croupier_cards_y - self.y_change
        self.canvas1.delete(self.hidden_card)

        while self.value_croupier < 17:
            self.create_cards(PlayerKind.croupier)
            time.sleep(0.5)

        if self.value_croupier < self.value_player:
            winner = WinnerKind.player

        elif self.value_croupier > self.value_player:
            winner = WinnerKind.croupier

        else:
            winner = WinnerKind.draw

        if self.value_croupier > 21 or self.value_player > 21:
            return

        self.end(winner)

    def end(self, winner: WinnerKind) -> None:
        """
        handles the end of a round

        :param winner: the rounds winner
        """
        print(f"winner is {winner}")
        if winner == WinnerKind.draw:
            text = "draw"
            x = 625

        else:
            text = f"{winner.value} won!"

            if winner == WinnerKind.player:
                x = 200
            elif winner == WinnerKind.croupier:
                x = 125
            else:
                raise ValueError("Invalid value for winner")

        self.hit_btn.configure(state="disabled")
        self.stand_btn.configure(state="disabled")
        self.frame_end = ctk.CTkFrame(self, width=500, height=500)
        self.frame_end.place(x=x, y=300)
        label_end = ctk.CTkLabel(
            self.frame_end,
            text=text,
            font=('Times New Roman', 300, 'bold')
        )
        label_end.pack()
        button_end_restart = ctk.CTkButton(
            self.frame_end,
            text="Again?",
            command=self.close,
            height=50
        )
        button_end_restart.pack(fill="x")
        button_end_end = ctk.CTkButton(
            self.frame_end,
            text="End the game",
            command=exit,
            height=50
        )
        button_end_end.pack(fill="x")

    def close(self) -> None:
        """
        restarts the game
        """
        self.hit_btn.configure(state="normal")
        self.stand_btn.configure(state="normal")
        self.frame_end.destroy()
        self.lst.clear()
        print(self.lst)
        self.delet()
        time.sleep(0.1)
        self.create_cards(PlayerKind.player)
        self.create_cards(PlayerKind.croupier)
        self.create_cards(PlayerKind.player)
        self.create_cards(PlayerKind.croupier)

if __name__ == '__main__':
    game = BlackjackGame()
    game.mainloop()


from jeu import core
from jeu.Etat import Etat
from jeu.IHM.Bouton1 import Bouton1

class PageGameOver:
    def __init__(self):  # constructeur
        self.couleur = (255,255,255)
        self.posbp3 = (400 - (190 / 2), 525 - 25)
        self.bp3 = Bouton1(self.posbp3[0], self.posbp3[1], Etat.MENU, True, "./Image/Template.png", (190, 50))
        self.massCursor = 2
        self.bRunOnce = 0
        self.score = 0
        self.money = 0
        self.nombreCoup = 0
        self.scoreMulti =0

        self.posbp4 = (30, 570)
        self.bp4 = Bouton1(self.posbp4[0], self.posbp4[1], Etat.SAUVEGARDE, True, "./Image/Template.png", (275, 50))

    def update(self):
        core.memory("maPartie").restart()

        if not core.memory("TexTitre").ready:
            core.memory("TexTitre").load()
        core.memory("TexTitre").show()

        core.Draw.text((0,0,0), 'GAME OVER ', (200, 80), 40, "./Font/8-BIT WONDER.TTF", False)

        self.bp3.show()
        self.bp3.updateRect()
        core.Draw.text((0,0,0), 'Retour ', (self.posbp3[0] + 5, self.posbp3[1] - 13), 20,
                       "./Font/8-BIT WONDER.TTF", False)

        core.Draw.text(self.couleur, 'Kill ' + str(self.score), (275, 230))
        core.Draw.text(self.couleur, 'Nombre coup ' + str(self.nombreCoup), (275, 280))
        core.Draw.text(self.couleur, 'Nombre coins ' + str(self.money), (275, 330))
        core.Draw.text(self.couleur, 'Score: kill + coin - (Nombre coup /2) :' + str(self.scoreMulti), (275, 380))

        self.bp4.show()
        self.bp4.updateRect()
        core.Draw.text((0,0,0), 'Sauvegarder ', (self.posbp4[0] + 5, self.posbp4[1] - 13), 20,
                       "./Font/8-BIT WONDER.TTF", False)

    def setScore(self):
        self.score = core.memory("maPartie").get_score()
        self.nombreCoup = core.memory("maPartie").get_nombreCoup()
        self.money = core.memory("maPartie").get_money()

        self.scoreMulti = self.score + self.money - (self.nombreCoup /2)


class Solution:
  def tree2str(self, t: TreeNode) -> str:
    if not t:
      return ''
    if not t.left and not t.right:
      return str(t.val)
    ans = str(t.val)
    ans += '(' + self.tree2str(t.left) + ')'
    if t.right:
      ans += '(' + self.tree2str(t.right) + ')'
    return ans

algorithms/606. Construct String from Binary Tree.py


import numpy as np
import scipy.io as scio
from .image_dataset import ImageDataset

class SynthDataset(ImageDataset):
    r'''Dataset reading from images.
    Args:
        Processes: A series of Callable object, which accept as parameter and return the data dict,
            typically inherrited the `DataProcess`(data/processes/data_process.py) class.
    '''

    def __init__(self, data_dir=None, data_list=None, cmd={}, **kwargs):
        self.load_all(**kwargs)
        self.data_dir = data_dir or self.data_dir
        self.data_list = data_list or self.data_list

        self.is_training = True

        self.debug = cmd.get('debug', False)

        self.image_paths = []
        self.targets = []
        self.get_all_samples()

    def get_all_samples(self):
        for i in range(len(self.data_dir)):
            data = scio.loadmat(self.data_list[i])

            img_paths = list(data['imnames'][0])
            gts = list(data['wordBB'][0])
            texts = list(data['txt'][0])

            img_paths=[self.data_dir[i]+'/img/'+timg[0].strip() for timg in img_paths]
            self.image_paths += img_paths

            for gt, text in zip(gts,texts):
                bboxes, words = self.load_ann(gt, text)

                lines = []
                for k in range(bboxes.shape[0]):
                    item = {
                        'poly':bboxes[k].tolist(),
                        'text':words[k]
                    }
                    lines.append(item)
                self.targets.append(lines)
        self.num_samples = len(self.image_paths)

    def load_ann(self, gt, text):
        bboxes = np.array(gt)
        bboxes = np.reshape(bboxes, (bboxes.shape[0], bboxes.shape[1], -1))
        bboxes = bboxes.transpose(2, 1, 0)
        bboxes = np.round(bboxes)

        words = []
        for text_ in text:
            text_ = text_.replace('\n', ' ').replace('\r', ' ')
            words.extend([w for w in text_.split(' ') if len(w) > 0])

        return bboxes, words


import csv
from nltk import FreqDist, bigrams
from nltk.corpus import stopwords
import os
import pprint
import re
import string

# from
# www.datasciencebytes.com/bytes/
# 2014/11/04/filter-common-words-from-documents/
stopword_list = stopwords.words('english')
stopword_set = set(stopword_list)

def clean_input(input):
    input = re.sub("\n+", " ", input)
    input = re.sub(' +', " ", input)
    clean_input = list()
    input = input.split(' ')
    for item in input:
        item = item.strip(string.punctuation)
        if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
            if item.lower() not in stopword_set:
                clean_input.append(item)
    return clean_input

def analyze_data(running_string):
    cleaned_input = clean_input(running_string)
    bigrams_output = bigrams(cleaned_input)
    bigrams_dist = FreqDist(bigrams_output)
    return bigrams_dist

def concat_csv():
    running_string = ""
    for fname in os.listdir():
        if 'csv' in fname:
            print("Found {0}".format(fname))
            with open(fname, newline='') as csvfile:
                rdr = csv.reader(csvfile, delimiter=',', quotechar='"')
                for row in rdr:
                    try:
                        print(row[2])
                        running_string += " {0}".format(row[2])
                    except:
                        pass
    return running_string

if __name__ == "__main__":
    ppp = pprint.PrettyPrinter()
    running_string = concat_csv()
    print("Running String Length: {0}".format(len(running_string)))
    bigrams_dist = analyze_data(running_string)
    ppp.pprint(bigrams_dist.most_common(20))


import os, shutil, time

# Empty a folder without deleting the folder itself.
def emptyFolder(folderPath):
    for root, dirs, files in os.walk(folderPath):
        for f in files:
            os.unlink(os.path.join(root, f)) # the EXACT same thing as os.remove :P
        for d in dirs:
            shutil.rmtree(os.path.join(root, d))

# File utilities
def getFilenameFromPath(path: str):
    name = os.path.basename(path)
    return name[0:name.index(".")]

def offerToDeleteAllInSensitiveDirectory(pathToSensitiveDirectory: str):
    if len(os.listdir(pathToSensitiveDirectory)) > 0:
        if input("Files exist in " + pathToSensitiveDirectory + " currently, remove them? (y/n): ")[0] == "y":
            print("5 seconds to change your mind...")
            time.sleep(5)
            emptyFolder(pathToSensitiveDirectory)


class Heap(object):
    """
    Une heap est une structure de données sous forme d'arbre.

    https://en.wikipedia.org/wiki/Heap_(data_structure)
    """

    def insert(self, value: int) -> None:
        """
        Ajoute une valeur dans l'arbre
        """
        pass

    def find_min(self) -> int:
        """
        Retourne la valeur minimum dans l'arbre
        """
        pass

    def delete_min(self) -> int:
        """
        Supprime et retourne la valeur minimum dans l'arbre
        """
        pass

    def decrease_key(self, current_value: int, new_value: int) -> None:
        """
        Modify une valeur dans l'arbre
        """
        pass

    def merge(self, fibonnaci_heap: object) -> None:
        """
        Fusionne deux arbres
        """
        pass

class FibonacciHeap():
    class Node:
        def __init__(self, value):
            self.value = value
            self.parent = None
            self.child = None
            self.left = None
            self.right = None
            self.deg = 0
            self.mark = False

    root_list = None
    min_node = None
    total_num_elements = 0

    def insert(self, value: int) -> None:
        if (not isinstance(value, int)):
            raise ValueError('La valeur doit être un int !')
        node = self.Node(value)
        node.left = node.right = node
        self.meld_into_root_list(node)
        if self.min_node is not None:
            if self.min_node.value > node.value:
                self.min_node = node
        else:
            self.min_node = node
        self.total_num_elements += 1
        pass

    def meld_into_root_list(self, node):
        if self.root_list is None:
            self.root_list = node
        else:
            node.right = self.root_list.right
            node.left = self.root_list
            self.root_list.right.left = node
            self.root_list.right = node
        pass

    def remove_from_root_list(self, node):
        if self.root_list is None:
            raise ValueError(
                'Fibonacci heap vide, impossible de supprimer un noeud !')
        if self.root_list == node:
            if self.root_list == self.root_list.right:
                self.root_list = None
                return
            else:
                self.root_list = node.right
        node.left.right = node.right
        node.right.left = node.left
        return

    def find_min(self) -> int:
        if self.min_node is None:
            raise ValueError("Fibonacci heap vide, pas de minimum !")
        return self.min_node.value

    def iterate(self, head=None):
        if head is None:
            head = self.root_list
        current = head
        while True:
            yield current
            if current is None:
                break
            current = current.right
            if current == head:
                break

    def delete_min(self) -> int:
        m = self.min_node
        if m is None:
            raise ValueError(
                'Fibonacci heap vide, impossible d\'extraire le minimum !')
        if m.child is not None:
            children = [x for x in self.iterate(m.child)]
            for i in range(0, len(children)):
                self.meld_into_root_list(children[i])
                children[i].parent = None
        self.remove_from_root_list(m)
        self.total_num_elements -= 1
        self.consolidate()
        if m == m.right:
            self.min_node = None
            self.root_list = None
        else:
            self.min_node = self.find_min_node()
        return m.value

    def consolidate(self):
        if self.root_list is None:
            return
        ranks_mapping = [None] * self.total_num_elements
        nodes = [x for x in self.iterate(self.root_list)]
        for node in nodes:
            degree = node.deg
            while ranks_mapping[degree] != None:
                other = ranks_mapping[degree]
                if node.value > other.value:
                    node, other = other, node
                self.merge_nodes(node, other)
                ranks_mapping[degree] = None
                degree += 1
            ranks_mapping[degree] = node
        return

    def merge_nodes(self, node, other):
        self.remove_from_root_list(other)
        other.left = other.right = other
        self.merge_with_child_list(node, other)
        node.deg += 1
        other.parent = node
        other.mark = False
        return

    def merge_with_child_list(self, parent, node):
        if parent.child is None:
            parent.child = node
        else:
            node.right = parent.child.right
            node.left = parent.child
            parent.child.right.left = node
            parent.child.right = node

    def find_min_node(self):
        if self.root_list is None:
            return None
        else:
            min = self.root_list
            for x in self.iterate(self.root_list):
                if x.value < min.value:
                    min = x
            return min

    def merge(self, fibonnaci_heap: Heap) -> None:
        if fibonnaci_heap.total_num_elements == 0:
            return
        if fibonnaci_heap.min_node.value < self.min_node.value:
            self.min_node = fibonnaci_heap.min_node
        self.total_num_elements += fibonnaci_heap.total_num_elements
        last = fibonnaci_heap.root_list.left
        fibonnaci_heap.root_list.left = self.root_list.left
        self.root_list.left.right = fibonnaci_heap.root_list
        self.root_list.left = last
        self.root_list.left.right = self.root_list
        pass

    def print(self, head=None):
        if self.root_list is not None:
            for heap in self.iterate():
                print('---')
                self.print_tree(heap)
                print()
            print('---')

    def print_tree(self, node):
        if node is None:
            return
        print(node.value, end=' ')
        if node.child is not None:
            print()
            for child in self.iterate(node.child):
                self.print_tree(child)

# Test de l'algorithme

print("Création de l'arbre...\n")
f = FibonacciHeap()

print("Insertion d'éléments dans l'arbre...\n")
f.insert(2)
f.insert(3)
f.insert(7)
f.insert(12)
f.insert(19)
f.insert(4)
f.insert(5)
f.insert(1)
print("Fait.\n")

print("Affichage de l'arbre...\n")
f.print()

print("\nLa plus petite valeur est : \n")
print(f.find_min())

print("\nSuppression de la plus petite valeur : \n")
print(f.delete_min())
print("\nFait !\n")

print("Affichage de l'arbre...\n")
f.print()

print("\nLa plus petite valeur est : \n")
print(f.find_min())

f2 = FibonacciHeap()
f2.insert(60)
f2.insert(32)

print("\nCréation de l'arbre numéro deux: \n")
f2.print()

print("\nMerge :\n")
f.merge(f2)
f.print()


import torch.nn.functional as F
import torch
import torch.nn as nn
from torch.autograd import Variable
from prediction.att_embeddings import Embeddings
from prediction.LSTM_module import LSTM_module

# choose device
USE_CUDA = torch.cuda.is_available()
if not USE_CUDA:
    DEVICE = torch.device('cpu')
else:
    DEVICE = torch.device('cuda:0')

class LSTM(nn.Module):
    def __init__(self, att_size, step_size, fea_size, pred_size=1):
        super(LSTM, self).__init__()

        self.att_size = att_size

        self.embedding = Embeddings([att_size, 100, 100, 50, 20, 10], step_size, fea_size, att_size) # output feature size is 10

        self.lstm = LSTM_module(fea_size, fea_size, fea_size) # output feature size is 1

        self.fc = nn.Linear(11, pred_size)

    def forward(self, atts, cases):
        atts = self.embedding(atts)
        cases, _ = self.lstm.loop(cases)
        cases = cases.unsqueeze(2)
        # print('merge',atts.size(), cases.size())
        outputs = self.fc(torch.cat([atts, cases], dim=2))
        return outputs.transpose(1, 2) # batch size * pred_size * n_cnt


#!/usr/bin/env python

from sys import stdin

index = {}

for line in stdin:

        row = line.rstrip('\n').split()

        neighbor = row[1].split(',')

        index[row[0]] = [neighbor,float(row[2])]

output = {}
for doc_id in index:
	size = len(index[doc_id][0])

	for doc in index[doc_id][0]:
		if doc in output:
			output[doc] += index[doc_id][1]/size
		else:
			output[doc] = index[doc_id][1]/size

for doc_id in output:
	output[doc_id] = output[doc_id]*0.85 +0.15

for doc_id in index:
	if doc_id in output:
		index[doc_id][1] = output[doc_id]

for doc_id in index:
	postings = ','.join(index[doc_id][0])
	print ('%s\t%s\t%s' % (doc_id, postings, index[doc_id][1]))


#!/usr/bin/env python

import copy
input_file = "input.txt"

def adj(mapData, x,y):
    ret = []
    for xx in range(x-1, x+2):
        for yy in range(y-1, y+2):

            if xx >= 0 and xx < len(mapData[0]):
                if yy >= 0 and yy < len(mapData):
                    if not (xx==x and yy==y):
                        ret.append(mapData[yy][xx])
    return ret

def countThings(x,y,mapData):
    t = 0
    l = 0
    o = 0
    for a in adj(mapData, x,y):
        if a == '#':
            l += 1
        elif a == '.':
            o += 1
        elif a == '|':
            t += 1
    return (t,l,o)

def printMap(mapData):
    for l in mapData:
        print( "".join(l) )
    print("")
input = list(map( lambda x: x.strip(), open(input_file).readlines() ))
mapData = []
for line in input:
    mapData.append( list(line) )

printMap(mapData)

last = 0
for m in range(0,1000000000):
    newData = copy.deepcopy(mapData)
    for x in range(0, len(mapData[0])):
        for y in range(0, len(mapData)):
            (t,l,o) = countThings(x,y, mapData)

            if mapData[y][x] == '.' and t >= 3:
                newData[y][x] = '|'

            if mapData[y][x] == '|' and l >= 3:
                newData[y][x] = '#'

            if mapData[y][x] == '#' and l >= 1 and t >=1:
                newData[y][x] = '#'

            if mapData[y][x] == '#' and not (l >=1 and t >=1):
                newData[y][x] = '.'

    if m % 1000 == 0:
        #print(1000000000 - m)
        t = 0
        l = 0
        o = 0
        for i in mapData:
            for j in i:
                if j == '#':
                    l +=1
                elif j == '.':
                    o += 1
                elif j == '|':
                    t +=1
        print("tree:{} lumberyard:{} openspace:{} :: {} ".format(t,l,o,m))
        #zoo = t * l
        #print(zoo, zoo - last)
        #print()
        #last = zoo

    mapData = copy.deepcopy(newData)

printMap(newData)

t = 0
l = 0
o = 0
for i in mapData:
    for j in i:
        if j == '#':
            l +=1
        elif j == '.':
            o += 1
        elif j == '|':
            t +=1

print("tree:{} lumberyard:{} openspace:{}".format(t,l,o))

print(t*l)


#coding:utf8

r"""modify xml file in required format no matter where you place your images
Example usage:
    python gen_trainval.py \
        --xmls_dir=/home/user/project/annotations/xmls

Then you can just delete your old xmls folder and use output xmls folder instead
"""

import os
import tensorflow as tf

flags = tf.app.flags
flags.DEFINE_string('xmls_dir', '', 'Your own dataset\'s xmls dir inside annotation folder')

FLAGS = flags.FLAGS

def gen_train_val():
    path = FLAGS.xmls_dir
    path_split = os.path.split(path)
    annotation_path = path_split[len(path_split)-1]
    file_list = os.listdir(path)
    fo = open(os.path.join(annotation_path, "trainval.txt"), "w")

    for files in file_list:
        file_name = os.path.splitext(files)[0]
        file_type = os.path.splitext(files)[1]
        if file_type == ".xml":
            fo.write(file_name + "\n")

    fo.close()

def main():
    gen_train_val()

if __name__ == "__main__":
    main()


import matplotlib.pyplot as plot

def single_plot(time, fx):
    plot.plot(time, fx, color='purple')

    plot.title('Wave')
    plot.xlabel('Time')
    plot.ylabel('Amplitude')

    plot.grid(True, which='both')
    plot.axhline(y=0, color='k')

    plot.show()

def dual_plot(time, fx1, fx2):
    plot.plot(time, fx1, color='purple')
    plot.plot(time, fx2, color='blue')

    plot.title('Wave')
    plot.xlabel('Time')
    plot.ylabel('Amplitude')

    plot.grid(True, which='both')
    plot.axhline(y=0, color='k')

    plot.show()


import re

from retriever_base import Wlppr, RetrieverBase

class RandomWallbaseRetriever(RetrieverBase):
    """
        Classe permettant de récupérer un fond d'écran aléatoire via le
        site wallbase.cc
    """

    WALLBASE_URL = 'http://wallbase.cc/random'

    WALL_PAGE_REGEX = '.*'
    TITLE_REGEX = '<title>(.*)</title>'
    TITLE_DATA_REGEX = '(.+) \- Wallpaper \(#(\d+)\) / Wallbase\.cc'
    DL_LINK_REGEX = '
.*.*
'

    def retrieve(self):
        """
            Récupère un fond d'écran aléatoire
        """

        self._reInit()

        page_content = RetrieverBase.urlGetContents(self.WALLBASE_URL)

        # récupération de l'url de la page du wall
        try:
            url_wall_page = re.compile(self.WALL_PAGE_REGEX).findall(page_content)[0]
        except IndexError:
            return

        # exploration de la page du wall pour trouver les infos intéressantes ...
        wall_page = RetrieverBase.urlGetContents(url_wall_page)

        try:
            data_title = re.compile(self.TITLE_REGEX).findall(wall_page)[0]
        except IndexError:
            data_title = ''

        no, title = self.parseTitle(data_title)

        # recherche du lien de téléchargement et de la taille du wall
        try:
            link, size_data = re.compile(self.DL_LINK_REGEX, re.DOTALL).findall(wall_page)[0]

            size = size_data.split('/')[1].strip('Wallpaper').strip()
        except IndexError:
            return

        self.wlpprs.append(Wlppr(no, title, { size: link }))

    def parseTitle(self, data_title):
        """
            Récupère le numéro et le titre d'un fond d'écran
            NB : les titres sont de la forme "Apple Inc. mac think  - Wallpaper (#72648) / Wallbase.cc"
        """

        try:
            title, no = re.compile(self.TITLE_DATA_REGEX).findall(data_title)[0]
        except IndexError:
            no, title = -1, 'Titre inconnu'

        return (int(no), title.strip())