from src.config.config import BLANK_DESCRIPTION
from src.encoder.create_encoder_from_path import create_encoder_from_path
from src.experiments.experiment_scripts.neural_nets.neural_net_configuration import (
    NNExpConf,
)
from src.experiments.experiment_scripts.neural_nets.neural_net_wrapper import (
    NNExpRunWrapper,
)
from src.experiments.experiment_scripts.neural_nets.use_lookup import use_lookup_seq
from src.experiments.experiment_scripts.types.experiment_types import ExperimentType
from src.experiments.helpers.experiment_summarization import ExperimentSummarization
from src.types.embedding_type import translate_from_embedding
from src.types.experiment_generator_part_type import ExperimentGeneratorPart
from src.types.experiment_summarization_fields import ExperimentSummarizationFields
from src.utils.create_experiment_id import create_experiment_id
from src.utils.get_train_test_valid_ds import get_train_test_valid_ds

class NNRunner:
    """Helper class which starts Transformer experiment.

    Firstly load data from configuration, then loads data, split, and one after one starts experiment with specified configuration.

    Same as TransformerRunner, ClassicRunner.
    """

    def __init__(
        self,
        experiment_type: ExperimentType,
        save_best: bool = False,
        save_model: bool = False,
        config_dict={},
    ) -> None:
        self.save_best = save_best
        self.save_model = save_model

        self.experiment_type = experiment_type

        self.config_object_getter = config_dict.get(self.experiment_type, None)

        if self.config_object_getter is not None:
            config_dict = self.config_object_getter()

            print(f"Loaded configuration {list(config_dict.keys())}")

            self.experiment_configurations, self.embeddding_index_dict = config_dict[
                ExperimentGeneratorPart.ExperimentConfiguration
            ]

            self.dataset_generator = config_dict[
                ExperimentGeneratorPart.DatasetGenerator
            ]

            self.experiment_type_str = self.experiment_type.value

            self.experiment_architectures = config_dict[
                ExperimentGeneratorPart.ExperimentArchitecture
            ]

    def run(self):
        if self.config_object_getter is None:
            print(f"Experiment was not specified well .. {self.config_object_getter}!")
            return

        for dataset_value in self.dataset_generator:
            if dataset_value is None:
                continue
            sets, loaded_data, paths, conf = dataset_value
            X_train, X_valid, X_test, y_train, y_valid, y_test = sets
            data_path, author_path = paths
            current_authors, current_sentences, current_preprocessing, norm_size = conf
            encoder = create_encoder_from_path(author_path)
            y_test = encoder.transform(y_test)
            y_train = encoder.transform(y_train)
            y_valid = encoder.transform(y_valid)

            (
                train_ds,
                val_ds,
                test_ds,
                train_records,
                valid_records,
                test_records,
            ) = get_train_test_valid_ds(
                X_train, X_valid, X_test, y_train, y_valid, y_test
            )

            for current_architecture in self.experiment_architectures:

                for conf_parameters in self.experiment_configurations:
                    (
                        vocab_size,
                        output_sequence_length,
                        trainable,
                        learning_settings,
                        embedding,
                    ) = conf_parameters
                    embedding_size, embedding_dictionary_name = embedding

                    try:

                        print("Settings = \n", learning_settings)
                        output_sequence_length = use_lookup_seq(
                            output_sequence_length,
                            current_authors,
                            current_sentences,
                            current_preprocessing,
                        )
                        if output_sequence_length is None:
                            print("Look up does not exists!")
                            continue

                        current_experiment_id = create_experiment_id(
                            self.experiment_type_str
                        )

                        embedding_type = translate_from_embedding(
                            embedding_dictionary_name
                        )

                        description = current_architecture.get_description(
                            current_experiment_id,
                            self.experiment_type_str,
                            current_authors,
                            current_sentences,
                            norm_size,
                            output_sequence_length,
                            trainable,
                            data_path,
                            learning_settings,
                            embedding_type,
                            vocab_size=vocab_size,
                            embedding_size=embedding_size,
                            embedding_name=embedding_dictionary_name,
                            preprocessing_type=current_preprocessing.value,
                        )

                        train_ds_trans = train_ds.batch(learning_settings.batch_size)
                        valid_ds_trans = val_ds.batch(1)
                        test_ds_trans = test_ds.batch(1)

                        current_model, stats = current_architecture.create_model(
                            current_authors,
                            train_ds,
                            val_ds,
                            vocab_size,
                            embedding_size,
                            output_sequence_length,
                            trainable,
                            self.embeddding_index_dict.get(
                                embedding_dictionary_name, None
                            ),
                        )

                        current_model.summary()

                        summarization = ExperimentSummarization(
                            experiment_id=current_experiment_id,
                            experiment_type=self.experiment_type_str,
                        )

                        summarization.set_records(
                            train_records, test_records, valid_records
                        )

                        if stats != BLANK_DESCRIPTION:
                            hits, misses = stats
                            summarization.state[
                                ExperimentSummarizationFields.MissingRatioTrain.value
                            ] = str((misses, hits, 100 * (misses / (hits + misses))))

                        summarization.state[
                            ExperimentSummarizationFields.EmbeddingSize.value
                        ] = embedding_size

                        nn_conf = NNExpConf(
                            nn_model=current_model,
                            train_ds=train_ds_trans,
                            valid_ds=valid_ds_trans,
                            test_ds=test_ds_trans,
                            learning_settings=learning_settings,
                            description=description,
                            save_model=self.save_model,
                            save_best=self.save_best,
                        )

                        wrapper = NNExpRunWrapper(current_experiment_id, summarization)

                        wrapper.run(nn_conf)

                    except Exception as e:
                        print(conf_parameters)
                        print(f"Error occured in {e}")


import socket

#при разрывах соед-я, перегрузах можем недополучать сообщ-е
#ф-я для допис-я ответа пока не получим полное сообщение
def myreceive(sock, msglen): # msglen - какой длины сообщ-е хотим получить, напр 1МБ
	msg = '' # received message
	while len(msg) < msglen:
		chunk = sock.recv(msglen-len(msg)) #get chunk of msg no more than осталось от  желаемого размера
		#print('chunk ', chunk)
		if chunk.decode() == '': # if get nothing then raise an error and try else
			raise RuntimeError("broken")
		msg = msg + chunk.decode() # otherwise append new part to already received part of message
		#print('msg is ', msg)
	return msg # when len msg = waited msglen

#клиент мб не готов принять все сообщ-е за раз => ф-я
def mysend(sock, msg):
	totalsent = 0
	while totalsent < len(msg):
		sent = sock.send(bytes(msg[totalsent:], 'utf-8')) # returns quantity of bytes successfully sent
		print('sent ', sent)
		if sent == 0:
			raise RuntimeError("broken")
		totalsent = totalsent + sent
		#return totalsent

HOST = '127.0.0.1'
PORT = 1234
LIMIT = 10

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

	s.bind((HOST, PORT))
	s.listen(LIMIT)
	while True:

		conn, addr = s.accept()
		#далее работает с этим клиентом,
		#остальные клиенты ждут в очереди = LIMIT
		# клиенту LIMIT+1 сервер откажет в соединении

		with conn:
			print('Connected by', addr)
			while True:

				#data = conn.recv(1024)
				#print(data.decode())
				data = myreceive(conn, 10) #чтобы получить точно 10 байт и не меньше
				print(data)

				if not data: break

				#conn.sendall(data) # echo-сервер отправляет те же данные что получил

				print('Your answer is ("answer #"): ')

				#data2 = bytes(input(), 'utf-8')
				#conn.sendall(data2)
				data2 = str(input()) #чтобы отправить точно полное сообщение и не меньше
				mysend(conn, data2)


class Solution:

    def __init__(self, rects: List[List[int]]):
        self.rects = rects
        self.range = []

        for i in range(len(rects)):
            num_points = (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1)
            self.range.append(num_points)

    def pick(self) -> List[int]:
        #returns a list with the randomly selected element from the specified sequence
        rect = random.choices(self.rects,self.range)[0]
        #returns an integer number selected element from the specified range.
        x = random.randint(rect[0], rect[2])
        y = random.randint(rect[1], rect[3])

        return [x,y]
# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick()


Sets = input()[1:-1]
left = True
i = 0
nums = []
while 1:
    if Sets[i] == "[":
        temp = ""
        while Sets[i] != "]":
            temp += Sets[i]
            i += 1
        temp += "]"
        nums.append(temp)
    else:
        i += 1
    if i == len(Sets):
        break
# print(nums)

def merge(Nums):
    for i in range(len(Nums)-1):
        From = Nums[i][1:-1].split(",")[0]
        To = Nums[i][1:-1].split(",")[1]
        NextF = Nums[i+1][1:-1].split(",")[0]
        NextT = Nums[i+1][1:-1].split(",")[1]
        if int(NextF) <= int(To):
            Nums[i] = "["+From+","+NextT+"]"
            Nums.remove(Nums[i+1])
            return True
    return False

for k in range(len(nums)-1):
    if not merge(nums):
        break
result = []
for s in nums:
    temp = []
    F = s[1:-1].split(",")[0]
    T = s[1:-1].split(",")[1]
    temp.append(int(F))
    temp.append(int(T))
    result.append(temp)
print(result)


import pathlib
from typing import Iterable
from src.utilis import list2sqlclass

class FileReader:

    def __init__(self, endpoint, end_signal=None, point_for_signal=None, signal=None,
                 data_class_for_converting=None):
        self._endpoint = endpoint
        self.point_for_signal = point_for_signal
        self.signal = signal
        self._end_signal = end_signal
        self.dataclass_for_converting = data_class_for_converting
        self._is_signal_sent = False

    def _send_maybe_signal(self, line: str):
        if self.point_for_signal is not None and line == self.point_for_signal:
            self._is_signal_sent = True
            yield self.signal
            return

        self._is_signal_sent = False
        return

    def read_generator_file(self, file_path: str):
        with pathlib.Path(file_path).open(mode="r") as f:
            line = f.readline().replace("\n", "")
            while line != self._endpoint:
                yield from self._send_maybe_signal(line)
                if not self._is_signal_sent:
                    values = line.split()
                    obj = list2sqlclass(values, self.dataclass_for_converting)
                    yield obj
                line = f.readline().replace("\n", "")
        yield self._end_signal
        return


a = int(input())
b = int(input())
arr = []

sum = 0
for i in range(a, b+1):
    cnt = 0
    if i == 1:
        continue
    for j in range(2, i):
        if i % j == 0:
            cnt += 1
            break
    if cnt == 0:
        sum += i
        arr.append(i)
if sum == 0:
    print(-1)
    exit()
print(sum)
print(arr[0])

baekjoon/lev 09. factors, multiples and decimals/2581.py


from random import SystemRandom

from pytezos.sandbox.node import SandboxedNodeTestCase
from pytezos import ContractInterface
from pytezos.michelson.parse import michelson_to_micheline
from pytezos.michelson.types.base import MichelsonType
from pytezos.crypto.key import Key

rnd = SystemRandom()

def get_random_key():
    curve = rnd.choice([b'ed', b'sp', b'p2'])
    return Key.generate(export=False, curve=curve)

