from __future__ import absolute_import, division, print_function

import numbers
import logging
import operator

import numpy as np

from glue.external.six import add_metaclass
from glue.core.contracts import contract, ContractsMeta
from glue.core.subset import InequalitySubsetState
from glue.core.util import join_component_view

__all__ = ['ComponentLink', 'BinaryComponentLink', 'CoordinateComponentLink']

def identity(x):
    return x

OPSYM = {operator.add: '+', operator.sub: '-',
         operator.truediv: '/', operator.mul: '*',
         operator.pow: '**'}

@add_metaclass(ContractsMeta)
class ComponentLink(object):

    """ ComponentLinks represent transformation logic between ComponentIDs

    ComponentLinks are be used to derive one
    :class:`~glue.core.component_id.ComponentID` from another:

    Example::

       def hours_to_minutes(hours):
           return hours * 60

       d = Data(hour=[1, 2, 3])
       hour = d.id['hour']
       minute = ComponentID('minute')
       link = ComponentLink( [hour], minute, using=hours_to_minutes)

       link.compute(d)  # array([ 60, 120, 180])
       d.add_component_link(link)
       d['minute'] # array([ 60, 120, 180])
    """

    @contract(using='callable|None',
              inverse='callable|None')
    def __init__(self, comp_from, comp_to, using=None, inverse=None, inverse_component_link=None):
        """
        :param comp_from: The input ComponentIDs
        :type comp_from: list of :class:`~glue.core.component_id.ComponentID`

        :param comp_to: The target component ID
        :type comp_from: :class:`~glue.core.component_id.ComponentID`

        :pram using: The translation function which maps data from
                     comp_from to comp_to (optional)

        The using function should satisfy::

               using(data[comp_from[0]],...,data[comp_from[-1]]) = desired data

        :param inverse:
            The inverse translation function, if exists (optional)

        :raises:
           TypeError if input is invalid

        .. note ::
            Both ``inverse`` and ``using`` should accept and return
            numpy arrays

        """
        from glue.core.data import ComponentID

        self._from = comp_from
        self._to = comp_to

        if using is None:
            using = identity

        if using is identity:
            if inverse is None:
                inverse = identity
            elif inverse is identity:
                pass
            else:
                raise ValueError("Cannot specify inverse if using is identity")

        self._using = using
        self._inverse = inverse

        self.hidden = False  # show in widgets?
        self.identity = self._using is identity

        if not isinstance(comp_from, list):
            raise TypeError("comp_from must be a list: %s" % type(comp_from))

        if not all(isinstance(f, ComponentID) for f in self._from):
            raise TypeError("from argument is not a list of ComponentIDs: %s" %
                            self._from)
        if not isinstance(self._to, ComponentID):
            raise TypeError("to argument is not a ComponentID: %s" %
                            type(self._to))

        if using is identity:
            if len(comp_from) != 1:
                raise TypeError("comp_from must have only 1 element, "
                                "or a 'using' function must be provided")

        if inverse_component_link is None:
            if inverse is not None:
                if len(comp_from) == 1:
                    self._inverse_component_link = ComponentLink([self._to], self._from[0],
                                                                 using=self._inverse,
                                                                 inverse=self._using,
                                                                 inverse_component_link=self)
                else:
                    raise ValueError("Can only use an inverse with one comp_from link")
            else:
                self._inverse_component_link = None
        else:
            self._inverse_component_link = inverse_component_link

    @contract(data='isinstance(Data)', view='array_view')
    def compute(self, data, view=None):
        """For a given data set, compute the component comp_to given
        the data associated with each comp_from and the ``using``
        function

        :param data: The data set to use
        :param view: Optional view (e.g. slice) through the data to use

        *Returns*:

            The data associated with comp_to component

        *Raises*:

            InvalidAttribute, if the data set doesn't have all the
            ComponentIDs needed for the transformation
        """
        logger = logging.getLogger(__name__)
        args = [data[join_component_view(f, view)] for f in self._from]
        logger.debug("shape of first argument: %s", args[0].shape)
        result = self._using(*args)
        # We call asarray since link functions may return Python scalars in some cases
        result = np.asarray(result)
        logger.debug("shape of result: %s", result.shape)
        if result.shape != args[0].shape:
            logger.warn("ComponentLink function %s changed shape. Fixing",
                        self._using.__name__)
            result.shape = args[0].shape
        return result

    def get_from_ids(self):
        """ The list of input ComponentIDs """
        return self._from

    @contract(old='isinstance(ComponentID)', new='isinstance(ComponentID)')
    def replace_ids(self, old, new):
        """Replace all references to an old ComponentID with references
        to new

        :parma old: ComponentID to replace
        :param new: ComponentID to replace with
        """
        for i, f in enumerate(self._from):
            if f is old:
                self._from[i] = new
        if self._to is old:
            self._to = new

    @contract(_from='list(isinstance(ComponentID))')
    def set_from_ids(self, _from):
        if len(_from) != len(self._from):
            raise ValueError("New ID list has the wrong length.")
        self._from = _from

    def get_to_id(self):
        """ The target ComponentID """
        return self._to

    def set_to_id(self, to):
        self._to = to

    def get_using(self):
        """ The transformation function """
        return self._using

    @property
    def inverse(self):
        if self._inverse is None:
            return None
        else:
            return self._inverse_component_link

    def get_inverse(self):
        """ The inverse transformation, or None """
        return self._inverse

    def __str__(self):
        args = ", ".join([t.label for t in self._from])
        if self._using is identity:
            result = "%s <-> %s" % (self._to, self._from[0])
        else:
            if self._inverse is None:
                result = "%s <- %s(%s)" % (self._to, self._using.__name__, args)
            else:
                result = "%s <-> %s(%s)" % (self._to, self._using.__name__, args)
        return result

    def to_html(self):
        args = ", ".join([t.to_html() for t in self._from])
        if self._using is identity:
            result = "%s ↔ %s" % (self._to.to_html(), self._from[0].to_html())
        else:
            if self._inverse is None:
                result = "%s ← %s(%s)" % (self._to.to_html(), self._using.__name__, args)
            else:
                result = "%s ↔ %s(%s)" % (self._to.to_html(), self._using.__name__, args)
        return result

    def __repr__(self):
        return str(self)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __add__(self, other):
        return BinaryComponentLink(self, other, operator.add)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __radd__(self, other):
        return BinaryComponentLink(other, self, operator.add)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __sub__(self, other):
        return BinaryComponentLink(self, other, operator.sub)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __rsub__(self, other):
        return BinaryComponentLink(other, self, operator.sub)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __mul__(self, other):
        return BinaryComponentLink(self, other, operator.mul)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __rmul__(self, other):
        return BinaryComponentLink(other, self, operator.mul)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __div__(self, other):
        return BinaryComponentLink(self, other, operator.div)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __rdiv__(self, other):
        return BinaryComponentLink(other, self, operator.div)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __truediv__(self, other):
        return BinaryComponentLink(self, other, operator.truediv)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __rtruediv__(self, other):
        return BinaryComponentLink(other, self, operator.truediv)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __pow__(self, other):
        return BinaryComponentLink(self, other, operator.pow)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __rpow__(self, other):
        return BinaryComponentLink(other, self, operator.pow)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __lt__(self, other):
        return InequalitySubsetState(self, other, operator.lt)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __le__(self, other):
        return InequalitySubsetState(self, other, operator.le)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __gt__(self, other):
        return InequalitySubsetState(self, other, operator.gt)

    @contract(other='isinstance(ComponentID)|component_like|float|int')
    def __ge__(self, other):
        return InequalitySubsetState(self, other, operator.ge)

class CoordinateComponentLink(ComponentLink):

    @contract(comp_from='list(isinstance(ComponentID))',
              comp_to='isinstance(ComponentID)',
              coords='isinstance(Coordinates)',
              index=int,
              pixel2world=bool)
    def __init__(self, comp_from, comp_to, coords, index, pixel2world=True):
        self.coords = coords
        self.index = index
        self.pixel2world = pixel2world

        # Some coords don't need all pixel coords
        # to compute a given world coord, and vice versa
        # (e.g., spectral data cubes)
        self.ndim = len(comp_from)
        self.from_needed = coords.dependent_axes(index)
        self._from_all = comp_from

        comp_from = [comp_from[i] for i in self.from_needed]
        super(CoordinateComponentLink, self).__init__(
            comp_from, comp_to, self.using)
        self.hidden = True

    def using(self, *args):

        attr = 'pixel2world_single_axis' if self.pixel2world else 'world2pixel_single_axis'
        func = getattr(self.coords, attr)

        args2 = [None] * self.ndim
        for f, a in zip(self.from_needed, args):
            args2[f] = a
        for i in range(self.ndim):
            if args2[i] is None:
                args2[i] = np.zeros_like(args[0])
        args2 = tuple(args2)

        return func(*args2[::-1], axis=self.ndim - 1 - self.index)

    def __str__(self):
        rep = 'pix2world' if self.pixel2world else 'world2pix'
        sup = super(CoordinateComponentLink, self).__str__()
        return sup.replace('using', rep)

class BinaryComponentLink(ComponentLink):

    """
    A ComponentLink that combines two inputs with a binary function

    :param left: The first input argument.
                 ComponentID, ComponentLink, or number

    :param right: The second input argument.
                  ComponentID, ComponentLink, or number

    :param op: A function with two inputs that works on numpy arrays

    The CompoentLink represents the logic of applying `op` to the
    data associated with the inputs `left` and `right`.
    """

    def __init__(self, left, right, op):
        from glue.core.data import ComponentID

        self._left = left
        self._right = right
        self._op = op

        from_ = []
        if isinstance(left, ComponentID):
            from_.append(left)
        elif isinstance(left, ComponentLink):
            from_.extend(left.get_from_ids())
        elif not isinstance(left, numbers.Number):
            raise TypeError("Cannot create BinaryComponentLink using %s" %
                            left)

        if isinstance(right, ComponentID):
            from_.append(right)
        elif isinstance(right, ComponentLink):
            from_.extend(right.get_from_ids())
        elif not isinstance(right, numbers.Number):
            raise TypeError("Cannot create BinaryComponentLink using %s" %
                            right)

        to = ComponentID("")
        null = lambda *args: None
        super(BinaryComponentLink, self).__init__(from_, to, null)

    def replace_ids(self, old, new):
        super(BinaryComponentLink, self).replace_ids(old, new)
        if self._left is old:
            self._left = new
        elif isinstance(self._left, ComponentLink):
            self._left.replace_ids(old, new)
        if self._right is old:
            self._right = new
        elif isinstance(self._right, ComponentLink):
            self._right.replace_ids(old, new)

    def compute(self, data, view=None):
        l = self._left
        r = self._right
        if not isinstance(self._left, numbers.Number):
            l = data[self._left, view]
        if not isinstance(self._right, numbers.Number):
            r = data[self._right, view]
        return self._op(l, r)

    def __str__(self):
        sym = OPSYM.get(self._op, self._op.__name__)
        return '(%s %s %s)' % (self._left, sym, self._right)

    def __repr__(self):
        return "<BinaryComponentLink: %s>" % self


# Zadanie 8. Utwórz słownik dla 10 krajów Europy zawierajacy listy 10 najpopularniejszych imion żeńskich.
# Zapisz imiona w wersji anglojęzycznej. Dodaj wszystki listy razem. Nowa lista powinna zawierać 100 elementów.
# Wyświetl tylko te imiona, które wystąpiły conajmniej w 6 krajach.

