import abc
import json
import typing

if typing.TYPE_CHECKING:
    from .typing import JSONDict

class DelayedStr(abc.ABC):
    """
    Abstract class that defines a string which computation can be delayed.

    The main interest of it is to postpone heavy processing,
    so that if ever useless, it is not executed at all.
    """

    def __init__(self):  # type: (...) -> None
        """
        Initializes the string computation result cache.
        """
        #: Cached string computation result.
        self.__str = None  # type: typing.Optional[str]

    def __repr__(self):  # type: (...) -> str
        """
        Canonical string representation.

        This method may be useless.
        Whatever, let's return the canonical representation of the string defined by this object.
        """
        return repr(str(self))

    def __str__(self):  # type: (...) -> str
        """
        Triggers the string computation on the first call, and cache it for later calls.
        """
        if self.__str is None:
            self.__str = self._computestr()
        return self.__str

    @abc.abstractmethod
    def _computestr(self):  # type: (...) -> str
        """
        String computation handler.

        :return:
            String computed for the object.

            Will be cached by :meth:`__str__()`.
        """
        raise NotImplementedError("Not implemented")

class FmtAndArgs(DelayedStr):
    """
    Makes it possible to prepare a string format with its corresponding arguments,
    as usual with the ``%`` operator,
    and have it computed if needed.
    """

    def __init__(
            self,
            fmt="",  # type: str
            *args  # type: typing.Any
    ):  # type: (...) -> None
        """
        Prepares the string format and arguments, possibly with initial values.

        :param fmt: Inital string format.
        :param args: Initial string arguments.
        """
        DelayedStr.__init__(self)

        #: String format.
        self.fmt = fmt  # type: str
        #: Format arguments.
        self.args = list(args)  # type: typing.List[typing.Any]

    def push(
            self,
            fmt,  # type: str
            *args  # type: typing.Any
    ):  # type: (...) -> FmtAndArgs
        """
        Pushes additional format and arguments.

        Makes it possible to prepare the string step by step, and/or conditionally.

        :param fmt: String format to appens.
        :param args: Corresponding arguments.
        :return: ``self``
        """
        self.fmt += fmt
        self.args.extend(args)
        return self

    def _computestr(self):  # type: (...) -> str
        return self.fmt % tuple(self.args)

class SafeRepr(DelayedStr):
    """
    Delays the computation of the safe canonical representation of an object.

    Same as ``unittest``, safe representation means that the string computed while not exceed a given length,
    so that it remains human readable.
    """

    def __init__(
            self,
            obj,  # type: typing.Any
            max_length=256,  # type: int
            focus=None,  # type: typing.Any
    ):  # type: (...) -> None
        """
        Stores the object reference for later safe representation computation.

        :param obj: Object to represent.
        :param max_length: Maximum length for the resulting string.
        :param focus: Data to focus on.
        """
        DelayedStr.__init__(self)

        #: Object to represent.
        self.obj = obj  # type: typing.Any
        #: Maximum length for the resulting string.
        self.max_length = max_length  # type: int
        #: Data to focus on.
        self.focus = focus  # type: typing.Any

    def _computestr(self):  # type: (...) -> str
        # ``focus`` parameter is set.
        if (self.focus is (str, bytes)) and isinstance(self.obj, type(self.focus)):
            _start = 0  # type: int
            _end = len(self.obj)  # type: int
            if len(self.obj) > self.max_length:
                _start = self.obj.find(self.focus)
                _start -= 10
                if _start < 0:
                    _start = 0
                _end = _start + self.max_length
                if _end > len(self.obj):
                    _start -= (_end - len(self.obj))
                    _end = len(self.obj)
            _anystr = type(self.obj)()  # type: typing.Union[str, bytes]
            if _start > 0:
                if isinstance(_anystr, str):
                    _anystr += "...[truncated] "
                if isinstance(_anystr, bytes):
                    _anystr += b'...[truncated] '
            _anystr += self.obj[_start:_end]
            if _end < len(self.obj):
                if isinstance(_anystr, str):
                    _anystr += " [truncated]..."
                if isinstance(_anystr, bytes):
                    _anystr += b' [truncated]...'
            return repr(_anystr)

        # ``focus`` parameter not set.
        # noinspection PyBroadException
        try:
            _repr = repr(self.obj)
        except Exception:
            _repr = object.__repr__(self.obj)
        if len(_repr) <= self.max_length:
            return _repr
        return _repr[:self.max_length] + " [truncated]..." + _repr[-1:]

def saferepr(
        obj,  # type: typing.Any
        max_length=256,  # type: int
        focus=None,  # type: typing.Any
):  # type: (...) -> SafeRepr
    """
    Safe representation of an object.

    :param obj: Object to represent.
    :param max_length: Maximum length for the resulting string.
    :param focus: Data to focus on.
    :return: :class:`SafeRepr` delayed computation object.
    """
    return SafeRepr(obj, max_length=max_length, focus=focus)

class JsonDump(DelayedStr):
    """
    Delays the dump of JSON data.
    """

    def __init__(
            self,
            json_data,  # type: JSONDict
            **kwargs,  # type: typing.Any
    ):  # type: (...) -> None
        """
        Stores the JSON data for later dump.

        :param json_data: JSON data to dump.
        :param kwargs: :func:`json.dumps()`-like arguments.
        """
        DelayedStr.__init__(self)

        #: JSON data to dump.
        self.json_data = json_data  # type: JSONDict
        #: :func:`json.dumps()`-like arguments.
        self.kwargs = kwargs  # type: typing.Dict[str, typing.Any]

    def _computestr(self):  # type: (...) -> str
        return json.dumps(self.json_data, **self.kwargs)

def jsondump(
        json_data,  # type: JSONDict
        **kwargs,  # type: typing.Any
):  # type: (...) -> JsonDump
    """
    Dump of JSON data.

    :param json_data: JSON data to dump.
    :param kwargs: :func:`json.dumps()`-like arguments.
    :return: :class:`JsonDump` delayed computation object.
    """
    return JsonDump(json_data, **kwargs)

class CallbackStr(DelayedStr):
    """
    String builder callback manager.
    """

    def __init__(
            self,
            callback,  # type: typing.Callable[..., str]  # noqa  ## Shadows name 'callback' from outer scope.
            *args,  # type: typing.Any
            **kwargs,  # type: typing.Any
    ):  # type: (...) -> None
        """
        Stores the callback with its arguments for later execution.

        :param callback: String builder callback.
        :param args: Callback positional arguments.
        :param kwargs: Callback named arguments.
        """
        DelayedStr.__init__(self)

        #: String builder callback.
        self.callback = callback  # type: typing.Callable[..., str]
        #: Callback positional arguments.
        self.args = args  # type: typing.Tuple[typing.Any, ...]
        #: Callback named arguments.
        self.kwargs = kwargs  # type: typing.Dict[str, typing.Any]

    def _computestr(self):  # type: (...) -> str
        return self.callback(*self.args, **self.kwargs)

def callback(
        callback,  # type: typing.Callable[..., str]  # noqa  ## Shadows name 'callback' from outer scope.
        *args,  # type: typing.Any
        **kwargs,  # type: typing.Any
):  # type: (...) -> CallbackStr
    """
    Stores a string builder callback with its arguments for later execution.

    :param callback: String builder callback.
    :param args: Callback positional arguments.
    :param kwargs: Callback named arguments.
    :return: :class:`CallbackStr` delayed computation object.
    """
    return CallbackStr(callback, *args, **kwargs)


import warnings

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

from keras.callbacks import History, Callback

def one_hot_encoding(labels,nb_labels = None):
    '''
    One-hot encoding of labels
    '''
    n = len(labels)

    if not nb_labels:
        nb_labels = labels.max() + 1
        if nb_labels != len(np.unique(labels)):
            warnings.warn('Bad numbering of labels. '+
                          'Or some labels are not present in dataset.\n'+
                          'Number of classes: '+str(nb_labels)+'.\n'
                          'Number of classes present: '+str(len(np.unique(labels)))+'.')

    y = np.zeros((n,nb_labels), dtype = bool)
    y[np.arange(n),labels.flatten()] = 1
    return y

def get_val_split(x,y,validation_split):
    '''
    Validation set creation
    validation_split is the portion of data used for validation (in [0,1])
    '''
    if validation_split == 0.:
        return [x,y], None
    elif validation_split >0. and validation_split <=1:
        index = np.random.permutation(x.shape[0])
        train_index = index[int(validation_split*x.shape[0]):]
        val_index =   index[:int(validation_split*x.shape[0])]
        return [x[train_index], y[train_index]], [x[val_index], y[val_index]]
    else:
        raise ValueError("The value given to validation_split is not between 0 and 1")

def lr_schedule(initial_lr,factor,epochs):
    '''
    utility for creating a learning rate schedule that drops the learning rate by some factor at the specified epochs
    epoch indices starts at 0
    '''
    def schedule(epoch):
        lr = initial_lr

        for i in range(len(epochs)):
            if epoch>= epochs[i]:
                lr *= factor
        return lr
    return schedule

colors = 'bgrcmykw'

def plot_history(history, metric_names = None, title = None, ignore_epochs = False, new_figure = True, val = True):
    """
    Plot the history returned by Keras' fit function

    metrics_names is a list containing the metrics/costs to be displayed
    If no metrics specified, model.metrics_names is used
    It uses one color per metric, dashed lines for validation set

    history is either a keras History object or a dictionary with keys 'epoch' and 'history'.
    """
    if isinstance(history,dict):
        epoch = history['epoch']
        history = history['history']
    elif isinstance(history, History):
        epoch = history.epoch
        history = history.history
    else:
        raise ValueError()

    if not metric_names:
        metric_names = [metric for metric in history.keys() if metric[:4] != 'val_']

    if ignore_epochs:
        epoch = range(len(history[metric_names[0]]))

    if new_figure:
        plt.figure()

    handles = [None]*len(metric_names)
    for i,metric in enumerate(metric_names):
        handles[i], = plt.plot(epoch,history[metric], '-'+colors[i],label = metric)
        if val and 'val_'+metric in history.keys():
            plt.plot(epoch,history['val_'+metric],'--'+colors[i])

    plt.legend(handles = handles)
    plt.xlabel('epoch')

    if title:
        plt.title(title)

def compare_histories(histories, metric_name, names, val = False, title = None):
    """
    Plots evolution of metric_name on training and eventually validation set for
    the histories in histories list.

    It uses one color per history, dashed lines for validation set
    A legend is added with names associated with histories

    A history is either a keras History object or a dictionary with keys 'epoch' and 'history'.
    """
    for i,history in enumerate(histories):
        if isinstance(history, History):
            histories[i] = history_todict(history)

    plt.figure()

    handles = [None]*len(histories)
    for i,history in enumerate(histories):
        handles[i], = plt.plot(history['epoch'],history['history'][metric_name],
                               '-'+colors[i],label = names[i])
        if val:
            plt.plot(history['epoch'],history['history']['val_'+metric_name],'--'+colors[i])

    plt.legend(handles = handles)
    plt.xlabel('epoch')
    if metric_name[-3:] == 'acc':
        plt.ylabel('accuracy')
    else:
        plt.ylabel(metric_name)

    if title:
        plt.title(title)

def history_todict(history):
    """
    returns python dictionary containing keras history object content.
    Easier to handle for pickle
    """
    if hasattr(history,'epoch'):
        return {'epoch' : history.epoch,'history' : history.history}
    elif hasattr(history,'batch'):
        return {'batch' : history.batch,'history' : history.history}