class TestStateless(SandboxedNodeTestCase):

    def test_now(self):
        code = """
        parameter unit;
        storage timestamp;
        code { DROP ;
               NOW ;
               NIL operation ;
               PAIR }
        """
        contract = ContractInterface.from_michelson(code).using(shell=self.client.shell)
        now = self.client.now()
        res = contract.default().run_code()
        self.assertEqual(now, res.storage)

    def test_lazy_storage_diff(self):
        code = """
        { parameter string ;
          storage (big_map string nat) ;
          code { UNPAIR ;
                 SWAP ;
                 PUSH nat 1 ;
                 SOME ;
                 DIG 2 ;
                 UPDATE ;
                 NIL operation ;
                 PAIR } }
        """
        contract = ContractInterface.from_michelson(code).using(shell=self.client.shell)
        res = contract.default('hello').run_code()
        self.assertEqual({'hello': 1}, res.storage)
        self.assertEqual(1, len(res.lazy_diff))
        res1 = contract.default('hello').interpret()
        self.assertEqual({'hello': 1}, res1.storage)

    def test_map_order(self):
        self.bake_block()

        random_keys = [
            (i, get_random_key())
            for i in range(100)
        ]
        payload = {
            key.public_key(): i
            for i, key in random_keys
        }

        ty_expr = michelson_to_micheline('map key int')
        ty = MichelsonType.match(ty_expr)
        val_expr = ty.from_python_object(payload).to_micheline_value()

        self.client.shell.head.helpers.scripts.typecheck_data.post(dict(
            data=val_expr,
            type=ty_expr
        ))


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.text as mpl_text
import matplotlib.transforms as mpl_transforms

from .csc import reconstruct

def plot_atom_and_coefs(D_hat, z_hat, prefix):
    n_atoms = D_hat.shape[0]

    E = np.sum(z_hat > 0, axis=(1, 2))
    i0 = E.argsort()[::-1]

    n_cols = 5
    n_rows = int(np.ceil(n_atoms / n_cols))
    fig = plt.figure(figsize=(3*n_cols + 2, 3*n_rows + 2))
    fig.patch.set_alpha(0)
    for i in range(n_rows):
        for j in range(n_cols):
            if n_cols * i + j >= n_atoms:
                continue
            k = i0[n_cols * i + j]
            ax = plt.subplot2grid((n_rows, n_cols), (i, j))
            scale = 1 / D_hat[k].max() * .99
            Dk = np.clip(scale * D_hat[k].swapaxes(0, 2), 0, 1)
            ax.imshow(Dk)
            ax.axis('off')
    fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95,
                        wspace=.1, hspace=.1)

    fig.savefig(f"hubble/{prefix}dict.pdf", dpi=300,
                bbox_inches='tight', pad_inches=0)

    fig = plt.figure()
    fig.patch.set_alpha(0)
    plt.imshow(z_hat.sum(axis=0).T > 0, cmap='gray')
    plt.axis('off')
    fig.tight_layout()
    fig.savefig(f"hubble/{prefix}z_hat.pdf", dpi=1200,
                bbox_inches='tight', pad_inches=0)

    fig = plt.figure()
    fig.patch.set_alpha(0)
    X_hat = np.clip(reconstruct(z_hat, D_hat), 0, 1)
    plt.imshow(X_hat.swapaxes(0, 2))
    plt.axis('off')
    fig.tight_layout()
    fig.savefig(f"hubble/{prefix}X_hat.pdf", dpi=1200,
                bbox_inches='tight', pad_inches=0)

def display_atom(atom, ax=None, style=None):
    """Display one atom in 1D/2D with the correct formating.

    * For 1D atom, plot all the signals of all channels.
    * For 2D atom, show the image with the correct cmap for
      grayscale image with only 1 channel.

    Parameters
    ----------
    atom: ndarray, shape (n_channels, *atom_support)
        Atom to display. This should be a 1D or 2D multivariate atom.
    ax: mpl.Axes or None
        Matplotlib axe to plot the atom.
    style: dict or None
        Style info for the atom. Can include color, linestyle, linewidth, ...
    """
    if style is None:
        style = {}
    if ax is None:
        fig, ax = plt.subplots(111)

    if atom.ndim == 2:
        ax.plot(atom.T, **style)
    elif atom.ndim == 3:
        cmap = 'gray' if atom.shape[0] == 1 else None
        atom = np.rollaxis(atom, axis=0, start=3).squeeze()
        ax.imshow(atom, cmap=cmap)
        ax.set_xticks([])
        ax.set_yticks([])
        for spine in ax.spines.values():
            spine.set(**style)
    else:
        raise ValueError(
            'display_atom utility can only be used for multivariate atoms in '
            f'1D or 2D. Got atom with shape {atom.shape}'
        )

def display_dictionaries(*list_D, styles=None, axes=None, filename=None):
    """Display utility for dictionaries

    Parameters
    ----------
    list_D: List of ndarray, shape (n_atoms, n_channels, *atom_support)
        Dictionaries to display in the figure.
    styles: Dict of style or None
        Style to display an atom

    """
    n_dict = len(list_D)
    D_0 = list_D[0]

    if styles is None and n_dict >= 1:
        styles = [dict(color=f'C{i}') for i in range(n_dict)]

    # compute layout
    n_atoms = D_0.shape[0]
    n_cols = max(4, int(np.sqrt(n_atoms)))
    n_rows = int(np.ceil(n_atoms / n_cols))

    if axes is None:
        fig, axes = plt.subplots(ncols=n_cols, nrows=n_dict * n_rows,
                                 squeeze=False)
    else:
        assert axes.shape >= (n_rows*n_dict, n_cols), (
            f"axes argument should have at least shape ({n_rows*n_dict}, "
            f"{n_cols}). Got {axes.shape}."
        )
        fig = axes[0, 0].get_figure()

    used_axes = 0
    for id_ax, D in enumerate(zip(*list_D)):
        used_axes += 1
        i, j = np.unravel_index(id_ax, (n_rows, n_cols))
        for k, (dk, style) in enumerate(zip(D, styles)):
            ik = n_dict * i + k
            ax = axes[ik, j]
            display_atom(dk, ax=ax, style=style)

    # hide the unused axis
    for id_ax in range(used_axes, n_cols * n_rows):
        i, j = np.unravel_index(id_ax, (n_rows, n_cols))
        for k in range(n_dict):
            ik = n_dict * i + k
            axes[ik, j].set_axis_off()

    if filename is not None:
        fig.savefig(f'{filename}.pdf', dpi=300)

    return fig

def median_curve(times, pobj):
    """Compute the Median curve, given a list of curves and their timing.

    Parameters
    ----------
    times : list of list
        Time point associated to pobj
    pobj : list of list
        Value of the cost function at a given time.

    Returns
    -------
    t: ndarray, shape (100,)
        Time points for the curve
    median_curve: ndarray, shape (100)
        Median value for the curves
    """
    T = np.max([np.max(tt) for tt in times])
    # t = np.linspace(0, T, 100)
    t = np.logspace(-1, np.log10(T), 100)
    curves = []
    for lt, lf in zip(times, pobj):
        curve = []
        for tt in t:
            i0 = np.argmax(lt > tt)
            if i0 == 0 and tt != 0:
                value = lf[-1]
            elif i0 == 0 and tt == 0:
                value = lf[0]
            else:
                value = (lf[i0] - lf[i0-1]) / (lt[i0] - lt[i0-1]) * (
                    tt - lt[i0-1]) + lf[i0-1]
            curve.append(value)
        curves.append(curve)
    return t, np.median(curves, axis=0)

class RotationAwareAnnotation(mpl_text.Annotation):
    """Text along a line that self adapt to rotation in the figure.

    this class is derived from the SO answer:
    https://stackoverflow.com/questions/19907140/keeps-text-rotated-in-data-coordinate-system-after-resizing#53111799

    Parameters
    ----------
    text: str
        Text to display on the figure
    anchor_point: 2-tuple
        Position of this text in the figure. The system of coordinates used to
        translate this position is controlled by the parameter ``xycoords``.
    next_point: 2-tuple
        Another point of the curve to follow. The annotation will be written
        along the line of slope dy/dx where dx = next_pt[0] - anchor_pt[0] and
        dy = next_pt[1] - anchor_pt[1].
    ax: Artiste or None
        The Artiste in which the
    **kwargs: dict
        Key-word arguments for the Annotation. List of available kwargs:
        https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.annotate.html
    """

    def __init__(self, text, anchor_pt, next_pt, ax=None, **kwargs):
        # Get the Artiste to draw on
        self.ax = ax or plt.gca()

        # Save the anchor point
        self.anchor_pt = np.array(anchor_pt)[None]

        # Compute the slope of the text in data coordinate system.
        dx = next_pt[0]-anchor_pt[0]
        dy = next_pt[1]-anchor_pt[1]
        ang = np.arctan2(dy, dx)
        self.angle_data = np.rad2deg(ang)

        # Create the text objects and display it
        kwargs.update(rotation_mode=kwargs.get("rotation_mode", "anchor"))
        kwargs.update(annotation_clip=kwargs.get("annotation_clip", True))
        super().__init__(text, anchor_pt, **kwargs)
        self.set_transform(mpl_transforms.IdentityTransform())
        self.ax._add_text(self)

    def _get_rotation(self):
        return self.ax.transData.transform_angles(
            np.array((self.angle_data,)), self.anchor_pt)[0]

    def _set_rotation(self, rotation):
        pass

    _rotation = property(_get_rotation, _set_rotation)


from django.http import HttpResponse
from django.shortcuts import redirect, render

from .forms import ProjectForm
from .models import Project

def projects(request):
    projects = Project.objects.all()
    context = {'projects': projects}
    return render(request, 'projects/projects.html', context)

def project(request, pk):
    projectObj = Project.objects.get(id=pk)
    #tags = projectObj.tags.all()
    print('projectObj :', projectObj)
    return render(request, 'projects/project.html', {'project': projectObj})

    # return render(request, 'projects/project.html', {'project': projectObj, 'tags': tags})

def createProject(request):
    form = ProjectForm()

    if request.method == 'POST':
        # print(request.POST)
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('projects')

    context = {'form': form}
    return render(request, 'projects/project_form.html', context)

def updateProject(request, pk):
    project = Project.objects.get(id=pk)
    form = ProjectForm(instance=project)

    if request.method == 'POST':
        # print(request.POST)
        form = ProjectForm(request.POST, request.FILES, instance=project)
        if form.is_valid():
            form.save()
            return redirect('projects')

    context = {'form': form}
    return render(request, 'projects/project_form.html', context)

def deleteProject(request, pk):
    project = Project.objects.get(id=pk)
    if request.method == 'POST':
        project.delete()
        return redirect('projects')
    context = {'object': project}
    return render(request, 'projects/delete_template.html', context)