UK = ['Lily','Amelia','Sophia','Olivia','Emily','Isla','Rosie','Aria','Freya','Ella']
US = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']
Scotland = ['Isabelle','Elsie','Luna','Poppy','Willow','Emily','Zara','Daisy','Sienna','Eva']
Canada = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']
Poland = ['Zuzanna','Zofia', 'Hanna', 'Julia', 'Maja', 'Laura', 'Oliwia', 'Alicja', 'Lena', 'Pola']
Wales = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']
Portugal = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']
Spain = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']
France = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']
Germany = ['Emily','Mia','Isabella','Ivy','Hannah','Layla','Grace','Sophie','Evelyn','Evie']

combined_list = UK + US + Scotland + Canada + Poland + Wales + Portugal + Spain + France + Germany

counting_dict = {}

for name in combined_list:
  if name in counting_dict.keys():
    counting_dict[name] += 1
  else:
    counting_dict[name] = 1

popular_names_dict = {}

for i,j in counting_dict.items():
    if j > 6:
        popular_names_dict[i] = j

popular_names = list(popular_names_dict.keys())

print(f'Imiona, ktore wystapily conajmniej w 6 krajach to: {popular_names}')


import json
import os
from os.path import join, dirname

import boto3
import requests
from boto3.session import Session
from jsonschema import validate, exceptions
from requests_aws4auth import AWS4Auth

opg_sirius_api_gateway_dev_aws = {
    "name": "original collections api on aws dev",
    "online_tool_endpoint": {
        "url": "https://dev.lpa.api.opg.service.justice.gov.uk/v1/lpa-online-tool/lpas",
        "method": "GET",
        "valid_lpa_online_tool_ids": ["A33718377316"],
        "invalid_lpa_online_tool_ids": ["banana"],
    },
    "use_an_lpa_endpoint": {
        "url": "https://dev.lpa.api.opg.service.justice.gov.uk/v1/use-an-lpa/lpas",
        "method": "GET",
        "valid_sirius_uids": ["700000000013"],
        "invalid_sirius_uids": ["9"],
    },
    "request_code_endpoint": {
        "url": "https://dev.lpa.api.opg.service.justice.gov.uk/v1/lpas/requestCode",
        "method": "POST",
        "valid_sirius_lpas": [
            {"caseUid": 700000000013, "actorUid": 700000000997},
            {"caseUid": 700000000013, "actorUid": 700000000971},
        ],
    },
}

opg_data_lpa_dev_aws = {
    "name": "new collections api on aws dev",
    "healthcheck_endpoint": {
        "url": "https://uml-XXXX.dev.lpa.api.opg.service.justice.gov.uk/v1/healthcheck",
        "method": "GET",
    },
    "online_tool_endpoint": {
        "url": "https://uml-XXXX.dev.lpa.api.opg.service.justice.gov.uk/v1/lpa-online-tool/lpas",
        "method": "GET",
        "valid_lpa_online_tool_ids": ["A33718377316"],
        "invalid_lpa_online_tool_ids": ["banana"],
    },
    "use_an_lpa_endpoint": {
        "url": "https://uml-XXXX.dev.lpa.api.opg.service.justice.gov.uk/v1/use-an-lpa/lpas",
        "method": "GET",
        "valid_sirius_uids": ["700000000047"],
        "invalid_sirius_uids": ["9"],
    },
    "request_code_endpoint": {
        "url": "https://uml-XXXX.dev.lpa.api.opg.service.justice.gov.uk/v1/use-an-lpa/lpas/requestCode",
        "method": "POST",
        "valid_sirius_lpas": [
            {"caseUid": 700000000013, "actorUid": 700000000997},
            {"caseUid": 700000000013, "actorUid": 700000000971},
        ],
    },
}

opg_data_lpa_local_mock = {
    "name": "new collections api local mock",
    "healthcheck_endpoint": {
        "url": "http://0.0.0.0:4343/v1/healthcheck",
        "method": "GET",
    },
    "online_tool_endpoint": {
        "url": "http://0.0.0.0:4343/v1/lpa-online-tool/lpas",
        "method": "GET",
        "valid_lpa_online_tool_ids": ["A39721583862"],
        "invalid_lpa_online_tool_ids": ["banana"],
    },
    "use_an_lpa_endpoint": {
        "url": "http://0.0.0.0:4343/v1/use-an-lpa/lpas",
        "method": "GET",
        "valid_sirius_uids": ["700000000138"],
        "invalid_sirius_uids": ["9"],
    },
    "request_code_endpoint": {
        "url": "http://0.0.0.0:4343/v1/use-an-lpa/lpas/requestCode",
        "method": "POST",
        "valid_sirius_lpas": [
            {"caseUid": 700000000138, "actorUid": 700000000997},
            {"caseUid": 700000000138, "actorUid": 700000000971},
        ],
    },
}

configs_to_test = [opg_data_lpa_dev_aws]

def pytest_html_report_title(report):
    report.title = "opg-data-lpa integration tests"

def send_a_request(
    test_config,
    url=None,
    method=None,
    payload=None,
    extra_headers=None,
    content_type=None,
):
    print(f"Using test_config: {test_config['name']}")

    headers = {
        "Content-Type": content_type if content_type else "application/json",
    }

    if extra_headers:
        for h in extra_headers:
            headers[h["header_name"]] = h["header_value"]

    if payload:
        body = json.dumps(payload)
    else:
        body = None

    if "CI" in os.environ:
        role_name = "integrations-ci"
    else:
        role_name = "operator"

    boto3.setup_default_session(
        region_name="eu-west-1",
    )

    client = boto3.client("sts")
    client.get_caller_identity()["Account"]

    role_to_assume = f"arn:aws:iam::288342028542:role/{role_name}"

    response = client.assume_role(
        RoleArn=role_to_assume, RoleSessionName="assumed_role"
    )

    session = Session(
        aws_access_key_id=response["Credentials"]["AccessKeyId"],
        aws_secret_access_key=response["Credentials"]["SecretAccessKey"],
        aws_session_token=response["Credentials"]["SessionToken"],
    )

    client = session.client("sts")
    client.get_caller_identity()["Account"]

    credentials = session.get_credentials()

    credentials = credentials.get_frozen_credentials()
    access_key = credentials.access_key
    secret_key = credentials.secret_key
    token = credentials.token

    auth = AWS4Auth(
        access_key,
        secret_key,
        "eu-west-1",
        "execute-api",
        session_token=token,
    )

    response = requests.request(method, url, auth=auth, data=body, headers=headers)

    print(f"response.status_code: {response.status_code}")
    print(
        f"response: {json.dumps(response.json(), indent=4) if len(response.text) > 0 else ''}"
    )

    return response.status_code, response.text

def is_valid_schema(data, schema_file):
    """Checks whether the given data matches the schema"""
    schema = load_data(schema_file, as_json=False)
    try:
        validate(data, schema)
        result = True
    except exceptions.ValidationError as e:
        print("well-formed but invalid JSON:", e)
        result = False
    except json.decoder.JSONDecodeError as e:
        print("poorly-formed text, not JSON:", e)
        result = False

    return result

def load_data(filename, as_json=True):
    relative_path = join("response_schemas", filename)
    absolute_path = join(dirname(__file__), relative_path)

    with open(absolute_path) as data_file:
        if as_json:
            return data_file.read()
        else:
            return json.loads(data_file.read())


# import csv

# csvfile = open("order_.csv","w")
# writer = csv.writer(csvfile)

# writer.writerow(["lati"])
f = open("order_20161101.txt")
print("经纬度")
count = 0
for line in f:
    count += 1
    if count > 2:
        break
    line1 = "\"" + line[55:75] + "\""
    line2 = "\"" + line[76:-1] + "\""
    print(line1)
    print(line2)


#trajectory_clustering.py
from initialization.config import *
from initialization.initialization import *

# from visualization.trajectory_visualization import *

import os
import numpy as np
import pandas as pd

from scipy.interpolate import interp1d
from scipy.spatial.distance import directed_hausdorff
from sklearn.cluster import DBSCAN

import similaritymeasures
import simplification

# from simplification.cutil import (
#     simplify_coords,
#     simplify_coords_idx,
#     simplify_coords_vw,
#     simplify_coords_vw_idx,
#     simplify_coords_vwp,
# )

def hausdorff( u, v):
    d = max(directed_hausdorff(u, v)[0], directed_hausdorff(v, u)[0])
    return d

def lineterp_traj(traj,npts=20):

    # Linear length along the line:
    distance = np.cumsum( np.sqrt(np.sum( np.diff(traj, axis=0)**2, axis=1 )) )
    distance = np.insert(distance, 0, 0)/distance[-1]
    alpha = np.linspace(0, 1, npts)

    method = 'slinear'
    interpolator =  interp1d(distance, traj, kind=method, axis=0)
    new_pts = interpolator(alpha)

    return new_pts

def get_trajectories(cell_df_list,traj_factor='tSNE',interp_pts=20, zeroed=False, method='trajectory'):

    x_lab = None
    y_lab = None

    if traj_factor == 'xy':
        # x,y
        x_lab = 'x'
        y_lab = 'y'

    elif traj_factor == 'pca':
        x_lab = 'PC1'
        y_lab = 'PC2'

    elif traj_factor == 'tSNE':
        # tSNE
        x_lab = 'tSNE1'
        y_lab = 'tSNE2'

    elif traj_factor == 'umap':

        x_lab = 'UMAP1'
        y_lab = 'UMAP2'

    print('Defining trajectories using: (', x_lab, y_lab, ')')

    traj_list = []

    #
    # Standard case - get entire tracjectory
    #

    if(method=='trajectory'):

        for i, traj in enumerate(cell_df_list):#traj_list:
            this_traj = cell_df_list[i]
            this_traj = this_traj[[x_lab,y_lab]].values

            if(zeroed):
                this_traj = this_traj - this_traj[0,:]

            if interp_pts is not None:
                new_pts = lineterp_traj(this_traj,npts=interp_pts)
                traj_list.append(new_pts)

            else:
                traj_list.append(this_traj)

    #
    # Trajectory segment clustering
    #
    elif(method=='segment'):

        if interp_pts is not None:

            print('WARNING: Using interp_pts = ',interp_pts, ' with method = ', method)
            print(' Curently no interpolation being done for segment method.')

        for i, traj in enumerate(cell_df_list):#traj_list:
            this_traj = cell_df_list[i]
            this_traj = this_traj[[x_lab,y_lab]].values

            if(zeroed):
                this_traj = this_traj - this_traj[0,:]

            for j in range(len(this_traj)-1):

                seg = this_traj[j:j+2,:]
                assert seg.shape == (2,2), 'expecting single step of trajectory'
                traj_list.append(seg)

    return traj_list

def trajectory_distances(traj_list, method='hausdorff'):

    '''
    Compute the distance matrix for trajectories in the list, using designated method.
    '''

    traj_count = len(traj_list)
    D = np.zeros((traj_count, traj_count))

    for i in range(traj_count):
        for j in range(i + 1, traj_count):

            if (method=='hausdorff'):
                distance = hausdorff(traj_list[i], traj_list[j])

            elif(method=='frechet'):
                distance = similaritymeasures.frechet_dist(traj_list[i], traj_list[j])

            elif(method=='area'):
                area = similaritymeasures.frechet_dist(traj_list[i], traj_list[j])
                distance = area

            elif(method=='dtw'):
                distance = similaritymeasures.frechet_dist(traj_list[i], traj_list[j])

            D[i, j] = distance
            D[j, i] = distance

    print('Completed distance matrix, shape: ', D.shape)
    return D