class History_batch(Callback):
    """Callback that records events into a `History` object.
    This callback is automatically applied to
    every Keras model. The `History` object
    gets returned by the `fit` method of models.

    recordings are made after every batch
    """

    def on_train_begin(self, logs=None):
        self.batch = []
        self.history = {}

    def on_batch_end(self, batch, logs=None):
        logs = logs or {}
        self.batch.append(batch)
        for k, v in logs.items():
            self.history.setdefault(k, []).append(v)


import time
import math
import inspect

def timeit(func):
    def timed(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print("Time Usage: %.3fs" % (end - start))
        return result

    return timed

@timeit
def primes(n):
    """ Returns  a list of primes < n """
    sieve = [True] * n
    for i in range(3, int(n ** 0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

for i in range(1, 4):
    print("There are %d primes within %d" % (len((primes(10 ** i))), 10 ** i))

# The syntax for decorators with arguments is a bit different - the decorator
# with arguments should return a function that will take a function and return
# another function. So it should really return a normal decorator.

def repeating(repeat):
    def decorator(func):
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            for _ in range(repeat):
                print(
                    "The answer of %s is"
                    % (func.__name__ + str(inspect.signature(func))),
                    result,
                )
            return result

        return wrapper

    return decorator

@repeating(5)
def pow(x, n):
    return x ** n

pow(4, 4)


# -*- coding: UTF-8 -*-
#!/usr/bin/env python3
import json
from pprint import pprint

def main():
    # In python dicts are analogous to json as they are the only mapping types
    some_dict = {
                    "String_key": "String_value",
                    1: [1, 2, 3, 4],
                    1.2: {
                        "some_nested_json_key": "some_nested_json_values"
                    }
                }
    dumped_json = json.dumps(some_dict)
    # Dumping JSON means converting it into the string format
    print('The Dumped JSON is')
    print(dumped_json)
    loaded_json = json.loads(dumped_json)
    print('The Loaded JSON is')
    pprint(loaded_json)
    # We can access key values in this loaded_json as we do normally in dicts

if __name__ == "__main__":
    main()


#!/bin/python3

import sys

def solve(year):
    # Complete this function
    if year >= 1700 and year <= 1917:
        if year%4 == 0:
            date = "12.09."+str(year)
        else:
            date = "13.09."+str(year)
    elif year == 1918:
        date = "26.09."+str(year)   #13 days later than usual
    elif year <= 2700:
        if year%400 == 0 or (year%4 == 0 and year%100 != 0):
            date = "12.09."+str(year)
        else:
            date = "13.09."+str(year)

    return(date)
year = int(input().strip())
result = solve(year)
print(result)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('pillbox', '0015_auto_20141217_1013'),
    ]

    operations = [
        migrations.AlterField(
            model_name='export',
            name='file_type',
            field=models.CharField(max_length=200, verbose_name=b'File Type', choices=[(b'json', b'JSON'), (b'csv', b'CSV'), (b'yaml', b'YAML'), (b'xml', b'XML')]),
            preserve_default=True,
        ),
    ]


import base64
import json
import os
import shutil
from pathlib import Path
from logging import getLogger

logger = getLogger(__name__)

class Utils:
    def __init__(self):
        self._temp_dir = "/tmp/data/"
        self._required_required_content_type = "application/pdf"
        self._required_input_extention = "pdf"
        self._required_output_extention = "tif"

    def json_parse(self, json_string):
        if isinstance(json_string, str):
            return json.loads(json_string)
        return json_string

    def get_content_type_from_header(self, headers):
        if headers.get("Content-Type"):
            return headers.get("Content-Type")
        elif headers.get("content-type"):
            return headers.get("content-type")

    def get_input_filename_from_header(self, headers):
        if headers.get("InputFileName"):
            return headers.get("InputFileName")
        elif headers.get("inputfilename"):
            return headers.get("inputfilename")

    def get_output_file_extention_from_header(self, headers):
        if headers.get("OutputFileExtention"):
            return headers.get("OutputFileExtention")
        elif headers.get("outputfileextention"):
            return headers.get("outputfileextention")

    def validate_content_type(self, content_type):
        if content_type != self._required_required_content_type:
            message = f"Content-Type is not {self._required_required_content_type}"
            logger.warning(message)
            raise LambdaRuntimeException(400, message)
        logger.info(f"Content-Type is {content_type}")

    def validate_input_filename(self, input_filename):
        if "\\" in input_filename or "/" in input_filename:
            message = "Invalid request parameter"
            logger.warning(message)
            raise LambdaRuntimeException(400, message)
        logger.info(f"Input filename is {input_filename}")

    def validate_input_file_extention(self, input_filename):
        extention = Path(input_filename).suffix
        if extention != f".{self._required_input_extention}":
            message = f"Input file extention is not {self._required_input_extention}"
            logger.warning(message)
            raise LambdaRuntimeException(400, message)
        logger.info(f"Input file extention is {extention}")

    def validate_output_file_extention(self, output_extention):
        if output_extention != self._required_output_extention:
            message = f"Output file extention is not {self._required_output_extention}"
            logger.warning(message)
            raise LambdaRuntimeException(400, message)
        logger.info(f"Output file extention is {output_extention}")

    def make_temp_dir(self):
        if os.path.exists(self._temp_dir):
            shutil.rmtree(self._temp_dir)
        os.makedirs(self._temp_dir)
        logger.info(f"Make directory {self._temp_dir}")

    def save_input_file(self, input_filename, input_file):
        save_file_path = f"{self._temp_dir}{input_filename}"
        with open(save_file_path, "wb") as f:
            f.write(base64.b64decode(input_file.encode("utf8")))
        logger.info(f"Save input file {save_file_path}")
        return save_file_path

    def change_extention(self, input_file_path, extention="tif"):
        output_file_path = Path(input_file_path).with_suffix(f".{extention}")
        logger.info(f"Output file path is {output_file_path}")
        return str(output_file_path)

    def success_response(self, output_file, code=200, content_type="application/pdf", encode=True):
        response = {
            "statusCode": code,
            "headers": {
                "content-type": content_type
            },
            "isBase64Encoded": encode,
            "body": base64.b64encode(output_file)
        }
        return response

class LambdaRuntimeException(Exception):
    def __init__(self, code, messages, content_type="application/json"):
        self._code = code
        self._messages = messages
        self._content_type = content_type

    def __str__(self):
        response = {
            "statusCode": self._code,
            "headers": {
                "Content-Type": self._content_type
            },
            "body": {
                "message": self._messages
            }
        }
        return json.dumps(response)


import mariadb
from os import path
import json
import src.config.globals as globals

CONEXCION_PATH = path.abspath('src/config/conexion.json')
SQL_PATH = path.abspath('Base_de_datos.sql')

def createDB():
    if path.exists(CONEXCION_PATH):
        file_conexion = open(CONEXCION_PATH, 'r')

        config = json.loads(file_conexion.read())

        globals.DB = mariadb.connect(**config)
        globals.DB.autocommit = True
    else:
        globals.DB = False


from django.urls import path
from .views import profile_page, all_profile_blogs, create_profile, update_profile, subscribe

urlpatterns = [
    path("create/",create_profile, name = "create-profile"),
    path("update/",update_profile, name = "update-profile"),
    path("<str:id>/",profile_page,name = "account"),
    path("<str:id>/subscribe/", subscribe, name = "subscribe"),
    path("<str:id>/blogs/", all_profile_blogs,name = "profile-blogs")
]


import nrekit
import tensorflow as tf
class APCNN:
    def __init__(self, data_loader, train_mode='Base', constraint_path=None, CL_rate=0.01, is_training=True):
        batch_size, max_length, word_embedding_dim = data_loader.batch_size, data_loader.max_length, data_loader.word_embedding_dim
        self.word = tf.placeholder(dtype=tf.int32, shape=[None, max_length], name='word')
        self.pos1 = tf.placeholder(dtype=tf.int32, shape=[None, max_length], name='pos1')
        self.pos2 = tf.placeholder(dtype=tf.int32, shape=[None, max_length], name='pos2')
        self.label = tf.placeholder(dtype=tf.int32, shape=[batch_size], name='label')
        self.ins_label = tf.placeholder(dtype=tf.int32, shape=[None], name='ins_label')
        self.length = tf.placeholder(dtype=tf.int32, shape=[None], name='length')
        self.scope = tf.placeholder(dtype=tf.int32, shape=[batch_size, 2], name='scope')
        # self.data_loader = data_loader
        self.rel_tot = data_loader.rel_tot
        self.word_vec_mat = data_loader.word_vec_mat
        self.mask = tf.placeholder(dtype=tf.int32, shape=[None, max_length], name="mask")
        # Embedding
        x = nrekit.network.embedding.word_position_embedding(self.word, self.word_vec_mat, self.pos1, self.pos2,
                                                             word_embedding_dim=word_embedding_dim, max_length=max_length)
        # Encoder
        x_train = nrekit.network.encoder.pcnn(x, self.mask, keep_prob=0.5)
        x_test = nrekit.network.encoder.pcnn(x, self.mask, keep_prob=1.0)
        # Selector
        self._train_logit, train_repre = nrekit.network.selector.bag_attention(x_train, self.scope, self.ins_label, self.rel_tot, True, keep_prob=0.5)
        self._test_logit, test_repre = nrekit.network.selector.bag_attention(x_test, self.scope, self.ins_label, self.rel_tot, False, keep_prob=1.0)
        self._test_logit = tf.add(self._test_logit, tf.constant(0.0), name='get_prob')
        if is_training:
            self.prob = tf.nn.softmax(self._train_logit, axis=-1)
            self.label_onehot = tf.one_hot(indices=self.label, depth=self.rel_tot, dtype=tf.int32)
            self._entropy_loss = nrekit.network.classifier.softmax_cross_entropy(self._train_logit, self.label, self.rel_tot)
            if train_mode == 'Base':
                self.constraint_loss = tf.constant(0.0)
            else:
                CLC = nrekit.network.ConstraintLoss.ConstraintLoss(batch_size, data_loader.rel_tot, data_loader.rel2id, constraint_path, CL_rate, self)
                if train_mode == 'Sem':
                    self.constraint_loss = CLC.Semantic()
                else:
                    self.constraint_loss = CLC.Coherent()
            # self.constraint_loss = nrekit.network.SL_loss.__constraint_loss__(self)

    def loss(self):
        self.total_loss = self._entropy_loss + self.constraint_loss
        return self.total_loss

    def train_logit(self):
        return self._train_logit

    def test_logit(self):
        return self._test_logit


import pygame as pg
import board
import sys

WIDTH = HEIGHT = 512
DIMENSION = 8
SQUARE_SIZE = WIDTH // DIMENSION
MAX_FPS = 15
IMAGES = {}
dark, light = pg.Color("light blue"), pg.Color("white")
positions = []

class Chess :

	def __init__(self):
		pg.init()
		self.screen = pg.display.set_mode((WIDTH,HEIGHT))
		pg.display.set_caption("Chess")
		self.clock = pg.time.Clock()

		self.gs = board.Board()

		#valid moves list
		self.valid_moves = self.gs.get_valid_moves()
		self.move_made = False # a move flag

		self._load_images() #load all images from the images file

		self.game_active = True #game state flag (active or not)

		self.square_selected = ()
		self.clicks, self.clicks_copy = [], []

		self.move_undoed = False

		#animation
		self.animate = False

		#Game Over
		self.game_over = False

	def run_game(self):
		while True :
			self._check_events()
			self._update_screen()

	def _check_events(self):
		for event in pg.event.get():
			if event.type == pg.QUIT:
				self.game_active == False
				sys.exit()
			elif event.type == pg.KEYDOWN:
				self._check_keydown_events(event)
			elif event.type == pg.MOUSEBUTTONDOWN:
				if not self.game_over:
					mouse_pos = pg.mouse.get_pos()
					i, j = mouse_pos[1] // SQUARE_SIZE, mouse_pos[0] // SQUARE_SIZE
					if self.square_selected == (i,j): #if we select again on the same square
						self.square_selected = ()
						self.clicks = []
					else:
						self.square_selected = (i,j)
						self.clicks.append(self.square_selected)

					if len(self.clicks) == 2:
						self.gs.update_enpassant_possible(self.clicks[0],self.clicks[1])
						if [self.clicks[0],self.clicks[1]] in self.valid_moves:
							#if the move is valid
							self.gs.move_piece(self.clicks[0], self.clicks[1])
							self.move_made = True
							self.clicks_copy = self.clicks
							self.animate = True
							self.square_selected = ()
							self.clicks = []
							self.move_undoed = False

						else:
							#if we select another piece
							self.clicks = [self.square_selected]

		if self.move_made: #if the move is made generate the next list of valid moves
			if self.animate:
				if self.clicks_copy[1] not in self.gs.checked_squares :
					self.animate_move(self.clicks_copy[0],self.clicks_copy[1],self.screen,self.gs.board,self.clock)
			self.animate = False
			self.valid_moves = self.gs.get_valid_moves()
			self.move_made = False

		if self.gs.checkmate:
			self.game_over = True
			if self.gs.white_turn:
				self.draw_text(self.screen, 'Black wins by checkmate')
			else:
				self.draw_text(self.screen, 'White wins by checkmate')
		elif self.gs.stalemate:
			self.game_over = True
			self.draw_text(self.screen, 'Stalemate')

	def _check_keydown_events(self,event):
		if event.key == pg.K_a:
			sys.exit()
		elif event.key == pg.K_u:
			if self.move_undoed == False :
				self.gs.undo_move()
				self.move_made = True
				self.move_undoed = True
				self.animate = False
		elif event.key == pg.K_r:
			self.gs = board.Board()
			self.valid_moves = self.gs.get_valid_moves()
			self.move_made = False
			self.square_selected = ()
			self.clicks, self.clicks_copy = [], []
			self.move_undoed = False
			self.animate = False
			self.game_over = False

	def _load_images(self):
		pieces = ['bRook', 'bKnight', 'bBishop', 'bQueen', 'bKing', 'bPawn',
					'wRook', 'wKnight', 'wBishop', 'wQueen', 'wKing', 'wPawn']
		for piece in pieces:
			IMAGES[piece] = pg.transform.scale(pg.image.load("images/" + piece + ".png"),(SQUARE_SIZE,SQUARE_SIZE))

	def _draw_screen(self,board,valid_moves,square_selected):
		self._draw_board(self.screen)
		self.highlight_square(board,valid_moves,square_selected)
		self._draw_pieces(self.gs.board)

	def _draw_board(self,screen):
		global colors
		colors = [light, dark]
		for i in range(DIMENSION):
			for j in range(DIMENSION):
				pg.draw.rect(screen, colors[(i+j)%2], pg.Rect(j*SQUARE_SIZE,
					i*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE))

	def _draw_pieces(self,board):
		for i in range(DIMENSION):
			for j in range(DIMENSION):
				piece = board[i][j]
				if piece != "0":
					image = IMAGES[piece]
					rect = image.get_rect()
					rect.x, rect.y = j*SQUARE_SIZE, i*SQUARE_SIZE
					rect.width, rect.height = SQUARE_SIZE, SQUARE_SIZE
					self.screen.blit(image,rect)

	def highlight_square(self,board,valid_moves,square_selected):
		if square_selected != ():
			i, j = square_selected
			if board[i][j][0] == ('w' if self.gs.white_turn else 'b'):
				surface = pg.Surface((SQUARE_SIZE, SQUARE_SIZE))
				red_surface = pg.Surface((SQUARE_SIZE, SQUARE_SIZE))
				surface.set_alpha(100)
				red_surface.set_alpha(100)
				surface.fill(pg.Color('orange'))
				red_surface.fill(pg.Color('red'))
				self.screen.blit(surface,(j*SQUARE_SIZE, i*SQUARE_SIZE))
				surface.fill(pg.Color('green'))
				king_i, king_j = self.gs.white_king_location if self.gs.white_turn else self.gs.black_king_location
				#self.gs.get_checked_squares(king_i,king_j,self.valid_moves)
				for move in valid_moves:
					if move[0] == square_selected:
						end_i, end_j = move[1]
						if (move[1] not in self.gs.checked_squares and self.gs.board[move[0][0]][move[0][1]][1:] == 'King') or self.gs.board[move[0][0]][move[0][1]][1:] != 'King' :
							self.screen.blit(surface, (end_j*SQUARE_SIZE, end_i*SQUARE_SIZE))
						elif move[1] in self.gs.checked_squares :
							self.screen.blit(red_surface, (end_j*SQUARE_SIZE, end_i*SQUARE_SIZE))

	def animate_move(self,start,end,screen,board,clock):
		#self._load_images()
		global colors
		start_i, start_j = start[0], start[1]
		end_i, end_j = end[0], end[1]
		#piece_moved = board[start_i][start_j]
		#piece_captured = board[end_i][end_j]
		di = end_i - start_i
		dj = end_j - start_j
		frames_per_second = 10
		frame_count = ( abs(di) + abs(dj) ) * frames_per_second
		for frame in range(frame_count + 1):
			r, c = start_i+di*frame/frame_count, start_j+dj*frame/frame_count
			self._draw_board(screen)
			self._draw_pieces(board)
			color = colors[(end_i+end_j) % 2]
			end_square = pg.Rect(end_j*SQUARE_SIZE,end_i*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE)
			pg.draw.rect(screen, color, end_square)
			if self.gs.piece_captured != '0':
				if self.gs.enpassant_move:
					screen.blit(IMAGES[self.gs.piece_captured], pg.Rect(end_j*SQUARE_SIZE,start_i*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE))
				else:
					screen.blit(IMAGES[self.gs.piece_captured], end_square)
			screen.blit(IMAGES[self.gs.piece_moved], pg.Rect(c*SQUARE_SIZE,r*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE))
			pg.display.flip()
			clock.tick(60)

	def draw_text(self,screen,text):
		font = pg.font.SysFont('ms serif.ttf',40,True,True)
		text_object = font.render(text,0,pg.Color('White'))
		text_location = pg.Rect(0,0,WIDTH,HEIGHT).move(WIDTH/2-text_object.get_width()/2,HEIGHT/2-text_object.get_height()/2)
		self.screen.blit(text_object,text_location)
		text_object = font.render(text,0,pg.Color('Red'))
		self.screen.blit(text_object,text_location.move(2,2))
		pg.display.flip()

	def _update_screen(self):
		self._draw_screen(self.gs.board,self.valid_moves,self.square_selected)
		self.clock.tick(MAX_FPS)
		pg.display.flip()

if __name__ == '__main__':
	chess = Chess()
	chess.run_game()


def inputInt(mensaje):
    validado = False
    while not validado:
        numero = input(mensaje)
        try:
            numero = int(numero)
            validado = True
        except:
            print("Error. Debe ingresar un número entero")
    return numero

def inputFloat(mensaje):
    validado = False
    while not validado:
        numero = input(mensaje)
        try:
            numero = float(numero)
            validado = True
        except:
            print("Error. Debe ingresar un número real")
    return numero

if __name__ == "__main__":
    a = inputInt('Ingrese un entero: ')
    print('El número entero ingresado es', a)
    b = inputFloat('Ingrese un real: ')
    print('El número real ingresado es', b)


#!/usr/bin/env python3

import sys, os, traceback, imp

import irc.client
import irc.events

from module import Module
from wrapper import Wrapper
import config
import util

class Face(irc.client.SimpleIRCClient):
    def __init__(self):
        irc.client.SimpleIRCClient.__init__(self)
        sys.path.append(config.modules_dir)

    # Where it all begins. Load modules, and connect.
    def go(self):
        self.load_modules()

        try:
            print("Connecting to {0} on port {1}".format(config.server, config.port))
            self.connect(config.server, config.port, config.nickname)
        except irc.client.ServerConnectionError as x:
            print(x)
            sys.exit(1)

        for event in irc.events.all:
            # 0 = highest priority
            self.connection.add_global_handler(event, self.global_handler, 0)

        try:
            self.start()
        except KeyboardInterrupt:
            self.connection.close()

    # This global handler receives all events and dispatches them to the
    # relevant modules.
    def global_handler(self, connection, event):
        p = Wrapper(self, connection, event, config, util)

        event_handled = False

        # tell all modules that this event has fired
        for module in self.modules:
            # a module returning True means it declares it's handled the
            # event and no further events should be handled (aside from
            # the global handler)
            event_handled = module.handle_event(event_handled, p)

    # Reload our own config, our modules, and ensure config changes are applied.
    def reload(self):
        # reload all the things
        imp.reload(config)
        imp.reload(util)
        self.load_modules()

        # if the nickname in the config file has changed then change our
        # nickname on IRC as well
        if self.connection.get_nickname() != config.nickname:
            self.connection.nick(config.nickname)

    # Loop through all modules, reload any existing ones and freshly load
    # any we haven't seen before.
    def load_modules(self):
        # load the filenames of all modules that exist in the modules directory
        module_filenames = [ f for f in os.listdir(config.modules_dir) if f.endswith(".py") and f != '__init__.py' ]

        print("Searching for modules")

        # create the modules list if not already set
        if not hasattr(self, "modules"):
            self.modules = []

        # reload any loaded modules rather than loading them from scratch
        if len(self.modules) > 0:
            for module in self.modules:
                # if it exists in the filenames list above, remove it as we
                # don't want to to load it again
                if module.filename in module_filenames:
                    module_filenames.remove(module.filename)

                # load it instead
                module.reload()

        # load all remaining unloaded modules
        for module_filename in module_filenames:
            self.modules.append(Module(module_filename))

    # Called when first connecting to the server. Join any channels we're
    # configured to join.
    def on_welcome(self, connection, event):
        print("> {0}".format(event.arguments[0]))

        for channel in config.channels:
            print("Joining {0}".format(channel))
            connection.join(channel)

    # Called when getting disconnected.
    def on_disconnect(self, connection, event):
        # TODO reconnect instead
        sys.exit(0)

def main():
    print("Starting up {0}".format(config.nickname))
    face = Face();
    face.go();

if __name__ == "__main__":
    main()


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

"""
here is the movement class or we define an image that we will move from the txt file.
"""

import pygame #Import pygame module.

from labyrinth_class import* #Import labyrinth_class class.

class Movement:
    """Here we call get_rect() fonction for moving picture hero,
    thank to labyrinth_class we generate structure with place
    where he can moves or not"""

    def __init__(self, file): #Creating constructor.
        self.file = file

        self.structure = []

    def position(self, image):
        """  Definition of positon method with initialization of picture. """

        self.image = image
        self.perso = pygame.image.load(self.image)

        #We put picture into a rectangle for move it.
        self.position = self.perso.get_rect()

        #This variable will go into list, and we will add to it for see if it's possible to move.
        self.x = 0

    def importation_file(self):
        """ Importation of the list from labyrinth class. """

        Labyrinth.generate(self)

    def positive_deplacement(self, nombre_case, deplacement_x, deplacement_y):

        self.nombre_case = nombre_case
        self.deplacement_x = deplacement_x
        self.deplacement_y = deplacement_y

        if self.structure[self.x + self.nombre_case][1] != "1":
            self.x += self.nombre_case
            self.position = self.position.move(deplacement_x, deplacement_y)

        elif self.structure[self.x + self.nombre_case][1] == "1":
            self.x += 0

    def negative_deplacement(self, nombre_case, deplacement_x, deplacement_y ):
        """ Definition of left movement. """

        self.nombre_case = nombre_case
        self.deplacement_x = deplacement_x
        self.deplacement_y = deplacement_y

        if self.structure[self.x - self.nombre_case][1] != "1":
            self.x -= self.nombre_case
            self.position = self.position.move(deplacement_x, deplacement_y)

        elif self.structure[self.x - self.nombre_case][1] == "1":
            self.x -= 0

    def display(self, window):
        """ Display picture to window. """

        window.blit(self.perso, self.position)
        pygame.display.flip()


def leer_numero():
    return input("Introduce un numero: ")
def suma_digitos(a):
    suma=0
    for e in a:
        suma+=int(e)
    if suma%2==0:
        print("La suma de los digitos de {} es {} y es par".format(a,suma))
    else:
        print("La suma de los digitos de {} es {} y es impar".format(a,suma))

#PP
a=leer_numero()
suma_digitos(a)


#!/usr/bin/env python

import itertools
import os
import logging
import shutil
import subprocess
import sys
import tempfile

import pandas
import requests
from Bio import SeqIO

from cref.app import BaseApp

logger = logging.getLogger('CReF')

class TerminalApp(BaseApp):
    """
    App to be run on the terminal
    """

    def reporter(self, state):
        pass

def run_cref(aa_sequence, output_dir, params):
    pandas.set_option('display.max_columns', 0)
    pandas.set_option('display.max_rows', 5)

    if not os.path.isdir(output_dir):
        os.makedirs(output_dir)

    app = TerminalApp(params)
    return app.run(aa_sequence, output_dir)

def configure_logger(log_level='INFO', include_pathname=False):
    logger = logging.getLogger('CReF')
    level = getattr(logging, log_level.upper(), None)
    if not isinstance(level, int):
        raise ValueError('Invalid log level: %s' % log_level)

    logger.propagate = False
    logger = logging.getLogger('CReF')
    logger.setLevel(level)

    ch = logging.StreamHandler()
    ch.setLevel(level)
    if include_pathname:
        template = ('%(asctime)s - %(name)s - %(levelname)s'
                    '(%(pathname)s, %(lineno)d)- %(message)s')
    else:
        template = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

    formatter = logging.Formatter(template, datefmt='%d/%m/%Y %I:%M:%S %p')
    ch.setFormatter(formatter)
    logger.addHandler(ch)

def read_fasta(filepath):
    records = []
    with open(filepath, 'rU') as fasta_file:
        records = list(SeqIO.parse(fasta_file, 'fasta'))
    return records

def predict_fasta(filepath, output_dir, params):
    sequences = read_fasta(filepath)
    output_filepaths = []
    for sequence in sequences:
        seq = str(sequence.seq).replace('X', '')
        output = run_cref(seq, output_dir, params)
        sequence_file = os.path.join(output_dir, 'sequence.txt')
        with open(sequence_file, 'w') as sequence_output:
            sequence_output.write(seq)
        output_filepaths.append(output)
    return output_filepaths

def _download_file(url, filepath):
    r = requests.get(url, stream=True)
    with open(filepath, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
    return filepath

def download_fasta(pdb_code, filepath):
    """"""
    url = ('http://www.rcsb.org/pdb'
           '/files/fasta.txt?structureIdList=' + pdb_code.upper())
    return _download_file(url, filepath)

def download_pdb(pdb_code, filepath):
    url = ('http://www.rcsb.org/pdb/download/downloadFile.do?'
           'fileFormat=pdb&compression=NO&structureId=' + pdb_code.upper())
    return _download_file(url, filepath)

def read_config():
    pdb_id = sys.argv[1].upper()
    excluded_pdbs = [x.strip() for x in sys.argv[2].split()]
    excluded_pdbs.append(pdb_id)

    fragment_size = range(5, 16, 2)
    number_of_clusters = range(4, 13)
    matrix = ["PAM30"]
    max_templates = [100]
    number_of_alignments = [1000]
    params_list = []
    print(len(list(itertools.product(
        fragment_size,
        number_of_clusters,
        matrix,
        max_templates,
        number_of_alignments))))
    for f, c, m, t, a in itertools.product(
            fragment_size,
            number_of_clusters,
            matrix,
            max_templates,
            number_of_alignments):
        print(f, c, t, a, m)
        params = {
            "id": (f, c, t, a, m),
            "exclude": {"pdbs": excluded_pdbs},
            "fragment_size": f,
            "number_of_clusters": c,
            "max_templates": t,
            "blast": {
                "number_of_alignments": a,
                "scoring": {
                    "matrix": m,
                    "gap_costs": "ungapped",
                }
            }
        }
        params['pdb'] = pdb_id
        params['output_dir'] = os.path.join(
            'predictions/benchmark',
            params['pdb'],
            '_'.join([str(x) for x in (f, c, t, a, m)]),
        )
        params_list.append(params)
    return params_list

def run_pymol(pdb_code, predicted_filepath):
    filepath = os.path.join(
        os.path.dirname(predicted_filepath),
        'experimental_structure.pdb'
    )
    experimental_pdb = download_pdb(pdb_code, filepath)
    output = subprocess.check_output([
        'pymol',
        predicted_filepath,
        experimental_pdb,
        '-r',
        'cref/utils/pymolbench.py'
    ])
    output = output.decode('utf-8').split('\n')
    rmsd = output[-4]
    imagepath = output[-3]
    return rmsd, imagepath

def rmsds_to_csv(rmsds, filename):
    results = []

    for key, value in rmsds.items():
            results.append(key + (value,))

    df = pandas.DataFrame(
        results,
        columns=['fragment_size', 'group_count', 'max_templates',
                 'max_blast', 'matrix', 'rmsd']
    )
    df.to_csv(filename + '.rmsd.csv')

def main():
    configure_logger('INFO')
    test_cases = read_config()
    results = {}

    for params in test_cases:
            print('Predicting', params['pdb'], params['id'])
            print(params)
            handler, fasta_file = tempfile.mkstemp(
                suffix='.fasta', prefix='tmp')
            download_fasta(params['pdb'], fasta_file)
            output_files = predict_fasta(
                fasta_file, params['output_dir'], params)
            rmsd, imagepath = run_pymol(params['pdb'], output_files[0])
            output_file = os.path.join(params['output_dir'], 'rmsd.txt')
            with open(output_file, 'w') as rmsd_file:
                rmsd_file.write(rmsd)
            results[params['id']] = rmsd

            shutil.copyfile(
                imagepath,
                os.path.join(params['output_dir'], 'alignment-pymol.png'),
            )
            print('Prediction written to', output_files)
            print('RMSD from reference structure:', rmsd)
            os.remove(fasta_file)
            rmsds_to_csv(results, params['pdb'])
    print(results)
    rmsds_to_csv(results, params['pdb'])

if __name__ == '__main__':
    main()


from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .scrapper import scrape_data_from_google_maps
from .google_scrape import scrpe
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Queries, Google_data
from .g_loc import *
import threading
from .news import scrape_api

from rest_framework import serializers
from .models import Google_data

class GoogleDataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Google_data
        fields = '__all__'

@api_view(['GET', 'POST'])
def get_newsdata(request):
    print(request.method)
    if request.method=='POST':
        country=request.data.get('country')
        if country:
            data = scrape_api(country)
            response_data = {
                'status': 'success',
                'message': 'Data retrieved successfully',
                'data': data
            }
            return JsonResponse(response_data, status=200)
        else:
            response_data = {
                'status': 'error',
                'message': 'Country parameter is missing or invalid'
            }
            return JsonResponse(response_data, status=400)

@api_view(['GET', 'POST'])
def save_data(request):
    if request.method == 'POST':
        longitude = request.data.get('longitude')
        latitude = request.data.get('latitude')
        query_type = request.data.get('type')

        # Check if data is exists
        existing_query = Queries.objects.filter(
            longitude=longitude,
            latitude=latitude,
            type=query_type,
            number_of_data=int(request.data['number_of_data'])
        ).first()

        if existing_query:
            # Data already exists
            google_data_list = Google_data.objects.filter(query_id=existing_query)
            serializer = GoogleDataSerializer(google_data_list, many=True)
            return Response(serializer.data)

        else:
            #  save the new data
            query = Queries(
                longitude=longitude,
                latitude=latitude,
                number_of_data=request.data['number_of_data'],
                type=query_type,
                status="pending"
            )
            query.save()
            longitude = longitude
            latitude = latitude
            content_type = query_type
            number_of_results = request.data['number_of_data']
            # s=threading.Thread(target=scrape_google_maps,args=(content_type,number_of_results,latitude,longitude,query))
            # s.start()
            print("scraper started")
            scrape_google_maps(content_type, number_of_results, latitude, longitude, query)
            google_data_list = Google_data.objects.filter(query_id=query)
            serializer = GoogleDataSerializer(google_data_list, many=True)
            return Response(serializer.data)

        # response_data = {'status': 'Data saved successfully!'}

        return Response(response_data)
    if request.method == 'GET':
        print("get request")
        print(request.GET)
        longitude = request.GET.get('longitude')
        latitude = request.GET.get('latitude')
        query_type = request.GET.get('type')

        # Check if data is exists
        existing_query = Queries.objects.filter(
            longitude=longitude,
            latitude=latitude,
            type=query_type,
            number_of_data=int(request.GET['number_of_data'])
        ).first()
        print(existing_query)

        if existing_query:
            # Data already exists
            google_data_list = Google_data.objects.filter(query_id=existing_query)
            serializer = GoogleDataSerializer(google_data_list, many=True)
            return Response(serializer.data)

        else:
            #  save the new data
            query = Queries(
                longitude=longitude,
                latitude=latitude,
                number_of_data=int(request.GET['number_of_data']),
                type=query_type,
                status="pending"
            )
            query.save()
            longitude = longitude
            latitude = latitude
            content_type = query_type
            number_of_results = int(request.GET['number_of_data'])
            # s=threading.Thread(target=scrape_google_maps,args=(content_type,number_of_results,latitude,longitude,query))
            # s.start()
            print("scraper started")
            scrape_google_maps(content_type, number_of_results, latitude, longitude, query)
            google_data_list = Google_data.objects.filter(query_id=query)
            serializer = GoogleDataSerializer(google_data_list, many=True)
            return Response(serializer.data)

        # response_data = {'status': 'Data saved successfully!'}

        return Response(response_data)

    return Response({'status': 'Invalid request method'}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE'])
def delete_data(request):
    try:
        longitude = request.data.get('longitude')
        latitude = request.data.get('latitude')
        query_type = request.data.get('type')

        # Check if any record with same latitude, longitude, or type exists
        matching_queries = Queries.objects.filter(
            Q(longitude=longitude) | Q(latitude=latitude) | Q(type=query_type)
        )

        if matching_queries.exists():
            # Remove the data that matches the criteria
            matching_queries.delete()
            return Response({'status': 'Data removed successfully!'})
        else:
            return Response({'status': 'No matching data found'}, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({'status': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter

def plot_poles(X, Y, rational_data, plot_imaginary=False):
    """
    Plot surface plot with poles
    """
    XX, YY = np.meshgrid(X,Y)

    Z = np.reshape(rational_data, XX.shape)

    if plot_imaginary:
        Z = Z.imag
    else:
        Z = Z.real

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot_surface(XX,YY,Z, cmap = cm.coolwarm, linewidth = 0, antialiased = False)
    ax.set_zlim(-10,10)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.set(xlabel = "Re(z)", ylabel = "Im(z)", zlabel = "f(z)")

    return fig

def plot_training_data(path):

    X = np.loadtxt(path + '/X.txt')
    data = np.loadtxt(path + '/output_data.txt')
    noised_data = np.loadtxt(path + '/noised_data.txt')

    fig, ax = plt.subplots()
    ax.plot(X, data, 'r')
    ax.set(xlabel = "x", ylabel = "f(x)")
    ax.plot(X, noised_data, 'x')
    fig.savefig(path + '/plots/training.svg')


#!/bin/env python3

"""
$LICENSE
"""

from mpps import pluginmanager
from queue import Empty
import sys
import globaldef

CONF = "./conf.d"
PLUGINS = "./plugins"

class MsgHandler:
    _p_handler = None

    def __init__(self, p):
        self._p_handler = p

    def process(self, msg):
        self.print_msg(msg)
        if msg.get_status() == "fin":
            self._p_handler.stop_plugin(msg.get_issuer())

    def print_msg(self, msg):
        outln = ""
        try:
            outln = ''.join(
                (msg.get_issuer(), "::", msg.get_longstatus(), "> "))
        except KeyError:
            print(''.join(("> ", "Unknown Message Type ",
                           msg.get_status(), " from Plugin ",
                           msg.get_issuer())))
        except Exception as e:
            print(e)

        if msg.get_status() != "data":
            for line in msg.get_content().split('\n'):
                print(outln + line)
        elif globaldef.debug:
            print(outln + str(msg.get_content()))

def collect():
    p_handler = pluginmanager.PluginManager(PLUGINS, CONF)
    m_handler = MsgHandler(p_handler)
    p_list = p_handler.get_plugins()
    print("Loading Plugins:")
    try:
        for i in p_list:
            print("LOADED> " + i)

            p_handler.load_plugin(i)
            print("\n")

            if not i == "examplePlugin":
                p_handler.add_callback(m_handler.process, i)
            p_handler.run_plugin(i)

        # Shut them down
        p_handler.shutdown_callbacks()

        print("\nCallbacks terminated\n")
        print("Remaining Non-callback Messages:")
        while p_handler.get_running_plugins():
            try:
                msg = p_handler.next_msg()
                m_handler.print_msg(msg)
                if msg.get_status() == "fin":
                    p_handler.stop_plugin(msg.get_issuer())
            except Empty:
                pass

    except KeyboardInterrupt:
        print("\n> CTRL+C detected")
    except ImportError as e:
        print(e)

    del p_handler
    print("\n> Exiting...")
    sys.exit(0)

def main():
    print("Example Usage of the Multiprocessing Plugin System (MPPS)\n")
    collect()

if __name__ == "__main__":
    main()


import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from matplotlib import pyplot as plt
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, precision_score, accuracy_score, recall_score, f1_score, classification_report

loan_df = pd.read_csv("D:\PythonData\Gini_Entropy.csv")
y = loan_df['Loan_Status']
loan_features = ['Cust_Id','Loan_Amt']
X = loan_df[loan_features]
train_X, test_X, train_y, test_y = train_test_split(X, y, random_state = 0, train_size=0.75)
print(train_X)
loan_model = DecisionTreeClassifier(random_state=1,criterion='gini')
loan_model.fit(X, y)
print(test_X)
loan_score_pred = loan_model.predict(test_X)
plt.figure(figsize=(18,18))
tree.plot_tree(loan_model, fontsize=9)
plt.show()
print("Confusion Matrix")
cm = confusion_matrix(test_y, loan_score_pred)
print(cm)
print("Accuracy Score ", accuracy_score(test_y, loan_score_pred))
print("Recall ", recall_score(test_y, loan_score_pred))
print("Precision ", precision_score(test_y, loan_score_pred))
print("F1 Score ", f1_score(test_y, loan_score_pred))
print("Classification Report ")
print(classification_report(test_y, loan_score_pred))


import re

with open('./text_analysis/my_text.txt') as file:
    text = file.read()

# Let's create a class called analyzer_text to analyze text
class TextAnalyzer:
    def __init__(self, text):
        self.text = text
        # Remove punctuation using a regex pattern
        # Replace '\n' between words with a space
        clean_text_enter = re.sub(r'\n', ' ', text)
        clean_text = re.sub(r'[.,!?¿"]', '', clean_text_enter)
        # lowercase, easier to read :)
        clean_text_lower = clean_text.lower()
        self.format_text = clean_text_lower

    def count_freq(self):
        # split text into list of words first
        words_list = self.format_text.split(" ")

        # create a dict to count words
        freq_dict = {}
        # using a set to remove duplicates
        for word in set(words_list):
            freq_dict[word] = words_list.count(word) # to count how many times the word appears in the word list
        return freq_dict

    def freq_unique_word(self, word):
        freq_dict = self.count_freq()

        if word in freq_dict:
            return f"The word {word.upper()} appears {freq_dict[word]} times in your text."
        else:
            return f"The word {word} is not in your text"

my_clean_text = TextAnalyzer(text)

print(my_clean_text.freq_unique_word("data"))


from flask import Flask, render_template, request
import json

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    valueButton = "input text"
    valueInput = ""
    if request.method == "POST":
        valueInput = valueButton

    return render_template("first.html", valueButton=valueButton, valueInput=valueInput)

@app.route("/open_input", methods=["GET", "POST"])
def openInput():
    literals = ["Object1", "Object2", "Object3", "Object4"]
    value = ""
    input1 = ""
    input2 = ""
    if request.method == "POST":
        input1 = request.form["input1"]
        input2 = request.form["input2"]
    return render_template(
        "openInput.html",
        literals=literals,
        input1=input1,
        input2=input2,
        literalsJson=json.dumps(literals),
    )

if __name__ == "__main__":
    app.run(debug=True)


import serial
import time
import pandas as pd
import numpy as np
from fileu import *
from Pumps.Pump import Pump as Pump
from Protocols.Protocol import Protocol as Protocol
from Valves.ViciValve import Valve as Valve
import argparse
import importlib
import threading
import sys
import os
from math import floor,ceil

dir = os.path.dirname(os.path.abspath(__file__))
for file in os.listdir(dir):
    if os.path.isdir(os.path.join(dir,file)):
        sys.path.append(os.path.join(dir,file))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--fluidics_class", type=str, dest="fluidics_class", default="Fluidics", action='store', help="Which Fluidics Class to use")
    args = parser.parse_args()

class Fluidics(object):
    def __init__(self,gui=False):
        self.verbose=True
        self.simulate = False
        # self.Protocol = Protocol(gui=gui)
        # self.Pump = Pump(gui=gui)
        # self.Valve = Valve(gui=gui)

        self.device = self.__class__.__name__
        self.file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),self.device+'_Status.txt')
        self.last_message = ""
        self.Valve_Commands = {}
        self.busy=False

        # self.thread = threading.Thread(target=self.run)
        # self.thread.daemon = True # without the daemon parameter, the function in parallel will continue even your main program ends
        # self.thread.start()
        if not gui:
            self.update_communication('Available')

    def update_user(self,message,level=20,logger='Fluidics'):
        logger = self.device +'***' + logger
        if self.verbose:
            update_user(message,level=level,logger=logger)

    def run(self):
        if not self.busy:
            # Read Communication
            current_message = self.read_communication()
            if self.last_message!=current_message:
                self.last_message = current_message
                print(current_message)
            if 'Command' in current_message:
                print(current_message)
                self.busy = True
                # interpret message
                message = current_message.split(':')[-1]
                self.update_communication('Running:'+message)
                protocol,chambers,other = self.interpret_message(message)
                self.execute_protocol(protocol,chambers,other)
                self.update_communication('Finished:'+message)
                self.busy = False
        precise_sleep(5)

    def read_communication(self):
        with open(self.file_path,'r') as f:
            message = f.read()
        if self.last_message !=message:
            self.last_message = message
            self.update_user(message)
        return message

    def update_communication(self,message):
        self.update_user(message)
        with open(self.file_path,'w') as f:
                f.write(message)

    def interpret_message(self,message):
        protocol,chambers,other = message.split('*')
        if '!' in other:
            other = other.split('!')[0]
            self.simulate = True
            self.Protocol.simulate = True
        if '+' in other:
            if other.split('+')[-1] =='':
                other = other.split('+')[0]
        chambers = chambers[1:-1].split(',')
        if 'Flush' in protocol:
            chambers = self.Valve_Commands
        if 'Prime' in protocol:
            chambers = self.Valve_Commands
        if 'Clean' in protocol:
            chambers = self.Valve_Commands
        return protocol,chambers,other

    def execute_protocol(self,protocol,chambers,other):
        steps = self.Protocol.get_steps(protocol,chambers,other)
        if not isinstance(steps,pd.DataFrame):
            self.update_user('Unknown Protocol: '+str(protocol))
        else:
            self.summarize_protocol(steps)
            if not self.simulate:
                for idx,step in steps.iterrows():
                    self.update_user(pd.DataFrame(step).T)
                    if step.direction == 'Wait':
                        if step.pause<100:
                            precise_sleep(step.pause)
                        else:
                            t = step.pause
                            self.update_user('          Wait '+str(round(t))+'s')
                            for i in range(10):
                                precise_sleep(t/10)
                                if t>0:
                                    self.update_user('          '+str(round((i+1)*10))+'% Complete')
                    else:
                        self.flow(step.port,step.volume,step.speed,step.pause,step.direction)
            else:
                precise_sleep(1) # wait 0.5 minutes
        self.simulate = False
        self.Protocol.simulate = False

    def flow(self,port,volume,speed,pause,direction):
        self.set_port(port)
        self.start_flow(volume,direction,speed)
        self.sleep(pause)

    def set_port(self,command):
        if not command in self.Valve_Commands.keys():
            self.update_user('          Unknown Tube: '+command)
        else:
            # self.update_user('          Tube: '+command)
            """ Set Port """
            self.Valve.set_port(int(self.Valve_Commands[command]['valve'])-1, int(self.Valve_Commands[command]['port'])-1)
            command = 'Valve'+str(self.Valve_Commands[command]['valve'])
            while command in self.Valve_Commands.keys():
                self.Valve.set_port(int(self.Valve_Commands[command]['valve'])-1, int(self.Valve_Commands[command]['port'])-1)
                command = 'Valve'+str(self.Valve_Commands[command]['valve'])

    def start_flow(self,volume,direction,speed):
        if volume>0:
            self.Pump.start_flow(volume,direction,speed)

    def sleep(self,t):
        if t>0:
            self.update_user('          Wait '+str(round(t))+'s')
            for i in range(10):
                time.sleep(t/10)
                if t>0:
                    self.update_user('          '+str(round((i+1)*10))+'% Complete')

    def summarize_protocol(self,steps):
        self.update_user('Protocol Summary')
        ports = np.unique(steps['port'])
        for port in ports:
            if len(port)>1:
                total_volume = np.sum([float(i) for i in steps[(steps['port']==port)&(steps['direction']=='Reverse')]['volume']])
                if total_volume>0:
                    self.update_user('Port: '+str(port)+'  Total Volume: '+str(total_volume)+'mL')
        total_time= np.sum([float(i) for i in steps['time_estimate'] if i!=''])
        if total_time<60:
            self.update_user('Estimated Total Time: '+str(int(total_time))+'s')
        elif total_time<60*60:
            minutes = floor(total_time/60)
            total_time = total_time-(minutes*60)
            self.update_user('Estimated Total Time: '+str(int(minutes))+'m'+str(int(total_time))+'s')
        else:
            hours = floor(total_time/(60*60))
            total_time = total_time-(hours*60*60)
            minutes = floor(total_time/60)
            total_time = total_time-(minutes*60)
            self.update_user('Estimated Total Time: '+str(int(hours))+'h'+str(int(minutes))+'m'+str(int(total_time))+'s')

if __name__ == '__main__':
    fluidics_class = args.fluidics_class
    module = importlib.import_module(fluidics_class)
    Fluidics_Class = getattr(module, fluidics_class)
    self = Fluidics_Class(gui=False)
    while True:
        self.run()


import datetime

from django.contrib.auth import get_user_model
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models

User = get_user_model()

import datetime

def today_year():
    return int(datetime.date.today().year)

class Category(models.Model):
    name = models.CharField(max_length=256,
                            verbose_name='Наименование категории')
    slug = models.SlugField(unique=True,
                            verbose_name='URL')

    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

    def __str__(self):
        return self.name

class Genre(models.Model):
    name = models.CharField(max_length=256)
    slug = models.SlugField(unique=True)

    class Meta:
        verbose_name = 'Жанр'
        verbose_name_plural = 'Жанры'

    def __str__(self):
        return self.name

class Title(models.Model):
    name = models.CharField(max_length=200)
    year = models.IntegerField(
        validators=[
            MaxValueValidator(datetime.date.today().year),
            MinValueValidator(0)
        ])
    description = models.TextField(blank=True)
    genre = models.ManyToManyField(Genre, related_name='genre')
    category = models.ForeignKey(
        Category, on_delete=models.SET_NULL, null=True, related_name='category'
    )

    class Meta:
        verbose_name = 'Произведение'
        verbose_name_plural = 'Произведения'

    def __str__(self):
        return self.name

class Review(models.Model):
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='reviews',
        verbose_name='Автор отзыва',
    )
    text = models.TextField(null=False, verbose_name='Отзыв')
    pub_date = models.DateTimeField(
        verbose_name='Дата публикации', auto_now_add=True
    )
    title = models.ForeignKey(
        Title,
        on_delete=models.CASCADE,
        related_name='reviews',
        verbose_name='Произведение',
    )
    score = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(100)],
        verbose_name='Оценка',
    )

    class Meta:
        unique_together = ['author', 'title']
        ordering = ['-pub_date']

    def __str__(self):
        return f'{self.id}'

class Comment(models.Model):
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='Автор комментария',
    )
    text = models.TextField(verbose_name='Комментарий')
    pub_date = models.DateTimeField(
        verbose_name='Дата публикации', auto_now_add=True
    )
    review = models.ForeignKey(
        Review,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='Отзыв',
    )

    class Meta:
        ordering = ['-pub_date']


def porta_and(entradas):

    for entrada in entradas:
        if(entrada == 0):
            return 0

    return 1

def porta_or(entradas):

    for entrada in entradas:
        if(entrada == 1):
            return 1

    return 0

def porta_not(entrada):

    1 if entrada == 0 else 0
    return entrada

def porta_xor(entradas):

    if entradas[0] == entradas[1]:

        return 0

    return 1

def porta_nor(entradas):

    return porta_not(porta_or(entradas))

def porta_nand(entradas):

    return porta_not(porta_and(entradas))

# exercício 1
def e_um(a, b, c, d):

    primeira_parte = porta_not(porta_or([a, porta_not(b), c]))
    segunda_parte = porta_or([a, porta_not(d), b])
    terceira_parte = porta_not(porta_and([primeira_parte, segunda_parte]))
    s = porta_and([terceira_parte, porta_not(a), b, porta_not(c)])

    print("Resultado da expressão do exercício 1 é: ", s)

# exercício 2
def e_dois(a, b, c, d):

    primeira_parte = porta_nor([a, b])
    segunda_parte = porta_not(porta_or([porta_not(a), primeira_parte, porta_not(d)]))
    terceira_parte = porta_not(porta_and([porta_not(b), d, porta_not(d)]))
    s = porta_or([segunda_parte, porta_not(d), terceira_parte])

    print("Resultado do exercício 2 com as entradas [", a, ", ", b , ", ", c , ", ", d, "] : ", s)

#exercício 5
def e_cinco(a, b, c, d):

    primeira_parte = porta_nor([a, porta_not(d)])
    segunda_parte = porta_and([primeira_parte, b])
    terceira_parte = porta_and([porta_not(a), b, porta_not(c)])
    quarta_parte = porta_and([b, porta_not(c)])
    quinta_parte = porta_and([porta_not(b), c])
    sexta_parte = porta_nor([segunda_parte, terceira_parte, quarta_parte, quinta_parte])
    setima_parte = porta_xor([b, c])
    oitava_parte = porta_and([sexta_parte, setima_parte])
    nona_parte = porta_and([a, b, d])
    decima_parte = porta_nor([oitava_parte, nona_parte, porta_not(b)])
    decima_primeira_parte = porta_or([porta_not(a), porta_not(b)])
    s = porta_and([decima_parte, decima_primeira_parte])

    print("Resultado do exercício 11 com as entradas [", a, ", ", b, ", ", c, ", ", d, "] : ", s)

#exercício 11
def e_onze(a, b, c, d):

    primeira_parte = porta_nand([a, b, c, d])
    segunda_parte = porta_and([porta_not(a), b, porta_not(c), d])
    terceira_parte = porta_and([porta_not(a), b, c, porta_not(d)])
    quarta_parte = porta_and([a, b, porta_not(c), d])
    quinta_parte = porta_and([a, b, c, d])
    s = porta_or([primeira_parte, segunda_parte, terceira_parte, quarta_parte, quinta_parte])

    print("Resultado do exercício 11 com as entradas [", a, ", ", b, ", ", c, ", ", d, "] : ", s)

#exercício 12
def e_doze(a, b, c, d):

    primeira_parte = porta_and([porta_not(a), b, porta_not(c), d])
    segunda_parte = porta_and([porta_not(a), b, c, porta_not(d)])
    terceira_parte = porta_and([a, porta_not(b), porta_not(c), porta_not(d)])
    quarta_parte = porta_and([a, porta_not(b), b, c])
    s = porta_or([primeira_parte, segunda_parte, terceira_parte, quarta_parte])

    print("Resultado do exercício 12 com as entradas [", a, ", ", b, ", ", c, ", ", d, "] : ", s)

# exercício 26
def e_vinte_seis(a, b, c):

    primeira_parte = porta_and([a, b, c,])
    segunda_parte = porta_and([a, b, porta_not(c)])
    terceira_parte = porta_and([a, porta_not(b), c])
    quarta_parte = porta_and([porta_not(a), b, c])
    s = porta_or([primeira_parte, segunda_parte, terceira_parte, quarta_parte])

    print("Resultado do exercício 26 com as entradas [", a, ", ", b , ", ", c , "] : ", s)

#exercicio 27
def e_vinte_sete(a, b):

    negacao_a = porta_nor([a, a])
    negacao_b = porta_nor([b, b])
    primeira_parte = porta_nor([negacao_a, b])
    segunda_parte = porta_nor([a, negacao_b])
    terceira_parte = porta_nor([primeira_parte, segunda_parte])
    s = porta_nor([terceira_parte, terceira_parte])

    print("Resultado do exercício 27 com as entradas [", a, ", ", b, "] : ", s)

#exercício 28
def e_vinte_oito(a, b):

    negacao_a = porta_nand([a, a])
    negacao_b = porta_nand([b, b])
    primeira_parte = porta_nand([a, b])
    segunda_parte = porta_nand([negacao_a, negacao_b])
    terceira_parte = porta_nand([primeira_parte, segunda_parte])
    s = porta_nand([terceira_parte, terceira_parte])

    print("Resultado do exercício 28 com as entradas [", a, ", ", b, "] : ", s)

#exercício 29
def e_vinte_nove(a, b, c):

    negacao_a = porta_nor([a, a])
    negacao_b = porta_nor([b, b])
    negacao_c = porta_nor([c, c])

    b_nor_c = porta_nor([b, c])
    primeira_parte = porta_nor([porta_nor([negacao_b, negacao_c]), b_nor_c])

    a_and_b_and_c = porta_nor([negacao_a, negacao_b, negacao_c])
    segunda_parte = porta_nor([a_and_b_and_c, a_and_b_and_c])

    terceira_parte = porta_nor([primeira_parte, segunda_parte])

    quarta_parte = porta_nor([[porta_nor([a, c])], negacao_b])

    quinta_parte = porta_nor([terceira_parte, quarta_parte])
    quinta_parte = porta_nor([quinta_parte, quinta_parte])

    sexta_parte = porta_nor([quinta_parte, a])

    s = porta_nor([sexta_parte, sexta_parte])

    print("Resultado do exercício 28 com as entradas [", a, ", ", b, ", ", c, "] : ", s)


import EightPuzzle
import copy
import queue

def BFS(Start, Goal):
	visited = []

	opened = queue.Queue()
	opened.put([Start])

	count = 0

	while not opened.empty():

		successors = []

		popped = opened.get()

		statePopped = popped[len(popped)-1]

		count+=1

		# print(statePopped)
		# print(count)

		if statePopped == Goal:
			return popped

		visited.append(statePopped)

		allPossibleNextStates = EightPuzzle.allNextStates(statePopped)

		for state in allPossibleNextStates:
			if state not in visited:
				successors.append(state)
				visited.append(state)

		for successor in successors:
			path = copy.deepcopy(popped)
			path.append(successor)
			opened.put(path)

	return "Goal State Not Found"

Start = [[2,8,3], [1,6,4], [7,0,5]]

Goal = [[2,8,0], [3,1,4], [7,6,5]]

list1 = BFS(Start, Goal)

for x in list1:
	print(x)


import logging
import re

from typing import Text, List, Optional, Dict, Any

from rasa.nlu.config import RasaNLUModelConfig
from rasa.shared.nlu.training_data.training_data import TrainingData
from rasa.shared.nlu.training_data.message import Message
from rasa.nlu.components import Component
from rasa.nlu.constants import TOKENS_NAMES, MESSAGE_ATTRIBUTES
from rasa.shared.nlu.constants import (
    INTENT,
    INTENT_RESPONSE_KEY,
    RESPONSE_IDENTIFIER_DELIMITER,
    ACTION_NAME,
)

logger = logging.getLogger(__name__)

class Token:
    def __init__(
        self,
        text: Text,
        start: int,
        end: Optional[int] = None,
        data: Optional[Dict[Text, Any]] = None,
        lemma: Optional[Text] = None,
    ) -> None:
        self.text = text
        self.start = start
        self.end = end if end else start + len(text)

        self.data = data if data else {}
        self.lemma = lemma or text

    def set(self, prop: Text, info: Any) -> None:
        self.data[prop] = info

    def get(self, prop: Text, default: Optional[Any] = None) -> Any:
        return self.data.get(prop, default)

    def __eq__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return (self.start, self.end, self.text, self.lemma) == (
            other.start,
            other.end,
            other.text,
            other.lemma,
        )

    def __lt__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return (self.start, self.end, self.text, self.lemma) < (
            other.start,
            other.end,
            other.text,
            other.lemma,
        )

class Tokenizer(Component):
    def __init__(self, component_config: Dict[Text, Any] = None) -> None:
        """Construct a new tokenizer using the WhitespaceTokenizer framework."""

        super().__init__(component_config)

        # flag to check whether to split intents
        self.intent_tokenization_flag = self.component_config.get(
            "intent_tokenization_flag", False
        )
        # split symbol for intents
        self.intent_split_symbol = self.component_config.get("intent_split_symbol", "_")
        # token pattern to further split tokens
        token_pattern = self.component_config.get("token_pattern", None)
        self.token_pattern_regex = None
        if token_pattern:
            self.token_pattern_regex = re.compile(token_pattern)

    def tokenize(self, message: Message, attribute: Text) -> List[Token]:
        """Tokenizes the text of the provided attribute of the incoming message."""

        raise NotImplementedError

    def train(
        self,
        training_data: TrainingData,
        config: Optional[RasaNLUModelConfig] = None,
        **kwargs: Any,
    ) -> None:
        """Tokenize all training data."""

        for example in training_data.training_examples:
            for attribute in MESSAGE_ATTRIBUTES:
                if (
                    example.get(attribute) is not None
                    and not example.get(attribute) == ""
                ):
                    if attribute in [INTENT, ACTION_NAME, INTENT_RESPONSE_KEY]:
                        tokens = self._split_name(example, attribute)
                    else:
                        tokens = self.tokenize(example, attribute)
                    example.set(TOKENS_NAMES[attribute], tokens)

    def process(self, message: Message, **kwargs: Any) -> None:
        """Tokenize the incoming message."""
        for attribute in MESSAGE_ATTRIBUTES:
            if isinstance(message.get(attribute), str):
                if attribute in [INTENT, ACTION_NAME, RESPONSE_IDENTIFIER_DELIMITER]:
                    tokens = self._split_name(message, attribute)
                else:
                    tokens = self.tokenize(message, attribute)

                message.set(TOKENS_NAMES[attribute], tokens)

    def _tokenize_on_split_symbol(self, text: Text) -> List[Text]:

        words = (
            text.split(self.intent_split_symbol)
            if self.intent_tokenization_flag
            else [text]
        )

        return words

    def _split_name(self, message: Message, attribute: Text = INTENT) -> List[Token]:
        text = message.get(attribute)

        # for INTENT_RESPONSE_KEY attribute,
        # first split by RESPONSE_IDENTIFIER_DELIMITER
        if attribute == INTENT_RESPONSE_KEY:
            intent, response_key = text.split(RESPONSE_IDENTIFIER_DELIMITER)
            words = self._tokenize_on_split_symbol(
                intent
            ) + self._tokenize_on_split_symbol(response_key)

        else:
            words = self._tokenize_on_split_symbol(text)

        return self._convert_words_to_tokens(words, text)

    def _apply_token_pattern(self, tokens: List[Token]) -> List[Token]:
        """Apply the token pattern to the given tokens.

        Args:
            tokens: list of tokens to split

        Returns:
            List of tokens.
        """
        if not self.token_pattern_regex:
            return tokens

        final_tokens = []
        for token in tokens:
            new_tokens = self.token_pattern_regex.findall(token.text)
            new_tokens = [t for t in new_tokens if t]

            if not new_tokens:
                final_tokens.append(token)

            running_offset = 0
            for new_token in new_tokens:
                word_offset = token.text.index(new_token, running_offset)
                word_len = len(new_token)
                running_offset = word_offset + word_len
                final_tokens.append(
                    Token(
                        new_token,
                        token.start + word_offset,
                        data=token.data,
                        lemma=token.lemma,
                    )
                )

        return final_tokens

    @staticmethod
    def _convert_words_to_tokens(words: List[Text], text: Text) -> List[Token]:
        running_offset = 0
        tokens = []

        for word in words:
            word_offset = text.index(word, running_offset)
            word_len = len(word)
            running_offset = word_offset + word_len
            tokens.append(Token(word, word_offset))

        return tokens


import re
import pandas as pd

PATTERN = '[a-zA-Z]+'

def top_companies(txt_file):
    '''
    creates dictionary of top companies and their buckets of products

    txt_file (txt) - txt file from the first mapreduce function with the
                        top companies
    '''
    txt = open(txt_file)
    d = {}
    companies = []

    for line in txt:
        words = re.findall(PATTERN, line)
        key = words.pop(0)
        d[key] = words
        companies.append(key)

    return d

def training_data(txt_file, csv_file):
    '''
    this should be a dictionary with company as key and values of quarterly
    training data as well as bucket data
    data = {'Apple': {'earnings': [1, 2, 3, 4],
                        'products': [iPhone, iPod]}

    txt_file - company and buckets
    csv_file - training data
    '''
    data_dict = top_companies(txt_file)
    training_dict = {}
    companies = []
    training_csv = open(csv_file)
    for line in training_csv:
        line = line.replace('\n', '')
        line = line.split(',')
        company_name = line[0]
        if float(line[6]) < 1:
            companies.append(company_name)
        eps = [line[6]]
        training_dict[company_name] = {}
        training_dict[company_name]['earnings'] = eps
        training_dict[company_name]['products'] = data_dict[company_name]

    return training_dict, companies

def read_sent_file(txt_file):
    '''
    reads the sent file returned by the mapreduce and return easily searchable
    dictionary of all of the data

    txt_file (txt) - this is the text file from running the second mapreduce,
                        it should have all of the sentiment data
    '''
    num_pattern = '[0-9]+\.[0-9]+|[0-9]+'
    name_pattern = '([a-zA-Z]+)\d'
    date_pattern = '[0-9]+'
    raw_data = open(txt_file)
    data_dict = {}
    for item in raw_data:
        item = item.split('\t')
        nums = [float(x) for x in re.findall(num_pattern, item[1])]
        # nums = [total_mentions, total_sentiment]
        name = re.findall(name_pattern, item[0])[0]
        data_type = item[0][-2] # whether we are looking at month or week
        date = int(re.findall(date_pattern, item[0])[0]) # week/month number
        if name in data_dict:
            data_dict[name][data_type][date] = nums
        else:
            data_dict[name] = {'m': {}, 'w': {}}
            data_dict[name][data_type][date] = nums

    return data_dict

def single_dp(data_dict, training_set, companies, typ, date, quarter):
    '''
    makes single data column with points of interest

    data_dict (dict) - dictionary of data points
    training_set (dict) - dictionary of companies with their top products and their
                    quarterly earning performance
    companies (list) - list of the top 100 companies
    typ (str) - using month or week?
    date (int) - which month or week?
    quarter (int) - which quarter are we analyzing?
    '''
    averages = []
    counts = []

    for company in companies:
        count = 0
        total = 0

        for item in training_set[company]['products']:
            try:
                count += data_dict[item][typ][date][0]
                total += data_dict[item][typ][date][1]
            except: #if no data exits
                None

        if count > 0:
            averages.append(total / count)
        else:
            averages.append(0)
        counts.append(total)

    avg_key = typ + str(date) + 'avg'
    count_key = typ + str(date) + 'cnt'
    temp_df = pd.DataFrame({avg_key: averages, count_key: counts})

    return temp_df

def mk_data_strct(data_dict, training_set, companies, m_r, w_r, quarter):
    '''
    makes a data struct with points of interest

    data_dict (dict) - dictionary of data points
    training_set (dict) - dictionary of companies with their top products and their
                    quarterly earning performance
    companies (list) - list of the top 100 companies
    m_r (tuple) - range of months to look at
    w_r (tuple) - range of weeks to look at
    quarter (int) - which quarter are we analyzing?
    '''
    frames = []

    # add the weekly data
    for week in range(w_r[0], w_r[1]):
        t_df = single_dp(data_dict, training_set, companies, 'w', week, quarter-1)
        frames.append(t_df)

    #add the monthly data
    for month in range(m_r[0], m_r[1]):
        t_df = single_dp(data_dict, training_set, companies, 'm', month, quarter-1)
        frames.append(t_df)

    data_table = pd.concat(frames, axis=1)

    # add actual results
    actual = []
    for company in companies:
        change = training_set[company]['earnings'][quarter-1]
        actual.append(change)

    data_table['EPS'] = actual

    return data_table

def CREATE_DATAFRAME(text_file, csv_file, sent_file, m_r, w_r, quarter):
    '''
    creates the whole pandas data frame

    text_file - company and buckets
    csv_file - training data
    sent_file - sentiment data
    m_r (tuple) - range of months to look at
    w_r (tuple) - range of weeks to look at
    quarter (int) - which quarter are we analyzing?
    '''
    data_dict = read_sent_file(sent_file)
    training_set, companies = training_data(text_file, csv_file)
    dataframe = mk_data_strct(data_dict, training_set, companies, m_r, w_r, quarter)

    return dataframe


from bs4 import BeautifulSoup
import json
import requests
from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler

app = Flask(__name__)

# Read config file to get the url to scrape , the class id and  schedular interval
with open('config.json', 'r') as config_file:
    config_json = json.load(config_file)

url = config_json['url']
web_hook = config_json['web_hook']
scheduler_interval = config_json['Scheduler_interval']

# Method to send slack notification
def notification(message):
    if web_hook:
        msg_post = json.dumps({'text': message})
        response = requests.post(web_hook,data = msg_post)

def scraper():
    print('in scraper')
    page = requests.get(url)
    soupe =  BeautifulSoup(page.content,'lxml')
    price = soupe.find("div", {"class": '_30jeq3 _16Jk6d'}).get_text()
    price = int(price.replace(',','')[1:])

    if price < config_json["desired_price"]:
        notification(f'Price droped : \n {url}')

# ASP scheduler setup
scheduler = BackgroundScheduler()
scheduler.configure()
scheduler.add_job(scraper, 'interval', seconds=scheduler_interval)

# cofig the routes for to start and stop the tracking

# Route to start the Tracker
@app.route('/start',methods=['GET'])
def start():
    if scheduler.running :
        return 'Already Tracking'
    else:
        scheduler.start()
        return 'Tracking Started'

# Route to pause the tracker
@app.route('/pause',methods=['GET'])
def pause():
    if scheduler.running:
        scheduler.pause()
        return 'Tracking Paused'
    else :
        return 'No job runnning'

#Route to stop the tracker
@app.route('/stop',methods=['GET'])
def stop():
    if scheduler.running:
        scheduler.shutdown(wait=False)
        return 'shuting down'
    else:
        return 'Scheduler not running'

#Route to check the current status of the tracker
@app.route('/status',methods = ['GET'])
def status():
    status  = {0 : 'STOPPED' , 1: 'RUNNING',2: 'PAUSED'}
    return str(status[scheduler.state])

# Start Flask app
if __name__  == "__main__":
    app.run(debug=True)


from fn_machine_learning_nlp.lib.file_manage import FileManage
from fn_machine_learning_nlp.lib.nlp.nlp_word2vec import NLPWord2Vec

import numpy as np

import argparse

parser = argparse.ArgumentParser(description="Find top similar words")
parser.add_argument("word",
                    help="input word")
parser.add_argument("-n", "--number",
                    help="number of top similar words to return",
                    default=5)
parser.add_argument("-m", "--model",
                    help="word2vec model saved in txt format",
                    default=FileManage.DEFAULT_NLP_FILE)

args, unknown_args = parser.parse_known_args()

model_file = args.model
num_return = int(args.number)
word = args.word

print("similar-words:")
print("-------------")
print("Searching top {} word similar to {} using model {}".format(num_return, word, model_file))

def get_sim(v1, v1_norm, w):
    v2 = w2v.get_word_vec(w)
    v2_norm = np.linalg.norm(v2)
    if v1_norm == 0 or v2_norm == 0:
        sim = 0
    else:
        sim = np.dot(v1, v2) / (v1_norm * v2_norm)

    return {
        "word": w,
        "sim": sim
    }

w2v = NLPWord2Vec()
w2v.load_model(model_file)

v1 = w2v.get_word_vec(word)
v1_norm = np.linalg.norm(v1)
all_words = w2v.word2vec.index2word

closest = []
init = False
for w in all_words:
    d = get_sim(v1, v1_norm, w)

    if init is False:
        if len(closest) < num_return:
            closest.append(d)
        if len(closest) == num_return and init is False:
            closest.sort(key=lambda u:u["sim"])
            init = True
    else:
        if d["sim"] > closest[0]["sim"]:
            closest[0] = d
            closest.sort(key=lambda u:u["sim"])

for c in closest:
    print("\t%-30s %s"%(c["word"] + ":", c["sim"]))


## Problem: Battleship
## You're playing Battleship on a grid of cells with R rows and C columns. There
## are 0 or more battleships on the grid, each occupying a single distinct cell.
## The cell in the ith row from the top and jth column from the left either
## contains a battleship (G{i,j} = 1) or doesn't (G{i,j} = 0).

## You're going to fire a single shot at a random cell in the grid. You'll
## choose this cell uniformly at random from the R * C possible cells. You're
## interested in the probability that the cell hit by your shot contains a
## battleship.

## Your task is to implement the function getHitProbability(R, C, G) which
## returns this probability.

## Note: Your return value must have an absolute or relative error of at most
## 10^(-6) to be considered correct.

## Constraints:
## 1 <= R, C <= 100
## G{i,j} ∈ {0, 1}

## Solution
## Time Complexity: O(R * C)
## Space Complexity: O(1)
## Explanation: Count the number of ships and divide by the total number of
## cells. Because the cells are either 0 or 1, the number of ships is the same
## as the sum of all the cells.

from typing import List

def getHitProbability(R: int, C: int, G: List[List[int]]) -> float:
    num_ships = 0

    for row in G:
        num_ships += sum(row)

    return num_ships / (R * C)

## Test Cases
if __name__ == "__main__":
    ## Test Case 1
    R = 2
    C = 3
    G = [[0, 0, 1],
         [1, 0, 1]]

    print("Test Case 1")
    print("Expected Return Value = 0.5")
    print("Actual Return Value   = {}".format(getHitProbability(R, C, G)))
    print("")

    ## Test Case 2
    R = 2
    C = 2
    G = [[1, 1],
         [1, 1]]

    print("Test Case 2")
    print("Expected Return Value = 1.0")
    print("Actual Return Value   = {}".format(getHitProbability(R, C, G)))
    print("")


import sys
sys.setrecursionlimit(5000)

user_input = input("Enter the numbers (space separated) : ")

# Using list comprehension to cook a fresh list of integer values in the user_input string
input_list = [int(i) for i in user_input.strip().split(" ")]

print(input_list)


from request import Request
import simpy, datetime, threading, copy
from cache import *
from osd_op import *

def runMappers(dc, scheduler, env):
  for i in dc.mapper_list.keys():
    request_generator(i, dc, scheduler, env)

def completion(req_old, dc, env):
  req = copy.deepcopy(req_old)
  finishTime = env.now
  req.set_endTime(finishTime)
  dc.mapper_list[req.mapper_id].outstanding_req +=1
  dc.outstanding_req[req.req_id] = [False, req.job.jid]
  if (dc.mapper_list[req.mapper_id].outstanding_req == req.job.split_size/4 ): # task is done, release mapper
    dc.mapper_list[req.mapper_id].outstanding_task.remove(req.task.task_id)
    dc.scheduler.slots[req.task.rack, req.task.cpu] = 0
    dc.mapper_list[req.mapper_id].outstanding_req = 0
    dc.lock.acquire()
    dc.jobStat.update(req.job.jid, finishTime) # update job finish time
    if dc.jobStat.isFinished(req.job.jid) and req.rtype == 'write': # finish write request
      dc.blk_dir.insertObj(req.job.objname, req.job.size, req.job.client,finishTime)
      dc.cache_layer['writeCache'].put(req.job.objname, req.job.size, dc.blk_dir)
    dc.lock.release()
    dc.scheduler.allocateJob()
    runMappers(dc, dc.scheduler, env)

def forwardRequest(req, dc, env):
  if (dc.placement == "consistent"):
    dest = dc.consistent_hash(req.name)
    if dest in req.path:
      req.path.append("DL")
      dc.datalake_access()
    else:
      req.path.append(dest)
      if dc.cache_layer[dest].cache.has_key(req.name):
        dc.cache_layer[dest].put(req.name, req.size, dc.blk_dir)
      else:
        req.path.append("DL")
        dc.datalake_access()

  elif (dc.placement == "directory"):
    if dc.blk_dir.haskey(req.name): # Cache Hit
      dest = dc.blk_dir.get_location(req.name) #
      req.path.append(dest)
      if dc.cache_layer[dest].has_key(req.name):
        dc.cache_layer[dest].put(req.name, req.size, dc.blk_dir)
        dc.blk_dir.put(req.name, req, req.dest, env.now)
    else: #Cache miss
       req.path.append("DL")
       dc.datalake_access()

def readReqEvent(req, dc, env):
  yield env.timeout(0)
  if dc.cache_layer[req.dest].has_key(req.name): # Local Cache Hit
    dc.cache_layer[req.dest].put(req.name, req.size, dc.blk_dir)
    dc.blk_dir.put(req.name, req, req.dest, env.now)
  else:
    forwardRequest(req, dc, env)
  generate_event(req, dc, env, 'readResponse')

def readResponseEvent(req, dc, env, links):
    source, dest = req.path[-1], req.path[-2]
    req.path.pop(len(req.path)-1)
    sLink, dLink = dc.get_link_id(source, dest)
    # Get the required amount of Bandwidth
    latency = 0
    if sLink:
      yield links[sLink].get(links[sLink].capacity)
      latency = float(req.job.size) / links[sLink].capacity
    if dLink:
      yield links[dLink].get(links[dLink].capacity)
      latency = max(float(req.job.size) / links[dLink].capacity, latency)

    yield env.timeout(latency)
    # Put the required amount of Bandwidth
    if sLink:
      yield links[sLink].put(links[sLink].capacity)
    if dLink:
      yield links[dLink].put(links[dLink].capacity)

    if (len(req.path) >= 2):
#      if req.name not in dc.cache_layer[dest].hashmap.keys():
      dc.cache_layer[req.dest].put(req.name, req.size, dc.blk_dir)
      dc.blk_dir.put(req.name, req, dest, env.now)
      generate_event(req, dc, env, "readResponse")

    else:
      req.path.pop(len(req.path)-1)
      completion(req,dc,env)

def writeReqEvent(req, dc, env, links):
  sLink, dLink = dc.get_link_id(req.path[-2], req.path[-1])
  # write 4MB chunk to local rack
  yield links[sLink].get(links[sLink].capacity)
  latency = float(req.size) / links[sLink].capacity
  yield env.timeout(latency)
  yield links[sLink].put(links[sLink].capacity)

  candidates = dc.get_replica_loc(req.dest)
  sLink, dLink = dc.get_link_id(req.dest, candidates[0])
  yield links[sLink].get(links[sLink].capacity)
  latency = float(dc.rep_size) / links[dLink].capacity
  yield env.timeout(latency)
  yield links[sLink].put(links[sLink].capacity)

#  for i in candidates:
#    sLink, dLink = dc.get_link_id(req.dest, i)
#    yield links[dLink].get(links[dLink].capacity)

#  for i in candidates:
#    sLink, dLink = dc.get_link_id(req.dest, i)
#    yield links[dLink].put(links[dLink].capacity)

  # write object and replicate to osd map, insert data to wb-cache and update directory
  dc.lock.acquire()
  candidates.append(req.dest)
  insert_osd_map(dc.osdMap, req.name, candidates, True)
  dc.blk_dir.put(req.name, req, 'writeCache', env.now)
  dc.lock.release()
  completion(req,dc,env)

def deleteReqEvent(req, dc, env):
  print('deleteReqEvent', req.job.objname)
  yield env.timeout(0)
  deleteObject(req, dc, env)
  completion(req, dc, env)

def deleteObject(req, dc, env):
  dc.lock.acquire()
  blk_loc = dc.blk_dir.get_all_blk_location(req.job.objname)
  for ind in blk_loc.index:
    for c in blk_loc[ind]:
      if c != 'writeCache':
        dc.cache_layer[c].remove(ind)
    dc.blk_dir.remove_block_entry(ind)
  if dc.blk_dir.haskeyObj(req.job.objname):

    dc.blk_dir.remove_obj_entry(req.job.objname)
    dc.cache_layer['writeCache'].remove(req.job.objname)
    delete_osd_map(dc.osdMap, req.job.objname)
  else:
    print('No nentry in OBJ dir', req.job.objname)
  dc.lock.release()

def flushEvent(dc, env, links): #flush based on FIFO
  count = 3
  time = 1
  candidates = dc.blk_dir.aged_items(time, count)

def generate_event(req_old, dc, env, event_type):
  req = copy.deepcopy(req_old)
  del req_old
  req.rtype = event_type
  req.set_startTime(env.now)
  if req.rtype == "read":
    event = env.process(readReqEvent(req, dc, env))
  elif req.rtype == "readResponse":
    env.process(readResponseEvent(req, dc, env, dc.links))
  elif req.rtype == "write":
    env.process(writeReqEvent(req, dc, env, dc.links))
  elif req.rtype == "delete":
    env.process(deleteReqEvent(req, dc, env))

def request_generator(mapper_id, dc, scheduler, env):
  q = dc.mapper_list[mapper_id].queue
  if q:
    if not dc.mapper_list[mapper_id].outstanding_task:
      task = q.popleft()
      dc.lock.acquire()
      if not (task.job.jid in dc.jobStat.df.index):
        dc.jobStat.insert(task.job.jid, task.job, env.now) # for job stats
      dc.mapper_list[mapper_id].outstanding_task.append(task.task_id)
      dc.lock.release()
      destination = "cache"+str(task.rack)
      source = task.mapper_id
      path = [source,destination]
      for i in range(task.offset, task.lenght, dc.chunk_size):
        scheduler.rid.increment()
        req_id = scheduler.rid.value()
        dc.lock.acquire()
        dc.outstanding_req[req_id] = [True, task.job.jid]
        dc.lock.release()
        req = Request(req_id, mapper_id, task , source, destination, path, i, dc.chunk_size, task.job.iotype)
  #      print("Request:", req.req_id, req.name, req.task.job.iotype, req.offset, req.end, mapper_id)
        generate_event(req, dc, env, task.job.iotype)
        if task.job.iotype == 'delete':
          break;


nm = input().split()
n = int(nm[0])
m = int(nm[1])
l=[0]*(n+1)
for _ in range(m):
    a,b,k=map(int, input().rstrip().split())
    for j in range(a,b+1):
            l[j]+=k
m=max(l[1:])
print(m)