# projectList = [
#
#    {
#        'id': '1',
#        'title': 'Ecommerce Website',
#        'description': 'Fully functional Ecommerce website'
#    },
#
#    {
#        'id': '2',
#        'title': 'Portfolio Website',
#        'description': 'A personal website to write articles and display work'
#    },
#
#    {
#        'id': '3',
#        'title': 'Social Network',
#        'description': 'An open source project built by the community'
#    },
#
# ]
#
# projectList = [
#    {
#        'id': '1',
#        'title': 'Ecommerce Website',
#        'description': 'Fully functional Ecommerce website',
#    },
#    {
#        'id': '2',
#        'title': 'Portfolio Website',
#        'description': 'Fully functional Portfolio website',
#    },
#    {
#        'id': '3',
#        'title': 'Social Website',
#        'description': 'Fully functional Social website',
#    },
# ]


#!/usr/bin/env python3
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path

import pytemscript
from pytemscript import __version__

here = path.abspath(path.dirname(__file__))

# Long description
with open(path.join(here, "README.rst"), "r", encoding="utf-8") as fp:
    long_description = fp.read()

setup(name='pytemscript',
      version=__version__,
      description='TEM Scripting adapter for FEI/TFS microscopes',
      author='Tore Niermann, Grigory Sharov',
      author_email='tore.niermann@tu-berlin.de, gsharov@mrc-lmb.cam.ac.uk',
      long_description=long_description,
      packages=['pytemscript'],
      platforms=['any'],
      license="GNU General Public License v3 (GPLv3)",
      python_requires='>=3.4',
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Intended Audience :: Science/Research',
          'Intended Audience :: Developers',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 3',
          'Topic :: Scientific/Engineering',
          'Topic :: Software Development :: Libraries',
          'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
          'Operating System :: OS Independent'
      ],
      install_requires=['comtypes'],
      entry_points={'console_scripts': ['pytemscript-server = pytemscript.server:run_server']},
      url="https://github.com/azazellochg/pytemscript",
      project_urls={
          "Source": "https://github.com/azazellochg/pytemscript",
          "Documentation": "https://pytemscript.readthedocs.io/"
      }
      )


def descb_func():
    from Crypto.Cipher import DES

    def pad(text):
        n = len(text) % 8
        return text + (b' ' * n)

    try:
        print('ENCRYPTION')
        text1 = input("NOTE:Secret message and key must be 8 or 16 bytes\nSecret Message :")
        key = input("Key :")
        des = DES.new(key.encode(), DES.MODE_ECB)
        padded_text = pad(text1.encode())
        encrypted_text = des.encrypt(padded_text)
        print(str(encrypted_text)[2:-1])

        print('\nDECRYPTION')
        aaa=des.decrypt(encrypted_text)
        print(str(aaa)[2:-1])
    except:
        print("Wrong Value..!")


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

import cv2
import numpy as np

# 鼠标按下是转为true
drawing = False
# true 绘制矩形 键盘 m 控制
mode = True
ix, iy=-1, -1

def draw_circle_rect(event, x, y, flags, param):
    global ix, iy, drawing, mode

    # 左键
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    if event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        if drawing == True:
            if mode == True:
                cv2.rectangle(img, (ix, iy), (x, y), (0,255,0), 1)
            else:
                cv2.circle(img, (x,y), 3, (0,0,255), 1)
    if event == cv2.EVENT_LBUTTONUP:
        drawing = False

# 创建图像窗口并将窗口与回调函数绑定
img = np.zeros((400, 600, 3), np.uint8)
cv2.namedWindow('canvas')
cv2.setMouseCallback('canvas', draw_circle_rect)

while(True):
    cv2.imshow('canvas', img)
    key = cv2.waitKey(10) & 0xFF
    if key == ord('m'):
        mode = not mode
    if key == 27:
        break

cv2.destroyAllWindows()


All = int(input())

for q in range(0, All):
    s=input()
    stack=[]
    ans=0
    for c in s:
        if c=='(':
            stack.append(c)
        elif c==')':
            if len(stack)!=0:
                ans+=2
                stack.pop()
    print(ans)


import re
import torch
import torch.distributed

from typing import List, Optional, Type

from transformers import (
    AutoTokenizer,
    AutoConfig,
    PreTrainedTokenizerBase,
)
from text_generation_server.models import CausalLM
from text_generation_server.models.causal_lm import CausalLMBatch
from text_generation_server.pb import generate_pb2
from text_generation_server.models.custom_modeling.opt_modeling import OPTForCausalLM
from text_generation_server.utils import (
    NextTokenChooser,
    StoppingCriteria,
    initialize_torch_distributed,
    weight_files,
    Weights,
)

# CREDIT: Papers with code => https://github.com/paperswithcode/galai/blob/main/galai/utils.py

# we split individual characters inside special tokens like [START_DNA]
CUSTOM_SEQ_RE = re.compile(r"(\[START_(DNA|SMILES|I_SMILES|AMINO)])(.*?)(\[END_\2])")

# token added to implement a custom sequence tokenization. This token is added at
# corpus cleaning step and removed in pretokenization. The digits are added to increase the chance
# that they do not occur in the corpus. The digits are escaped so that the token does not appear
# literally in the source code in case we ever include it in the training data.
SPLIT_MARKER = f"SPL{1}T-TH{1}S-Pl3A5E"

def _insert_split_marker(m: re.Match):
    """
    Applies split marker based on a regex match of special tokens such as
    [START_DNA].
    Parameters
    ----------
    n : str
        Input text to split
    Returns
    ----------
    str - the text with the split token added
    """
    start_token, _, sequence, end_token = m.groups()
    sequence = re.sub(r"(.)", rf"{SPLIT_MARKER}\1", sequence, flags=re.DOTALL)
    return f"{start_token}{sequence}{SPLIT_MARKER}{end_token}"

def escape_custom_split_sequence(text):
    """
    Applies custom splitting to the text for GALILEO's tokenization
    Parameters
    ----------
    text : str
        Input text to split
    Returns
    ----------
    str - the text with the split token added
    """
    return CUSTOM_SEQ_RE.sub(_insert_split_marker, text)

# END CREDIT

class GalacticaCausalLMBatch(CausalLMBatch):
    @classmethod
    def from_pb(
        cls,
        pb: generate_pb2.Batch,
        tokenizer: PreTrainedTokenizerBase,
        dtype: torch.dtype,
        device: torch.device,
    ) -> "GalacticaCausalLMBatch":
        inputs = []
        next_token_choosers = []
        stopping_criterias = []
        prefix_offsets = []
        top_n_tokens = []
        read_offsets = []
        requests_idx_mapping = {}

        # Parse batch
        max_truncation = 0
        padding_right_offset = 0
        max_decode_tokens = 0
        for i, r in enumerate(pb.requests):
            requests_idx_mapping[r.id] = i
            # Add escape_custom_split_sequence to the CausalLMBatch logic
            inputs.append(escape_custom_split_sequence(r.inputs))
            next_token_choosers.append(NextTokenChooser.from_pb(r.parameters, device))
            stopping_criteria = StoppingCriteria.from_pb(
                r.stopping_parameters, tokenizer
            )
            stopping_criterias.append(stopping_criteria)
            top_n_tokens.append(r.top_n_tokens)
            max_truncation = max(max_truncation, r.truncate)
            max_decode_tokens += stopping_criteria.max_new_tokens
            padding_right_offset = max(
                padding_right_offset, stopping_criteria.max_new_tokens
            )

        tokenized_inputs = tokenizer(
            inputs,
            return_tensors="pt",
            padding=True,
            return_token_type_ids=False,
            truncation=True,
            max_length=max_truncation,
        ).to(device)
        for _ in pb.requests:
            input_len = tokenized_inputs["input_ids"].shape[1]
            prefix_offsets.append(0)
            read_offsets.append(input_len)

        input_lengths = tokenized_inputs["attention_mask"].sum(1)
        max_input_length = input_lengths.max()

        input_ids = tokenized_inputs["input_ids"]
        # Allocate maximum attention_mask
        attention_mask = input_ids.new_zeros(
            (pb.size, max_input_length + padding_right_offset)
        )
        # Copy tokenizer attention_mask into fully allocated attention_mask
        attention_mask[:, :max_input_length] = tokenized_inputs["attention_mask"]

        position_ids = tokenized_inputs["attention_mask"].long().cumsum(-1) - 1
        position_ids.masked_fill_(tokenized_inputs["attention_mask"] == 0, 1)
        all_input_ids = tokenized_inputs["input_ids"].T.split(1, dim=1)
        top_n_tokens_tensor = torch.tensor(
            top_n_tokens, device=device, dtype=torch.int64
        )

        max_tokens = len(inputs) * max_input_length + max_decode_tokens

        return cls(
            batch_id=pb.id,
            requests=pb.requests,
            requests_idx_mapping=requests_idx_mapping,
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=None,
            all_input_ids=list(all_input_ids),
            input_lengths=input_lengths.tolist(),
            prefix_offsets=prefix_offsets,
            read_offsets=read_offsets,
            next_token_choosers=next_token_choosers,
            stopping_criterias=stopping_criterias,
            top_n_tokens=top_n_tokens,
            top_n_tokens_tensor=top_n_tokens_tensor,
            max_input_length=max_input_length.item(),
            padding_right_offset=padding_right_offset,
            max_tokens=max_tokens,
        )

class GalacticaSharded(CausalLM):
    def __init__(
        self,
        model_id: str,
        revision: Optional[str] = None,
        quantize: Optional[str] = None,
        dtype: Optional[torch.dtype] = None,
        trust_remote_code: bool = False,
    ):
        self.process_group, rank, world_size = initialize_torch_distributed()
        if torch.cuda.is_available():
            device = torch.device(f"cuda:{rank}")
            dtype = torch.float16 if dtype is None else dtype
        else:
            device = torch.device("cpu")
            dtype = torch.float32 if dtype is None else dtype

        tokenizer = AutoTokenizer.from_pretrained(
            model_id,
            revision=revision,
            padding_side="left",
            truncation_side="left",
            trust_remote_code=trust_remote_code,
        )

        config = AutoConfig.from_pretrained(
            model_id,
            revision=revision,
            tp_parallel=True,
            trust_remote_code=trust_remote_code,
        )
        config.quantize = quantize
        tokenizer.pad_token_id = config.pad_token_id

        torch.distributed.barrier(group=self.process_group)
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
        weights = Weights(
            filenames, device=device, dtype=dtype, process_group=self.process_group
        )
        if config.quantize == "gptq":
            weights._set_gptq_params(model_id)

        model = OPTForCausalLM(config, weights)

        torch.distributed.barrier(group=self.process_group)
        super(CausalLM, self).__init__(
            model=model,
            tokenizer=tokenizer,
            requires_padding=True,
            dtype=dtype,
            device=device,
            rank=rank,
            world_size=world_size,
        )

    @property
    def batch_type(self) -> Type[CausalLMBatch]:
        return GalacticaCausalLMBatch

    def decode(self, generated_ids: List[int]) -> str:
        # Do not skip special tokens as they are used for custom parsing rules of the generated text
        return self.tokenizer.decode(
            generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
        )

    def forward(
        self, input_ids, attention_mask, position_ids, past_key_values: Optional = None
    ):
        outputs = self.model.forward(
            input_ids=input_ids,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            use_cache=True,
        )
        return outputs.logits, outputs.past_key_values


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

