"""Python build/install"""

import os
import subprocess
import tempfile
import shutil

from build_util import wget, unpack, version_dict, cpu_cores

def install(dir_name,version=None):
    if not os.path.exists(os.path.join(dir_name,'bin','qmake')):
        print('installing qt version',version)
        name = 'qt-everywhere-opensource-src-'+version+'.tar.gz'
        try:
            tmp_dir = tempfile.mkdtemp()
            path = os.path.join(tmp_dir,name)
            major_version = '.'.join(version.split('.')[:2])
            if major_version == '4.8':
                url = os.path.join('http://download.qt.io/archive/qt/',major_version,version,name)
            else:
                url = os.path.join('http://download.qt.io/archive/qt/',major_version,version,'single',name)
            wget(url,path)
            unpack(path,tmp_dir)
            qt_dir = os.path.join(tmp_dir,'qt-everywhere-opensource-src-'+version)

            options = [
                   '-opensource','-opengl','-no-accessibility','-no-sql-db2',
                   '-no-sql-ibase','-no-sql-mysql','-no-sql-oci','-no-sql-odbc',
                   '-no-sql-psql','-no-sql-sqlite','-no-sql-sqlite2', '-no-sql-tds',
                   '-nomake','examples',
            ]

            cfg_path = os.path.join(qt_dir,'configure')
            if major_version == '4.8':
                # confirm the license early so it doesn't pause for user input
                cfg_data = open(cfg_path).read().replace('OPT_CONFIRM_LICENSE=no','OPT_CONFIRM_LICENSE=yes')
                open(cfg_path,'w').write(cfg_data)
                options.extend([
                        '-no-sql-sqlite_symbian',
                        '-no-xmlpatterns','-no-multimedia','-no-phonon','-no-phonon-backend',
                        '-no-webkit','-no-javascript-jit','-no-script','-no-scripttools',
                        '-no-declarative','-no-nis','-fast','-nomake','demos',
                        '-nomake','docs','-nomake','translations',
                ])
            else:
                cpu_cores = '1' # bug in dependencies
                options.extend([
                        '-confirm-license','-no-avx','-no-avx2','-no-avx512',
                        '-no-dbus','--no-harfbuzz','-no-ssl','-skip','wayland',
                ])

            # only install the required components
            if subprocess.call([cfg_path,'-prefix',dir_name]+options
                               ,cwd=qt_dir):
                raise Exception('qt failed to configure')
            if subprocess.call(['make','-j',cpu_cores],cwd=qt_dir):
                raise Exception('qt failed to make')
            if subprocess.call(['make','install'],cwd=qt_dir):
                raise Exception('qt failed to install')
        finally:
            shutil.rmtree(tmp_dir)

def versions():
    return version_dict(install)


class County:
    def __init__(self, countyData):
        self.StateShortName = countyData['StateShortName']
        # self.StateName = countyData['StateName']
        self.CountyName = countyData['CountyName']
        self.TotalArea = countyData['TotalArea']
        self.Population = countyData['Population']
        self.Latitude = countyData['Latitude']
        self.Longitude = countyData['Longitude']
        self.CountyWikiLink = countyData['CountyWikiLink']


n = int(input())
s = 3
i = 0
j = 0
for i in range(n):
    for j in range(s, -1,-1):
        if n < 3:
            print("До старта", s, "секунд(ы)")
            s = s - 1
            j = j + 1
            print("Старт", str(n + 1) + "!!!")
        i = i + 1
        break


"""Install *enpacken*.

Usage: pip install .
"""

import pathlib
import setuptools

parent = pathlib.Path(__file__).parent
long_description = (parent / "README.md").read_text()
version = (parent / "VERSION").read_text().strip()

setuptools.setup(
    name="enpacken",
    version=version,
    description="Find package installation candidates",
    author="Laurie",
    author_email="laurie_opperman@hotmail.com",
    maintainer="Laurie",
    maintainer_email="laurie_opperman@hotmail.com",
    license="MIT",
    long_description=long_description,
    long_description_content_type="text/markdown",
    classifiers=[
        "Environment :: Console",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3 :: Only",
        "Natural Language :: English",
        "Operating System :: POSIX :: Linux",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: MacOS",
        "License :: OSI Approved :: MIT License"
    ],
    keywords="package wheel distribution platform candidate",
    project_urls={
        "Source": "https://github.com/EpicWink/enpacken",
        "Bugs": "https://github.com/EpicWink/enpacken/issues"
    },
    packages=setuptools.find_packages(where="src"),
    package_dir={"": "src"},
    install_requires=["wheel"],
    extras_require={"dev": ["pytest", "pytest-cov"]},
    entry_points={"console_scripts": ["enpacken=enpacken.__main__:main"]}
)


import os
import dialogflow_v2 as dialogflow

class ChatAgent:
    def __init__(self, projectID):
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "Exported_Agent_Path.json"
        self.dialogflow_session_client = dialogflow.SessionsClient()
        self.PROJECT_ID = projectID

    def detect_intent_from_text(self, text, session_id, language_code='en'):
        session = self.dialogflow_session_client.session_path(self.PROJECT_ID, session_id)
        text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = self.dialogflow_session_client.detect_intent(session=session, query_input=query_input)
        return response.query_result


from abc import abstractmethod
from typing import List, Tuple, NamedTuple
from os import path

from .cli import Game

here = path.abspath(path.dirname(__file__))
DEFAULT_WORD_FILE = path.join(here, 'words', 'words.txt')

class Word(NamedTuple):
    word: str
    path: List[Tuple[int, int]]

class WordReader(object):
    """
    Read list of words from a file.
    """
    @staticmethod
    def read_from_file(file_name: str) -> List[str]:
        with open(file_name, 'r') as f:
            words = f.readlines()
        return words

class Node(object):
    def __init__(self, value: str):
        self.value = value
        self.children: List[Node] = []

class NodeBoard(object):
    def __init__(self, game: Game):
        self.nodes = NodeBoardBuilder(game).build()

    def __iter__(self):
        self.i = 0
        self.j = -1
        return self

    def __next__(self):
        if self.j < Game.WIDTH - 1:
            self.j += 1
            result = self.nodes[self.i][self.j]
            return result
        elif self.i < Game.HEIGHT - 1:
            self.j = 0
            self.i += 1
            result = self.nodes[self.i][self.j]
            return result
        else:
            raise StopIteration

class NodeBoardBuilder(object):
    """
    A game where every cell is linked to each other
    """

    def __init__(self, game: Game):
        self.game = game

    def build(self) -> List[List[Node]]:
        nodes = self._create_nodes()
        return self._link_nodes(nodes)

    def _create_nodes(self) -> List[List[Node]]:
        """
        Creates Nodes from board cells.
        """
        all_nodes = []
        for i in range(Game.WIDTH):
            node_row = []
            for j in range(Game.HEIGHT):
                node = Node(self.game[i, j])
                node_row.append(node)
            all_nodes.append(node_row)
        return all_nodes

    def _link_nodes(self, nodes):
        """
        Links all created nodes to each other.
        """
        for i in range(Game.WIDTH):
            for j in range(Game.HEIGHT):
                self._link_adjacent_nodes(nodes, i, j)
        return nodes

    def _link_adjacent_nodes(self, nodes, i, j):
        """
        Links adjacent nodes of node in index i, j to each other.
        """
        for x, y in self._adjacent_indices(i, j):
            try:
                self._link_two_adjacent_nodes(nodes[i][j], nodes[x][y])
            except IndexError:
                pass

    def _link_two_adjacent_nodes(self, node: Node, adjacent_node: Node):
        node.children.append(adjacent_node)

    def _adjacent_indices(self, i: int, j: int) -> List[Tuple[int, int]]:
        return [
            (i-1, j-1), (i-1, j), (i-1, j+1), (i, j-1),
            (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1)
        ]

class Solver(object):
    """
    Solves a game.
    """

    def __init__(self) -> None:
        self.possible_words = WordReader.read_from_file(
            DEFAULT_WORD_FILE
        )

    @abstractmethod
    def solve(self, game: Game) -> List[str]:
        pass

class SimpleSolver(Solver):

    def solve(self, game: Game) -> List[str]:
        board = game.board
        if (board[0][0] + board[0][1] + board[0][2] == "hei"):
            return ["hei"]
        return []

class NodeSolver(Solver):

    def solve(self, game: Game) -> List[str]:
        nodes = NodeBoard(game)
        found_words = []
        for node in nodes:
            new_words = self.traverse_starting_from_node(node)
            found_words += new_words
        return found_words

    def traverse_starting_from_node(self, node: Node) -> List[str]:
        return []


# Write your solution here
def first_word(str):
    index = str.find(' ')
    return str[0:index]
def second_word(str):
    index = str.find(' ')
    str = str[index + 1:]
    index2 = str.find(' ')
    if index2 == -1:
        return str[0:]
    else:
        return str[0:index2]
def last_word(str):
    x = 0
    while x < len(str):
        if str[x] == ' ':
            index = x + 1
        x += 1
    return str[index:]

# You can test your function by calling it within the following block
if __name__ == "__main__":
    sentence = "once upon a time there was a programmer"
    print(first_word(sentence))
    print(second_word(sentence))
    print(last_word(sentence))


import sys
import os
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

class MainWindow(QMainWindow):
    from pyecharts import Geo
    # 存放数据 攻击来源 攻击次数
    import requests
    # 采用百度的api
    import json
    def ip2address(ip):
        r = requests.get(
            'http://api.map.baidu.com/location/ip?ip=' + ip + '&ak=X7K1gs9RPEoakNnYOtcIgPeMaqGu7TVu&coor=bd09ll')
        result = r.json()
        city = result['content']['address_detail']['city']
        return city

    def ipGeo(data):
        geo = Geo(
            "攻击来源",
            "精确到市",
            title_color="#fff",
            title_pos="center",
            width=1200,
            height=600,
            background_color="#404a59",
        )
        attr, value = geo.cast(data)
        geo.add(
            "",
            attr,
            value,
            visual_range=[0, 2000],
            visual_text_color="#fff",
            symbol_size=15,
            is_visualmap=True,
        )
        geo.render()
    def __init__(self):
        cwd = os.getcwd()
        super(MainWindow, self).__init__()
        self.setWindowTitle('攻击来源')
        self.setGeometry(100,100,1250,630)
        self.browser=QWebEngineView()
        #加载外部的web界面
        self.browser.load(QUrl('file:///C:/Users/intbjwww/PycharmProjects/web-project-NSN/code/render.html'))
        self.setCentralWidget(self.browser)
if __name__ == '__main__':
    app=QApplication(sys.argv)
    win=MainWindow()
    win.show()
    app.exit(app.exec_())


from django.conf.urls import url
from . import views

app_name = 'student'

urlpatterns = [
    # /student/
    url(r'^$', views.index, name='index'),

    url(r'^listofstudents/$', views.listofstudents, name='listofstudents'),

    url(r'^listofcourses/$', views.listofcourses, name='listofcourses'),

    url(r'^(?P<student_id>[0-9]+)/$', views.detail, name='detail'),

    # /student/student/add/
    url(r'^student/add/$', views.StudentCreate.as_view(), name='student-add'),

    # /student/student/add/
    url(r'^student/course-add/$', views.CourseCreate.as_view(), name='course-add'),

    url(r'^student/grade-add/$', views.AddGrades.as_view(), name='grade-add'),

]


import math
from functools import partial

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from timm.models.layers import trunc_normal_, DropPath
from torch import Tensor
from torch.nn import init
from torch.nn.modules.utils import _pair

class DWConv2d(nn.Module):
    def __init__(self, in_chans, out_chans, kernel_size=3, padding=1, bias=False):
        super(DWConv2d, self).__init__()
        self.depthwise = nn.Conv2d(in_chans, in_chans, kernel_size=kernel_size,
                                   padding=padding, groups=in_chans, bias=bias)
        self.pointwise = nn.Conv2d(in_chans, out_chans, kernel_size=1, bias=bias)

        nn.init.kaiming_uniform_(self.depthwise.weight, a=math.sqrt(5))
        nn.init.kaiming_uniform_(self.pointwise.weight, a=math.sqrt(5))

    def forward(self, x):
        return self.pointwise(self.depthwise(x))