# Compute and plot the clusters with these settings.
def find_max_clusters(D):

    # Find the cluster parameters that maximizes the number of clusters.
    epsrange = np.linspace(1,100,100)
    eps_count = []
    for eps in epsrange:

        mdl = DBSCAN(eps=eps, min_samples=10,metric='precomputed')
        cluster_lst = mdl.fit_predict(D)
        eps_count.append([eps,len(np.unique(np.asarray(cluster_lst)))])

    arr=np.asarray(eps_count)
    mask = (arr[:, 1] == np.max(arr[:,1]))
    filt_arr = arr[mask, :]

    eps=filt_arr[0,0] # This takes the first one.
    print('Determined maximum number of clusters where eps =  ', eps)

    return eps

def cluster_trajectories(traj_list, D, eps, label=''):

    # Plot the result.
    mdl = DBSCAN(eps=eps, min_samples=10,metric='precomputed')
    cluster_lst = mdl.fit_predict(D)

    # # plot_traj_cluster(interp_traj_list, cluster_lst)
    # plot_traj_cluster_avg(traj_list, cluster_lst, label)

    return cluster_lst

def simplify_trajectories(traj_list, method='rdp', param=1.0):

    '''
    method: str;
                'rdp' Ramer–Douglas–Peucker
                'vw' Visvalingam-Whyatt
    '''

    simpl_traj_list = []

    for traj in traj_list:

        traj = traj.copy(order='C') # Otherwise ValueError: ndarray is not C-contiguous

        if(method == 'rdp'):

            # Using Ramer–Douglas–Peucker
            simpl_traj = simplify_coords(traj, param) # param=eps

        elif (method == 'vw'):
            # Using Visvalingam-Whyatt
            simpl_traj = simplify_coords_vw(traj, param)

        simpl_traj_list.append(simpl_traj)

    return simpl_traj_list

def get_trajectory_segments(traj_list):

    seg_list = []
    for traj in traj_list:

        for j in range(len(traj)-1):

            seg = traj[j:j+2,:]
            assert seg.shape == (2,2), 'expecting single step of trajectory'

            seg_list.append(seg)

    return seg_list

def traj_clusters_2_df(df_in, cell_df_list, cluster_lst):

    '''
    Add a column for the trajectory label from cluster_lst into the original dataframe
    Using the unique id from  cell_df_list
    '''

    df = df_in.copy()

    assert len(cell_df_list) == len(cluster_lst)
    df['traj_id'] = np.nan # Initialize all, some will stay NaN if not long enough to anylse

    for i, cell_df in enumerate(cell_df_list):

        this_cell_id = cell_df['uniq_id'].unique()[0] # index [0] because it's a list
        this_traj_id = cluster_lst[i]

        # Now find the same unique id in the input dataframe (full-length)
        df_inds = list(df.index[df['uniq_id']==this_cell_id])

        df.at[df_inds,'traj_id'] = this_traj_id

    return df


st = open('24_2426.txt').readline()
# st = st.replace('B', ' ').replace('A', ' ').replace('C', ' ')
# print(max(len(i) for i in st.split()))
maxx = float('-inf')
count = 1
for i in range(len(st) - 1):
    if st[i] in '123' and st[i + 1] in '123':
        count += 1
        maxx = max(maxx, count)
    else:
        count = 1
print(maxx)


#!/usr/bin/python

import latticex.rosetta as cb

import tensorflow as tf
import sys
import numpy as np
np.set_printoptions(suppress=True)

xa = tf.Variable(
    [
        [1.892, 2],
        [3, 4.43],
        [.0091, .3]
    ]
)
xb = tf.Variable(
    [
        [5.3,  .7],
        [6, -0.7],
        [3,  -2.001]
    ]
)

print("xa:\n", xa)
print("xb:\n", xb)

#
init = tf.compat.v1.global_variables_initializer()
sess = tf.compat.v1.Session()
sess.run(init)

###########

###########
cb.deactivate()


def makeAdjMatrix(file_name):

    file_in = open(file_name, "r")
    nodes_N, edges_M = map(int, file_in.readline().split())

    adjMat = [[0 for _ in range(nodes_N+1)] for _ in range(nodes_N+1)]

    for i in range(edges_M):
        # u = int(input())
        # v = int(input())
        # w = int(input())

        u, v, w = map(int, file_in.readline().split())

        adjMat[u][v] = w

    return adjMat

def graphRepr(adjMat):
    file_out = open("output1A.txt", 'w')
    for i in adjMat:
        for j in i:
            file_out.write(f"{j} ")
        file_out.write(f"\n")

graph1 = makeAdjMatrix("input1a_1.txt")
graphRepr(graph1)


import csv
import logging
import os
import requests
from iip_smr_web_app import settings_app
import xml.etree.ElementTree as ET

log = logging.getLogger(__name__)

LATIN_TEXT = 0
LATIN_WORDNUM = 1
LATIN_NUMBER = 6
LATIN_WORD = 7
LATIN_POS1 = 8
LATIN_POS2 = 9
LATIN_LEMMA = 10
XML1 = 11
XML2 = 12
NEWBUFF = 3

KWIC_BUFF = 2

POSDICT = {"ADV": "adverb", "V": "verb", "N": "noun", "PREP": "preposition", "CC": "conjunction", "ADJ": "adjective"}
REVPOSDICT = {"noun": "N", "verb": "V", "adjective": "ADJ", "adverb": "ADV"}
MOODDICT = {"IND": "indicative", "PTC": "participle", "IMP": "imperative", "SUB": "subjunctive"}

# data is formatted as a list of dictionaries
# each dictionary is a lemma
# LEMMA DICTIONARY FORMAT
# [ lemma: normalized form of word
#   pos: part of speech of lemma
#   count: # of times word appears in inscriptions
#   forms : dictionary of different forms of word]
# FORMS DICTIONARY FORMAT
# [ form: string of form
#   count: # of times form appears
#   pos: pos information about the form
#   kwics: list of duples of the form, first index is kwic, second is inscrp id]
# (kwics and inscription ids should correspond to each other)

def get_latin_words_pos_new():

    log.debug( 'start' )

    with requests.Session() as s:
        log.debug( f'LATIN_CSV_NEW_URL, ``{settings_app.LATIN_CSV_NEW_URL}``' )
        download = s.get(settings_app.LATIN_CSV_NEW_URL)
        log.debug( f'download, ``{download}``' )
        decoded = download.content.decode('utf-8')
        words = {}
        csv_reader = csv.reader(decoded.splitlines(), delimiter=",")
        line_count = 0
        curtext = ""
        textrows = []
        dbwords = []
        for row in csv_reader:
            row_word = row[LATIN_LEMMA + NEWBUFF]
            if line_count > 0 and len(row_word) > 0 and row_word[:1] != "?":
                if curtext != row[LATIN_TEXT + NEWBUFF]:
                    go_through_text_new(textrows, words, dbwords)
                    curtext = row[LATIN_TEXT + NEWBUFF]
                    textrows = [row]
                else:
                    textrows.append(row)
            line_count += 1
        go_through_text_new(textrows, words, dbwords)
        sorted_words = {k: v for k, v in sorted(words.items(), key = lambda item: item)}
        mapped_db = map(lambda x: "\n".join(x), dbwords)
        return {"lemmas": count_words(sorted_words), "db_list": "\n\n\n".join(mapped_db)}

def count_words(words):
    counted = []
    for lemma, lemma_dict in words.items():
        total = 0
        for form, form_dict in lemma_dict["forms"].items():
            formlen = len(form_dict["kwics"])
            total += formlen
            form_dict["count"] = formlen
        lemma_dict["count"] = total
        counted.append(lemma_dict)
    return counted

def go_through_text_new(text_rows, words, dbwords):
    dbwordlist = []
    row_len = len(text_rows)

    for x in range(0, row_len):
        row = text_rows[x]

        lemma = row[LATIN_LEMMA + NEWBUFF].lower()
        if lemma.find("|") > -1:
            lemma = lemma.replace("|", " | ")

        pos1 = row[LATIN_POS1 + NEWBUFF]
        latext = row[LATIN_TEXT + NEWBUFF]
        #getting pos info
        pos2 = getXML1POS(row[XML1 + NEWBUFF], pos1, row[LATIN_POS2 + NEWBUFF])
        if pos2 is None:
            pos2 = row[LATIN_POS2 + NEWBUFF].lower()
            if pos2 == "":
                pos2 = "undefined"
        else:
            pos1 = pos2[0]
            pos2 = pos2[1]
            if pos1 in REVPOSDICT:
                pos1 = REVPOSDICT.get(pos1)

        pos_string = row[LATIN_WORD + NEWBUFF]+ " (" + pos2 + ")"
        lemma_string = lemma + " " + pos1

        #adding to doubletree list
        dbwordlist.append(row[LATIN_LEMMA + NEWBUFF].upper() + "/" + pos1)

        form = row[LATIN_WORD + NEWBUFF]
        KWICstr = ""
        for y in range(x - KWIC_BUFF, x + KWIC_BUFF + 1):
            if y >= 0 and y < row_len:
                KWICstr += " " + text_rows[y][LATIN_WORD + NEWBUFF]

        incp_id = row[LATIN_TEXT + NEWBUFF][:-4]
        KWIC = [KWICstr, incp_id]

        lemma_dict = words.get(lemma_string)
        if lemma_dict is not None:
            form_dict = lemma_dict.get("forms").get(pos_string)
            if form_dict is not None:
                form_dict.get("kwics").append(KWIC)
            else:
                form = {"form": form, "pos": pos2, "kwics": [KWIC]}
                lemma_dict["forms"][pos_string] = form
        else:
            forms = {"form": form, "pos": pos2, "kwics": [KWIC]}
            words[lemma_string] = {"lemma": lemma, "pos": pos1, "forms": {pos_string: forms} }
    dbwords.append(dbwordlist)

def getXML1POS(xmlString, pos, match):
    try:
        root = ET.ElementTree(ET.fromstring(xmlString)).getroot()
        first = None
        for elem in root.findall("word/entry/infl"):
            if first is None:
                first = elem
            if checkMatch(elem, pos, match):
                return parseByPos(elem)
        if first is None:
            return None
        else:
            return parseByPos(first)
    except Exception as e:
        #print(e)
        return None

def checkMatch(el, pos, match):
    if el.find('pofs') is not None and el.find('pofs').text == POSDICT[pos]:
        if pos == "N":
            return el.find('case') is not None and match.lower() == el.find('case').text[:3]
        if pos == "V":
            return el.find('mood') is not None and MOODDICT[match] == el.find('mood').text
        if pos == "ADJ":
            return (el.find('case') is not None and match.lower() == el.find('case').text[:3]) \
            or (el.find('comp') is not None and match.lower() == el.find('comp').text[:3])
        return False
    else:
        return False

def getXML2POS(xmlString):
    try:
        root = ET.ElementTree(ET.fromstring(xmlString)).getroot()
        if root.tag == "infl":
            return parseByPos(root)
        for elem in root.findall("infl"):
            return parseByPos(elem)
    except Exception as e:
        return None

def parseByPos(el):
    pos = el.find('pofs').text
    if pos == "noun":
        return (pos, pPart(el, "decl") + pPart(el, "case") + pPart(el, "gend") + pPart(el, "num"))
    elif pos == "verb":
        return (pos, pPart(el, "pers") + pPart(el, "num") + pPart(el, "voice") + pPart(el, "tense") + pPart(el, "mood"))
    elif pos == "adjective":
        return (pos, pPart(el, "decl") + pPart(el, "case") + pPart(el, "gend") + pPart(el, "num") + pPart(el, "comp"))
    elif pos == "pronoun":
        return (pos, pPart(el, "case") + pPart(el, "gend") + pPart(el, "num"))
    else:
        return None