import re
import webbrowser
import sublime
import sublime_plugin
from . import mw_utils as utils
from . import mw_html

class MediawikerChangelogCommand(sublime_plugin.TextCommand):

    DRAW_TYPE = sublime.HIDDEN + sublime.PERSISTENT

    def run(self, edit, version='sublime'):
        self.MARKED = utils.props.get_setting('config_icon_checked')
        self.UNMARKED = utils.props.get_setting('config_icon_unchecked')
        self.RADIO_MARKED = utils.props.get_setting('config_icon_radio_checked')
        self.RADIO_UNMARKED = utils.props.get_setting('config_icon_radio_unchecked')
        self.EDIT_ICON = utils.props.get_setting('config_icon_edit')
        self.BACK_ICON = utils.props.get_setting('config_icon_back')
        self.LIST_ICON = utils.props.get_setting('config_icon_unnumbered_list')

        self.html = mw_html.MwHtmlAdv(html_id='mediawiker_changelog', user_css=False)
        self.set_css()
        # self.html.debug = True

        with open(utils.p.from_package('Changelog.mediawiki', posix=False, is_abs=True), 'r', encoding='utf-8') as cl:
            log = cl.read()

        self.process_h2_regions(log, 2, version)

    def set_css(self):
        base_font_size = self.html.css_rules['body']['font-size']
        self.html.css_rules['body']['padding'] = '20px'
        self.html.css_rules['h2'] = {'font-size': self.html.get_font_size(base_font_size, 0.4), 'color': '#81CFE0'}
        self.html.css_rules['h3'] = {'font-size': self.html.get_font_size(base_font_size, 0.2), 'font-weight': 'none'}
        self.html.css_rules['h4'] = {'font-size': self.html.get_font_size(base_font_size, 0.1), 'font-weight': 'none'}
        self.html.css_rules['h5'] = {'font-size': self.html.get_font_size(base_font_size, 0.1), 'font-weight': 'bold'}
        self.html.css_rules['.kbd'] = {'color': '#A6C8AA', 'font-weight': 'bold', 'font-size': self.html.get_font_size(base_font_size, 0.1)}
        self.html.css_rules['.success2'] = {'padding': '5px', 'color': self.html.css_rules['.success']['color']}
        self.html.css_rules['.undefined'] = {'padding': '5px', 'color': '#c0c0c0'}
        self.html.css_rules['.command'] = {'color': '#7D9DF8', 'font-weight': 'bold'}
        self.html.css_rules['.snippet'] = {'color': '#8CCAC8', 'font-weight': 'none'}
        self.html.css_rules['.property'] = {'color': '#A2DED0', 'font-weight': 'none'}
        self.html.css_rules['.tag'] = {'color': '#FDE3A7', 'font-weight': 'none'}
        self.html.css_rules['.note_base'] = {
            'background-color': '#0F4026',
            'border-radius': '4px',
            'margin': '1rem'
        }
        self.html.css_rules['.note_head'] = {
            'border-top-left-radius': '4px',
            'border-top-right-radius': '4px',
            'padding': '0.2rem 0.2rem 0.2rem 0.7rem',
            'display': 'block',
            'background-color': '#83C6A3',
            'color': '#0F4026',
            'font-weight': 'bold'
        }
        self.html.css_rules['.note'] = {
            'color': '#c8f7c5',
            'border-bottom-left-radius': '4px',
            'border-bottom-right-radius': '4px',
            'padding': '0.7rem',
            'display': 'block'
        }

    def process_h2_regions(self, data, level, version):
        # group 1: header name
        # group 2: header data

        data = self.process_urls(data)
        data = self.process_kbd(data)
        data = self.process_templates(data)
        data = self.process_src(data)
        data = self.process_decoration(data)
        data = self.process_headers(data, 3)
        data = self.process_headers(data, 4)
        data = self.process_headers(data, 5)
        data = self.process_lists(data)

        blocks = []
        pattern = r'^={%(level)s}([^=]+)={%(level)s}\s?\n((.|\n)*?)(?=(^={%(level)s}[^=]|\Z))' % {'level': level}
        headers = reversed(re.findall(pattern, data, re.MULTILINE))
        if headers:
            for r in headers:
                blocks.append(self.html.h2(r[0]))
                blocks.append(r[1])
        html = self.html.build(blocks)

        if version == 'sublime':
            view = sublime.active_window().new_file()
            view.set_name('{} changelog'.format(utils.p.PM))
            view.settings().set('gutter', False)
            view.settings().set('word_wrap', True)
            view.settings().set('wrap_width', 120)
            view.add_phantom('changelog', view.sel()[0], html, sublime.LAYOUT_INLINE, on_navigate=self.on_navigate)
            view.set_scratch(True)
        elif version == 'browser':
            preview_file = utils.p.from_package('{}_changelog.html'.format(utils.p.PML), name='User', posix=False, is_abs=True)
            html = html.replace('', '<meta charset="UTF-8"/>')
            with open(preview_file, 'w', encoding='utf-8') as tf:
                tf.write(html)

            webbrowser.open('file://{}'.format(tf.name))

    def on_navigate(self, url):
        webbrowser.open(url)

    def escape(self, line):
        return line.replace(' ', ' ').replace('<', '<').replace('>', '>')

    def process_urls(self, data):

        def url(m):
            if not m.group(2):
                url_name = m.group(1)
            else:
                url_name = m.group(2)
            return self.html.link(m.group(1), url_name)

        lines = []
        pattern = r'\[{1}([^\[\]]+?)\s([^\[\]]+)?\]{1}'
        for line in data.splitlines():
            line = re.sub(pattern, url, line)
            lines.append(line)
        return '\n'.join(lines)

    def process_kbd(self, data):
        '''  => <tt> '''
        lines = []
        for line in data.splitlines():
            line = line.replace('', '<tt class="kbd">').replace('', '</tt>')
            lines.append(line)
        return '\n'.join(lines)

    def process_templates(self, data):
        ''' templates => plugin commands '''

        def repl(m):
            return self.html.code(m.group(2), css_class=m.group(1).lower()) if m else ''

        def repl_note(m):

            return self.html.note('Note', m.group(2)) if m else ''

        lines = []
        # pattern = r'\{{2}(%s)\|([^\{\}]+)\}{2}'
        pattern = r'\{{2}(%s)\|([^\{\}]+)\}{2}'

        for line in data.splitlines():
            line = re.sub(pattern % 'Command', repl, line)
            line = re.sub(pattern % 'Snippet', repl, line)
            line = re.sub(pattern % 'Property', repl, line)
            line = re.sub(pattern % 'Tag', repl, line)
            line = re.sub(pattern % 'Note', repl_note, line)
            lines.append(line)
        return '\n'.join(lines)

    def process_src(self, data):
        lines = []
        lines_src = []
        is_source = False
        for line in data.splitlines():

            if line.startswith('<source') and line.endswith('">'):
                is_source = True
                continue
            if line.startswith('</source>'):
                is_source = False
                src = '\n
'.join(lines_src)
                lines_src = []
                lines.append(self.html.note('Source', src, code=True))
                continue

            if is_source:
                lines_src.append(self.escape(line))
            else:
                lines.append(line)

        return '\n'.join(lines)

    def process_headers(self, data, lvl):
        lines = []
        pattern = r'^={%(level)s}([^=]+)={%(level)s}\s?$' % {'level': lvl}

        for line in data.splitlines():
            header = re.search(pattern, line)
            if header:
                h = header.group(1)
                line = self.html.h(lvl, h)
            lines.append(line)

        return '\n'.join(lines)

    def process_decoration(self, data):
        lines = []
        pattern_b = r'\'{3}([^\']+)\'{3}'
        pattern_i = r'\'{2}([^\']+)\'{2}'

        for line in data.split('\n'):
            line = re.sub(pattern_b, self.html.b(r'\1'), line)
            line = re.sub(pattern_i, self.html.i(r'\1'), line)
            lines.append(line)

        return '\n'.join(lines)

    def process_lists(self, data):
        lines = []
        lvl = 0
        for line in data.splitlines():
            if line.startswith(('*', ':')):
                line_lvl = len(line) - len(line.lstrip('*:'))
                if line_lvl > lvl:
                    # TODO: make sub uls inside li tag
                    # lines.append('
') if line_lvl > 1 else ''
                    lines.append(self.html.ul())
                elif line_lvl < lvl:
                    lines.append(self.html.ul(True))
                    # lines.append('
') if lvl > 1 else ''
                lvl = line_lvl
                if line.startswith('*'):
                    line = self.html.li(line[line_lvl:].strip(), icon=self.LIST_ICON, css_class='undefined')
                elif line.startswith(':'):
                    line = self.html.li(line[line_lvl:].strip(), icon=None)
            else:
                if lvl and not line.startswith(('*', ':')):
                    lines.append(self.html.ul(True) * lvl)
                    lvl = 0
            lines.append(line)

        if lvl:
            lines.append(self.html.ul(True) * lvl)
        return '\n'.join(lines)


list1= [10, 20, 0, 40, 0]
def test():
    try:
        var1 = 3
        if (list1[var1]/list1[var1 + 1] > 1): #The division by list1 [var1 + 1] is actually zero, hence it is ZeroDivision Error
            value = var1 + 1
    except ZeroDivisionError:
        print("1")
    except IndexError:
        print("2")
    finally:
        print("4")
    print("5")
test()


"""Draw blue circles upon mouse double click."""
from cvlib import *

w, h = 600, 300

# mouse callback function
def draw_circle(event, x, y, flags, param):
    if event == cv.EVENT_LBUTTONDBLCLK:
        cv.circle(img, (x, y), 50, BLUE, -1)