class GroupNorm(nn.GroupNorm):
    """
    Input: tensor in shape [B, C, H, W]
    """
    def __init__(self, num_channels, **kwargs):
        super().__init__(1, num_channels, **kwargs)

class DWConvSeq(nn.Module):
    def __init__(self, dim=768):
        super(DWConvSeq, self).__init__()
        self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)

    def forward(self, x, H, W):
        B, N, C = x.shape
        x = x.transpose(1, 2).view(B, C, H, W)
        x = self.dwconv(x)
        x = x.flatten(2).transpose(1, 2)

        return x

def make_divisible(v, divisor=8, min_value=None):
    min_value = min_value or divisor
    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
    # Make sure that round down does not go down by more than 10%.
    if new_v < 0.9 * v:
        new_v += divisor
    return new_v

class SqueezeExcite(nn.Module):
    def __init__(self, in_chs, se_ratio=0.25, reduced_base_chs=None,
                 act_layer=nn.ReLU, gate_fn=nn.Sigmoid, divisor=1, **_):
        super(SqueezeExcite, self).__init__()
        self.gate_fn = nn.Sigmoid()
        reduced_chs = make_divisible((reduced_base_chs or in_chs) * se_ratio, divisor)
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.conv_reduce = nn.Conv2d(in_chs, reduced_chs, 1, bias=True)
        self.act1 = act_layer(inplace=True)
        self.conv_expand = nn.Conv2d(reduced_chs, in_chs, 1, bias=True)

    def forward(self, x):
        x_se = self.avg_pool(x)
        x_se = self.conv_reduce(x_se)
        x_se = self.act1(x_se)
        x_se = self.conv_expand(x_se)
        x = x * self.gate_fn(x_se)
        return x

class SEMlp(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0., linear=False, use_se=True):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        # self.dwconv = DWConv(hidden_features)
        self.dwconv = DWConvSeq(hidden_features)
        self.gamma = nn.Parameter(torch.ones(hidden_features), requires_grad=True)
        self.act = act_layer()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)
        self.linear = linear
        if self.linear:
            self.relu = nn.ReLU(inplace=True)
        self.se = SqueezeExcite(out_features, se_ratio=0.25) if use_se else nn.Identity()
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            trunc_normal_(m.weight, std=.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)
        elif isinstance(m, nn.Conv2d):
            fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
            fan_out //= m.groups
            m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
            if m.bias is not None:
                m.bias.data.zero_()

    def forward(self, x, H, W):
        B, N, C = x.shape
        x = self.fc1(x)
        if self.linear:
            x = self.relu(x)
        # import pdb; pdb.set_trace()
        x = self.drop(self.gamma * self.dwconv(x, H, W)) + x
        x = self.fc2(x)
        x = self.drop(x)
        x = self.se(x.permute(0, 2, 1).reshape(B, C, H, W)).reshape(B, C, N).permute(0, 2, 1)
        return x

class DeformableProjEmbed(nn.Module):
    """ feature map to Projected Embedding
    """
    def __init__(self, in_chans=512, emb_chans=128):
        super().__init__()
        self.kernel_size = kernel_size = 3
        self.stride = stride = 1
        self.padding = padding = 1
        self.proj = nn.Conv2d(in_chans, emb_chans, kernel_size=kernel_size, stride=stride,
                              padding=padding)
        self.offset_conv = nn.Conv2d(in_chans, 2 * kernel_size * kernel_size, kernel_size=kernel_size,
                                     stride=stride, padding=padding)
        nn.init.constant_(self.offset_conv.weight, 0.)
        nn.init.constant_(self.offset_conv.bias, 0.)
        self.modulator_conv = nn.Conv2d(in_chans, 1 * kernel_size * kernel_size, kernel_size=kernel_size,
                                     stride=stride, padding=padding)
        nn.init.constant_(self.modulator_conv.weight, 0.)
        nn.init.constant_(self.modulator_conv.bias, 0.)
        self.norm = nn.BatchNorm2d(emb_chans)
        self.act = nn.GELU()

    def deform_proj(self, x):
        # h, w = x.shape[2:]
        max_offset = min(x.shape[-2], x.shape[-1]) // 4
        offset = self.offset_conv(x).clamp(-max_offset, max_offset)
        modulator = 2. * torch.sigmoid(self.modulator_conv(x))
        x = torchvision.ops.deform_conv2d(input=x,
                                          offset=offset,
                                          weight=self.proj.weight,
                                          bias=self.proj.bias,
                                          padding=self.padding,
                                          mask=modulator,
                                          stride=self.stride,
                                          )
        return x

    def forward(self, x):
        x = self.deform_proj(x)
        x = self.act(self.norm(x))
        return x

class DeformableMLP(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        stride: int = 1,
        padding: int = 0,
        dilation: int = 1,
        groups: int = 1,
        bias: bool = True,
    ):
        super(DeformableMLP, self).__init__()

        if in_channels % groups != 0:
            raise ValueError('in_channels must be divisible by groups')
        if out_channels % groups != 0:
            raise ValueError('out_channels must be divisible by groups')
        if stride != 1:
            raise ValueError('stride must be 1')
        if padding != 0:
            raise ValueError('padding must be 0')

        self.in_channels = in_channels
        self.out_channels = out_channels
        self.stride = _pair(stride)
        self.padding = _pair(padding)
        self.dilation = _pair(dilation)
        self.groups = groups

        self.weight = nn.Parameter(torch.empty(out_channels, in_channels // groups, 1, 1))  # kernel size == 1

        if bias:
            self.bias = nn.Parameter(torch.empty(out_channels))
        else:
            self.register_parameter('bias', None)

        self.offset_modulator_conv = DWConv2d(in_channels, 3 * in_channels)

        self.norm = nn.BatchNorm2d(in_channels)
        self.act = nn.GELU()
        self.reset_parameters()

    def reset_parameters(self) -> None:
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))

        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)

    def forward(self, input: Tensor) -> Tensor:
        B, C, H, W = input.size()
        offset_modulator = self.offset_modulator_conv(input)
        offset_y, offset_x, modulator = torch.chunk(offset_modulator, 3, dim=1)
        modulator = 2. * torch.sigmoid(modulator)
        offset = torch.cat((offset_y, offset_x), dim=1)
        max_offset = max(H, W) // 4
        offset = offset.clamp(-max_offset, max_offset)
        x = torchvision.ops.deform_conv2d(input=input,
                                          offset=offset,
                                          weight=self.weight,
                                          bias=self.bias,
                                          padding=self.padding,
                                          mask=modulator,
                                          stride=self.stride,
                                          dilation=self.dilation
                                          )

        x = self.act(self.norm(x))
        return x