def pPart(elem, part):
    if elem.find(part) is None:
        return ""
    else:
        str = elem.find(part).text + " "
        if part == "num":
            str = str[:1] + " "
        return str

def findMatch():
    with requests.Session() as s:
        download = s.get(settings_app.LATIN_CSV_URL)
        decoded = download.content.decode('utf-8')
        csv_reader = csv.reader(decoded.splitlines(), delimiter=",")
        line_count = 1
        curtext = ""
        textrows = []
        for row in csv_reader:
            if line_count == 5:
                xmlString = row[XML1]
                pos = row[LATIN_POS1]
                match = row[LATIN_POS2]
                try:
                    root = ET.ElementTree(ET.fromstring(xmlString)).getroot()
                    first = None
                    for elem in root.findall("word/entry/infl"):
                        if first is None:
                            first = elem
                        if checkMatch(elem, pos, match):
                            print(parseByPos(elem))
                    if first is None:
                        print("")
                    else:
                        print(parseByPos(first))
                except Exception as e:
                        print(e)
            line_count += 1


#!/usr/bin/env python3

from code.album import Album, RepeatedStickers, CSVSticker

if __name__ == "__main__":
    album = Album()
    album.add_figure('GER9')
    album.add_figure('CMR19')
    album.add_figure('BRA10')
    album.add_figure('BRA4')
    repetidas = RepeatedStickers()
    repetidas.add_figure('BRA1')
    repetidas.add_figure('BRA1')
    repetidas.add_figure('BRA1')
    repetidas.add_figure('BRA1')
    CSVSticker.write('figurinhas.csv', album.figurinhas_coladas)
    CSVSticker.write('repetidas.csv', repetidas.repetidas)

    album2 = Album()
    repetidas2 = RepeatedStickers()

    for figurinha in CSVSticker.reader('figurinhas.csv'):
        if album2.check_is_present(figurinha):
            repetidas2.add_figure(figurinha)
        else:
            album2.add_figure(figurinha)

    for figurinha in CSVSticker.reader('repetidas.csv'):
        if album2.check_is_present(figurinha):
            repetidas2.add_figure(figurinha)
        else:
            album2.add_figure(figurinha)


# from isOdd import isOdd
from progress1bar import ProgressBar
# import time
# import emoji
# import matplotlib.pyplot as plt
# import numpy as np

# print(isOdd(2))  # False
# print(isOdd(3))  # True

bar = FillingSquaresBar('Processing', max=20)
bar = Bar('Processing', max=20)
for i in range(20):
    time.sleep(0.5)
    bar.next()
bar.finish()

# print(emoji.emojize('Python is :thumbs_up:'))
# print(emoji.emojize('Python is :thumbsup:', language='alias')) # Поддержка псевдонимов
# print(emoji.demojize('Python is 👍'))
# print(emoji.emojize("Python is fun :red_heart:"))
# print(emoji.emojize("Python is fun :red_heart:", variant="emoji_type"))
# print(emoji.is_emoji("👍"))

# plt.style.use('_mpl-gallery-nogrid')

# # make data
# x = [2,4,6]
# colors = plt.get_cmap('YlGnBu')(np.linspace(0.2, 0.7, len(x)))

# # plot
# fig, ax = plt.subplots()
# ax.pie(x, colors=colors, radius=3, center=(4, 4),
#        wedgeprops={"linewidth": 1, "edgecolor": "white"}, frame=True)

# ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
#        ylim=(0, 8), yticks=np.arange(1, 8))

# plt.show()

# x = [1, 4, 2, 4, 7, 3]
# plt.plot(x)
# plt.show()


import os
import re
from sklearn.utils import shuffle
import pandas as pd
import nltk
from sklearn.model_selection import KFold
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer

def read_text_file(file_path):

    file = ""
    with open(file_path, 'r') as f:
        file+=f.read()
    return file

def read_files(path):

    files = []
    for file in os.listdir():
        if file.endswith(".txt"):
            file_path = f"{path}\{file}"
            files.append(read_text_file(file_path))
    return files

def load_dataset() :

    negative_dataset_path = "D:\college material\\4th year\\2nd term\\NLP\\Sentiment-analysis-of-movies-reviews\\txt_sentoken\\neg"
    positive_dataset_path = "D:\college material\\4th year\\2nd term\\NLP\\Sentiment-analysis-of-movies-reviews\\txt_sentoken\\pos"
    os.chdir(negative_dataset_path)
    negative_dataset = read_files(negative_dataset_path)
    os.chdir(positive_dataset_path)
    positive_dataset = read_files(positive_dataset_path)

    return positive_dataset,negative_dataset

def remove_stop_words(dataset):

    stop_words = set(stopwords.words("english"))
    for i in range(len(dataset)):
        dataset[i] = [word for word in dataset[i] if word.casefold() not in stop_words]
    return dataset

def remove_numbers(dataset):
    for i in range(len(dataset)):
        dataset[i] = re.sub("\d+",' ', dataset[i])
        #dataset[i] = word_tokenize(dataset[i])
    return dataset

def remove_punctuation(dataset):

    for i in range(len(dataset)):
        dataset[i] = re.sub("[^a-zA-z | ^\w+'t]",' ', dataset[i])
        dataset[i] = word_tokenize(dataset[i])
    return dataset

def stemming(dataset):

    porter_stemmer = PorterStemmer()
    for i in range(len(dataset)):
        dataset[i] = [porter_stemmer.stem(word) for word in dataset[i]]
        dataset[i] = ' '.join(dataset[i])
    return dataset

def preprocess(dataset):

    dataset = remove_numbers(dataset)
    dataset = remove_punctuation(dataset)
    dataset = remove_stop_words(dataset)
    dataset = stemming(dataset)
    return dataset

def prepare_dataset():

    positive_dataset, negative_dataset = load_dataset()
    positive_dataset = preprocess(positive_dataset)
    positive_dataset = pd.DataFrame(positive_dataset)
    positive_dataset.columns = ['Review']
    positive_dataset['Label'] = ["pos" for i in range(1000)]
    negative_dataset = preprocess(negative_dataset)
    negative_dataset = pd.DataFrame(negative_dataset)
    negative_dataset.columns = ['Review']
    negative_dataset['Label'] = ["neg" for i in range(1000)]
    dataset = pd.concat([positive_dataset,negative_dataset],ignore_index=True,sort=False)
    return dataset


a = 'heap'
b = 'pea'
# a = 'qwerty'
# b = 'asdfgh'
len_a = len(a)
len_b = len(b)

t = [[0 for j in range(len_b+1)]for i in range(len_a+1)]

for i in range(len_a+1):
    for j in range(len_b+1):
        if i == 0 or j == 0:
            t[i][j] = 0
            continue
        if a[i-1]==b[j-1]:
            t[i][j] = 1+t[i-1][j-1]
        else:
            t[i][j] = max(t[i-1][j],t[i][j-1])

Insertion = 0
Deletion = 0
Insertion = len_b - t[len_a][len_b]
Deletion = len_a - t[len_a][len_b]

print("Insertion: ",Insertion)
print("Deletion: ", Deletion)


from collections import defaultdict

class Solution(object):
    def shortestPathLength(self, graph):
        """
        :type graph: List[List[int]]
        :rtype: int
        """
        N = len(graph)
        queue = [(i, 1 << i) for i in range(N)]
        dist = defaultdict(lambda: N * N)
        for i in range(N):
            dist[(i, 1 << i)] = 0

        while queue:
            node, path = queue.pop(0)
            d = dist[(node, path)]
            if path == 2 ** N - 1:
                return d
            for nex in graph[node]:
                temp = (1 << nex) | path
                if dist[(nex, temp)] > d + 1:
                    dist[(nex, temp)] = d + 1
                    queue.append((nex, temp))

python/BFS/Shortest Path Visiting All Nodes/Shortest Path Visiting All Nodes.py


# -*- coding: utf-8 -*-
"""
Created on Sat Apr  6 12:51:24 2019

@author: Stefan
"""
import pandas as pd
import numpy as np
import cv2
import glob
from sklearn.model_selection import train_test_split

#images1=[cv2.imread(file) for file in glob.glob('C:/Users/Stefan/Desktop/PackageWallStuff/MaskiOdDosegasniAnotacii/*.bmp')]
#images1=list(np.float_(images))
images1=[cv2.imread(file) for file in glob.glob('E:/fax/package_wall/PackageWall/packageWallAnnotationVisualization/*.bmp')]
sliki=[cv2.imread(file) for file in glob.glob('E:/fax/sivi_sliki/*.bmp')]
X_train,X_test,X1_train,X1_test=train_test_split(sliki,images1,test_size=0.15)
X_train,X_val,X1_train,X1_val=train_test_split(X_train,X1_train,test_size=0.15)
pom=[]
A=[]
B=[]
glavno=[]
#tr=images1[3][75:80,40:44,:]

for broj in range(len(X1_train)):
   for i in range(144):
       for j in range(176):
            if ((X1_train[broj][i,j,1]!=X1_train[broj][i,j,0]) and (X1_train[broj][i,j,1]!=X1_train[broj][i,j,2]) and (X1_train[broj][i,j,2]==X1_train[broj][i,j,0])):
                pom.append(1)

            else:
                pom.append(0)

val=[]
for broj in range(len(X1_val)):
   for i in range(144):
       for j in range(176):
            if ((X1_val[broj][i,j,1]!=X1_val[broj][i,j,0]) and (X1_val[broj][i,j,1]!=X1_val[broj][i,j,2]) and (X1_val[broj][i,j,2]==X1_val[broj][i,j,0])):
                val.append(1)

            else:
                val.append(0)
#A.append(X_train[broj][i-2:i+3,j-2:j+3,:])
pom1=np.asarray(pom)
pom1=pom1.reshape(len(X1_train),144,176)
val=np.asarray(val)
val=val.reshape(len(X1_val),144,176)
#tr=pom1[2][2:7,5:10]
for broj in range(len(X1_train)):
   for i in range(2,142):
       for j in range(2,174):
           #pp=np.sum(pom1[broj][i-2:i+3,j-2:j+3])
           #if pp!=0:
               #A.append(X_train[broj][i-2:i+3,j-2:j+3,:])
           if pom1[broj][i,j]==1:
               A.append(X_train[broj][i-2:i+3,j-2:j+3,:])

A_val=[]
for broj in range(len(X1_val)):
   for i in range(2,142):
       for j in range(2,174):
           #pp=np.sum(pom1[broj][i-2:i+3,j-2:j+3])
           #if pp!=0:
               #A.append(X_train[broj][i-2:i+3,j-2:j+3,:])
           if val[broj][i,j]==1:
               A_val.append(X_val[broj][i-2:i+3,j-2:j+3,:])
import random
for l in range(6*len(A)):
    br=random.randint(0,len(X1_train)-1)
    x=random.randint(4,140)
    y=random.randint(4,170)
    pp=np.sum(pom1[br][x-2:x+3,y-2:y+3])
    if pp==0:
        B.append(X_train[br][x-2:x+3,y-2:y+3,:])
B_val=[]
for l in range(5*len(A_val)):
    br=random.randint(0,len(X1_val)-1)
    x=random.randint(4,140)
    y=random.randint(4,170)
    pp=np.sum(val[br][x-2:x+3,y-2:y+3])
    if pp==0:
        B_val.append(X_val[br][x-2:x+3,y-2:y+3,:])

#B=B+nn
y1=[]
x1=A+B;
xp_val=A_val+B_val
xp_val=np.asarray(xp_val)
yp_val=[]
for i in range(len(A)):
    y1.append(1)
for i in range(len(B)):
    y1.append(0)