# Create a black image, a window and bind the function to window
img = np.zeros((h, w, 3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image', draw_circle)

while(1):
    cv.imshow('image', img)
    if cv.waitKey(20) & 0xFF == 27:
        break
cv.destroyAllWindows()


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics.pairwise import pairwise_distances
import networkx as nx
import itertools
from networkx.drawing.nx_agraph import graphviz_layout
from __future__ import division
import collections
from networkx.algorithms.richclub import rich_club_coefficient
import seaborn as sns
import random
import math
from operator import itemgetter
from community import community_louvain
from networkx.algorithms import community
from itertools import count
import community
from math import floor

def Hist_degree(G,prob, Rand, Type):
    """ Plots the degree distribution of the directed graph G and of a random network.
    Inputs:
        G : directed graph
        prob: probability to add an edge between a pair of nodes in the Erdos Renyi model
        Rand: type of random model: CM (configuration model) or ER (Erdos-Renyi) or WS (Watts-Strogatz) or BA (Bbarabasi-Albert)
        Type: type of degree to be plotted: degree (both), in-degree (in) or out-degree (out)
    """

    if Rand=="ER":
        # erdos renyi
        random_graph= nx.erdos_renyi_graph(n= len(G), p= prob, directed = True)

    elif Rand=='CM':
        #configuration model
        random_graph= nx.configuration_model(sorted([d for n, d in G.degree()]))
    elif Rand=='WS':
        # watts strogatz model
        random_graph= nx.watts_strogatz_graph(n= len(G), k=floor(stat.mean(sorted([d for n, d in G.degree()]))), p=prob)
    else:
        # barabasi albert graph
                random_graph= nx.barabasi_albert_graph(n= len(G), m=floor(stat.mean(sorted([d for n, d in G.degree()]))))

    if Type == 'out':
        out_list =[]
        out_list_r = []
        for elmt in G.out_degree:
            out_list.append(elmt[1])

        for relmt in random_graph.out_degree :
            out_list_r.append(relmt[1])
        x1 = pd.Series(out_list_r)
        x2 = pd.Series(out_list)

        newbins = np.arange(min(x2), max(x2), 1)
        plt.hist(x1, density=True, bins = newbins,alpha=0.5, color = 'grey')
        plt.hist(x2, density=True, bins = newbins, alpha=0.3, color='blue')
        plt.title('Out degree distribution')
        plt.xlabel('out degree')
        plt.ylabel('density')

    if Type == 'in':
        in_list =[]
        in_list_r = []
        for elmt in G.in_degree:
            in_list.append(elmt[1])
        for relmt in random_graph.in_degree :
            in_list_r.append(relmt[1])
        x1 = pd.Series(in_list_r)
        x2 = pd.Series(in_list)

        newbins = np.arange(min(x2), max(x2), 1)
        plt.hist(x1, density=True, bins = newbins,alpha=0.5, color = 'grey')
        plt.hist(x2, density=True, bins = newbins,alpha=0.3, color='green')
        plt.title('In degree distribution')
        plt.xlabel('In degree')
        plt.ylabel('density')

    if Type == 'both':
        random_graph.to_undirected()
        both_list =[]
        both_list_r =[]
        for elmt in G.degree():
            both_list.append(elmt[1])
        for relmt in random_graph.degree :
            both_list_r.append(relmt[1])

        x1 = pd.Series(both_list_r)
        x2 = pd.Series(both_list)
        newbins = np.arange(min(x2), max(x2), 1)
        plt.hist(x1, density=True,bins = newbins, alpha=0.5, color = 'grey')
        plt.hist(x2, density=True, bins = newbins,alpha=0.3, color='red')
        plt.title('Degree distribution')
        plt.xlabel('degree')
        plt.ylabel('density')

    plt.legend(['random graph distribution', 'degree distribution'])

    return x2 , x1, random_graph


# simple_calculator.py

# Let's write a simple REPL (read evaluate print loop) calculator that can handle addition, subtraction, multiplication, and division.
# Ask the user for an operator and each operand. Don't forget that input returns a string, which you can convert to a float using float(user_input) where user_input is the string you got from input. Below is some sample input/output.

import sys

def operator(num1, num2):
    if user_operation == "+":
        calculation = num1 + num2
        return calculation
    if user_operation == "-":
        calcluation = num1 - num2
        return calculation
    if user_operation == "*":
        calculation = num1 * num2
        return calculation
    if user_operation == "/":
        calculation = num1 / num2
        return calculation

operator_list = ["+", "-", "*", "/"]

while True:
    user_operation = input("\nWhat is the operation you would like to perform? Type \"done\" if you are finished.\n")
    if user_operation in operator_list:
        pass
    elif user_operation == "done":
        break
    else:
        print("\nYou did not enter a correct operator value. Please start over and try again.\n")
        sys.exit()
    user_num1 = input("What is the first number?")
    user_num1 = float(user_num1)
    user_num2 = input("What is the second number?")
    user_num2 = float(user_num2)
    calculation = operator(user_num1, user_num2)
    print(f"Your calculation is {calculation}")


from .models import SpotifyToken
from django.utils import timezone
from datetime import timedelta
from .credentials import CLIENT_ID, CLIENT_SECRET
from requests import post, put, get
import math

BASE_URL = "http://api.spotify.com/v1/me/"

def get_user_tokens(session_id):
    user_tokens = SpotifyToken.objects.filter(user=session_id)
    if user_tokens.exists():
        return user_tokens[0]
    else:
        return None

# save the spotify token in a new model or update a new model
# with the new spotify tokens
def update_or_create_user_tokens(session_id, access_token,
                                 token_type, expires_in, refresh_token):
    tokens = get_user_tokens(session_id)
    # change the expires in into a time stamp
    # expires in is just a number of seconds
    expires_in = timezone.now() + timedelta(seconds=expires_in)

    if tokens:
        tokens.access_token = access_token
        tokens.refresh_token = refresh_token
        tokens.expires_in = expires_in
        tokens.token_type = token_type
        tokens.save(update_fields=['access_token',
                                   'refresh_token',
                                   'token_type', 'expires_in'])
    else:
        tokens = SpotifyToken(user=session_id, access_token=access_token,
                              refresh_token=refresh_token,
                              token_type=token_type, expires_in=expires_in)
        tokens.save()

# tell us if the user is already authenticated

def is_spotify_authenticated(session_id):
    tokens = get_user_tokens(session_id)
    if tokens:
        expiry = tokens.expires_in
        if expiry <= timezone.now():
            # refresh token if the expiry has passed
            refresh_spotify_token(session_id)
        return True

    return False

def refresh_spotify_token(session_id):
    refresh_token = get_user_tokens(session_id)
    response = post('https://accounts.spotify.com/api/token', data={
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET
    }).json()
    access_token = response.get('access_token')
    token_type = response.get('token_type')
    expires_in = response.get('expires_in')

    update_or_create_user_tokens(
        session_id, access_token, token_type, expires_in, refresh_token)

# session_id = host session id in this case
def execute_spotify_api_request(session_id, endpoint, method='GET'):
    if method not in ['POST', 'PUT', 'GET']:
        return {'Error': f'{method} is not a valid method'}
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    if method == 'POST':
        print("Trying POST: " + BASE_URL + endpoint)
        response = post(BASE_URL + endpoint, headers=headers)
        print(response)
    elif method == 'PUT':
        response = put(BASE_URL + endpoint, headers=headers)
        print(response)
    elif method == 'GET':
        response = get(BASE_URL + endpoint, {}, headers=headers)
        try:
            return response.json()
        except:
            return {'Error': 'Issue with request'}

def toggle_play_pause_song(session_id, play):
    if play:
        endpoint = "player/play"
        execute_spotify_api_request(session_id, endpoint, 'PUT')
        return
    else:
        endpoint = "player/pause"
        execute_spotify_api_request(session_id, endpoint, 'PUT')
        return

def skip_song(session_id, back=False):
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    if back:
        response = post("https://api.spotify.com/v1/me/player/previous", headers=headers)
    else:
        response = post("https://api.spotify.com/v1/me/player/next", headers=headers)

def seek_in_song(session_id, ms):
    ms = float(ms)
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    url = f"https://api.spotify.com/v1/me/player/seek?position_ms={math.floor(ms)}"

    response = put(url, headers=headers)
    print(response)
    return response

def update_volume(session_id, new_volume):
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    url = f"https://api.spotify.com/v1/me/player/volume?volume_percent={int(new_volume)}"
    response = put(url, headers=headers)
    return response


# -*- coding: utf-8 -*-
from cadnano.proxies.cnproxy import UndoCommand
from cadnano.cntypes import (
    OligoT
)

class ApplyColorCommand(UndoCommand):
    def __init__(self, oligo: OligoT, color: str):
        super(ApplyColorCommand, self).__init__("apply color")
        self._oligo = oligo
        self._new_color = color
        self._old_color = oligo.getColor()
    # end def

    def redo(self):
        olg = self._oligo
        nc = self._new_color
        olg._setColor(nc)
        olg.oligoPropertyChangedSignal.emit(olg, 'color', nc)
    # end def

    def undo(self):
        olg = self._oligo
        oc = self._old_color
        olg._setColor(oc)
        olg.oligoPropertyChangedSignal.emit(olg, 'color', oc)
    # end def
# end class


"""
	This module converts string to voice using PyTtsx3 and win32com module
	* To use it's function just import like this -
		from tts import tts
"""
import pyttsx3
def tts(msg):
	engine = pyttsx3.init()
	rate = engine.getProperty('rate')
	engine.setProperty('rate', rate-60)
	# voices = engine.getProperty('voices')
	# engine.setProperty('voice',voices[1].id)
	engine.setProperty('voice', 'Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0')
	engine.say(msg)
	engine.runAndWait()

# tts('say neola')

# engine = pyttsx3.init()
# rate = engine.getProperty('rate')
# engine.setProperty('rate', rate-60)
# voices = engine.getProperty('voices')
# engine.setProperty('voice',voices[1].id)
# engine.say('The quick brown fox jumped over the lazy dog.')
# engine.runAndWait()


import os

DEBUG = False
SITE_ID = 1
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))
MEDIA_URL = STATIC_URL + "media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/"
ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)
SECRET_KEY = ""
ADMINS = ()
MANAGERS = ADMINS
LOGIN_URL = "/admin/"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'dev.db',
    }
}

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.static",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'compressor',
    'social_auth',
    'core',
)

try:
    import django_extensions
except ImportError:
    pass
else:
    INSTALLED_APPS += ('django_extensions',)

MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"

AUTHENTICATION_BACKENDS = (
    'social_auth.backends.twitter.TwitterBackend',
    'social_auth.backends.facebook.FacebookBackend',
    'django.contrib.auth.backends.ModelBackend',
)

# Set these in local_settings.py
TWITTER_CONSUMER_KEY     = ""
TWITTER_CONSUMER_SECRET  = ""
FACEBOOK_APP_ID          = ""
FACEBOOK_API_SECRET      = ""
FACEBOOK_EXTENDED_PERMISSIONS = ["offline_access"]

LOGIN_REDIRECT_URL = '/logged_in/'
LOGIN_ERROR_URL    = '/login_error/'

COMPRESS = True
COMPRESS_OUTPUT_DIR = "cache"

try:
    from local_settings import *
except ImportError:
    pass

TEMPLATE_DEBUG = DEBUG


# coding: utf-8

# In[32]:

import numpy as np
import cv2
img_k1 = cv2.imread('key1.png')
gray_k1 = cv2.cvtColor(img_k1, cv2.COLOR_BGR2GRAY)
gray_k1 = np.array(gray_k1)
img_k2 = cv2.imread('key2.png')
gray_k2 = cv2.cvtColor(img_k2, cv2.COLOR_BGR2GRAY)
gray_k2 = np.array(gray_k2)
img_E = cv2.imread('E.png')
gray_E = cv2.cvtColor(img_E, cv2.COLOR_BGR2GRAY)
gray_E = np.array(gray_E)
img_I = cv2.imread('I.png')
gray_I = cv2.cvtColor(img_I, cv2.COLOR_BGR2GRAY)
gray_I = np.array(gray_I)
img_Eprime = cv2.imread('Eprime.png')
gray_Eprime = cv2.cvtColor(img_Eprime, cv2.COLOR_BGR2GRAY)
gray_Eprime = np.array(gray_Eprime)

gray_I2= np.zeros(gray_Eprime.shape,np.uint8)
w = [0,0,0]
w = np.array(w)
x = [0,0,0]
x = np.array(x)
e = [0,0,0]
e = np.array(e)
size = gray_k1.shape;
W = size[1]
H = size[0]