class DeformableMLPBlock(nn.Module):
    def __init__(self, in_chans=512, emb_chans=64, drop_path=0.):
        super().__init__()
        # spatial deformable proj
        self.sdp = DeformableProjEmbed(in_chans=in_chans, emb_chans=emb_chans)
        self.dmlp = DeformableMLP(emb_chans, emb_chans)
        self.cmlp1 = SEMlp(emb_chans)
        self.cmlp2 = SEMlp(emb_chans)
        h, w = 3, 3
        self.norm1 = GroupNorm(emb_chans)
        self.pooling = nn.AvgPool2d((h, w), stride=1, padding=(h//2, w//2), count_include_pad=False)
        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
    def forward(self, x):
        x = self.sdp(x)
        B, C, H, W = x.shape
        x_ = x.reshape(B, C, -1).permute(0, 2, 1)
        x_ = self.cmlp1(x_, H, W)
        x_ = x_.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
        x = x_ + self.pooling(self.norm1(x))

        x_ = x.reshape(B, C, -1).permute(0, 2, 1)
        x_ = self.cmlp2(x_, H, W)
        x_ = x_.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
        x = x_ + self.drop_path(self.dmlp(x))

        return x

class DMLP(nn.Module):
    def __init__(self, vit_params):
        super().__init__()
        emb_chans = vit_params['emb_chans']
        self.head1 = DeformableMLPBlock(in_chans=64, emb_chans=emb_chans)
        self.head2 = DeformableMLPBlock(in_chans=128, emb_chans=emb_chans)
        self.head3 = DeformableMLPBlock(in_chans=320, emb_chans=emb_chans)
        self.head4 = DeformableMLPBlock(in_chans=512, emb_chans=emb_chans)
        self.pred = nn.Conv2d(emb_chans, vit_params['nclass'], 1)

    def forward(self, c1, c2, c3, c4):
        size = c1.size()[2:]
        c4 = self.head4(c4)
        c4 = F.interpolate(c4, size, mode='bilinear', align_corners=True)

        c3 = self.head3(c3)
        c3 = F.interpolate(c3, size, mode='bilinear', align_corners=True)

        c2 = self.head2(c2)
        c2 = F.interpolate(c2, size, mode='bilinear', align_corners=True)

        c1 = self.head1(c1)
        out = c1 + c2 + c3 + c4
        out = self.pred(out)
        return out


"""This service allows to delete executed task"""
import os
import sys
import time
import MySQLdb
from rq import Worker, Queue, Connection
from methods.connection import get_redis, get_cursor

r = get_redis()

def delete_task(id):
    """Deletes task from db (table tasks)"""
    cursor, db = get_cursor()
    if not cursor or not db:
        # log that failed getting cursor
        return False
    if id == "ALL":
        q = "DELETE FROM tasks"
    else:
        q = f"DELETE FROM tasks WHERE id={id}"
    try:
        cursor.execute(q)
    except MySQLdb.Error as error:
        print(error)
        # Log
        return False
        # sys.exit("Error:Failed to delete a task")
    db.commit()
    return True

if __name__ == '__main__':

    q = Queue('delete_task', connection=r)
    with Connection(r):
        worker = Worker([q], connection=r,  name='delete_task')
        worker.work()


# https://www.algoexpert.io/questions/river-sizes
# Graphs

'''
   O(wh) Time and O(wh) Space
   BFS Solution
'''
def riverSizes(matrix):
    (width, height) = (len(matrix[0]), len(matrix))
    # to keep track of visited cells in the matrix
    visited = [[False for x in range(width)] for y in range(height)]
    result = []

    # a hash map of co-ordinates of all the cells that are ones
    ones_coordinates = {}
    for x in range(height):
        for y in range(width):
            if matrix[x][y] == 1:
                # if a cell has value == 1, put it's co-ordinates in the map
                ones_coordinates[(x,y)] = (x,y)

    for x in range(height):
        for y in range(width):
            # if current cell has value 1 and it has not yet been visited
            if matrix[x][y] == 1:
                if visited[x][y] is True:
                    continue

                # mark it as visited
                visited[x][y] = True
                # river size = 1
                current_river_size = 1

                # get it's adjacents cells in all directions
                adjacents = []
                get_adjacents(adjacents, x, y, height, width)

                # as long as all the adjacent cells and their adjacent cells have not been checked
                while len(adjacents) > 0:
                    # keep checking adjacent cell one at a time
                    adj = adjacents.pop(0)
                    # if the adjacent cell has value = 1
                    if adj in ones_coordinates:
                        current_adjacent = ones_coordinates[adj]
                        current_adjacent_x = current_adjacent[0]
                        current_adjacent_y = current_adjacent[1]

                        # and it has not yet been visited
                        if visited[current_adjacent_x][current_adjacent_y] is False:
                            # increment the current river size
                            current_river_size += 1
                            # mark it as visited
                            visited[current_adjacent_x][current_adjacent_y] = True
                            # add it's adjacents the queue
                            get_adjacents(adjacents, current_adjacent_x, current_adjacent_y, height, width)

                # any river size >= 1 is valid, add it to the result
                if current_river_size >= 1:
                    result.append(current_river_size)

    return result

'''Another Solution'''
# GLOBAL VARIABLE
river_size = 0
def riverSizes(matrix):
	visited = [[False for value in row] for row in matrix]
	result = []

	for row_no, row_list in enumerate(matrix):
		for col_no, value_in_row in enumerate(matrix[row_no]):
			if not visited[row_no][col_no]:
				if matrix[row_no][col_no] == 1:
					global river_size
					river_size = 1
					visited[row_no][col_no] = True
					found_a_one(row_no, col_no, matrix, visited)
					result.append(river_size)
	return result

def found_a_one(row_number, col_number, matrix, visited):
	global river_size
	up_index = row_number - 1 if row_number - 1 >= 0 else None
	down_index = row_number + 1 if row_number + 1 < len(matrix) else None
	left_index = col_number - 1 if col_number - 1 >= 0 else None
	right_index = col_number + 1 if col_number + 1 < len(matrix[row_number]) else None
	go_up, go_down, go_left, go_right = False, False, False, False

	if up_index is not None:
		# visit the element
		if not visited[up_index][col_number]:
			visited[up_index][col_number] = True
			if matrix[up_index][col_number] == 1:
				river_size += 1
				print(f'Visited [{up_index}][{col_number}]: Size = {river_size}')
				found_a_one(up_index, col_number, matrix, visited)

	if down_index is not None:
		if not visited[down_index][col_number]:
			visited[down_index][col_number] = True
			if matrix[down_index][col_number] == 1:
				river_size += 1
				print(f'Visited [{down_index}][{col_number}]: Size = {river_size}')
				found_a_one(down_index, col_number, matrix, visited)

	if left_index is not None:
		if not visited[row_number][left_index]:
			visited[row_number][left_index] = True
			if matrix[row_number][left_index] == 1:
				river_size += 1
				print(f'Visited [{row_number}][{left_index}]: Size = {river_size}')
				found_a_one(row_number, left_index, matrix, visited)

	if right_index is not None:
		if not visited[row_number][right_index]:
			visited[row_number][right_index] = True
			if matrix[row_number][right_index] == 1:
				river_size += 1
				print(f'Visited [{row_number}][{right_index}]: Size = {river_size}')
				found_a_one(row_number, right_index, matrix, visited)

def get_adjacents(result, x, y, height, width):
    if x - 1 >= 0:
        result.append((x-1,y))
    if x + 1 < height:
        result.append((x+1,y))
    if y - 1 >= 0:
        result.append((x, y-1))
    if y + 1 < width:
        result.append((x, y+1))

import unittest
class TestProgram(unittest.TestCase):
    def test_case_1(self):
        testInput = [[1, 0, 0, 1, 0], [1, 0, 1, 0, 0], [0, 0, 1, 0, 1], [1, 0, 1, 0, 1], [1, 0, 1, 1, 0]]
        expected = [1, 2, 2, 2, 5]
        self.assertEqual(sorted(riverSizes(testInput)), expected)
        print("Test Case: Passed")

if __name__ == "__main__":
    test = TestProgram()
    test.test_case_1()
'''

# Kunal Wadhwa

'''


import pytest
from unittest.mock import patch, call
from collections import Counter
import pendulum
import yaml
from copy import deepcopy
from omspy.brokers.zerodha import Zerodha
from omspy.orders.stop import *

@pytest.fixture
def stop_order():
    with patch("omspy.brokers.zerodha.Zerodha") as broker:
        broker.order_place.side_effect = range(10000, 10100)
        stop_order = StopOrder(
            symbol="aapl",
            side="buy",
            quantity=100,
            price=930,
            order_type=("LIMIT", "SL-M"),
            trigger_price=850,
            broker=broker,
        )
        return stop_order

@pytest.fixture
def stop_limit_order():
    with patch("omspy.brokers.zerodha.Zerodha") as broker:
        broker.order_place.side_effect = range(10000, 10100)
        stop_limit_order = StopLimitOrder(
            symbol="aapl",
            side="buy",
            quantity=100,
            price=930,
            order_type=("LIMIT", "SL-M"),
            trigger_price=850,
            stop_limit_price=830,
            broker=broker,
        )
        return stop_limit_order

@pytest.fixture
def trailing_stop_dict():
    with patch("omspy.brokers.zerodha.Zerodha") as broker:
        broker.order_place.side_effect = range(10000, 10100)
        stop_limit_order = dict(
            symbol="aapl",
            side="buy",
            quantity=100,
            price=930,
            order_type=("LIMIT", "SL-M"),
            trigger_price=850,
            trail_by=10,
            broker=broker,
        )
        return stop_limit_order

@pytest.fixture
def order_dict():
    with patch("omspy.brokers.zerodha.Zerodha") as broker:
        broker.order_place.side_effect = range(10000, 10100)
        return dict(
            symbol="aapl",
            side="buy",
            quantity=100,
            price=930,
            order_type=("LIMIT", "SL-M"),
            trigger_price=850,
            broker=broker,
        )

def test_stop_order(stop_order):
    assert stop_order.count == 2
    assert stop_order.orders[0].order_type == "LIMIT"
    order = Order(
        symbol="aapl",
        side="sell",
        quantity=100,
        trigger_price=850,
        price=930,
        order_type="SL-M",
        parent_id=stop_order.id,
    )
    # Copy over from existing order as these are system attributes
    order.id = stop_order.orders[-1].id
    order.timestamp = stop_order.orders[-1].timestamp
    assert stop_order.orders[-1] == order
    assert [o.order_type for o in stop_order.orders] == ["LIMIT", "SL-M"]

def test_stop_order_execute_all(stop_order):
    broker = stop_order.broker
    stop_order.execute_all()
    assert broker.order_place.call_count == 2
    assert stop_order.orders[0].order_id == 10000
    assert stop_order.orders[1].order_id == 10001
    for i in range(10):
        stop_order.execute_all()
    assert broker.order_place.call_count == 2

def test_stop_limit_order_defaults(stop_limit_order):
    order = stop_limit_order
    assert len(order.orders) == 2
    assert [o.order_type for o in order.orders] == ["LIMIT", "SL"]
    assert [o.price for o in order.orders] == [930, 830]
    assert [o.trigger_price for o in order.orders] == [0, 850]
    assert [o.side for o in order.orders] == ["buy", "sell"]

def test_stop_limit_order_execute_all(stop_limit_order):
    broker = stop_limit_order.broker
    stop_limit_order.execute_all()
    assert broker.order_place.call_count == 2
    print(stop_limit_order.orders[0])
    assert stop_limit_order.orders[0].order_id == 10000
    assert stop_limit_order.orders[1].order_id == 10001
    for i in range(10):
        stop_limit_order.execute_all()
    assert broker.order_place.call_count == 2
    # TODO: add test for order_type
    # TODO: add test for side

def test_trailing_stop_defaults(trailing_stop_dict):
    order = TrailingStopOrder(**trailing_stop_dict)
    assert order._stop_loss == 850
    assert order._next_trail == 940
    trailing_stop_dict.update({"side": "sell", "price": 900, "trigger_price": 950})
    order = TrailingStopOrder(**trailing_stop_dict)
    assert order._stop_loss == 950
    assert order._next_trail == 890

def test_trailing_stop_market_order(trailing_stop_dict):
    dct = trailing_stop_dict
    dct["price"] = 0
    dct["order_type"] = ("MARKET", "SL-M")
    order = TrailingStopOrder(**trailing_stop_dict)
    assert order._stop_loss == 850
    assert order._next_trail == 0

def test_trailing_stop_run_buy(trailing_stop_dict):
    dct = trailing_stop_dict
    order = TrailingStopOrder(**trailing_stop_dict)
    ltps = (935, 940, 941, 955, 940, 948, 961, 930)
    sl = (850, 850, 860, 870, 870, 870, 880, 880)
    for l, s in zip(ltps, sl):
        order.run(ltp=l)
        assert order._stop_loss == s
        assert order.orders[-1].trigger_price == s
    assert order.broker.order_modify.call_count == 3

def test_trailing_stop_run_sell(trailing_stop_dict):
    dct = trailing_stop_dict
    dct.update({"side": "sell", "trigger_price": 1000})
    order = TrailingStopOrder(**trailing_stop_dict)
    ltps = (930, 950, 980, 917, 894, 897, 920, 887)
    sl = (1000, 1000, 1000, 990, 980, 970, 970, 960)
    for l, s in zip(ltps, sl):
        order.run(ltp=l)
        print(l, s)
        assert order._stop_loss == s
        assert order.orders[-1].trigger_price == s
    assert order.broker.order_modify.call_count == 4

def test_trailing_stop_run_no_price(trailing_stop_dict):
    dct = trailing_stop_dict
    dct["price"] = 0
    dct["order_type"] = ("MARKET", "SL-M")
    order = TrailingStopOrder(**trailing_stop_dict)
    ltps = (935, 940, 941, 955, 940, 948, 961, 930)
    for l in ltps:
        order.run(ltp=l)
        assert order.orders[-1].trigger_price == 850

def test_target_order_defaults(order_dict):
    order_dict["target"] = 950
    order = TargetOrder(**order_dict)
    order.execute_all()
    assert order.orders[0].order_type == "LIMIT"
    assert order.orders[0].price == 930
    assert order.orders[-1].order_type == "SL-M"
    assert order.orders[-1].trigger_price == 850

def test_target_order_buy_target_hit(order_dict):
    order_dict["target"] = 950
    order = TargetOrder(**order_dict)
    order.execute_all()
    for ltp in (930, 944, 910, 864, 930, 940, 950):
        order.run(ltp=ltp)
    assert order.broker.order_place.call_count == 2
    order.broker.order_modify.assert_called_once()
    # TODO: Check do not hit target after SL hit
    # TODO: Do not call target after modify hit

def test_target_order_sell_target_hit(order_dict):
    order_dict.update({"side": "sell", "price": 830, "target": 800})
    order = TargetOrder(**order_dict)
    order.execute_all()
    for ltp in (830, 817, 824, 801, 800):
        order.run(ltp=ltp)
    assert order.broker.order_place.call_count == 2
    order.broker.order_modify.assert_called_once()


import pygame
#this code should be the literal same thing as healthBar.py but with mana instead of health
#using magic will decrease the overall "hp" of the class
class manaBar(pygame.sprite.Sprite):
   def __init__(self, x, y, mana, maxMana):
      super().__init__()
      self.font = pygame.font.SysFont("caladea", 35)
      self.mana = mana
      self.maxMana = maxMana
      self.manaStr = f"{mana} / {maxMana}"
      self.bar = self.font.render(self.manaStr, False, (0,0,0), (0,0,200))
      self.image = self.bar
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y
      self.x = x
      self.y = y
   def update(self, mana):
      """
      creates mana bar based on max mana and the current mana, after each attack magic is used on enemy it will decrease its health.
      args: none
      return: none
      """
      self.mana = mana
      if self.mana >= 0:
         self.manaStr = f"{self.mana} / {self.maxMana}"
      else:
         self.manaStr = f"0 / {self.maxMana}"
      self.bar = self.font.render(self.manaStr, False, (0,0,0), (0,0,200))
      self.image = self.bar
      self.rect = self.image.get_rect()
      self.rect.x = self.x
      self.rect.y = self.y


import sqlite3
import re
from collections import Counter
import time
import datetime
import csv
import numpy as np
import pandas
import itertools

# custom function for regex in SQLite
def regexp(expr, item):
    reg = re.compile(expr)
    return reg.search(item) is not None

# establish connection to pedestrian db
conn_ped = sqlite3.connect('pedestrian.db')
conn_ped.create_function("REGEXP", 2, regexp)
cursor_ped = conn_ped.cursor()

# establish connection to parking db
conn_par = sqlite3.connect('parking.db')
conn_par.create_function("REGEXP", 2, regexp)
cursor_par = conn_par.cursor()

# create list of dates for pedestrian
dates_lower = [d.strftime('%d-%b-%Y') for d in pandas.date_range('20160101','20161231')]
dates_ped = [date.upper() for date in dates_lower]

# create list of dates for parking
dates_par = [d.strftime('%m/%d/%Y') for d in pandas.date_range('20160101','20161231')]

# open output file
output_file = open('output_pedestrian_and_parking_year_sum.csv', 'w')
output_file.write("unix_time,count_pedestrian,count_parking\n")

buffer = []

# for every day in 2016
for i,date in enumerate(dates_ped):
  t_pedestrian = [' ' + date + '.*']
  t_parking = [dates_par[i] + '.*']

  # get all the the PEDESTRIAN sensor counts for a day
  cursor_ped.execute('SELECT SUM(hourly_count) FROM data WHERE date_time REGEXP ?', t_pedestrian)
  count_pedestrian = str(cursor_ped.fetchall()[0][0])

  # get all the the PARKING sensor counts for a day
  cursor_par.execute('SELECT COUNT(st_marker_id) FROM data WHERE departure_date REGEXP ?', t_parking)
  count_parking = str(cursor_par.fetchall()[0][0])

  # convert date to unix time, date is converted to lovercase because %b should be lowercase, but the dates are with uppercase in the db
  unix_date = time.mktime(datetime.datetime.strptime(date.lower(), "%d-%b-%Y").timetuple())

  data_point = str(unix_date)[:-2] + ',' + count_pedestrian + ',' + count_parking
  buffer.append(data_point)
  print(date)

# write buffer to file
output_file.write("\n".join(buffer) + "\n")

output_file.close()
print("Done")


import unittest
from chemotaxis_model import ChemotaxisModel, ReceptorStates, State,  \
    T2_CONC, StateAggregationFactory, R_CONC, B_CONC, Y_CONC

IGNORE_TEST = False
NUM_METHYL = 3
# States are: is_boundL (T/F), is_phosphorylated (T/F), is_boundR (T/F)
NUM_STATES = 2*2*2*NUM_METHYL

#############################
# Tests
#############################
# pylint: disable=W0212,C0111,R0904
class TestChemotaxisModelBasic(unittest.TestCase):

  def setUp(self):
    self.model = ChemotaxisModel()
    self.model.initialize()
    self.model.run(start=0, end=10)
    self.receptor = ReceptorStates(self.model.getResult())

  def testConstructor(self):
    if IGNORE_TEST:
      return
    self.assertTrue('Yp =' in self.model._antimony_model)

  def testInitialize(self):
    if IGNORE_TEST:
      return
    rr = self.model.initialize()
    self.assertTrue(abs(self.model._rr.R - float(R_CONC)) <= 1e-9)

  def testRun(self):
    if IGNORE_TEST:
      return
    self.model.initialize()
    self.model.run()

  def testGetVariable(self):
    Y = self.model.getVariable("Y")
    Yp = self.model.getVariable("Yp")
    b = [y == Y_CONC for y in Y + Yp]
    self.assertTrue(b)
    #
    fYp = self.model.getVariable("fYp")
    b = [y <= 1 and 0 <= y for y in fYp]
    self.assertTrue(b)
    #
    fBp = self.model.getVariable("fBp")
    b = [y <= 1 and 0 <= y for y in fBp]
    self.assertTrue(b)
    #
    B = self.model.getVariable("B")
    Bp = self.model.getVariable("Bp")
    b = [y == B_CONC for y in B + Bp]
    self.assertTrue(b)
    #
    var = self.model.getVariable("J1_2R")
    self.assertEqual(len(var), len(Bp))
    #
    time = self.model.getVariable("time")
    self.assertEqual(len(time), len(Bp))

# pylint: disable=W0212,C0111,R0904
class TestState(unittest.TestCase):

  def setUp(self):
    self.model = ChemotaxisModel()
    self.model.initialize()
    self.model.run(start=0, end=10)

  def _testBasics(self, l, p, r, m, expected_name):
    """
    :param bool l: is ligand bound
    :param bool p: is phosphorylated
    :param int m: methylation
    """
    state = State(l,p,r, m, self.model.getResult())
    name = state.getName()
    self.assertEqual(name, expected_name)
    pairs = zip(state.getData(), self.model.getResult()[name])
    b = all([abs(x-y) <= 1e-3*abs(min(x,y)) for x,y in pairs])
    if not b:
      import pdb; pdb.set_trace()
    self.assertTrue(b)

  def testBasics(self):
    self._testBasics(True, True, False, 2, 'LT2p')
    self._testBasics(False, True, False, 2, 'T2p')
    self._testBasics(True, False, False, 2, 'LT2')
    self._testBasics(True, True, True, 3, 'LT3pR')

# pylint: disable=W0212,C0111,R0904
class TestReceptorStates(unittest.TestCase):

  def setUp(self):
    self.model = ChemotaxisModel()
    self.model.initialize()
    self.model.run(start=0, end=10)

  def testBasic(self):
    receptor = ReceptorStates(self.model.getResult())
    self.assertEqual(len(receptor._states), NUM_STATES)
    # Select a state that should have no occupancy
    state = [s for s in receptor._states if
                s.is_boundL and (s.methylation == 2) and
                s.is_phosphorylated][0]
    b = all([x < 0.01 for x in state.getNominalData()])
    self.assertTrue(b)

  def _testSelectStates(self, func, expected):
    receptor = ReceptorStates(self.model.getResult())
    states = receptor.selectStates(func)
    self.assertEqual(len(states), expected)

  def testSelectStates(self):
    func = (lambda l,p,r,m: l)
    self._testSelectStates(func, NUM_STATES/2)
    func = (lambda l,p,r,m: p)
    self._testSelectStates(func, NUM_STATES/2)
    func = (lambda l,p,r,m: m == 2)
    self._testSelectStates(func, NUM_STATES/NUM_METHYL)

  # TODO: Losing about 3% of the receptors
  def testSumStates(self):
    # Test that the sum of all states results in the Receptor conc
    func = (lambda l,p,r,m: True)
    receptor = ReceptorStates(self.model.getResult())
    total = receptor.sumStates(func)
    T = float(T2_CONC)
    b = all([abs(T-x)/T < 0.01 for x in total])
    self.assertTrue(b)

  def testFrcStates(self):
    # Test that the sum of all states results in the Receptor conc
    func = (lambda l,p,r,m: True)
    receptor = ReceptorStates(self.model.getResult())
    total = receptor.frcStates(func)
    b = all([abs(1-x) < 0.01 for x in total])
    self.assertTrue(b)

# pylint: disable=W0212,C0111,R0904
class TestStateAggregationFactory(unittest.TestCase):

  def setUp(self):
    self.model = ChemotaxisModel()
    self.model.initialize()
    self.model.run(start=0, end=10)
    self.receptor = ReceptorStates(self.model.getResult())
    self.factory = StateAggregationFactory(self.receptor)

  def testGetFunc(self):
    func = self.factory._getFunc("_", 0, lambda x: True)
    self.assertTrue(func(True))
    func = self.factory._getFunc("T", 0, lambda x: x in ["T", "F"])
    self.assertTrue(func(True))
    self.assertFalse(func(False))
    with self.assertRaises(ValueError):
      self.factory._getFunc("T", 0, lambda x: x in ["F"])
    func = self.factory._getFunc("2", 0, lambda x: int(x) < 5)
    self.assertTrue(func(2))
    self.assertFalse(func(3))

  def testV(self):
    value = self.factory.v("t____")
    expected = self.receptor.sumStates(lambda l,p,r,m: True)
    pairs = zip(value, expected)
    b = all([abs(x-y) < abs(y)*0.001 for x,y in pairs])
    self.assertTrue(b)
    count = len(expected)
    names = ["_T_3", "T__3", "TT__", "T___", "_T__", "___3", "____"]
    for name in names:
      try:
        variable = "f%s" % name
        value = self.factory.v(variable)
        self.assertEqual(len(value), count)
        variable = "t%s" % name
        value = self.factory.v(variable)
        self.assertEqual(len(value), count)
      except Exception as e:
        import pdb; pdb.set_trace()
        pass

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


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from .update import BasicUpdateBlock, SmallUpdateBlock
from .extractor import BasicEncoder, SmallEncoder
from .corr import CorrBlock, AlternateCorrBlock
from .utils.utils import coords_grid, upflow8

try:
    autocast = torch.cuda.amp.autocast
except:
    # dummy autocast for PyTorch < 1.6
    class autocast:
        def __init__(self, enabled):
            pass
        def __enter__(self):
            pass
        def __exit__(self, *args):
            pass

class RAFT(nn.Module):
    def __init__(self, small=False,dropout=0,alternate_corr=False,mixed_precision=False,iterations=24):
        super(RAFT, self).__init__()
    # parser.add_argument('--name', default='raft', help="name your experiment")
    # parser.add_argument('--stage', help="determines which dataset to use for training")
    # parser.add_argument('--restore_ckpt', help="restore checkpoint")
    # parser.add_argument('--small', action='store_true', help='use small model')
    # parser.add_argument('--validation', type=str, nargs='+')

    # parser.add_argument('--lr', type=float, default=0.00002)
    # parser.add_argument('--num_steps', type=int, default=100000)
    # parser.add_argument('--batch_size', type=int, default=6)
    # parser.add_argument('--image_size', type=int, nargs='+', default=[384, 512])
    # parser.add_argument('--gpus', type=int, nargs='+', default=[0,1])
    # parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision')

    # parser.add_argument('--iters', type=int, default=12)
    # parser.add_argument('--wdecay', type=float, default=.00005)
    # parser.add_argument('--epsilon', type=float, default=1e-8)
    # parser.add_argument('--clip', type=float, default=1.0)
    # parser.add_argument('--dropout', type=float, default=0.0)
    # parser.add_argument('--gamma', type=float, default=0.8, help='exponential weighting')
    # parser.add_argument('--add_noise', action='store_true')
    # parser.add_argument('--model', help="restore checkpoint")
    # parser.add_argument('--dataset', help="dataset for evaluation")
    # parser.add_argument('--small', action='store_true', help='use small model')
    # parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision')
    # parser.add_argument('--alternate_corr', action='store_true', help='use efficent correlation implementation')

        if small:
            self.hidden_dim = hdim = 96
            self.context_dim = cdim = 64
            self.corr_levels = 4
            self.corr_radius = 3

        else:
            self.hidden_dim = hdim = 128
            self.context_dim = cdim = 128
            self.corr_levels = 4
            self.corr_radius = 4

        self.iters=iterations
        self.mixed_precision = mixed_precision
        self.small = small
        self.dropout = dropout
        self.alternate_corr = alternate_corr

        # feature network, context network, and update block
        if small:
            self.fnet = SmallEncoder(output_dim=128, norm_fn='instance', dropout=dropout)
            self.cnet = SmallEncoder(output_dim=hdim+cdim, norm_fn='none', dropout=dropout)
            self.update_block = SmallUpdateBlock(self.corr_levels,self.corr_radius,hidden_dim=hdim)

        else:
            self.fnet = BasicEncoder(output_dim=256, norm_fn='instance', dropout=dropout)
            self.cnet = BasicEncoder(output_dim=hdim+cdim, norm_fn='batch', dropout=dropout)
            self.update_block = BasicUpdateBlock(self.corr_levels,self.corr_radius,hidden_dim=hdim)

    def freeze_bn(self):
        for m in self.modules():
            if isinstance(m, nn.BatchNorm2d):
                m.eval()

    def initialize_flow(self, img):
        """ Flow is represented as difference between two coordinate grids flow = coords1 - coords0"""
        N, C, H, W = img.shape
        coords0 = coords_grid(N, H//8, W//8, device=img.device)
        coords1 = coords_grid(N, H//8, W//8, device=img.device)

        # optical flow computed as difference: flow = coords1 - coords0
        return coords0, coords1

    def upsample_flow(self, flow, mask):
        """ Upsample flow field [H/8, W/8, 2] -> [H, W, 2] using convex combination """
        N, _, H, W = flow.shape
        mask = mask.view(N, 1, 9, 8, 8, H, W)
        mask = torch.softmax(mask, dim=2)

        up_flow = F.unfold(8 * flow, [3,3], padding=1)
        up_flow = up_flow.view(N, 2, 9, 1, 1, H, W)

        up_flow = torch.sum(mask * up_flow, dim=2)
        up_flow = up_flow.permute(0, 1, 4, 2, 5, 3)
        return up_flow.reshape(N, 2, 8*H, 8*W)

    def forward(self, image1, image2, flow_init=None, upsample=True, test_mode=False):
        """ Estimate optical flow between pair of frames """

        # TODO: THIS Was in the original when replicating
        # image1 = 2 * (image1 / 255.0) - 1.0
        # image2 = 2 * (image2 / 255.0) - 1.0

        image1 = image1.contiguous()
        image2 = image2.contiguous()

        hdim = self.hidden_dim
        cdim = self.context_dim

        # run the feature network
        with autocast(enabled=self.mixed_precision):
            fmap1, fmap2 = self.fnet([image1, image2])

        fmap1 = fmap1.float()
        fmap2 = fmap2.float()
        if self.alternate_corr:
            corr_fn = AlternateCorrBlock(fmap1, fmap2, radius=self.corr_radius)
        else:
            corr_fn = CorrBlock(fmap1, fmap2, radius=self.corr_radius)

        # run the context network
        with autocast(enabled=self.mixed_precision):
            cnet = self.cnet(image1)
            net, inp = torch.split(cnet, [hdim, cdim], dim=1)
            net = torch.tanh(net)
            inp = torch.relu(inp)

        coords0, coords1 = self.initialize_flow(image1)

        if flow_init is not None:
            coords1 = coords1 + flow_init

        flow_predictions = []
        for _ in range(self.iters):
            coords1 = coords1.detach()
            corr = corr_fn(coords1) # index correlation volume

            flow = coords1 - coords0
            with autocast(enabled=self.mixed_precision):
                net, up_mask, delta_flow = self.update_block(net, inp, corr, flow)

            # F(t+1) = F(t) + \Delta(t)
            coords1 = coords1 + delta_flow

            # upsample predictions
            if up_mask is None:
                flow_up = upflow8(coords1 - coords0)
            else:
                flow_up = self.upsample_flow(coords1 - coords0, up_mask)

            flow_predictions.append(flow_up)

        if test_mode:
            return coords1 - coords0, flow_up
        return flow_predictions


import pandas as pd
import numpy as np
import nltk
nltk.download('punkt')
import sklearn
from numpy import argmax

def transform(headlines):
	tokens = [w for s in headlines for w in s ]
	print()
	print('All Tokens:')
	print(tokens)

	results = []
	label_enc = sklearn.preprocessing.LabelEncoder()
	onehot_enc = sklearn.preprocessing.OneHotEncoder()

	encoded_all_tokens = label_enc.fit_transform(list(set(tokens)))
	encoded_all_tokens = encoded_all_tokens.reshape(len(encoded_all_tokens), 1)

	onehot_enc.fit(encoded_all_tokens)

	for headline_tokens in headlines:
		print()
		print('Original Input:', headline_tokens)

		encoded_words = label_enc.transform(headline_tokens)
		print('Encoded by Label Encoder:', encoded_words)

		encoded_words = onehot_enc.transform(encoded_words.reshape(len(encoded_words), 1))
		# print('Encoded by OneHot Encoder:')
		# print(encoded_words)
		results.append(np.sum(encoded_words.toarray(), axis=0))

	return results

def euclideanDistance(str1, str2):
	str1_tokens = nltk.word_tokenize(str1)
	str2_tokens = nltk.word_tokenize(str2)

	transformed_result = transform([str1_tokens, str2_tokens])
	score = sklearn.metrics.pairwise.euclidean_distances([transformed_result[0]], [transformed_result[1]])[0][0]
	return score

s1 = "one is two ok three and my o l"
s2 = "one is two ok there and ma o l"
print(euclideanDistance(s1, s2))


import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET

url = 'http://py4e-data.dr-chuck.net/comments_69242.xml'
data = urllib.request.urlopen(url).read()
tree = ET.fromstring(data)
results = tree.findall('comments/comment')
lst = list()
for item in results:
    find1 = int(item.find('count').text)
    lst.append(find1)
a = sum(lst)
print(a)


import time
import datetime
from bson import ObjectId

from galah.db.models import Submission, Assignment

# Set up configuration and logging
from galah.base.config import load_config
from galah.shepherd.api import send_test_request
config = load_config("sisyphus")
shepherd_config = load_config("shepherd")

import logging
logger = logging.getLogger("galah.sisyphus.rerun_test_harness")

def _rerun_test_harness(assignment):
    try:
        # Get assignment
        assn = Assignment.objects.get(id = ObjectId(assignment))

        if not assn.test_harness:
            logger.info("Attempting to rerun test harnesses on assignment "
                        "with no test harnesses")
            return

        # Form the submissions query
        query = {
            "assignment": ObjectId(assignment),
            "most_recent": True
        }

        # Grab the most recent submissions from each user.
        submissions = list(Submission.objects(**query))

        if not submissions:
            logger.info("No submissions found for this assignment.")
            return

        # Send a bunch of test requests to shepherd to be rerun.
        for i in submissions:
            i.test_request_timestamp = datetime.datetime.now()
            i.save()
            logger.info("Sent test request to shepherd for %s" % str(i.id))
            send_test_request(shepherd_config["PUBLIC_SOCKET"], i.id)

            time.sleep(30)
    except Exception as e:
        logger.error(str(e))

        raise


#!/usr/bin/env python
"""
Python implementation of
- Tiny Encryption Algorithm (TEA)
- XTEA
- RAIDEN
- function to compute the differential trail (round differences)
  given the input-output difference pair of the F function
- functions to print the differential trail
- functions that computes the probability of the trail heuritically
- function to print the heuristic probability

Block size: 64bits
Key size: 128bits
"""

from ctypes import c_uint32, c_uint64
import numpy as np
from copy import copy
import math

# Constants
ROUNDS = 64

WORD_BIT_SIZE = 32
WORD_HEX_SIZE = WORD_BIT_SIZE//4
BLOCK_UINT32_SIZE = 2
BLOCK_BYTE_SIZE = BLOCK_UINT32_SIZE*WORD_BIT_SIZE//8
KEY_UINT32_SIZE = 4
KEY_BYTE_SIZE = KEY_UINT32_SIZE*WORD_BIT_SIZE//8

BLOCK_BIT_SIZE = 64

#
#  Helpers for c_uint32 math
#

def change_bit(vector, position):
    if position >= BLOCK_BIT_SIZE:
        print("ERROR: position greater than block size.")
        return 0
    return vector ^ (0x1 << position)

def split_block(vector):
    return [c_uint32(vector >> WORD_BIT_SIZE).value, c_uint32(vector & 0xFFFFFFFF).value]

def join_blocks(b):
    return c_uint64(b[0] << WORD_BIT_SIZE ^ b[1]).value

def hamming_weight(vector):
    weight = 0
    for i in range(BLOCK_BIT_SIZE):
        weight = weight + ((vector >> i) & 0x1)
    return weight

def raiden_lshift(a, s):
    """ Left shift s """
    shift = min(s, WORD_BIT_SIZE)
    return c_uint32(a << shift).value

def lshift(a, s):
    """ Left shift s """
    return c_uint32(a << s).value

def rshift(a, s):
    """ Right shift s """
    return c_uint32(a >> s).value

def lshift_add(a, b, s):
    """ Left shift s and add b """
    result = lshift(a,s) + c_uint32(b).value
    return c_uint32(result).value

def rshift_add(a, b, s):
    """ Right shift s and add b """
    result = rshift(a, s) + c_uint32(b).value
    return c_uint32(result).value

def add(a, b):
    """ Add a and b """
    result = c_uint32(a).value + c_uint32(b).value
    return c_uint32(result).value

def add64(a, b):
    """ Add a and b, where a,b contains two 32 bit words """
    result = [add(a[0],b[0]), add(a[1],b[1])]
    return result

def sub(a, b):
    """ Subract a and b """
    result = c_uint32(a).value - c_uint32(b).value
    return c_uint32(result).value

def sub64(a, b):
    """ Subract a and b """
    result = [sub(a[0],b[0]), sub(a[1],b[1])]
    return result

def xor(a, b):
    """ XOR a, b """
    return c_uint32(a).value ^ c_uint32(b).value

def xor3(a, b, c):
    """ XOR a, b, and c """
    middle = c_uint32(a).value ^ c_uint32(b).value
    return c_uint32(middle ^ c_uint32(c).value).value

def bitwise_and(a, b):
    """ AND a, b """
    return c_uint32(a).value & c_uint32(b).value

def print_block(vector):
    print("{0:016x} ".format(vector), end='')
    # print("{0:016x} ".format(v))

def print_word(w):
    print("{0:0{1}x} ".format(w, WORD_HEX_SIZE), end='')

def print_array(v):
    # print( str(hex(v[0])) + " " + str(hex(v[1])))
    for x in v:
        # print("{}".format(hex(int(x))[2:].rjust(WORD_HEX_SIZE,'0')))
        print("{0:0{1}x} ".format(x, WORD_HEX_SIZE), end='')
        # print("{0:#0{1}x}".format(x,WORD_HEX_SIZE)), # to print with 0x

def print_array2(v):
    print( str(hex(v[0]))[2:WORD_HEX_SIZE+2] + " " + str(hex(v[1]))[2:WORD_HEX_SIZE+2] )

def random_word():
    return np.random.randint(0,2**WORD_BIT_SIZE)

def random_message():
    return [np.random.randint(0,2**WORD_BIT_SIZE) for i in range(BLOCK_UINT32_SIZE)]

def random_key():
    return [np.random.randint(0,2**WORD_BIT_SIZE) for i in range(KEY_UINT32_SIZE)]

def random_permutation():
    return random_message()

def random_permutation_encrypt_block(input_block=0, input_key=0, nrounds=0):
    return random_message()

def tea_F_function(block, k0, k1, delta_i):
    left_shift = 4
    right_shift = 5
    return xor3(
                lshift_add(block, k0, left_shift),
                add(block, delta_i),
                rshift_add(block, k1, right_shift)
            )

def tea_encrypt_block(input_block, input_key, starting_round=0, nrounds=ROUNDS, verb=False):
    """
    Encrypt a single 64-bit block using a given key
    @param block: list of two c_uint32s
    @param key: list of four c_uint32s
    """
    block = copy(input_block)
    key = copy(input_key)
    assert len(block) == BLOCK_UINT32_SIZE
    assert len(key) == KEY_UINT32_SIZE
    summation = 0x0
    delta = 0x9e3779b9
    for i in range(starting_round, starting_round+nrounds):
        if verb:
            print("round: " + str(i))
            print("input: "),
            print_array(block)
            print("")
            # print("input:  b[0] = " + str(block[0]) + " - b[1] = " + str(block[1]))
        if ((i % 2) == 0 ):
            summation = c_uint32(summation + delta).value
            tmp = tea_F_function(block[1],key[0],key[1],summation)
            block[0] = add( block[0], tmp)
        else:
            tmp = tea_F_function(block[0],key[2],key[3],summation)
            block[1] = add(block[1],tmp)
        if verb:
            print("input: "),
            print_array(block)
            print("")
            # print("output: b[0] = " + str(block[0]) + " - b[1] = " + str(block[1]))
    return block

def tea_decrypt_block(input_block, input_key, nrounds=ROUNDS, verb=False):
    """
    Decrypt a single 64-bit block using a given key
    @param block: list of two c_uint32s
    @param key: list of four c_uint32s
    """
    block = copy(input_block)
    key = copy(input_key)
    assert len(block) == BLOCK_UINT32_SIZE
    assert len(key) == KEY_UINT32_SIZE
    summation = (0x9e3779b9*((ROUNDS+1)//2)) % 2**WORD_BIT_SIZE # for 64 rounds: 0xc6ef3720
    delta = 0x9e3779b9
    for i in range(nrounds-1,-1,-1):

        if verb:
            print("round: " + str(i))
            print("input: "),
            print_array(block)
            print("")

        if ((i % 2) == 1 ):
            tmp = tea_F_function(block[0],key[2],key[3],summation)
            block[1] = sub( block[1], tmp)
        else:
            tmp = tea_F_function(block[1],key[0],key[1],summation)
            block[0] = sub( block[0], tmp)
            summation = c_uint32(summation - delta).value
        if verb:
            print("input: "),
            print_array(block)
            print("")
    return block

def xtea_F_function(block, key, delta_i):
    # (((b1 << 4) ^ (b1 >> 5)) + b1) ^ (delta_i + key);
    left_shift = 4
    right_shift = 5
    tmp = xor(lshift(block, left_shift),rshift(block, right_shift))
    tmp = add(tmp, block)
    return xor(tmp, add(delta_i, key))

def xtea_encrypt_block(input_block, input_key, starting_round=0, nrounds=ROUNDS, verb=False):
    """
    Encrypt a single 64-bit block using a given key
    @param block: list of two c_uint32s
    @param key: list of four c_uint32s
    """
    block = copy(input_block)
    key = copy(input_key)
    assert len(block) == BLOCK_UINT32_SIZE
    assert len(key) == KEY_UINT32_SIZE
    summation = 0x0
    delta = 0x9e3779b9
    for i in range(starting_round, starting_round+nrounds):

        if verb:
            print("round: " + str(i))
            print("input: "),
            print_array(block)
            print("")
            # print("input:  b[0] = " + str(block[0]) + " - b[1] = " + str(block[1]))

        if ((i % 2) == 0 ):
            round_key = key[bitwise_and(summation, 3)] # key[delta_i & 3]
            tmp = xtea_F_function(block[1], round_key, summation)
            block[0] = add( block[0], tmp)
            summation = c_uint32(summation + delta).value
        else:
            round_key = key[bitwise_and(rshift(summation, 11), 3)] # key[(sum>>11) & 3]
            tmp = xtea_F_function(block[0], round_key, summation)
            block[1] = add(block[1], tmp)

        if verb:
            print("input: "),
            print_array(block)
            print("")
            # print("output: b[0] = " + str(block[0]) + " - b[1] = " + str(block[1]))

    return block

def xtea_decrypt_block(input_block, input_key, nrounds=ROUNDS, verb=False):
    """
    Decrypt a single 64-bit block using a given key
    @param block: list of two c_uint32s
    @param key: list of four c_uint32s
    """
    block = copy(input_block)
    key = copy(input_key)
    assert len(block) == BLOCK_UINT32_SIZE
    assert len(key) == KEY_UINT32_SIZE
    summation = (0x9e3779b9*((ROUNDS+1)//2)) % 2**WORD_BIT_SIZE # for 64 rounds: 0xc6ef3720
    delta = 0x9e3779b9
    for i in range(nrounds-1,-1,-1):

        if verb:
            print("round: " + str(i))
            print("input: "),
            print_array(block)
            print("")

        if ((i % 2) == 1 ):
            round_key = key[bitwise_and(rshift(summation, 11), 3)] # key[(sum>>11) & 3]
            tmp = xtea_F_function(block[0], round_key, summation)
            block[1] = sub( block[1], tmp)
        else:
            summation = c_uint32(summation - delta).value
            round_key = key[bitwise_and(summation, 3)] # key[delta_i & 3]
            tmp = xtea_F_function(block[1], round_key, summation)
            block[0] = sub( block[0], tmp)

        if verb:
            print("input: "),
            print_array(block)
            print("")

    return block

def raiden_F_function(block, key):
    # ((k + x) << 9) ^ (k − x) ^ ((k + x) >> 14)

    # tmp1 = rshift(add(key,block),9)
    # tmp2 = sub(key, block)
    # tmp3 = lshift(add(key, block), 14)
    # return xor3(tmp1, tmp2, tmp3)

    tmp1 = lshift(add(key,block),9)
    tmp2 = sub(key, block)
    tmp3 = rshift(add(key, block), 14)
    return xor3(tmp1, tmp2, tmp3)

def raiden_key_schedule_one_round(key):
    tmp1 = add(key[0], key[1])
    tmp2 = add(key[2], key[3])
    tmp3 = raiden_lshift(key[0], key[2])
    # tmp3 = key[0] << key[2]
    tmp4 = xor( tmp2, tmp3)

    return add(tmp1, tmp4)

def raiden_key_schedule(key, nrounds=ROUNDS):
    round_keys = [0 for i in range(nrounds)]
    for i in range(nrounds):
        round_keys[i] = raiden_key_schedule_one_round

def raiden_encrypt_block(input_block, input_key, starting_round=0, nrounds=ROUNDS, verb=False):
    """
    Encrypt a single 64-bit block using a given key
    @param block: list of two c_uint32s
    @param key: list of four c_uint32s
    """
    block = copy(input_block)
    key = copy(input_key)
    assert len(block) == BLOCK_UINT32_SIZE
    assert len(key) == KEY_UINT32_SIZE
    for i in range(starting_round, starting_round+nrounds):

        if verb:
            print("round: " + str(i))
            print("input: "),
            print_array(block)
            print("")
            # print("input:  b[0] = " + str(block[0]) + " - b[1] = " + str(block[1]))

        if ((i % 2) == 0 ):
            # sk.       = k[i%4]=((k[0]+k[1])+((k[2]+k[3])^(k[0]<<k[2])));
            key[i%4] = raiden_key_schedule_one_round(key)
            # key[i%4] = add(( add(key[0], key[1])), xor( add(key[2], key[3]), ( key[0] << key[2] ) ) )
            round_key = key[i%4]
            tmp = raiden_F_function(block[1], round_key)
            block[0] = add( block[0], tmp)
        else:
            tmp = raiden_F_function(block[0], round_key)
            block[1] = add(block[1], tmp)

        if verb:
            print("input: "),
            print_array(block)
            print("")
            # print("output: b[0] = " + str(block[0]) + " - b[1] = " + str(block[1]))

    return block

# VERIFY DIFFERENTIAL TRAIL PROBABILITIES

def compute_round_differences(alpha, beta):
    round_differences = [[0x00000000,0x00000000] for i in range(len(alpha)+1)]
    round_differences[0] = [sub(alpha[1],beta[0]), alpha[0]]

    for i in range(len(alpha)):
        # print("i = " + str(i))
        if (((i+1) % 2) == 1):
            # print("LEFT  = round_differences[i][0], beta[i] = " + str(hex(round_differences[i][0])) + ", " + str(hex(beta[i])))
            # print("RIGHT = round_differences[i][1].         = " + str(hex(round_differences[i][1])) )
            left = add(round_differences[i][0], beta[i])
            right = round_differences[i][1]
        else:
            # print("RIGHT = round_differences[i][1], beta[i] = " + str(hex(round_differences[i][1])) + ", " + str(hex(beta[i])))
            # print("LEFT  = round_differences[i][0].         = " + str(hex(round_differences[i][0])) )
            right = add(round_differences[i][1], beta[i])
            left = round_differences[i][0]
        round_differences[i+1] = [left, right]

    return round_differences

def print_round_differences(round_differences, alpha, beta):
    print("\nInput/Output differences:")
    print("\n             LEFT    RIGHT       alpha   ->    beta")
    print("round  0: ", end='')
    print_array(round_differences[0])
    print(" | ", end='')
    print("")
    for i in range(1,len(round_differences)):
        print("round %2d: " % (i), end='')
        print_array(round_differences[i])
        print(" | ", end='')
        print("{0:0{1}x} ".format(alpha[i-1], WORD_HEX_SIZE), end='')
        print(" -> ", end='')
        print("{0:0{1}x} ".format(beta[i-1], WORD_HEX_SIZE), end='')
        print("")

def print_round_differences_latex_table(round_differences, alpha, beta, accumulated_expected_probability):
    print("\nInput/Output differences:")
    print("\n             LEFT    RIGHT       alpha   ->    beta")
    print(" 0 & \\texttt{ 0x", end='')
    print_word(round_differences[0][0])
    print("} & \\texttt{ 0x", end='')
    print_word(round_differences[0][1])
    # print_array(round_differences[0])
    print("} & - & - & - \\\\")
    for i in range(1,len(round_differences)):
        print("%2d & \\texttt{ 0x" % (i), end='')
        # print_array(round_differences[i])
        print_word(round_differences[i][0])
        print("} & \\texttt{ 0x", end='')
        print_word(round_differences[i][1])
        print("} & ", end='')
        print("\\texttt{{ 0x{0:0{1}x} }} ".format(alpha[i-1], WORD_HEX_SIZE), end='')
        print(" & ", end='')
        print("\\texttt{{ 0x{0:0{1}x} }}".format(beta[i-1], WORD_HEX_SIZE), end='')
        print(" & $2^{{- {:5.2f} }}$".format(round(accumulated_expected_probability[i],2)), end='')
        print(" \\\\")

def compute_heuristic_and_expected_probability(encrypt_block_algorithm, key, number_of_rounds, round_differences, expected_probability, verb=True):
    trail_len = len(expected_probability)
    accumulated_expected_probability = [sum(expected_probability[0:i]) for i in range(0,trail_len+1)]
    heuristic_probability_both       = [0 for i in range(0,trail_len)]
    heuristic_probability_left       = [0 for i in range(0,trail_len)]
    heuristic_probability_right      = [0 for i in range(0,trail_len)]

    # define number of sample

    max_num_samples = 100000000 # increase/decrease if the testing device can manage more/less
    num_samples = int(math.ceil(2**accumulated_expected_probability[number_of_rounds]))
    num_samples = min(num_samples, max_num_samples)

    # if verb:
    print("\nTesting {} rounds\n".format(number_of_rounds))
    print("For " + str(number_of_rounds) + " rounds, " + str(num_samples) + " are needed")
    print("Taking " + str(num_samples) + " samples")

    # create input message set

    messages = [random_message() for i in range(num_samples)]

    #set counters

    counter_left  = [0 for i in range(trail_len)]
    counter_right = [0 for i in range(trail_len)]
    counter_both  = [0 for i in range(trail_len)]

    # start counting for each round and for each message

    for r in range(0, number_of_rounds+1):
        for m in messages:
            m1 = add64(m,round_differences[0])

            c  = encrypt_block_algorithm(m , key, nrounds=r)
            c1 = encrypt_block_algorithm(m1, key, nrounds=r)
            d = sub64(c1, c)

            if verb:
                print("r = " + str(r+1) + ": message number = " + str(i) + ": ", end='')
                print(" | (c,c1,d) = ", end='')
                print_array(c)
                print(" - ", end='')
                print_array(c1)
                print(" - ", end='')
                print_array(d)
                print("")

            if (sub64(c1,c)      == round_differences[r]): # if ((sub(c1[0],c[0]) == round_differences[r][0]) and (sub(c1[1],c[1]) == round_differences[r][1])):
                counter_both[r]  = counter_both[r]  + 1

            if ((sub(c1[0],c[0]) == round_differences[r][0])):
                counter_left[r]  = counter_left[r]  + 1

            if ((sub(c1[1],c[1]) == round_differences[r][1])):
                counter_right[r] = counter_right[r] + 1

        heuristic_probability_both[r]  = float(counter_both[r]) /float(num_samples)
        heuristic_probability_left[r]  = float(counter_left[r]) /float(num_samples)
        heuristic_probability_right[r] = float(counter_right[r])/float(num_samples)

    return [[heuristic_probability_both, heuristic_probability_left, heuristic_probability_right], \
            accumulated_expected_probability, \
            [counter_both, counter_left, counter_right], \
            num_samples]

def print_heuristic_vs_expected_probability(heuristic_probabilities, accumulated_expected_probability, counters, num_samples, number_of_rounds):
    print("\n#samples = " + str(num_samples))
    print("\n           Heu.Pr -  Heu.Pr. -  Heu.Pr. - Exp.Pr. - Counters")
    print("           [both]    [left]     [right]                     \n")
    for r in range(0, len(heuristic_probabilities[0])):
        print("r = %2d - " % (r), end='')

        # heuristic probability

        # both
        if heuristic_probabilities[0][r] != 0:
            print("2^{:06.2f}".format(round(math.log(heuristic_probabilities[0][r],2),2)), end='')
        else:
            print("NA      ", end='')

        print(" - ", end='')

        # left
        if heuristic_probabilities[1][r] != 0:
            print("2^{:06.2f}".format(round(math.log(heuristic_probabilities[1][r],2),2)), end='')
        else:
            print("NA      ", end='')

        print(" - ", end='')

        # right
        if heuristic_probabilities[2][r] != 0:
            print("2^{:06.2f}".format(round(math.log(heuristic_probabilities[2][r],2),2)), end='')
        else:
            print("NA      ", end='')

        print(" - ", end='')

        # accumulated expected probability

        if (r == 0):
            print("2^ 0    ", end='')
        else:
            print("2^-{:05.2f}".format(round(accumulated_expected_probability[r],2)), end='')

        print(" - [" + str(counters[0][r]) + ", " + str(counters[1][r]) + ", " + str(counters[2][r]) + "]")

        if (r == number_of_rounds or r == 0):
            print("------------------------------------------------------------------------")


# import pydicom
# import os
import time
import datetime
#
# path = r""
# file = os.listdir(path)[0]
# file_path = os.path.join(path, file)
#
# dcm = pydicom.read_file(file_path)
# kvp = dcm.KVP
x = "20181129"

def time_add(x):
    year = int(x[0:4])
    month = int(x[4:6])
    day = int(x[6:8])
    if month ==10:
        new_year = year + 1
        new_month = 1
        new_day = day
    elif month == 11:
        new_year = year + 1
        if day >=28:
            new_month = 3
            new_day = day - 27
        else:
            new_month = 2
            new_day = day
    elif month == 12:
        new_year = year + 1
        new_month = 3
        if day == 31:
            new_day = 30
        else:
            new_day = day
    else:
        new_year = year
        new_month = month + 3
        if day == 31:
            new_day = 30
        else:
            new_day = day
    s = "%04d"%new_year + "%02d"%new_month + "%02d"%new_day
    # new_time = str(new_year) + str(new_month) + str(new_day)
    print(s)

# time_add(x)

def t_add(x):
    year = int(x[0:4])
    month = int(x[4:6])
    day = int(x[6:8])
    detester = "%04d"%year + "-" + "%02d"%month + "-" + "%02d"%day
    date = datetime.datetime.strptime(detester,"%Y-%m-%d")
    delta = datetime.timedelta(days=90)
    n_days = date+delta
    print(n_days)

list = "10998750201803190181"
t_add(x)
# x = 20180506
# a=x//10000
# b=(x-a*10000)//100
# c=x-a*10000-b*100
# # ll_30 = int(ll) - 30
# # print(ll_30)
# # gmt = time.gmtime()
# # time.struct_time(tm_year=a, tm_mon=b, tm_mday=c, tm_hour=6, tm_min=48, tm_sec=13, tm_wday=0, tm_yday=140, tm_isdst=0)
# gmt = str(a) + "-" + str(b) + "-" + str(c)
# print(a)
# print(b)
# print(c)
# print(gmt)


import os
from typing import Any, Union

import numpy as np
from numpy import ndarray
from ocha.dataset.cross_validator import CrossValidator
from ocha.experiment.experiment import Experiment, ExperimentConfig
from ocha.experiment.results import ExperimentResult, RemakeResult, TestResult, TrainResult, ValidResult
from ocha.util.timer import Timer
from pandas import DataFrame

from ..context import Atmacup15Context
from ..dataset import Atmacup15Dataset
from ..metrics import RMSE
from .lgb import LGBMRegression, LGBMRegressionConfig

class Atmacup15ExperimentConfig(ExperimentConfig):
    version: int
    n_fold: int
    seed: int
    scoring: RMSE
    cross_validator: CrossValidator
    folds: list[int] | None = None

    def model_post_init(self, __context: Any) -> None:
        super().model_post_init(__context)
        os.makedirs("./oof/lgb", exist_ok=True)
        os.makedirs("./models/lgb", exist_ok=True)
        os.makedirs("./submission/lgb", exist_ok=True)

class Atmacup15Experiment(Experiment):
    context: Atmacup15Context
    config: Atmacup15ExperimentConfig

    def build_conf(self, fold: int, categorical_features: list[str]) -> LGBMRegressionConfig:
        return LGBMRegressionConfig(
            save_dir="lgb",
            save_file_name=f"fold-{fold}",
            model_file_type="pickle",
            seed=self.config.seed,
            categorical_features=categorical_features,
            num_boost_round=10000,
            max_bin=500,
            verbose_eval=500,
            is_debug=True,
        )

    def build_model(self, conf: LGBMRegressionConfig) -> LGBMRegression:
        return LGBMRegression(config=conf, scoring=self.config.scoring)

    def run(self) -> ExperimentResult:
        timer = Timer()
        timer.start()

        train_result = self.train()

        print("Saveing oof ...")
        oof_df = self.save_oof(train_result.oof_prediction, train_result.score)
        print("done.")

        print("Prediction ...")
        test_result = self.test()
        print("done.")

        print("Saving submission_df ...")
        submission_df = self.save_submission(test_result.test_prediction, train_result.score)

        timer.end()

        print(f"Experiment End. [score: {train_result.score}, time: {timer.result}]")

        return ExperimentResult(
            fit_results=train_result.fit_results,
            oof_prediction=train_result.oof_prediction,
            test_prediction=test_result.test_prediction,
            oof_df=oof_df,
            submission_df=submission_df,
            score=train_result.score,
            time=timer.result,
        )

    def train(self) -> TrainResult:
        fit_results = []
        oof_prediction = np.zeros(len(self.context.sample_oof_df))
        for fold in self.get_folds():
            train_idx, valid_idx = self.config.cross_validator.fold_index(fold=fold)
            train = self.context.train.iloc[train_idx].reset_index(drop=True)
            valid = self.context.train.iloc[valid_idx].reset_index(drop=True)
            dataset = Atmacup15Dataset(train=train, valid=valid, test=self.context.test)
            dataset.processing_train()
            dataset.processing_valid()

            conf = self.build_conf(fold=fold, categorical_features=dataset.categorical_features)
            model = self.build_model(conf=conf)
            result = model.fit(dataset.train_X, dataset.train_y, dataset.valid_X, dataset.valid_y)

            fit_results.append(result)
            oof_prediction[valid_idx] = result.oof_prediction

        score = self.config.scoring.execute(self.context.train["score"].values, oof_prediction)

        return TrainResult(fit_results=fit_results, oof_prediction=oof_prediction, score=score)

    def valid(self) -> ValidResult:
        oof_prediction = np.zeros(len(self.context.train))
        for fold in self.get_folds():
            train_idx, valid_idx = self.config.cross_validator.fold_index(fold=fold)
            train = self.context.train.iloc[train_idx].reset_index(drop=True)
            valid = self.context.train.iloc[valid_idx].reset_index(drop=True)
            dataset = Atmacup15Dataset(train=train, valid=valid, test=self.context.test)
            dataset.processing_train()
            dataset.processing_valid()

            conf = self.build_conf(fold=fold, categorical_features=dataset.categorical_features)
            model = self.build_model(conf=conf)
            model.load()

            oof_prediction[valid_idx] = model.predict(dataset.valid_X)

        score = self.config.scoring.execute(self.context.train["score"].values, oof_prediction)

        return ValidResult(oof_prediction=oof_prediction, score=score)

    def test(self) -> TestResult:
        predictions = []
        for fold in self.get_folds():
            train_idx, valid_idx = self.config.cross_validator.fold_index(fold=fold)
            train = self.context.train.iloc[train_idx].reset_index(drop=True)
            valid = self.context.train.iloc[valid_idx].reset_index(drop=True)
            dataset = Atmacup15Dataset(train=train, valid=valid, test=self.context.test)
            dataset.processing_train()
            dataset.processing_test()

            conf = self.build_conf(fold=fold, categorical_features=dataset.categorical_features)
            model = self.build_model(conf=conf)
            model.load()

            prediction = model.predict(dataset.test_X)
            predictions.append(prediction)

        test_prediction = np.mean(predictions, axis=0)

        return TestResult(test_prediction=test_prediction)

    def test_seq(self, test_X: Union[DataFrame, ndarray]) -> TestResult:
        pass

    def optimize(self) -> None:
        pass

    def save_oof(self, oof_prediction: ndarray, score: float) -> DataFrame:
        oof_df = self.context.make_oof(oof_prediction)
        oof_df.to_csv(
            f"./oof/lgb/v{self.config.version}_oof_cv{score:.4f}.csv",
            index=False,
        )

        return oof_df

    def save_submission(self, test_prediction: ndarray, score: float) -> DataFrame:
        submission_df = self.context.make_submission(test_prediction)
        submission_df.to_csv(
            f"./submission/lgb/v{self.config.version}_submission_cv{score:.4f}.csv",
            index=False,
        )

        return submission_df

    def remake(self) -> RemakeResult:
        valid_result = self.valid()
        test_result = self.test()

        oof_df = self.save_oof(valid_result.oof_prediction, valid_result.score)
        submission_df = self.save_submission(test_result.test_prediction, valid_result.score)

        return RemakeResult(oof_df=oof_df, submission_df=submission_df, score=valid_result.score)


def convert(s, numRows):
    len_s = len(s)
    if numRows == 1:
        return s
    if len_s <= numRows:
        return s
    else:
        outString = ''
        iter_size = numRows + (numRows - 2)
        iter_num = len_s / iter_size
        if len_s % iter_size != 0:
            iter_num += 1
        row_max = iter_num * (numRows - 1)
        s_log = []
        for i in range(len_s):
            group = i / iter_size
            pos = i % iter_size
            delta = pos - (numRows - 1)
            nrow = 0
            ncol = 0
            if delta <= 0:
                nrow = pos
            else:
                nrow = numRows - delta - 1
                ncol = delta
            indice = group * (numRows - 1) + ncol + row_max * nrow
            s_log.append(indice)
        outIndices = sorted(range(len(s_log)), key=lambda k: s_log[k])
        for i in outIndices:
            outString += s[i]
        return outString

if __name__ == '__main__':
    print(convert("ABC", 2))


import os
import subprocess
from pytube import YouTube, Playlist
import configparser
config = configparser.ConfigParser()
config.read('youtube_config.ini')
DOWNLOAD_DIR = config.get('download', 'download_dir')

yt = YouTube("https://www.youtube.com/watch?v=VMXTeEkAxeo")
videoStreams = yt.streams.filter()
for i in range(len(videoStreams)):
    print(i, '. ', videoStreams[i])
# print(videoStreams)
theVideo = videoStreams.filter(progressive=True, type='video', file_extension='mp4').get_highest_resolution()
print(theVideo)
theAudio = videoStreams.filter().get_audio_only()
print(theAudio)
# videoStreams = yt.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution()
# print(videoStreams)
# print(videoStreams.url)
# print(videoStreams.default_filename)
# print(videoStreams.title)
# print(videoStreams.type)
# print(videoStreams.subtype)
# print(videoStreams.video_codec)
# print(videoStreams.filesize)
# videoStreams = yt.streams.filter(progressive=True, file_extension='mp4')
# for i in range(len(videoStreams)):
#     print(i, '. ', videoStreams[i])
# videoNum = int(input("Which stream do you want to download? "))
# videoStreams[videoNum].download(DOWNLOAD_DIR)
# default_filename = videoStreams[videoNum].default_filename


# Write a function:
# def solution(A, B)
# that, given two arrays A and B consisting of N integers, returns the size of a non-overlapping set containing a maximal number of segments.

# we have to search for the next one (next non-overlapping) whose ending is the least since least ending
# cannot be a worse choice than a smaller start with larger ending.
def solution(A, B):
    N = len(A)
    if N == 0:
        return 0
    count = 1
    i = 1
    curr_end = B[0]
    while i < N:
        if A[i] > curr_end:
            count += 1
            curr_end = B[i]
        i += 1
    return count


# list1 = [2,3,4,10,29,83,28]
# for i in list1:
#     if i and i>6:
#         print(i)
#
# while(True):
#     inp = input("Enter a value ")
#     if int(inp)>100:
#         print("nice")
#         break
#     else:
#         print("Try Again")
#         continue
#

# Guess game
# i=0
# n=18
# while(i<9):
#     inp=input("enter the number ")
#     if int(inp)== n:
#         print("congratulation, you win")
#         break
#     elif int(inp)> n:
#         print("Number is Too big,try again")
#         i = i + 1
#         continue
#     elif int(inp)< n:
#         print("Number is too small,try again")
#         i = i + 1
#         continue
#     else:
#         print("Enter worng word")
# def hello(l):
#     """This is for checking doc string"""
#     return 1
# print(hello.__doc__)

# Try except
# print("Enter Num 1 ")
# num1=input()
# print("Enter num 2 ")
# num2 = input()
# try:
#     print("The sum of these two numbers is ",int(num1)+int(num2))
# except Exception as e:
#     print(e)
#
# print("This line is very important ")

# Astrologer's star
i = 0
j = 0
n = int(input("Enter your number "))
inp = int(input("Enter 1 or 0 "))
if inp == 1:
    for i in range(0,n):
        for j in range(i+1):
            print("*", end=" ")
        print("\r")
elif inp == 0:
    for i in range(n, 0, -1):
        for j in range(i+1):
            print("*", end=" ")
        print("\r")
else:
    print("Wrong")

# l = 10
#
#
# def function1(n):
#     # l=5
#     m = 8
#     global l
#     l = l + 5
#     print(l, m)
#     print(n)
#
#
# function1("This is Rony")
# print(l)


import heapq

T = int(input())

for tc in range(T):
    V, E = map(int, input().split())
    graph = [[] for _ in range(V+1)]
    # 그래프 추가해주기
    for _ in range(E):
        a, b, x = map(int, input().split())
        graph[a].append((b,x))
        graph[b].append((a,x))

    start = 0
    min_distance = 999999999
    distance = [999999999] * (V+1)
    queue = []
    heapq.heappush(queue, (0, 0))
    print(queue)

    while queue:
        cost, now = heapq.heappop(queue)
        if distance[now] == min_distance:
            distance[now] = cost
            for pos, co in graph[now]:
                if distance[pos] > co:
                    heapq.heappush(queue, [co,pos])

    print("#{} {}".format(tc+1, sum(distance)))


# Function using loop and constructing a new list
def remove_duplicates_loop(input_list):
    unique_list = []

    for item in input_list:
        if item not in unique_list:
            unique_list.append(item)

    return unique_list

# Function using sets
def remove_duplicates_set(input_list):
    return list(set(input_list))

# Example list with duplicates
original_list = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]

# Call the functions and print the results
new_list_loop = remove_duplicates_loop(original_list)
new_list_set = remove_duplicates_set(original_list)

print("Original list:", original_list)
print("New list (using loop):", new_list_loop)
print("New list (using sets):", new_list_set)


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# https://leetcode.com/problems/maximum-binary-tree/
class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """

        return self.constructTree(nums)

    def constructTree(self, nums):
        if len(nums) == 0:
            return None

        if len(nums) == 1:
            return TreeNode(nums[0])

        maxnum = max(nums)
        idx = nums.index(maxnum)
        left = nums[0:idx]
        right = nums[idx+1:]
        tree = TreeNode(maxnum)
        tree.left = self.constructTree(left)
        tree.right = self.constructTree(right)
        return tree


def extractKarmatranslationsWordpressCom(item):
	'''
	Parser for 'karmatranslations.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('Across a Millennium to Love You',       'Across a Millennium to Love You',                      'translated'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	titlemap = [
		('Across a Millennium to Love You Chapter',  'Across a Millennium to Love You',      'translated'),
	]

	for titlecomponent, name, tl_type in titlemap:
		if titlecomponent.lower() in item['title'].lower():
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


#!/usr/bin/env python3
# -------------------------------------------------------------
# proj:    gan-stronomy
# file:    gen_dataset.py
# authors: Mark Sabini, Zahra Abdullah, Darrith Phan
# desc:    Generates custom dataset from Recipe1M and the embedding
#          model trained by Salvador et al. (Im2Recipe)
# -------------------------------------------------------------
import util
import os
import numpy as np
import subprocess
import sys

# Squeezes image to [-1, 1], and also makes sure it's in [C, H, W] format
def preprocess_img(img):
    img_scale = np.array(np.transpose(img, (2, 0, 1)), dtype=np.float32) / 255.0
    return img_scale * 2.0 - 1.0

def save_img(id, img, raw_img_path):
    out_filename = id + '.png'
    img.save(os.path.join(raw_img_path, out_filename), format='PNG')

def gen_dataset(N, data_path, compute_embed=True):
    data_path = os.path.abspath(data_path)
    raw_img_path = os.path.join(data_path, 'imgs')
    temp_path = os.path.join(data_path, 'temp_lmdb')
    util.create_dir(data_path)
    util.create_dir(raw_img_path)
    util.create_dir(temp_path)
    # Data from the entire raw dataset
    print('Loading data...')
    lmdb_data = util.load_lmdb()
    recipe2img_id = util.map_recipe_id_to_img_id(lmdb_data)
    recipe_classes = util.load_classes()
    # Data to go into our custom set
    print('Sampling recipe ids...')
    recipe_ids = util.sample_ids(lmdb_data, N)
    recipe_ids_decode = [recipe_id.decode('utf-8') for recipe_id in recipe_ids]
    util.repickle(recipe_ids_decode, os.path.join(data_path, 'temp_keys.pkl'))
    # Fill in everything except embeddings
    print('Filling in everything except embeddings...')
    dataset = {}
    classes = {} # Maps raw class to the smallest number needed
    error_recipe_ids = []
    for i, recipe_id in enumerate(recipe_ids):
        if i % 100 == 0:
            print('Filling in entry %d/%d...' % (i, N))
        sample = {}
        sample['recipe_id'] = recipe_id.decode('utf-8')
        sample['img_id'] = recipe2img_id[recipe_id][-1]
        sample['class_raw'] = recipe_classes[recipe_id.decode('utf-8')]
        if sample['class_raw'] not in classes:
            classes[sample['class_raw']] = len(classes)
        sample['class'] = classes[sample['class_raw']]
        try:
            img = util.resize_crop_img(util.get_img_path(sample['img_id'], util.RAW_IMG_PATH))
            save_img(sample['img_id'], img, raw_img_path)
            sample['img_pre'] = preprocess_img(img)
            dataset[recipe_id.decode('utf-8')] = sample
        except FileNotFoundError:
            print('Could not find image with id %s. Skipping' % sample['img_id'])
            error_recipe_ids.append(sample['recipe_id'])

    # Hacky business to compute embeddings
    if not compute_embed:
        print('Skipping embeddings...')
    else:
        print('Computing embeddings...')
        lmdb_slice = util.slice_lmdb(recipe_ids, lmdb_data)
        util.save_lmdb_data(lmdb_slice, temp_path)
        subprocess.run(['python',
                        util.GEN_EMBEDDINGS_ROOT,
                        '--model_path=%s' % util.MODEL_PATH,
                        '--data_path=%s' % data_path,
                        '--path_results=%s' % data_path])
        embeddings = util.unpickle2(os.path.join(data_path, 'rec_embeds.pkl'))
        embedding_ids = util.unpickle2(os.path.join(data_path, 'rec_ids.pkl'))
        for i, embedding_id in enumerate(embedding_ids):
            if embedding_id in dataset:
                dataset[embedding_id]['recipe_emb'] = embeddings[i]
    print('Saving dataset...')
    util.repickle({'data': dataset, 'class_mapping': classes}, os.path.join(data_path, 'data.pkl'))
    print('...done!')

def main():
    if len(sys.argv) < 3:
        print('Usage: python3 gen_dataset.py [N] [output_path]')
        exit()

    gen_dataset(int(sys.argv[1]), sys.argv[2], compute_embed=True)

if __name__ == '__main__':
    main()


from emb_viz import (EmbeddingVisualizerInterface, FuzzyEmbeddingVisualizer,
                     SymbolicEmbeddingVisualizer)
import pickle
import argparse
import pickle
from PIL import Image
import cv2
import os
import glob

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("img_dir", type=str)
    parser.add_argument("config_path", type=str, help="Path to config file.")
    parser.add_argument("checkpoint_path",
                        type=str,
                        help="Path to checkpoint file.")
    parser.add_argument("output_type",
                        type=str,
                        help="Output type choice (viz_emb, backbone).")
    parser.add_argument("embedding_type", type=str, help="")
    parser.add_argument("--default-config-path",
                        type=str,
                        default="vissl/config/defaults.yaml",
                        help="Path to default config file")
    parser.add_argument("--viz-thres",
                        type=float,
                        default=0.,
                        help="Masking out embeddings/symbols bellow threshold")
    args = parser.parse_args()

    img_dir = args.img_dir
    config_path = args.config_path
    checkpoint_path = args.checkpoint_path
    output_type = args.output_type
    default_config_path = args.default_config_path
    viz_thres = args.viz_thres
    emb_type = args.embedding_type

    # 0. PCA mapping
    pca = pickle.load(open("pca.pkl", "rb"))

    # 1. Setup embedding visualizer module
    if emb_type == "fuzzy":
        emb_viz_module = EmbeddingVisualizerInterface(
            FuzzyEmbeddingVisualizer(
                config_path,
                default_config_path,
                checkpoint_path,
                output_type,
                True,
                pca=pca,
                viz_thres=viz_thres,
            ))
    elif emb_type == "symbolic":
        emb_viz_module = EmbeddingVisualizerInterface(
            SymbolicEmbeddingVisualizer(
                config_path,
                default_config_path,
                checkpoint_path,
                output_type,
                True,
                pca=pca,
                viz_thres=viz_thres,
            ))

    img_paths = glob.glob(os.path.join(img_dir, "*.png"))
    imgs = []
    for img_path in img_paths:
        img = Image.open(img_path).convert("RGB")
        imgs.append(img)

    if len(imgs) == 0:
        raise Exception(f"No images found (img_dir: {img_dir})")

    for img_path in img_paths:
        img = Image.open(img_path).convert("RGB")
        emb_viz = emb_viz_module.generate(img)

        #emb_viz = np.transpose(emb_viz, (2, 0, 1))
        #emb_viz = cv2.cvtColor(emb_viz, cv2.COLOR_BGR2RGB)
        emb_viz = emb_viz[..., [2, 1, 0]]
        cv2.imwrite(img_path[:-4] + "_pca.png", emb_viz)


#encoding=utf-8

import json
import logging

from . import backend, httpserver, logconf, wsserver

from oslo_config import cfg
from twisted.internet import reactor
from twisted.web.server import Site
from autobahn.twisted.resource import WebSocketResource
from twisted.web.resource import Resource

log = logging.getLogger(__name__)

opt_server_group = cfg.OptGroup(name='server',
                            title='Foldex Server IP Port')

server_opts = [
    cfg.StrOpt('host', default='127.0.0.1',
               help=('Host IP')),
    cfg.IntOpt('port', default=8893,
               help=('Host Port')),
]

CONF = cfg.CONF
CONF.register_group(opt_server_group)
CONF.register_opts(server_opts, opt_server_group)

class Server(object):
    def run(self):
        cfg.CONF(default_config_files=['/etc/foldex/foldex.conf'])
        host, port = CONF.server.host, CONF.server.port

        try:
            factory = wsserver.BroadcastPreparedServerFactory(u"ws://127.0.0.1:{}".format(port))
            factory.protocol = wsserver.WSServerProtocol
            wsresource = WebSocketResource(factory)

            backend.init_ws(factory)
            backend.start_heartbeat_monitor()

            root = Resource()
            root.putChild('ws', wsresource)
            root.putChild('v1', httpserver.VDIResource())
            site = Site(root)

            reactor.suggestThreadPoolSize(30)
            reactor.listenTCP(port, site)

            log.debug("Serving HTTP/WS at port {}".format(port))
            reactor.run()
        except KeyboardInterrupt:
            log.info("Terminating...")
        except Exception as e:
            log.debug(e)
            log.error("Failed to start server")
            raise
        finally:
            backend.stop_heartbeat_monitor()