for i in range(len(A_val)):
    yp_val.append(1)
for i in range(len(B_val)):
    yp_val.append(0)

from keras.utils import to_categorical
y1=to_categorical(y1,num_classes=2,dtype='int32')
yp_val=to_categorical(yp_val,num_classes=2,dtype='int32')
x1=np.asarray(x1)
#X_train=np.asarray(X_train)
#X_test=np.asarray(X_test)

p1=[]
for broj in range(len(X1_test)):
   for i in range(2,142):
       for j in range(2,174):
            if ((X1_test[broj][i,j,1]!=X1_test[broj][i,j,0]) and (X1_test[broj][i,j,1]!=X1_test[broj][i,j,2]) and (X1_test[broj][i,j,2]==X1_test[broj][i,j,0])):
                p1.append(1)

            else:
                p1.append(0)

p1=np.asarray(p1)
y_true=p1.reshape(len(X1_test),140,172)
y_true=to_categorical(y_true,num_classes=2,dtype='int32')

for broj in range(len(X_test)):
   for i in range(2,142):
       for j in range(2,174):
           glavno.append(X_test[broj][i-2:i+3,j-2:j+3,:])

glavno=np.asarray(glavno)
import matplotlib.pyplot as plt
plt.figure(1)
plt.imshow(images1[3])
plt.imshow(pom1[3])

#images1=images1/np.linalg.norm(images1,ord=1,axis=1,keepdims=True)
#pom=np.reshape(images1, (120,76032))
#np.savetxt('sli.csv', images1, delimiter=',')
#prva=images1[1:95]
#prva=prva/np.linalg.norm(prva,ord=1,axis=1,keepdims=True)
#print(prva)
#druga=images1[96:120]


import sys
input = sys.stdin.readline

def solution(board, skill):
    answer = 0
    row_len = len(board[0])
    col_len = len(board)
    arr = [[0 for _ in range(len(board[0])+1)] for _ in range(len(board)+1)]
    for _type, r1, c1, r2, c2, degree in skill:
        deg = degree if _type == 2 else -1 * degree
        arr[r1][c1] += deg
        arr[r2+1][c2+1] += deg
        deg *= -1
        arr[r2+1][c1] += deg
        arr[r1][c2+1] += deg

    for i in range(col_len):
        for j in range(1, row_len):
            arr[i][j] += arr[i][j-1]

    for i in range(1, col_len):
        for j in range(row_len):
            arr[i][j] += arr[i-1][j]

    for i in range(col_len):
        for j in range(row_len):
            if arr[i][j] + board[i][j] > 0:
                answer += 1

    return answer

if __name__ == '__main__':
    board = [[5,5,5,5,5],[5,5,5,5,5],[5,5,5,5,5],[5,5,5,5,5]]
    skill = [[1,0,0,3,4,4],[1,2,0,2,3,2],[2,1,0,3,1,2],[1,0,1,3,3,1]]
    solution(board, skill)

programers/2022 KAKAO BLIND RECRUITMENT/파괴되지 않은 건물.py

파괴되지 않은 건물.py


################################################################
#  https://techwithtim.net/tutorials/flask/a-basic-website/    #
# https://pythonprogramming.net/practical-flask-introduction/  #
################################################################

from flask import Flask, render_template, redirect, url_for, request, session
from datetime import timedelta
import requests
from string import Template
from datetime import datetime

base_url = ' https://api.gdeltproject.org/api/v2/doc/doc'
geo_base_url = "https://api.gdeltproject.org/api/v2/geo/geo"

app = Flask(__name__)
app.secret_key = "hello"
app.permanent_session_lifetime = timedelta(minutes=5)

@app.route("/")  # this sets the route to this page
def home():
	#return "Hello! this is the main page
HELLO
"  # some basic inline html
    #return render_template("index.html", content="Testing", n=4)
    return render_template("index.html")

################################################################
# http://localhost:5000/timelinevoltone/covid/china/science
@app.route("/gdeltdocapi", methods=["POST", "GET"])#/<topic>/<sourcecountry>/<theme>")
def gdeltdocapi():#topic, sourcecountry, theme):

    # ====================================================
    # QUERY
    # ====================================================
    title = "Search from GDELT DOC 2.0 API"
    msg = ""
    searchterm = None
    domain = None
    sourcecountry = None
    sourcelang = None
    theme = None
    tone = None
    startdatetime = None
    enddatetime = None
    timespan = None
    mode = None
    format = None
    trans = None
    #st = None
    if request.method == "POST":
        searchterm = request.form["searchterm"]
        #st = request.form.get("searchterm")
        #print("Search term: ", searchterm)

        domain = request.form["domain"]
        #print("Domain: ", domain)

        sourcecountry = request.form["sourcecountry"]
        #print("Source country: ", sourcecountry)

        sourcelang = request.form.get("sourcelang")
        #print("Source lang: ", sourcelang)

        theme = request.form.get("theme")
        print("Theme: ", theme)

        tone = request.form.get("tone")
        #print("Tone:", tone)

        startdatetime = request.form.get("startdatetime")
        #print("Start date: ", startdatetime)

        enddatetime = request.form.get("enddatetime")
        #print("End date: ", enddatetime)

        timespan = request.form.get("timespan")
        if timespan == "":
            timespan = "3months"
        #print("Timespan: ", timespan)

        mode = request.form.get("mode")
        #print("Mode: ", mode)

        format = request.form.get("format")
        #print("Format: ", format)

        trans = request.form.get("trans")
        #print("Trans: ", trans)

    else:
        if searchterm == None:
            return render_template("gdeltdocapi.html")

    #searchterm = request.form.get("nm")
    # params = {'query': [topic, "sourcecountry:{}".format(sourcecountry), "theme:{}".format(theme)], 'mode': 'timelinetone'}
    # https://api.gdeltproject.org/api/v2/doc/doc?query=covid&mode=ArtList&maxrecords=75&trans=googtrans&startdatetime=20170101103000&enddatetime=20200817211158
    # https://zhuoyunao.github.io/#api=doc&query=covid&timelinemode=TimelineTone&timelinesmooth=0&startdatetime=20200101000000&enddatetime=20200301235959

    params = {}
    query = []
    query.append(searchterm)
    msg = msg + "Search term: " + searchterm + ", "
    if sourcecountry != "":
        sourcecountry = "sourcecountry:"+sourcecountry
        query.append(sourcecountry)
        msg = msg + "Source country: " + sourcecountry + ", "
    if domain != "":
        domain = "domain:"+domain
        query.append(domain)
        msg = msg + "Domain: " + domain + ", "
    if sourcelang != "":
        sourcelang = "sourcelang:"+sourcelang
        query.append(sourcelang)
        msg = msg + "Source lang: " + sourcelang + ", "
    if theme != "":
        theme = "theme:"+theme
        query.append(theme)
        msg = msg + "Theme: " + theme + ", "
    if tone != "":
        query.append(tone)
        msg = msg + "Tone: " + tone + ", "

    params['query'] = query
    #print(query)
    params['mode'] = mode #'timelinevolinfo'
    msg = msg + "Mode: " + mode + ", "
    if mode != "artlist":
        params['TIMELINESMOOTH'] = "5"
        msg = msg + "TIMELINESMOOTH: " + "5" + ", "
    params['format'] = format
    msg = msg + "Format: " + format + ", "

    if mode == "artlist": # only translation provided for artlist
        if trans != None:
            params['trans'] = trans

    if startdatetime == "" or enddatetime == "":
        if timespan == "":
            timespan = "1w"
        params['timespan'] = timespan
        msg = msg + "Timespan: " + timespan + ", "
    else:
        # work out the date time format: YYYYMMDDHHMMSS
        # from 2020-04-01T12:30
        startdatetime = startdatetime.replace("-", "")
        msg = msg + "Start date: " + startdatetime + ", "
        startdatetime = startdatetime+"000000"
        #print(startdatetime)
        params['startdatetime'] = startdatetime

        enddatetime = enddatetime.replace("-", "")
        msg = msg + "End date: " + enddatetime
        enddatetime = enddatetime+"235959"
        params['enddatetime'] = enddatetime

    params['maxrecords'] = 200 # max up to 250

    response = requests.get(base_url, params=params)#, verify=False)
    print(response.url)

    theurl = response.url
    #print(msg)
    return render_template("gdeltdocresponse.html", result=theurl, title=title, msg=msg)

####################################################################
# gdeltdeoapi
@app.route("/gdeltgeoapi", methods=["POST", "GET"])
def gdeltgeoapi():
    title = "Search from GDELT GEO 2.0 API"
    msg = ""
    # ====================================================
    # QUERY
    # https://zhuoyunao.github.io/#api=geo&query=covid&geomode=PointData&geotimespan=1d
    # https://zhuoyunao.github.io/#api=geo&query=covid&geomode=PointHeatmap&geoformat=GeoJSON&geotimespan=1d
    # https://zhuoyunao.github.io/#api=geo&query=covid&geomode=PointData&geoformat=html&geotimespan=7d
    # https://zhuoyunao.github.io/#api=geo&query=covid&geomode=PointHeatmap&geoformat=GeoJSON&geotimespan=7d
    #
    # ====================================================
    searchterm = None
    domain = None
    location = None
    locationcc = None
    sourcecountry = None
    sourcelang = None
    theme = None
    tone = None
    timespan = None
    mode = None
    format = None
    #maxpoints = 1000

    # ================================================
    # Access the form data
    if request.method == "POST":
        searchterm = request.form["searchterm"]
        #print("Search term: ", searchterm)

        domain = request.form["domain"]
        #print("Domain: ", domain)

        location = request.form["location"]
        #print("Location: ", location)

        locationcc = request.form["locationcc"]
        #print("LocationCC: ", locationcc)

        sourcecountry = request.form["sourcecountry"]
        #print("Source country: ", sourcecountry)

        sourcelang = request.form.get("sourcelang")
        #print("Source lang: ", sourcelang)

        theme = request.form.get("theme")
        #print("Theme: ", theme)

        tone = request.form.get("tone")
        #print("Tone:", tone)

        timespan = request.form.get("timespan")
        if timespan == "":
            timespan = "24h" # default
        #print("Timespan: ", timespan)

        mode = request.form.get("mode")
        #print("Mode: ", mode)

        format = request.form.get("format")
        #print("Format: ", format)

    else:
        if searchterm == None:
            return render_template("gdeltgeoapi.html")

    # =================================================
    # Setup the URL parameters for the query
    params = {}
    query = []
    query.append(searchterm)
    msg = msg + " " + "Search term: " + searchterm + ", "
    if domain != "":
        domain = "domain:"+domain
        query.append(domain)
        msg = msg + " " + "Domain: " + domain + ", "
    if location != "":
        location = "location:"+location
        query.append(location)
        msg = msg + "Location: " + location + ", "
    if locationcc != "":
        locationcc = "locationcc:"+locationcc
        query.append(locationcc)
        msg = msg + "LocationCC: " + locationcc + ", "
    if sourcecountry != "":
        sourcecountry = "sourcecountry:"+sourcecountry
        query.append(sourcecountry)
        msg = msg + "Source Country: " + sourcecountry + ", "
    if sourcelang != "":
        sourcelang = "sourcelang:"+sourcelang
        query.append(sourcelang)
        msg = msg + "Source language: " + sourcelang + ", "
    if theme != "":
        theme = "theme:"+theme
        query.append(theme)
        msg = msg + "Theme: " + theme + ", "
    if tone != "":
        query.append(tone)
        msg = msg + "Tone: " + tone + ", "

    params['query'] = query
    #print(query)
    params['mode'] = mode #'timelinevolinfo'
    msg = msg + "Mode: " + mode + ", "
    params['format'] = format
    msg = msg + "Format: " + format + ", "
    params['timespan'] = timespan
    msg = msg + "timespan: " + timespan

    # =================================================
    # Send the request to GDELT and get the response
    response = requests.get(geo_base_url, params=params)#, verify=False)
    print(response.url)

    # =================================================
    # Show the result to user
    theurl = response.url

    return render_template("gdeltgeoresponse.html", result=theurl, msg=msg, title=title)