r = 0.00001
epoch = 1
while epoch < 2:

    for i in range(1,W):
            for j in range(1,H):
                k1 = gray_k1[j,i]
                k2 = gray_k2[j,i]
                I = gray_I[j,i]
                x[0] = k1
                x[1] = k2
                x[2] = I  #x[k1,k2,I]
                a = np.dot(w,x)
                e = gray_E[j,i] - a
                w = w + r * e * x

    epoch = epoch + 1

for i in range(1,W):
        for j in range(1,H):
            color = (gray_Eprime[j,i] - w[0]*gray_k1[j,i] - w[1]*gray_k2[j,i])/w[2]
            if color > 255:
                color = 255
            if color < 0:
                color = 0
            gray_I2[j,i] = color

cv2.imshow('My Image', gray_I2)
cv2.imwrite('Decryption.jpg', gray_I2)
cv2.waitKey(0)
cv2.destroyAllWindows()

# In[29]:

print(w)


import implementation_files.combined as combined
import implementation_files.implementation as implementation
import csv

PATH = 'result/csv/csv_result.csv'

def setupFieldNamesList(dataSet):
    returnList = []
    for point in dataSet:
        returnList.append(point['columnName'])

    return returnList

def setupWriteRowDict(index, dataSet, fieldNames):
    returnDict = {}
    for field in fieldNames:
        for point in dataSet:
            if field == point['columnName']:
                if len(point['dataset']) > index:
                    returnDict[field] = point['dataset'][index]
                else:
                    returnDict[field] = None

    return returnDict

def insertDataPoints(writer, dataSet, fieldNames):
    highestNumber = combined.findLongestDataset(dataSet)
    for x in range(0, highestNumber):
        writer.writerow(
            setupWriteRowDict(x, dataSet, fieldNames)
        )

def writeFile(dataSet):
    with open(PATH, 'w', newline='', encoding='utf-8') as file:
        fieldNames = setupFieldNamesList(dataSet)
        writer = csv.DictWriter(file, fieldnames=fieldNames)
        writer.writeheader()

        insertDataPoints(writer, dataSet, fieldNames)

def implement():
    dataSet = combined.createSingleDataSet()
    writeFile(dataSet)


import os
import unittest
from random import randint

from sample.service.utils.folder_helper import FolderHelper

class FolderTest(unittest.TestCase):
    # Config with Default and Expected values
    # TODO: Add a Mock frame and if is possible a BDD (cucumber like) framework to Mock connections with fs & variables.
    # TODO: Add methods for failing Scenarios
    MAX_SIZE_FILE = 500
    MAX_SIZE_TOTAL_FOLDER = 2700
    ADDED_BYTES_VALUE = 600
    INPUT_FILE_NAME = './test01/'
    INPUT_BK_FILE_NAME = '/test-dir/'
    OUT_PUT_BK_FILE = '/test-dir-bk/'
    NAME_INPUT_FOLDER = 'test01'
    EXPECTED_ORIGINAL_LAST_SIZE = 200
    EXPECTED_MODIFIED_LAST_SIZE = 300
    original_data_chunks = {}

    @classmethod
    def setUpClass(cls):
        current_directory = os.getcwd()
        content_file1 = FolderHelper.generate_random_content(3)
        content_file2 = FolderHelper.generate_random_content(3)
        FolderHelper.save_data_to_file(content_file1, current_directory + FolderTest.INPUT_BK_FILE_NAME + "file1.text")
        FolderHelper.save_data_to_file(content_file2, current_directory + FolderTest.INPUT_BK_FILE_NAME + "file2.text")

    def test_files_chunk(self):
        """  This method tests the files creation process
        """
        # Testing number of chunks created
        folder_helper = FolderHelper()
        data_chunks = folder_helper.partition(FolderTest.MAX_SIZE_FILE,
                                              FolderTest.MAX_SIZE_TOTAL_FOLDER,
                                              FolderTest.INPUT_FILE_NAME,
                                              FolderTest.NAME_INPUT_FOLDER)
        number_chunks = len(data_chunks)
        self.assertEqual(number_chunks, FolderHelper.partitions_size(FolderTest.MAX_SIZE_TOTAL_FOLDER,

                                                                     FolderTest.MAX_SIZE_FILE))
        # Validating size of intermediary key space
        random_key = randint(1, number_chunks - 1)
        partition_key = FolderTest.NAME_INPUT_FOLDER + str(random_key)
        size_random_partition = data_chunks[partition_key][1]
        self.assertEqual(size_random_partition, FolderTest.MAX_SIZE_FILE)
        FolderTest.original_data_chunks = data_chunks

        # Validating size of last key space
        self.assertEqual(data_chunks[FolderTest.NAME_INPUT_FOLDER + str(number_chunks)][1],
                         FolderTest.EXPECTED_ORIGINAL_LAST_SIZE)

    def test_files_update(self):
        """  This method test the files update process.
        """
        # Modifying a folder and testing number of partitions
        folder_helper = FolderHelper()
        folder_modified_size = FolderTest.MAX_SIZE_TOTAL_FOLDER + FolderTest.ADDED_BYTES_VALUE
        new_number_chunks = FolderHelper.partitions_size(folder_modified_size, FolderTest.MAX_SIZE_FILE)

        modified_data_chunks = folder_helper.repartition(FolderTest.MAX_SIZE_FILE,
                                                         FolderTest.MAX_SIZE_TOTAL_FOLDER,
                                                         FolderTest.INPUT_FILE_NAME,
                                                         FolderTest.NAME_INPUT_FOLDER,
                                                         FolderTest.ADDED_BYTES_VALUE,
                                                         FolderTest.original_data_chunks)
        self.assertEqual(new_number_chunks, len(modified_data_chunks))

        # Validating size of intermediary key space
        random_key_new = randint(1, new_number_chunks - 1)
        partition_key_new = FolderTest.NAME_INPUT_FOLDER + str(random_key_new)
        size_random_partition_new = modified_data_chunks[partition_key_new][1]
        self.assertEqual(size_random_partition_new, FolderTest.MAX_SIZE_FILE)

        # Validating size of last key space
        self.assertEqual(modified_data_chunks[FolderTest.NAME_INPUT_FOLDER + str(new_number_chunks)][1],
                         FolderTest.EXPECTED_MODIFIED_LAST_SIZE)

    def test_back_up(self):
        """  This method test the backup creation process
        """
        # Validating backup creation
        folder_helper = FolderHelper()
        current_directory = os.getcwd()

        input_dir = current_directory + FolderTest.INPUT_BK_FILE_NAME
        output_dir = current_directory + FolderTest.OUT_PUT_BK_FILE

        folder_helper.backup_folder(input_dir, output_dir)
        # Getting sure there are not issues with existing folder
        folder_helper.backup_folder(input_dir, output_dir)
        self.assertEqual(os.path.getsize(input_dir), os.path.getsize(output_dir))

    @classmethod
    def tearDownClass(cls):
        current_directory = os.getcwd()
        FolderHelper.remove_folder(current_directory + FolderTest.INPUT_BK_FILE_NAME)
        FolderHelper.remove_folder(current_directory + FolderTest.OUT_PUT_BK_FILE)
        FolderHelper.remove_folder(current_directory + FolderTest.INPUT_FILE_NAME.replace(".", ""))

if __name__ == '__main__':
    unittest.main()


import socket
import json
import time

local_port = None
tello_drone_ip = None
tello_drone_port = None
timeout = None
s = None

local_port = 9000
tello_drone_ip = "192.168.10.1"
tello_drone_port = 8889
timeout = 5.0

def connect():
    conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    conn.bind(('', local_port))
    conn.connect((tello_drone_ip, tello_drone_port))
    conn.settimeout(timeout)
    conn.send(b'command')
    conn.send(b'streamon')


def ADDFACTORIAL(iNo):
    isum=0
    for i in range(1,int(iNo/2+1)):
        if iNo%i==0:
            isum=isum+i
    return isum

def main():
    print(ADDFACTORIAL(int(input("ENTER THE NUMBER :"))))

if __name__ == "__main__":
    main()


import telebot as tb
from telebot import types

bot = tb.TeleBot('Insert your token here.')

name, last_name, age = '', '', 0

@bot.message_handler(content_types=['text'])
def start(message):
    if message.text == '/reg':
        bot.send_message(message.from_user.id, "What's your name?")
        bot.register_next_step_handler(message, get_name)
    else:
        bot.send_message(message.from_user.id, 'Write /reg')

def get_name(message):
    global name
    name = message.text
    bot.send_message(message.from_user.id, "What's your last name?")
    bot.register_next_step_handler(message, get_last_name)

def get_last_name(message):
    global last_name
    last_name = message.text
    bot.send_message(message.from_user.id, 'How old are you?')
    bot.register_next_step_handler(message, get_age)

def get_age(message):
    global age
    if age == 0:
        try:
            age = int(message.text)
        except Exception:
            bot.send_message(message.from_user.id, 'Enter only numbers!')

    key = types.InlineKeyboardMarkup()
    yes = types.InlineKeyboardButton(text='Yes', callback_data='Yes')
    key.add(yes)
    no = types.InlineKeyboardButton(text='No', callback_data='No')
    key.add(no)

    question = f"Your name is {name}, " \
               f"\nyour last name is {last_name} " \
               f"\nand you're {age} years old, right?"

    bot.send_message(message.from_user.id, text=question, reply_markup=key)

@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    if call.data == 'Yes':
        bot.send_message(call.message.chat.id, 'Nice to meet you!')
    elif call.data == 'No':
        bot.send_message(call.message.chat.id, "Let's do it again! Write /reg")

bot.polling(none_stop=True, interval=1)


import numpy as np
import matplotlib.pyplot as plt
import random
from math import pi, sin, cos

def check(radius, point):
    return (radius/2)**2 > (point[0]**2+point[1]**2)

def get1(radius):
    x = 1
    y = 1
    while(x**2+y**2 > 1):
        x = random.random()*2-1
        y = random.random()*2-1
    return [x*radius, y*radius]

def get2(radius):
    dist = random.random()*radius
    theta = random.random()*2*pi
    return [dist*cos(theta), dist*sin(theta)]

def get3(radius):
    phi = random.random()*2*pi
    theta = random.random()*pi
    return [radius*cos(theta)*cos(theta+phi), radius*cos(theta)*sin(theta+phi)]

def draw(arr, radius, index, trys, save):
    fig, ax = plt.subplots(figsize=(10, 10))
    circle = plt.Circle((0, 0), radius, fill=False, color='black', lw=0.2)
    ax.set_xlim((-radius, radius))
    ax.set_ylim((-radius, radius))
    ax.add_artist(circle)
    ax.scatter(arr[0], arr[1], s=0.001)
    if save: fig.savefig('res'+str(index+1)+'.png')
    else: plt.show()

if __name__ == '__main__':
    radius = 1.00
    trytimes = 1000000
    get = [get1, get2, get3]
    for i in range(3):
        res = np.array([get[i](radius) for j in range(trytimes)])
        draw(res.T, radius, i, trytimes, True)
        compared = np.array([check(radius, point) for point in res])
        print(i, np.count_nonzero(compared))


class VotingBooth:

    def __init__(self, identifier, country):
        self._identifier = identifier
        self._country = country
        self._region = None

    @property
    def region(self):
        return self._region

    @region.setter
    def region(self, region):
        if region in self._country:
            self._region = region
        else:
            raise ValueError(f'Region {region} is not allowed')

booth = VotingBooth(123, ['Mexico', 'Morelos'])
print(booth.region)
booth.region = 'Mexico'
print(booth.region)


#!/usr/bin/env python3
"""
Usage:
signature_server.py [--host HOST] [--port PORT] [--delay DELAY] [--quiet]

Options:
--quiet             Do not print each request
--host HOST         The host to bind the server to. [default: localhost]
--port PORT         The port to bind the server to. [default: 9000]
--delay DELAY       The artificial delay (in ms) between each comparison of bytes of the signature [default: 0.05]
"""
import base64
import random
from docopt import docopt
from bottle import request, run, response, get
import time
import itertools
import sys
import util

__author__ = 'peter'

KEY = util.get_random_bytes(random.randint(10, 100))

@get('/check_signature')
def check_signature():
    file = base64.urlsafe_b64decode(request.query.file)
    sig = base64.urlsafe_b64decode(request.query.signature)
    if not insecure_compare(file, sig):
        response.status = 500
        return 'Boo!'
    else:
        return 'Yay!'

@get('/get_key')
def get_key():
    return KEY

def insecure_compare(file, sig):
    s = util.sha1_hmac(file, KEY)
    if not quiet:
        print(util.to_hex(sig))
        print(util.to_hex(s))
    for b1, b2 in itertools.zip_longest(s, sig):
        if b1 != b2:
            return False
        time.sleep(delay)
    return True

def main(argv=None):
    args = docopt(__doc__, argv=argv)
    global delay, quiet

    try:
        delay = float(args['--delay'])
        quiet = args['--quiet']
    except ValueError:
        print('Provided delay "{}" is no valid float!'.format(args['--delay']))
        sys.exit(-1)
    run(host=args['--host'], port=args['--port'], quiet=args['--quiet'])

if __name__ == '__main__':
    main()


import os
from testsuite_support.builder_and_runner import BuilderAndRunner, GPRINSTALL, GPRLS

bnr = BuilderAndRunner()
OK = True

bnr.run(['gprbuild', '-p', '-q', '-aPmylib', '-Pmain/main.gpr'],
        output='run.out')

for line in open("run.out"):
    OK = False
    print('1:' + line)

bnr.call([GPRLS, '-U', '-aPmylib', '-Pmain/main.gpr', '--debugF',
          'helper.o', 'main.o', 'asm.o'])
print('----------')
bnr.call([GPRLS, '-U', '-aPmylib', '-Pmain/main.gpr', '--debugF'])
print('----------')
bnr.call([GPRLS, '-aPmylib', '-Pmain/main.gpr', '--debugF'])

bnr.run(['gprbuild', '-p', '-q', '-Pmylib/mylib.gpr'], output='run.out')

for line in open("run.out"):
    OK = False
    print('2:' + line)

bnr.run([GPRINSTALL, '-p', '-q', '-Pmylib/mylib.gpr',
         '--prefix=' + os.path.join(os.getcwd(), 'install')], output='run.out')

for line in open("run.out"):
    OK = False
    print('3:' + line)

bnr.run(['gprbuild', '-p', '-q',
         '-aPinstall/share/gpr', '-Pmain/main.gpr'], output='run.out')
for line in open("run.out"):
    OK = False
    print('4:' + line)

print('----------')
bnr.call([GPRLS, '-U', '-aPinstall/share/gpr', '-Pmain/main.gpr', '-d', '--debugF',
          'helper.o', 'asm.o'])

print('----------')
bnr.run([GPRLS, '-v', '-U', '-aPinstall/share/gpr', '-Pmain/main.gpr', '-d',
         '--debugF'],
        output='run.out')

outp = False
start_line = os.path.join("main", "obj", "asm.o")
for line in open("run.out"):
    if line.find(start_line) > 0:
        outp = True
    if outp:
        print(line[:-1])

if OK:
    print('OK')
else:
    print('NOK')


import unittest
from typing import List

class Solution:

    @staticmethod
    def floodFill(image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
            from collections import deque

            queue = deque()
            row_length, column_length = len(image), len(image[0])
            target_color = image[sr][sc]
            directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

            if target_color != newColor:
                queue.append((sr, sc))
            while queue:
                for pixel in range(len(queue)):
                    r, c = queue.popleft()
                    image[r][c] = newColor
                    for dy, dx in directions:
                        nr, nc = r + dy, c + dx
                        if 0 <= nr < row_length and 0 <= nc < column_length and image[nr][nc] == target_color:
                            queue.append((nr, nc))
            return image

class FloodFill(unittest.TestCase):

    def test_case_1(self):
        image = [[1, 1, 1], [1, 1, 0], [1, 0, 1]]
        sr = 1
        sc = 1
        new_color = 2
        expected_output = [[2, 2, 2], [2, 2, 0], [2, 0, 1]]
        self.assertListEqual(expected_output, Solution.floodFill(image, sr, sc, new_color))

    def test_case_2(self):
        image = [[0, 0, 0], [0, 1, 1]]
        sr = 1
        sc = 1
        new_color = 1
        expected_output = [[0, 0, 0], [0, 1, 1]]
        self.assertListEqual(expected_output, Solution.floodFill(image, sr, sc, new_color))


import cv2
import numpy as np

img = cv2.imread("101/ders6/wolf.jpg")

cv2.rectangle(img,(500,210),(150,150),[0,0,255],3)
cv2.imshow("new",img)

cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)


from twilio.rest import Client
def make_call():
    account_sid = "Your Account"
    auth_token = "Your Auth"
    client = Client(account_sid, auth_token)

    call = client.calls.create(
                            url='http://demo.twilio.com/docs/voice.xml',
                            to='+918210410103',
                            from_='+19402919532')
    print(call.sid)


import pickle
import itertools
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.utils import class_weight
from sklearn import metrics
import matplotlib.pyplot as plt
from imblearn.under_sampling import RandomUnderSampler
from sklearn.metrics import classification_report
from sklearn.model_selection import StratifiedKFold