####################################################################
# gdeltgkggeojson api
@app.route("/gdeltgkggeojsonapi", methods=["POST", "GET"])
def gdeltgkggeojsonapi():
    title = "Search from GDELT GKG GEOJSON API"

    # ====================================================
    # QUERY
    # ====================================================
    searchterm = None
    domain = None
    lang = None
    geoname = None
    timespan = None
    outputtype = None
    outputfields = None
    gcamvar = None
    maxrows = None
    #maxpoints = 1000

    # ================================================
    # Access the form data
    if request.method == "POST":
        searchterm = request.form["searchterm"]
        print("Search term: ", searchterm)

        domain = request.form["domain"]
        print("Domain: ", domain)

        lang = request.form["lang"]
        print("Language: ", lang)

        geoname = request.form["geoname"]
        print("Geoname: ", geoname)

        timespan = request.form.get("timespan")
        print("Timespan: ", timespan)

        gcamvar = request.form.get("gcamvar")
        print("GCAMVAR: ", gcamvar)

        maxrows = request.form.get("maxrows")
        print("maxrows: ", maxrows)

        outputtype = request.form.get("outputtype")
        print("OUTPUTTYPE: ", outputtype)

        outputfields = request.form.get("outputfields")
        print("OUTPUTFIELDS: ", outputfields)

    else:
        if searchterm == None:
            return render_template("gdeltgkggeojsonapi.html")

    # =================================================
    # Setup the URL parameters for the query
    #
    # Feed of all Monitored News Coverage in the Last Hour.
    # https://api.gdeltproject.org/api/v1/gkg_geojson
    #
    # Feed of Food Security Coverage in the Last Hour.
    # https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=FOOD_SECURITY)
    #
    # Feed of BBC.co.uk Coverage in the Last 24 Hours.
    # https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=domain:bbc.co.uk&TIMESPAN=1440
    #
    # Feed of Arabic Language Coverage of Last 2 Hours
    # https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=lang:Arabic&TIMESPAN=120
    #
    # Feed of Arabic Language Coverage of Last 2 Hours With Custom Output Fields
    # https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=lang:Arabic&TIMESPAN=120&OUTPUTFIELDS=url,name,sharingimage,tone,lang
    #
    # Feed of Anxiety Emotion Over Last Two Hours.  Here we use the special GCAMVAR parameter
    # to include the RID "Anxiety" emotion assessed through the GDELT GCAM pipeline by
    # looking up its variable name in the GCAM Master Codebook.
    # https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=&TIMESPAN=120&OUTPUTFIELDS=url,name,sharingimage,tone,lang&GCAMVAR=c8.3
    #
    # Feed For Animated Map of Anxiety Over Last 24 Hours.
    # https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=&TIMESPAN=1440&OUTPUTFIELDS=tone&GCAMVAR=c8.3&OUTPUTTYPE=2
    #
    # ===================================================

    # =============================================
    gkggeojson_url =  "https://api.gdeltproject.org/api/v1/gkg_geojson"

    params = {}

    # To search for only Arabic-language FOOD_SECURITY coverage, use the URL
    # "https://api.gdeltproject.org/api/v1/gkg_geojson?QUERY=lang:Arabic,FOOD_SECURITY"
    # Construct query parameter as follows:
    # QUERY=atheme,lang:Arabic,domain:thedomain,geoname:locationname
    # Individual query terms are separated by commas,
    # words separated by spaces are treated as phrase matches (they should NOT be surrounded by quote marks).

    # =============================================
    # The available parameters are listed below.
    # Note that they must be specified in all
    # capital letters.
    # ===============================================

    query = ""
    if searchterm != "":
        query = searchterm

    if domain != "":
        if query != "":
            domain = ",domain:"+domain
        else:
            domain = "domain:"+domain
        query = query+domain
    if lang != "":
        if query != "":
            lang = ",lang:"+lang
        else:
            lang = "lang"+lang
        query = query + lang
    if geoname != "":
        if query != "":
            geoname = ",geoname:"+geoname
        else:
            geoname = "geoname:"+geoname
        query = query + geoname

    params['QUERY'] = query
    print(query)

    if timespan != "":
        params['TIMESPAN'] = timespan

    if outputtype != "":
        params['OUTPUTTYPE'] = outputtype # "1" for "article", "2" generates "location+time" output

    if len(outputfields) > 0:
        fields = ""
        for i in range(len(outputfields)):
            if fields != "":
                fields = outputfields[i]
            else:
                fields = fields+","+outputfields[i]
        params["OUTPUTFIELDS"] = fields
        print(fields)

    if gcamvar != "":
        params['GCAMVAR'] = gcamvar

    if maxrows != "":
        params['MAXROWS'] = maxrows

    # =================================================
    # Send the request to GDELT and get the response
    response = requests.get(gkggeojson_url, params=params)#, verify=False)
    print(response.url)

    # =================================================
    # Show the result to user
    theurl = response.url

    return render_template("gdeltgkggeojsonresponse.html", result=theurl, title=title)

###########################################################################
# gdelt context api
# =========================================================================
@app.route("/gdeltcontextapi", methods=["POST", "GET"])
def gdeltcontextapi():
    title = "The GDELT Context Search API"

    # ====================================================
    # QUERY
    # ====================================================
    searchterm = None
    domain = None
    isquote = None
    format = None
    timespan = None
    startdatetime = None
    enddatetime = None
    maxrows = None
    searchlang = None
    sort = None

    # ================================================
    # Access the form data
    if request.method == "POST":
        searchterm = request.form["searchterm"]
        print("Search term: ", searchterm)

        domain = request.form["domain"]
        print("Domain: ", domain)

        isquote = request.form["isquote"]
        print("ISQUOTE: ", isquote)

        format = request.form.get("format")
        print("Format: ", format)

        timespan = request.form.get("timespan")
        print("Timespan: ", timespan)

        startdatetime = request.form.get("startdatetime")
        print("Start date: ", startdatetime)

        enddatetime = request.form.get("enddatetime")
        print("End date: ", enddatetime)

        maxrows = request.form.get("maxrows")
        print("MAXROWS: ", maxrows)

        searchlang = request.form.get("searchlang")
        print("SEARCHLANG: ", searchlang)

        sort = request.form.get("sort")
        print("SORT: ", sort)

    else:
        if searchterm == None:
            return render_template("gdeltcontextapi.html")

    # ==========================================
    # Construct the request to gdelt context api
    context_url =  "https://api.gdeltproject.org/api/v2/context/context?"

    params = {}

    query = []
    query.append(searchterm)

    if domain != "":
        domain = "domain:"+domain
        query.append(domain)

    params['query'] = query
    print(query)

    if isquote != "":
        params['isquote'] = isquote

    params['mode'] = 'artlist'
    params['format'] = format

    if timespan != "":
        params['timespan'] = timespan

    elif startdatetime != "" and enddatetime != "":
        # work out the date time format: YYYYMMDDHHMMSS
        # from 2020-04-01T12:30
        startdatetime = startdatetime.replace("-", "")
        startdatetime = startdatetime+"000000"
        print(startdatetime)
        params['startdatetime'] = startdatetime

        enddatetime = enddatetime.replace("-", "")
        enddatetime = enddatetime+"235959"
        params['enddatetime'] = enddatetime

    if maxrows == "":
        maxrows = 75
    params['maxrecords'] = maxrows

    if searchlang != "":
        params['searchlang'] = searchlang
    if sort != "":
        params['sort'] = sort

    # =================================================
    # Send the request to GDELT and get the response
    response = requests.get(context_url, params=params)#, verify=False)
    print(response.url)

    # =================================================
    # Show the result to user
    theurl = response.url

    return render_template("contextresponse.html", result=theurl, title=title)

########################################################################
# Stability dashboard API
# ======================================================================
@app.route("/stabilitydashboardapi", methods=["POST", "GET"])
def stabilitydashboardapi():
    title = "The GDELT Stability Dashboard API: Stability Timeline"

    # ====================================================
    # QUERY
    # ====================================================
    msg = ""
    loc = None
    var = None
    output = None
    timeres = None
    smooth = None
    numdays = None
    mode = None
    autocap = None

    # ================================================
    # Access the form data
    if request.method == "POST":

        loc = request.form["loc"]
        #print("LOC: ", loc)

        var = request.form["var"]
        #print("VAR: ", var)

        output = request.form["output"]
        #print("OUTPUT: ", output)

        timeres = request.form.get("timeres")
        #print("TIMERES: ", timeres)

        smooth = request.form.get("smooth")
        #print("SMOOTH: ", smooth)

        numdays = request.form.get("numdays")
        #print("NUMDAYS: ", numdays)

        mode = request.form.get("MODE")
        #print("MODE: ", mode)

        autocap = request.form.get("autocap")
        #print("AUTOCAP: ", autocap)

    else:
        if loc == None:
            return render_template("stabilitydashboardapi.html")

    # ==========================================
    # Construct the request to gdelt stability api
    stabilityendpoint = "https://api.gdeltproject.org/api/v1/dash_stabilitytimeline/dash_stabilitytimeline"

    params = {}

    params["LOC"] = loc
    msg = msg + "LOC: " + loc + ", "
    params["VAR"] = var
    msg = msg + "VAR: " + var + ", "
    params["OUTPUT"] = output
    msg = msg + "OUTPUT: " + output + ", "
    params["TIMERES"] = timeres
    msg = msg + "TIMERES: " + timeres + ", "
    params["SMOOTH"] = smooth
    msg = msg + "SMOOTH: " + smooth + ", "
    params["NUMDAYS"] = numdays
    msg = msg + "NUMDAYS: " + numdays + ", "
    if mode == "multi":
        params["MODE"] = mode
        msg = msg + "MODE: " + mode + ", "

    if autocap == "2": # Turn the outlier detetor off
        params["AUTOCAP"] = autocap
        msg = msg + "AUTOCAP: " + autocap

    # =================================================
    # Send the request to GDELT and get the response
    response = requests.get(stabilityendpoint, params=params)#, verify=False)
    print(response.url)

    # =================================================
    # Show the result to user
    theurl = response.url

    return render_template("stabilityresponse.html", result=theurl, msg=msg, title=title)

#################################################################
# GDELT Thematic Word Cloud Dashboard API
# ===============================================================
@app.route("/wordclouddashboardapi", methods=["POST", "GET"])
def wordclouddashboardapi():

    title = "The GDELT Thematic Word Cloud Dashboard API"

    # ====================================================
    # QUERY
    # ====================================================
    msg = ""
    loc = None
    var = None
    output = None

    # ================================================
    # Access the form data
    if request.method == "POST":

        loc = request.form["loc"]
        #print("LOC: ", loc)

        var = request.form["var"]
        #print("VAR: ", var)

        output = request.form["output"]
        #print("OUTPUT: ", output)

    else:
        if loc == None:
            return render_template("wordclouddashboardapi.html")

    # ==========================================
    # Construct the request to gdelt word cloud dashboard api
    wordcloudendpoint = "https://api.gdeltproject.org/api/v1/dash_thematicwordcloud/dash_thematicwordcloud"

    params = {}

    params["LOC"] = loc
    msg = msg + "LOC: " + loc + ", "
    params["VAR"] = var
    msg = msg + "VAR: " + var + ", "
    params["OUTPUT"] = output
    msg = msg + "OUTPUT: " + output

    # =================================================
    # Send the request to GDELT and get the response
    response = requests.get(wordcloudendpoint, params=params)#, verify=False)
    print(response.url)

    # =================================================
    # Show the result to user
    theurl = response.url

    return render_template("wordcloudresponse.html", result=theurl, msg=msg, title=title)