class Random_Forest_model:
    def __init__(self, labels=None, dataset=None, title=None):
        self.labels = labels
        self.dataset = dataset
        self.title = title

    #split train 80, test 20
    #save the datasets in pickle files
    def train_test_stratified(self):
        train_set, test_set, train_label, test_label = train_test_split(self.dataset, self.labels, stratify=self.labels,test_size=0.30)
        title = "../datasets/train_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(train_set, fp)
        title = "../datasets/train_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(train_label, fp)
        title = "../datasets/test_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(test_set, fp)
        title = "../datasets/test_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(test_label, fp)

    def train_validation_undersampling(self, train_set, train_label, sampling_strategy):
        self.train_set, self.validation_set, self.train_label, self.validation_label = train_test_split(train_set, train_label, stratify=train_label,test_size=0.15)
        # RandomUnderSampler
        sampler = RandomUnderSampler(sampling_strategy=sampling_strategy, random_state=42)
        self.train_set, self.train_label = sampler.fit_sample(self.train_set, self.train_label)
        print(self.train_set.shape)
        print(self.train_label.shape)
        sampler = RandomUnderSampler(sampling_strategy=sampling_strategy, random_state=42)
        self.validation_set, self.validation_label = sampler.fit_sample(self.validation_set, self.validation_label)
        print(self.validation_set.shape)
        print(self.validation_label.shape)
        title = "../datasets/train_under_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_set, fp)
        title = "../datasets/train_under_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_label, fp)
        title = "../datasets/validation_under_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_set, fp)
        title = "../datasets/validation_under_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_label, fp)

    def train_validation_raw(self, train_set, train_label):
        self.train_set, self.validation_set, self.train_label, self.validation_label = train_test_split(train_set, train_label, stratify=train_label, test_size=0.15)
        title = "../datasets/train_raw_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_set, fp)
        title = "../datasets/train_raw_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_label, fp)
        title = "../datasets/validation_raw_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_set, fp)
        title = "../datasets/validation_raw_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_label, fp)

    def random_forest_model(self, weight_flag=False):
        if weight_flag is True:
            #fit the model
            model = RandomForestClassifier(class_weight='balanced', bootstrap= True, max_depth= 20, max_features= 5, min_samples_leaf= 15, min_samples_split= 30, n_estimators= 100)
        else:
            model = RandomForestClassifier(bootstrap=False, max_depth=20, max_features=4, min_samples_leaf=5,
                                           min_samples_split=10, n_estimators=400, criterion='entropy')
        return model

    def random_forest_fit(self, model, train_set, train_label):
        model = model.fit(train_set, train_label)
        #saving the model into a pickle file
        title_model = '../results/trained_rf_'+str(self.title)+'.p'
        pickle.dump(model, open(title_model, 'wb'))
        return model

    def random_forest_prediction(self, model, test_set, test_label):
        self.predictions = model.predict(test_set)
        score = model.score(test_set, test_label)
        report = classification_report(test_label, self.predictions)
        title = "../results/report_"+self.title+".txt"
        write_report = open(title,"w")
        write_report.write(report)
        print(report)
        return report

    def plot_confusion_matrix_multi(self, cm,target_names, cmap=None, normalize=True):
        accuracy = np.trace(cm) / float(np.sum(cm))
        misclass = 1 - accuracy
        if cmap is None:
            cmap = plt.get_cmap('Blues')
        plt.figure(figsize=(8, 6))
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title('Confusion Matrix for the Random Forest for mobility data \n Stratified sample \n', size=16)
        plt.colorbar()
        if target_names is not None:
            tick_marks = np.arange(len(target_names))
            plt.xticks(tick_marks, target_names, size=14)
            plt.yticks(tick_marks, target_names, size=14)
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        thresh = cm.max() / 1.5 if normalize else cm.max() / 2
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            if normalize:
                plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="grey" if cm[i, j] > thresh else "black", size=14)
            else:
                plt.text(j, i, "{:,}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="grey" if cm[i, j] > thresh else "black", size=14)
        plt.tight_layout()
        plt.ylabel('True label', size=14)
        plt.gcf().subplots_adjust(bottom=0.20)
        plt.xlabel('\n Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass), size=14)
        plt.savefig('../results/cm_'+str(self.title)+'.png')

    def confusion_matrix(self, test_label, target_names, cmap=None, normalize=True):
        cm = metrics.confusion_matrix(test_label, self.predictions)
        accuracy = np.trace(cm) / float(np.sum(cm))
        misclass = 1 - accuracy
        if cmap is None:
            cmap = plt.get_cmap('Blues')
        plt.figure(figsize=(8, 6))
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title('confusion_matrix'+self.title)
        plt.colorbar()
        if target_names is not None:
            tick_marks = np.arange(len(target_names))
            plt.xticks(tick_marks, target_names, rotation=45)
            plt.yticks(tick_marks, target_names)
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        thresh = cm.max() / 1.5 if normalize else cm.max() / 2
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            if normalize:
                plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="white" if cm[i, j] > thresh else "black")
            else:
                plt.text(j, i, "{:,}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="white" if cm[i, j] > thresh else "black")
        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
        plt.savefig('../results/cm_'+str(self.title)+'.png')


import cv2
import os
import numpy as np
from scipy.signal import find_peaks
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split

debug = True

def display(input_image, frame_name="OpenCV Image"):
    if not debug:
        return
    h, w = input_image.shape[0:2]
    new_w = 800
    new_h = int(new_w * (h / w))
    input_image = cv2.resize(input_image, (new_w, new_h))
    cv2.imshow(frame_name, input_image)
    cv2.waitKey(0)

def preprocessImage(input_image):
    """
    Preprocess the image to get the text regions
    :param input_image: the given image
    :return: connected_image the image with connected text regions
    bw_image: the binarized image
    """
    grayscale = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)

    # find the gradient map
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    grad = cv2.morphologyEx(grayscale, cv2.MORPH_GRADIENT, kernel)

    # Binarize the gradient image
    _, bw_image = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    bw_inverted_image = cv2.bitwise_not(bw_image)

    # connect horizontally oriented regions
    # kernel value (9,1) can be changed to improve the text detection
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
    connected_image = cv2.morphologyEx(bw_image, cv2.MORPH_CLOSE, kernel)

    inverted_image = cv2.bitwise_not(connected_image)

    return inverted_image, bw_inverted_image

def preprocessText(input_image):
    """
    Preprocess the image to make it easier to find the text
    :param input_image: the given image
    :return: the preprocessed image
    """
    grayscale = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
    binary_image = cv2.threshold(grayscale, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

    # define the kernel and invert the image
    kernel = np.ones((3, 3), np.uint8)
    inverted_image = cv2.bitwise_not(binary_image)

    # dilate the image
    dilated_image = cv2.dilate(inverted_image, kernel, iterations=1)

    # Remove the dilated image from the original image
    removed_image = cv2.subtract(grayscale, dilated_image)

    # Perform thinning of the result image
    inverted_image = cv2.bitwise_not(removed_image)
    eroded_image = cv2.erode(inverted_image, kernel, iterations=1)

    final_image = np.copy(eroded_image)

    return final_image

def detectLines(input_image, display_img):
    current_directory = os.getcwd()
    final_directory = os.path.join(current_directory, r'lines')
    if not os.path.exists(final_directory):
        os.makedirs(final_directory)

    display_img = cv2.cvtColor(display_img, cv2.COLOR_BGR2GRAY)

    # Compute and smooth the vertical projection of brightness
    vertical_projection = cv2.reduce(input_image, 1, cv2.REDUCE_SUM, dtype=cv2.CV_32F)
    vertical_projection = cv2.GaussianBlur(vertical_projection, (3, 3), 0)
    row_sum = np.sum(vertical_projection, axis=1)

    # Find the peaks in the vertical projection
    peaks, _ = find_peaks(row_sum, height=900000, distance=20, width=10)
    coordinates = {}

    # Draw the detected lines on the original image
    for i, peak in enumerate(peaks):
        coordinates[i] = peak

        if i == 0:
            continue
        else:
            line = display_img[coordinates[i-1]:peak, 5:display_img.shape[1]-5]
            # Find the rows that contain only white pixels and remove them from the image
            white_rows = np.all(line >= 245, axis=1)
            cropped_image = line[~white_rows, :]

            # cv2.imwrite(f"lines/line{i}.png", cropped_image)

    return coordinates

def detectWords(input_coordinates, input_image, display_img):
    display_img = cv2.cvtColor(display_img, cv2.COLOR_BGR2GRAY)
    coords = []

    for i in range(len(input_coordinates)):
        x, y, w, h = 15, input_coordinates[i] - 35, input_image.shape[1]-20, 60
        line = display_img[y:y + h, x:x + w]
        lineb = cv2.blur(line, (25, 25))

        # Compute the horizontal projection of brightness
        horizontal_projection = cv2.reduce(lineb, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32F)

        # Smooth the horizontal projection with a Gaussian filter
        horizontal_projection = cv2.GaussianBlur(horizontal_projection, (5, 5), 0)
        col_sum = np.sum(horizontal_projection, axis=0)

        # Find the peaks in the horizontal projection
        peaks, _ = find_peaks(col_sum, height=15000, distance=60)
        coordinates = []

        # Draw the detected lines on the original image
        for j, peak in enumerate(peaks):
            coordinates.append(peak)

            if j == 0:
                word = line[0:line.shape[0], 15:peak]
            elif j == len(input_coordinates)-1:
                word = line[0:line.shape[0], peak:line.shape[1]-15]
            else:
                word = line[0:line.shape[0], coordinates[j-1]:peak]

            # Save the line image to a file (x,y)
            # cv2.imwrite(f"words/line{i}_word{j + 1}.png", word)

        coords.append(coordinates)

    return coords

def detectLetters(input_coordinates, input_image, display_img):
    current_directory = os.getcwd()
    final_directory = os.path.join(current_directory, r'letters')
    if not os.path.exists(final_directory):
        os.makedirs(final_directory)

    display_img = cv2.cvtColor(display_img, cv2.COLOR_BGR2GRAY)
    coords = []

    for i in range(len(input_coordinates)):
        if i == 0:
            continue
        # Calculate the coordinates of each line
        x1, y1, x2, y2 = 5, input_coordinates[i-1], display_img.shape[1]-5, input_coordinates[i]
        cropped_image = input_image[y1:y2, x1:x2]
        # white_rows = np.all(line >= 245, axis=1)
        # cropped_image = line[~white_rows, :]

        # Convert the image to binary format and find the white columns
        binary_image = np.where(cropped_image >= 240, 1, 0)
        white_columns = np.all(binary_image == 1, axis=0)

        # Identify the letter boundaries
        boundaries = []
        start_index = None
        for k, is_white in enumerate(white_columns):
            if is_white and start_index is None:
                start_index = k
            elif not is_white and start_index is not None:
                end_index = k - 1
                if len(boundaries) == 0 or start_index > boundaries[-1][1] + 1:
                    boundaries.append((start_index, end_index))
                else:
                    boundaries[-1] = (boundaries[-1][0], end_index)
                start_index = None

        # Extract the letters
        letters = []
        lcoordinates = []
        for start, end in boundaries:
            if start == 0:
                temp_end = end
                continue

            letter = cropped_image[0:cropped_image.shape[0], temp_end:start]
            lcoords = (temp_end, 0, start, cropped_image.shape[0])
            lcoordinates.append(lcoords)
            letters.append(letter)

            if start == boundaries[-1][0]:
                letter = cropped_image[0:cropped_image.shape[0], start:start + 40]
                lcoords = (start, 0, start+40, cropped_image.shape[0])
                lcoordinates.append(lcoords)
                letters.append(letter)

            temp_end = end

        # for j, letter in enumerate(letters):
        #     cv2.imwrite(f"letters/line{i}_letter{j + 1}.png", letter)

        coords.append(lcoordinates)

    return coords

def returnCharacters(filepath):
    chars = []
    with open(filepath, 'r') as file:
        for line in file:
            for char in line:
                if char == ' ' or char == '\n':
                    continue
                chars.append(char)

    return chars

if __name__ == "__main__":
    image = cv2.imread("text1_v2.png")
    display_image = np.copy(image)
    connected, thresh = preprocessImage(image)

    lines_coordinates = detectLines(connected, display_image)
    # words_coordinates = detectWords(lines_coordinates, thresh, display_image)

    processed_image = preprocessText(display_image)
    pro_invert = cv2.bitwise_not(processed_image)
    letter_coordinates = detectLetters(lines_coordinates, pro_invert, display_image)

    file_path = 'text1_v2.txt'
    characters = returnCharacters(file_path)
    y = characters
    X = []

    for line in letter_coordinates:
        for letter in line:
            x1, y1, x2, y2 = letter
            temp = pro_invert[y1:y2, x1:x2]
            resized = cv2.resize(temp, (32, 32), interpolation=cv2.INTER_CUBIC)
            X.append(resized.flatten())

    # Split the dataset
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    # Train the KNN model
    k = 3
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)

    # Make predictions
    y_pred = knn.predict(X_test)

    # Evaluate the accuracy of the classifier
    accuracy = knn.score(X_test, y_test)
    print(f"Accuracy: {accuracy}")

    test_letter = cv2.imread('dataset/j.png')
    processed_image = preprocessText(test_letter)
    pro_invert = cv2.bitwise_not(processed_image)
    test_letter = cv2.resize(pro_invert, (32, 32), interpolation=cv2.INTER_CUBIC)

    prediction = knn.predict(test_letter.reshape(-1, 1024))
    print(f"Prediction: {prediction}")


import atexit
import time
from multiprocessing import Pool

from loguru import logger
from tqdm import tqdm

from reprobench.core.worker import BenchmarkWorker
from reprobench.managers.base import BaseManager

class LocalManager(BaseManager):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.num_workers = kwargs.pop("num_workers")
        self.start_time = None
        self.workers = []

    def exit(self):
        for worker in self.workers:
            worker.terminate()
            worker.join()

        logger.info(f"Total time elapsed: {time.perf_counter() - self.start_time}")

    def prepare(self):
        atexit.register(self.exit)
        self.start_time = time.perf_counter()

    @staticmethod
    def spawn_worker(job):
        server_address, run_id = job
        worker = BenchmarkWorker(server_address, run_id)
        worker.run()

    def spawn_workers(self):
        self.pool = Pool(self.num_workers)
        jobs = ((self.server_address, run_id) for run_id in self.queue)
        self.pool_iterator = self.pool.imap_unordered(self.spawn_worker, jobs)
        self.pool.close()

    def wait(self):
        progress_bar = tqdm(desc="Executing runs", total=len(self.queue))
        for _ in self.pool_iterator:
            progress_bar.update()
        progress_bar.close()
        self.pool.join()


import poseidon.poseidon
from requests.models import PreparedRequest

def CreateLogicalAsset(accessKey, secretKey, orgId, url, modelId):
    accessURL = url + '/asset-service/v2.1/logical-assets'
    params = {"action": "create", "orgId": orgId}
    req = PreparedRequest()
    req.prepare_url(accessURL, params)
    print(req.url)

    body={"assetInstance": {"modelId": modelId,
                            "name": {"defaultValue": "Demo_Python_Asset",
                                    "i18nValue": {"zh_CN": "演示Python断言", "en_US": "Asset_Demo_Python_Asset",
                                    "ja_JP": "デモPythonアサート", "es_ES": "DeclaraciónDePythonDeDemostración"}},
                            "timezone": "+08:00",
                            "description": "Asset_Description",
                            "attributes": {"Int_Attribute": 1,
                                           "Float_Attribute": 1.23,
                                           "String_Attribute": "Asset"},
                            "tags": {"AssetKey1":"AssetValue1",
                                     "AssetKey2":"AssetValue2",
                                     "AssetKey3":"AssetValue3"}
                            }
        }
    print(body)

    response = poseidon.poseidon.urlopen(accessKey, secretKey, req.url, body)
    print(response)

    AssetId = response["data"]
    return AssetId