######################################################
# /campaign tracker
# ====================================================
@app.route("/campaigntracker")#, methods=["POST", "GET"])
def campaigntracker():

    title = "The GDELT Campaign Tracker Dashboard"

    return render_template("campaigntracker.html", title=title)

####################################################
# GDELT SUMMARY: ONLINE NEWS SUMMARY
# /onlinenewssummary
# ===================================================
@app.route("/onlinenewssummary")
def onlinenewssummary():
    title = " The GDELT online news summary"

    #theurl = "https://api.gdeltproject.org/api/v2/summary/summary"
    gdeltsummaryurl = "https://api.gdeltproject.org/api/v2/summary/summary"

    return render_template("onlinenewssummary.html", result=gdeltsummaryurl, title=title)

##################################################
# GDELT SUMMARY: ONLINE NEWS COMPARER
# /onlinenewscomparer
# ================================================
@app.route("/onlinenewscomparer")
def onlinenewscomparer():
    title = "The GDELT online news comparer"
    onlinenewscomparerurl = "https://api.gdeltproject.org/api/v2/summary/summary?d=web&t=compare"

    return render_template("onlinenewscomparer.html", result=onlinenewscomparerurl, title=title)

################################################
# Television Explorer
# /tvexplorer
# ===============================================
@app.route("/tvexplorer")
def tvexplorer():
    title = "GDELT Television Explorer"
    tvexplorerurl = "https://api.gdeltproject.org/api/v2/summary/summary?d=iatv"

    return render_template("tvexplorer.html", result=tvexplorerurl, title=title)

#######################################################
# GDELT Query interface on doc and geo api
# /gdeltquery
# =====================================================
@app.route("/gdeltquery")
def gdeltquery():
    title = "GDELT Query Interface based on both DOC 2.o and GEO 2.0 API"
    queryurl = "https://zhuoyunao.github.io"

    return render_template("gdeltquery.html", result=queryurl, title=title)

########################################################
# GDELT Live Trends Dashboard
# /livetrendsdashboard
########################################################
@app.route("/livetrendsdashboard")
def livetrendsdashboard():
    title = "GDELT Live Trends Dashboard"
    dashboardurl = "http://live.gdeltproject.org/"

    return render_template("livetrendsdashboard.html", result=dashboardurl, title=title)

####################################################################

@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "POST":
        session.permanent = True  # <--- makes the permanent session
        user = request.form["nm"]
        session["user"] = user
        return redirect(url_for("user"))
    else:
        if "user" in session:
            return redirect(url_for("user"))

        return render_template("login.html")

@app.route("/user")
def user():
    if "user" in session:
        user = session["user"]
        return f"
{user}
"
    else:
        return redirect(url_for("login"))

@app.route("/logout")
def logout():
    session.pop("user", None)
    return redirect(url_for("login"))

if __name__ == "__main__":

    #app.run(debug=True)
    # Externally visible server
    app.run(debug=True, host='0.0.0.0')


# https://realpython.com/python-bitwise-operators/

# write a function which convert a decimal number into a binary number.

def deci_to_binary(number):
	# check if the number is less
	if number < 0:
		isNegative = True
		abs(number)
	else:
		isNegative = False

	result=''
	while number > 0:
		result = str(number%2) + result
		number = number//2
	if isNegative:
		result = '-' + result

	return result
if __name__ == '__main__':
	binary = deci_to_binary(100)
	print(binary)


from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, json
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from app import app, db
from app.forms import URLForm, LoginForm, RegistrationForm
from app.models import User, Product, Price, ProductToUser, Category

@app.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():

    form = URLForm()

    form.name.choices = [(a.id, a.name) for a in Product.query.order_by('name')]

    if form.validate_on_submit():
        return render_template('/product page/<name>', form=form)
    return render_template('index.html', form=form, product=Product)

@app.route('/reset_db')
def reset_db():
    flash("Resetting database: deleting old data and repopulating with dummy data")
    # clear all data from all tables
    meta = db.metadata
    for table in reversed(meta.sorted_tables):
        print('Clear table {}'.format(table))
        db.session.execute(table.delete())
    db.session.commit()

    # adding dummy data--

    c1 = Category(name="Toys")
    c2 = Category(name="Electronics")

    db.session.add(c1)
    db.session.add(c2)
    db.session.commit()

    a1 = Product(name="Nintendo Switch with Neon Blue and Neon Red Joy‑Con",
                 description="Play your way with the Nintendo Switch gaming system. Whether you’re at home or on the "
                             "go, solo or with friends, the Nintendo Switch system is designed to fit your life. Dock "
                             "your Nintendo Switch to enjoy HD gaming on your TV. Heading out? Just undock your console and "
                             "keep playing in handheld mode.",
                 url="https://www.amazon.com/dp/B07VGRJDFY/ref=cm_gf_atz_iaaa_d_p0_c0_qd0coEtwouCW5V9Zr4M2HQ8",
                 favorite=False, category=c1,
                 image="https://images-na.ssl-images-amazon.com/images/I/71Qk2M1CIgL._AC_SL1500_.jpg")
    a2 = Product(name="Echo Dot Kids Edition",
                 description="Designed with kids in mind - They can ask Alexa to play music, hear stories, call "
                             "approved friends and family, and explore a world of kid-friendly skills.",
                 url="https://www.amazon.com/dp/B07Q2MXPH6/ref=cm_gf_atz_iaaa_d_p0_c0_qd0O2FWT6ajLcfkyxyUA27t",
                 favorite=True, category=c2,
                 image="https://images-na.ssl-images-amazon.com/images/I/619hTFl4%2BIL._AC_SL1000_.jpg")
    a3 = Product(name="Really RAD Robots - Turbo Bot",
                 description="Turbo Bot is built for speed! With a full function remote control including a turbo "
                             "Boost switch!",
                 url="https://www.amazon.com/dp/B07NSTW6FT/ref=cm_gf_atz_iaaa_d_p0_c0_qd01g4cV1qjOSc2nnti4MzZ",
                 favorite=False, category=c1,
                 image="https://images-na.ssl-images-amazon.com/images/I/61QEo-fe1JL._AC_SL1418_.jpg")
    a4 = Product(name="Hot Wheels Toy Story 4 Bundle Vehicles, 6 Pack",
                 description="The beloved cast becomes a 5-pack of unique and highly coveted Character Cars.",
                 url="https://www.amazon.com/gp/product/B07L8YMFH8/ref=cg_htl-lcat_3a2_w?pf_rd_m=ATVPDKIKX0DER&pf_rd_"
                     "s=desktop-top-slot-6&pf_rd_r=YDW1WMNXF1Y3FFJY0KH5&pf_rd_t=0&pf_rd_p=b4c22792-984a-4880-8b60-"
                     "44dfcac63ee9&pf_rd_i=gf-events--holiday-toy-list",
                 favorite=True, category=c1,
                 image="https://images-na.ssl-images-amazon.com/images/I/81ytG6lfGTL._AC_SL1500_.jpg")
    a5 = Product(name="Beats Solo3 Wireless On-Ear Headphones - Matte Black",
                 description="With up to 40 hours of battery life, Beats Solo3 wireless is your perfect everyday "
                             "headphone.",
                 url="https://www.amazon.com/dp/B01LWWY3E2/ref=cm_gf_aaam_iaaa_d_p0_c0_qd0PoZ3uEKKhZA1d0qZjrgk",
                 favorite=False, category=c2,
                 image="https://images-na.ssl-images-amazon.com/images/I/71sBjbHYbKL._AC_SL1500_.jpg")

    db.session.add(a1)
    db.session.add(a2)
    db.session.add(a3)
    db.session.add(a4)
    db.session.add(a5)

    v1 = Price(price=299.00, datetime=datetime(2019, 10, 14), productID=1)
    v2 = Price(price=289.00, datetime=datetime(2019, 10, 16), productID=1)
    v3 = Price(price=249.00, datetime=datetime(2019, 10, 18), productID=1)
    v4 = Price(price=299.00, datetime=datetime(2019, 10, 20), productID=1)
    v5 = Price(price=309.00, datetime=datetime(2019, 10, 22), productID=1)
    v6 = Price(price=34.99, datetime=datetime(2019, 10, 14), productID=2)
    v7 = Price(price=39.99, datetime=datetime(2019, 10, 16), productID=2)
    v8 = Price(price=44.99, datetime=datetime(2019, 10, 18), productID=2)
    v9 = Price(price=34.99, datetime=datetime(2019, 10, 20), productID=2)
    v10 = Price(price=39.99, datetime=datetime(2019, 10, 22), productID=2)
    v11 = Price(price=39.99, datetime=datetime(2019, 10, 14), productID=3)
    v12 = Price(price=37.99, datetime=datetime(2019, 10, 16), productID=3)
    v13 = Price(price=41.99, datetime=datetime(2019, 10, 18), productID=3)
    v14 = Price(price=38.99, datetime=datetime(2019, 10, 20), productID=3)
    v15 = Price(price=43.99, datetime=datetime(2019, 10, 22), productID=3)
    v16 = Price(price=24.99, datetime=datetime(2019, 10, 14), productID=4)
    v17 = Price(price=26.99, datetime=datetime(2019, 10, 16), productID=4)
    v18 = Price(price=28.99, datetime=datetime(2019, 10, 18), productID=4)
    v19 = Price(price=23.99, datetime=datetime(2019, 10, 20), productID=4)
    v20 = Price(price=24.99, datetime=datetime(2019, 10, 22), productID=4)
    v21 = Price(price=249.00, datetime=datetime(2019, 10, 14), productID=5)
    v22 = Price(price=199.00, datetime=datetime(2019, 10, 16), productID=5)
    v23 = Price(price=179.00, datetime=datetime(2019, 10, 18), productID=5)
    v24 = Price(price=239.00, datetime=datetime(2019, 10, 20), productID=5)
    v25 = Price(price=219.00, datetime=datetime(2019, 10, 22), productID=5)

    db.session.add(v1)
    db.session.add(v2)
    db.session.add(v3)
    db.session.add(v4)
    db.session.add(v5)
    db.session.add(v6)
    db.session.add(v7)
    db.session.add(v8)
    db.session.add(v9)
    db.session.add(v10)
    db.session.add(v11)
    db.session.add(v12)
    db.session.add(v13)
    db.session.add(v14)
    db.session.add(v15)
    db.session.add(v16)
    db.session.add(v17)
    db.session.add(v18)
    db.session.add(v19)
    db.session.add(v20)
    db.session.add(v21)
    db.session.add(v22)
    db.session.add(v23)
    db.session.add(v24)
    db.session.add(v25)

    pu1 = ProductToUser(userID=1, productID=1)
    pu2 = ProductToUser(userID=1, productID=2)
    pu3 = ProductToUser(userID=1, productID=4)
    pu4 = ProductToUser(userID=2, productID=1)
    pu5 = ProductToUser(userID=2, productID=3)
    pu6 = ProductToUser(userID=2, productID=4)
    pu7 = ProductToUser(userID=2, productID=5)

    db.session.add(pu1)
    db.session.add(pu2)
    db.session.add(pu3)
    db.session.add(pu4)
    db.session.add(pu5)
    db.session.add(pu6)
    db.session.add(pu7)

    u1 = User(username="john", email="john@john.com")
    u2 = User(username="evan", email="evan@gmail.com")

    db.session.add(u1)
    db.session.add(u2)

    db.session.commit()

    u1.set_password("firewater")
    u2.set_password("earthair")

    db.session.commit()

    return redirect(url_for('index'))

@app.route('/main')
def main():
    return render_template('main.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

@app.route('/recently-searched', methods=['GET', 'POST'])
def recently():
    products = Product.query.all()

    return render_template('recently-searched.html', searched_products=products)

@app.route('/product-page/<name>', methods=['GET', 'POST'])
def product(name):

    new_product = Product.query.filter_by(name=name).first()

    new_prices = Price.query.filter_by(productID=new_product.id).all()

    new_category = Category.query.filter_by(id=new_product.categoryID).first()

    related_products = Product.query.filter_by(categoryID=new_category.id).all()

    # x = []
    # y = []
    # for price in new_prices:
    #     x.append(price.datetime)
    #     y.append(price.price)
    # plt.plot(x, y)
    # plt.xlabel('Date')
    # plt.ylabel('Price')
    # graph = plt.show()

    return render_template('product-page.html', product=new_product, prices=new_prices, category=new_category,
                           related_products=related_products)

@app.route('/saved-products', methods=['GET', 'POST'])
def saved_products():
    return render_template('saved-products.html')


import sys
sys.stdin=open('input.txt')

n = int(input())
tri = [list(map(int, input().split())) for _ in range(n)]

for i in range(1, n):
    for j in range(len(tri[i])):
        if j == 0:
            tri[i][j] += tri[i-1][j]
        elif j == i:
            tri[i][j] += tri[i-1][j-1]
        else:
            maxv = max(tri[i-1][j-1], tri[i-1][j])
            tri[i][j] += maxv

print(max(tri[n-1]))


import csv
import pandas as pd
import numpy as np
def main():
    data = pd.read_csv("/Users/vishaalbommena/Desktop/year_prediction.csv", sep=',', quotechar='"', header=0)
    data = data[['label', 'TimbreAvg1', 'TimbreAvg2', 'TimbreAvg3', 'TimbreAvg4', 'TimbreAvg5', 'TimbreCovariance1', 'TimbreCovariance2', 'TimbreCovariance3', 'TimbreCovariance4', 'TimbreCovariance5']]
    X = data.as_matrix()
    X = X[:int(0.01*len(X))]
    pred = X[int(0.01*len(X)):int(0.2*len(X))]
    '''
    train = X[:int(0.6*len(X))]
    validation = X[int(0.6*len(X)) + 1: int(0.6*len(X)) + int(0.2*len(X))]
    test = X[int(0.6*len(X)) + int(0.2*len(X)) + 1: int(0.6*len(X)) + int(0.2*len(X)) + int(0.2*len(X))]
    '''
    return X, pred


import sys
import random
import numpy as np
import os
import subprocess
import uuid
import shutil
import time
import pickle
from ws2vtk import main as ws2vtk
from llres_maybe import scale_params
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

## Dennis Conway

#
# with open('wae.pickle') as f:
#     b = pickle.load(f)

blob = [1, 0, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
# background, intensity, strength, attenuation, xpos, ypos, xrad, yrad, theta, zpos, zrad, xrot, yrot
def pad_model(b, no_blobs):
    no_blobs = len(b[1:])/9
    b = list(b)
    # b[6] = 0
    inserts = []
    for i in range(no_blobs):
        for j in [7, 10, 11]:
            inserts.append(i*9+1+j)
    for i in inserts[::-1]:
        b.insert(i, 0)
    return b

def get_model(b, no_blobs):
    b = pad_model(b, no_blobs)
    c=' '.join(map(str,b))
    print(c)

    model_template = './template'
    target_model = './targ'

    callString='./saveModel '+ model_template + ' ' + c + ' > ' + target_model
    os.system(callString)
    time.sleep(2)
    # mtNS, N, E, D = ws2vtk(target_model, './oneblob.resp')

    # return mtNS, N, E, D

def test_yr_blobs(fwd, blobs):
    rms = [runw3(fwd, scale_params(blobs[0]), 1, off_diag=False)]
    for idx, b in enumerate(blobs[1:]):
        if (blobs[idx] != b).any():
            rms.append(runw3(fwd, scale_params(b), 1, off_diag=False))
        else:
            rms.append(rms[-1])
    return rms

def runw3(inv, b, no_blobs, off_diag=True):
    get_model(b, no_blobs)
    p1 = subprocess.Popen(['./wsinv3dmt'])
    p1.wait()
    #rmses = [runw3(hey, pad_model(scale_params(i[0]), 1), 1) for i in traj[:200]]
    time.sleep(12)
    # return
    #storing response and model files with unique identifier
    response='./fwd_resp.02.new'
    inv.w3 = inv.pop_data(response)
    rms = np.sqrt(np.average((inv.w3 - inv.data)**2/inv.data_errors**2))
    return rms


import asyncio
import os

import discord

from kilroy.user.discord import DiscordUser
from .. import Connection, Message, Channel

class DiscordChannel(Channel):

    def __init__(self, discord_channel):
        self.__channel = discord_channel

    @staticmethod
    def from_kwargs(connection, **kwargs):
        '''
            kwargs:
                channel_id - indicates a private channel or server channel
                user_id - indicates a DM
        '''
        server = None
        if "server_id" in kwargs:
            server = connection.get_server(str(kwargs["server_id"]))
        if "channel_id" in kwargs:
            if server is not None:
                t = server
            else:
                t = connection
            channel = t.get_channel(str(kwargs["channel_id"]))
        elif "user_id" in kwargs:
            channel = connection.get_user_info(kwargs["user_id"])
        else:
            raise ValueError()

        return DiscordChannel(channel)

    def get_id(self):
        return self.__channel.id

    async def get_users(self):
        if self.__channel.is_private:
            users = self.__channel.recipients
        else:
            users = self.__channel.server.members
        retval = []
        for user in users:
            retval += [DiscordUser(user)]
        return retval

    async def send_text(self, connection, text):
        await connection.send_message(self.__channel, text)

class DiscordMessage(Message):
    def __init__(self, message):
        self.__discord_message = message

    def __str__(self):
        return self.__discord_message.content

    def get_channel(self):
        return DiscordChannel(self.__discord_message.channel)

    def get_author(self):
        return DiscordUser(self.__discord_message.author)

class DiscordConnection(discord.Client, Connection):
    MESSAGE_CLASS = DiscordMessage
    CHANNEL_CLASS = DiscordChannel
    CONFIG_ENTRY_NAME = "discord"
    CLIENT_NAME = "discord"

    KEY_FILE_LOCATION = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        ".keys.yaml"
        )

    CONFIG_ENTRY_DATA = {
        CONFIG_ENTRY_NAME : {
            "client_oauth_token" : "YOUR_OAUTH_TOKEN"
        }
    }

    def __init__(self, **kwargs):
        self.__key = kwargs['client_oauth_token']
        discord.Client.__init__(self)
        Connection.__init__(self)

    async def send_message_text(self, message_text):
        await asyncio.sleep(.1)

    async def start_connection(self):
        await self.start(self.__key)

    async def end_connection(self):
        await self._set_connection_state(False)
        await self.close()
        await asyncio.sleep(.5)

    async def on_ready(self):
        await self._set_connection_state(True)

    async def on_message(self, message):
        my_message = DiscordMessage(message)
        await self._message_handler(my_message)

    def get_user_info(self):
        info = self.user
        if info is not None:
            return DiscordUser(info)
        return None


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

root=tk.Tk()
root.title("PYPT graphs")
root.geometry("400x1000")

def enable_dark_mode():
 choice=var2.get()
 if choice==1:
  plt.style.use('dark_background')
 elif choice==0:
  plt.style.use('default')

def another_graph():
 global label6,label7,label8,label9,entry6,entry7,entry8,entry9
 choice=var.get()
 if choice==1:

  label6=tk.Label(root, text="Enter y-values", font=("Times New Roman",10))
  label6.pack(pady=10)

  entry6=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
  entry6.pack(pady=10)

  label7=tk.Label(root, text="Enter error bar for y values", font=("Times New Roman",10))
  label7.pack(pady=10)

  entry7=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
  entry7.pack(pady=10)

  label8=tk.Label(root, text="enter title for line 1", font=("Times New Roman",10))
  label8.pack(pady=10)

  entry8=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
  entry8.pack(pady=10)

  label9=tk.Label(root, text="enter title for line 2", font=("Times New Roman",10))
  label9.pack(pady=10)

  entry9=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
  entry9.pack(pady=10)

  button2=tk.Button(root, text="create graph with now two lines", command=graph2)
  button2.pack()

def graph2():
 x=[]
 y=[]
 y2=[]
 a = entry1.get().split(",")
 for i in range(len(a)):
  x.append(float(a[i]))

 b = entry2.get().split(",")
 for i in range(len(b)):
   y.append(float(b[i]))
 y_err = float(entry3.get())

 c = entry6.get().split(",")
 for i in range(len(c)):
   y2.append(float(c[i]))

 y2_err = float(entry7.get())
 fig, ax = plt.subplots()

 ax.errorbar(x, y, yerr=y_err,label=entry8.get() ,color="red", fmt='o-', markersize=4, capsize=5, capthick=1)
 ax.errorbar(x, y2, yerr=y2_err, label=entry9.get(),color="blue", fmt='o-', markersize=4, capsize=5, capthick=1)
 ax.set_xlabel(entry4.get())
 ax.set_ylabel(entry5.get())

 ax.legend()
 plt.show()

def graph():
 x=[]
 y=[]
 x_vals = entry1.get().split(",")
 for i in range(len(x_vals)):
  x.append(float(x_vals[i]))

 y_vals = entry2.get().split(",")
 for i in range(len(y_vals)):
   y.append(float(y_vals[i]))
 y_err = float(entry3.get())

 fig, ax = plt.subplots()

 ax.errorbar(x, y, yerr=y_err ,color="red", fmt='o-', markersize=4, capsize=5, capthick=1)
 ax.set_xlabel(entry4.get())
 ax.set_ylabel(entry5.get())

 ax.legend()
 plt.show()

label1=tk.Label(root, text="Enter x-values seperated by a comma", font=("Times New Roman",10))
label1.pack(pady=10)

entry1=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
entry1.pack(pady=10)

label2=tk.Label(root, text="Enter y-values seperated by a comma", font=("Times New Roman",10))
label2.pack(pady=10)

entry2=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
entry2.pack(pady=10)

label3=tk.Label(root, text="Enter error bars for y", font=("Times New Roman",10))
label3.pack(pady=10)

entry3=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
entry3.pack(pady=10)

label4=tk.Label(root, text="Enter title for x values", font=("Times New Roman",10))
label4.pack(pady=10)

entry4=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
entry4.pack(pady=10)

label5=tk.Label(root, text="Enter title for y values", font=("Times New Roman",10))
label5.pack(pady=10)

entry5=tk.Entry(root,width=48, borderwidth=4, font=("Times New Roman", 10))
entry5.pack(pady=10)

button=tk.Button(root, text="create graph with one line", command=graph)
button.pack()
var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="Enter another graph", variable=var, onvalue=1, offvalue=0,command=another_graph)
checkbutton.pack()
var2 = tk.IntVar()
checkbutton2 = tk.Checkbutton(root,text="Dark Mode", variable=var2, onvalue=1, offvalue=0,command=enable_dark_mode)
checkbutton2.pack()
root.mainloop()