from __future__ import unicode_literals

import re
import os
import cchardet
import copy
from cherrypy.lib import httputil
import six
from six.moves import urllib

import lxml.html
from lxml import etree
from lxml.builder import ElementMaker

import libgutenberg.GutenbergGlobals as gg
from libgutenberg.GutenbergGlobals import NS, xpath
from libgutenberg.MediaTypes import mediatypes as mt
from libgutenberg.Logger import info, debug, warning, error

from ebookmaker.CommonCode import Options

options = Options()

BROKEN = 'resource://ebookmaker.parsers/broken.png'

RE_GUTENBERG = re.compile(r'Project Gutenberg', re.I)
RE_AUTHOR = re.compile(r"^Author:\s+(.+)$", re.I | re.M)
RE_TITLE = re.compile(r"^Title:\s+(.+)$", re.I | re.M)
RE_LANGUAGE = re.compile(r"^Language:\s+(.+)$", re.I | re.M)
# Release Date: September 5, 2009 [EBook #29915]
RE_RELEASEDATE = re.compile(r"^(Release|Posting)\s+Date:\s+(.+)\[", re.I | re.M)
RE_EBOOKNO = re.compile(r'\[E(?:Book|Text) #(\d+)\]', re.I | re.M)

REB_XML_CHARSET = re.compile(br'^<\?xml.*encoding\s*=\s*["\']([^"\'\s]+)', re.I)
RE_HTML_CHARSET = re.compile(r';\s*charset\s*=\s*([^"\'\s]+)', re.I)
REB_HTML_CHARSET = re.compile(br';\s*charset\s*=\s*([^"\'\s]+)', re.I)
REB_PG_CHARSET = re.compile(br"^Character Set Encoding:\s+([-\w\d]+)\s*$", re.I | re.M)

# XML 1.1 RestrictedChars
# [#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]
RE_RESTRICTED = re.compile('[\x01-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f]')

XML_NAMESTARTCHAR = 'A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff' \
                    '\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f' \
                    '\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd'
                    # u'\U00010000-\U000effff'
XML_NAMECHAR = XML_NAMESTARTCHAR + '.0-9\u00b7\u0300-\u036f\u203f-\u2040-'

RE_XML_NAME = re.compile('^[%s][%s]*$' % (XML_NAMESTARTCHAR, XML_NAMECHAR))

URI_MARK_CHARS = "-_.!~*'()"
URI_RESERVED_CHARS = ';/?:@&=+$,'

RE_URI_FRAGMENT = re.compile('[' + URI_MARK_CHARS + URI_RESERVED_CHARS + '%A-Za-z0-9]+')
RE_NO_WS = re.compile(r'^\S.*')

# all bogus encoding names used in PG go in here
BOGUS_CHARSET_NAMES = {'iso-latin-1': 'iso-8859-1',
                       'big5': 'big5hkscs',
                       'big-5': 'big5hkscs',

                       # python has bogus codec name
                       'macintosh': 'mac_roman',
                       }
COREATTRS = ["class", "dir", "id", "lang", "style", "title"]

STYLE_LINK = '<link href="pgepub.css" rel="stylesheet"/>'
IMAGE_WRAPPER = """<?xml version="1.0"?>{doctype}

    <title>{title}</title>
    {style}

      {backlink}

"""

# exported
em = ElementMaker(makeelement=lxml.html.xhtml_parser.makeelement,
                  namespace=str(NS.xhtml),
                  nsmap={None: str(NS.xhtml)})

def webify_url(url):
    """ make the url for a parser, accounting for platform """
    if re.search(r'^https?://', url):
        return url
    if url.startswith('file:'):
        return url
    if url.startswith('resource:'):
        return url
    if re.search(r'^[a-zA-z]:', url):
        return 'file:///' + url.replace(os.path.sep, '/')
    url = os.path.abspath(url).replace(os.path.sep, '/')
    if url.startswith('/'):
        url = url[1:]
    return 'file:///' + url

class ParserAttributes(object): # pylint: disable=too-few-public-methods
    """ Object to hold attributes for the lifetime of a parser.

    Typical attributes held here would be:
      - url
      - orig_url
      - mediatpye
      - orig_mediatpye
      - referrer
      - id

    mediatype and orig_mediatype are of type HeaderElement

    mediatype is not necessarily the same as orig_mediatype,
    because parsers may convert between input and output, eg.
    reST to xhtml.

    """

    HeaderElement = httputil.HeaderElement

    def __init__(self):
        self.url = None
        self.orig_url = None
        self.mediatype = None
        self.orig_mediatype = None
        self.id = None
        self.rel = set()
        self.referrer = None
        self.title = None

    def update(self, more_attribs):
        for k, v in vars(more_attribs).items():
            if v:
                setattr(self, k, v)

    def get(self, name, default=None):
        return getattr(self, name, default)

    def __str__(self):
        a = []
        for k, v in vars(self).items():
            a.append('%s=%s' % (k, v))
        return '\n'.join(a)

class ParserBase(object):
    """ Base class for more specialized parsers. """

    def __init__(self, attribs=None):
        self.attribs = attribs or ParserAttributes()
        self.attribs.mediatype = self.attribs.orig_mediatype
        self.fp = None
        self.buffer = None
        self.unicode_buffer = None

    def reset(self):
        """ Make the parser safe for re-use.

        This method is called before parser is reused.

        """
        pass

    def pre_parse(self):
        """ Do a lightweight parse, that allows iterlinks () to succeed.

        Spider.py needs to use iterlinks () to grab dependencies, but
        does not need a full parse. If a lightweight parse doesn't
        make sense, you may also do a full parse here and save the
        result.

        """
        pass

    def parse(self):
        """ Do a full parse.

        When this gets called, a pre_parse has already been done,
        so you might safely reuse any cached results.

        """

        pass

    def get_charset_from_content_type(self):
        """ Get charset from server content-type. """

        charset = self.attribs.orig_mediatype.params.get('charset')
        if charset:
            debug('Got charset %s from server' % charset)
            return charset
        return None

    def get_charset_from_meta(self): # pylint: disable=R0201
        """ Parse header metadata for charset.

        Header metadata can be either of:

          - html metadata
          - rst enconding comment
          - pg header charset line

        Override this as required.

        """

        return None

    def guess_charset_from_body(self):
        """ Guess charset from text. """

        result = cchardet.detect(self.bytes_content())
        charset = result.get('encoding')
        if charset:
            debug('Got charset %s from text sniffing' % charset)
            return charset
        return None

    def bytes_content(self):
        """ Get document content as raw bytes. """

        if self.buffer is None:
            if self.fp is None:
                return b''
            try:
                debug("Fetching %s ..." % self.attribs.url)
                self.buffer = self.fp.read()
                self.fp.close()
            except IOError as what:
                error(what)

        return self.buffer

    def unicode_content(self):
        """ Get document content as unicode string. """

        if self.unicode_buffer is None:
            data = (self.decode(self.get_charset_from_content_type()) or
                    self.decode(self.get_charset_from_meta()) or
                    self.decode(self.guess_charset_from_body()) or
                    self.decode('utf-8') or
                    self.decode('windows-1252'))

            if not data:
                if data == '':
                    info('Continuing parse despite missing file')
                    self.unicode_buffer = ''
                else:
                    raise UnicodeError("Text in Klingon encoding ... giving up.")

            # normalize line-endings
            if '\r' in data or '\u2028' in data:
                data = '\n'.join(data.splitlines())
            self.unicode_buffer = data

        return self.unicode_buffer

    def decode(self, charset):
        """ Try to decode document contents to unicode. """
        if charset is None:
            return None

        charset = charset.lower().strip()

        if charset in BOGUS_CHARSET_NAMES:
            charset = BOGUS_CHARSET_NAMES[charset]

        if charset == 'utf-8':
            charset = 'utf_8_sig'

        try:
            debug("Trying to decode document with charset %s ..." % charset)
            buffer = self.bytes_content()
            buffer = REB_PG_CHARSET.sub(b'', buffer)
            buffer = buffer.decode(charset)
            self.attribs.orig_mediatype.params['charset'] = charset
            return buffer
        except LookupError as what:
            # unknown charset,
            error("Invalid charset name: %s (%s)" % (charset, what))
        except UnicodeError as what:
            # mis-stated charset, did not decode
            error("Text not in charset %s (%s)" % (charset, what))
        return None

    def mediatype(self):
        """ Return parser output mediatype. Helper function. """
        if self.attribs.mediatype:
            return self.attribs.mediatype.value
        return None

    # Links are found in HTMLParserBase and CSSParser. These methods
    # are overwritten there.

    def iterlinks(self): # pylint: disable=R0201
        """ Return all links in document.

        returns a list of url, dict
        dict may contain any of: tag, id, rel, type.

        """

        return []

    def rewrite_links(self, dummy_f): # pylint: disable=R0201
        """ Rewrite all links using the function f. """
        return

    def remap_links(self, dummy_url_map): # pylint: disable=R0201
        """ Rewrite all links using the dictionary url_map. """
        return

class TxtParser(ParserBase):
    """ Base class for text files we don't want to convert.
    """

    def __init__(self, attribs=None):
        ParserBase.__init__(self, attribs)
        self.attribs.mediatype = ParserAttributes.HeaderElement(mt.txt)

    def serialize(self):
        return bytes(self.unicode_content(), 'utf8')

class HTMLParserBase(ParserBase):
    """ Base class for more HTMLish parsers.

    (HTMLParser, GutenbergTextParser)

    """

    def __init__(self, attribs=None):
        ParserBase.__init__(self, attribs)
        self.attribs.mediatype = ParserAttributes.HeaderElement(mt.xhtml)
        self.xhtml = None
        self._xhtml = None

    def reset(self):
        if self._xhtml is not None:
            self.xhtml = self._xhtml
            self._xhtml = None

    @staticmethod
    def add_class(elem, class_):
        """ Add a class to html element. """
        classes = elem.get('class', '').split()
        classes.append(class_)
        elem.set('class', ' '.join(classes))

    def get_charset_from_meta(self):
        """ Parse text for hints about charset. """

        charset = None
        html = self.bytes_content()

        match = REB_XML_CHARSET.search(html)
        if match:
            charset = match.group(1).decode('ascii')
            debug('Got charset %s from xml declaration' % charset)
        else:
            match = REB_HTML_CHARSET.search(html)
            if match:
                charset = match.group(1).decode('ascii')
                debug('Got charset %s from html meta' % charset)

        return charset

    def iterlinks(self):
        """ Return all links in document. """

        # To keep an image even in non-image build specify
        # class="x-ebookmaker-important"

        keeps = xpath(self.xhtml, "//img[contains (@class, 'x-ebookmaker-important')]")
        for keep in keeps:
            keep.set('rel', 'important')

        # iterate links

        for (elem, dummy_attribute, url, dummy_pos) in self.xhtml.iterlinks():
            yield url, elem

    def rewrite_links(self, f):
        """ Rewrite all links using the function f. """
        self.xhtml.rewrite_links(f)

    def remap_links(self, url_map):
        """ Rewrite all links using the dictionary url_map. """
        def f(url):
            """ Remap function """
            ur, frag = urllib.parse.urldefrag(url)
            if ur in url_map:
                debug("Rewriting redirected url: %s to %s" % (ur, url_map[ur]))
                ur = url_map[ur]
            return "%s#%s" % (ur, frag) if frag else ur

        self.rewrite_links(f)

    @staticmethod
    def strip_links(xhtml, manifest):
        """ Strip all links to urls not in manifest.

        This includes  <link href> and  and, if strip_links is set, .
        Assume links and urls are already made absolute.

        """

        if options.strip_links:
            for link in xpath(xhtml, '//xhtml:a[@href]'):
                href = urllib.parse.urldefrag(link.get('href'))[0]
                if href not in manifest:
                    debug("strip_links: Deleting  to %s not in manifest." % href)
                    del link.attrib['href']

        for link in xpath(xhtml, '//xhtml:link[@href]'):
            href = link.get('href')
            if href not in manifest:
                debug("strip_links: Deleting <link> to %s not in manifest." % href)
                link.drop_tree()

        for image in xpath(xhtml, '//xhtml:img[@src]'):
            src = image.get('src')
            if src not in manifest:
                debug("strip_links: Replacing  with src %s not in manifest." % src)
                image.tag = NS.xhtml.span
                image.text = image.get('alt', '')
                for attr  in image.attrib:
                    if attr not in COREATTRS:
                        del image.attrib[attr]

    def make_toc(self, xhtml):
        """ Build a TOC from HTML headers.

        Return a list of tuples (url, text, depth).

        Page numbers are also inserted because DTBook NCX needs the
        play_order to be sequential.

        """

        def id_generator(i=0):
            """ Generate an id for the TOC to link to. """
            while True:
                yield 'pgepubid%05d' % i
                i += 1

        def get_header_text(header):
            """ clean header text
                also, replace breaks with whitespace. tidy used to put whitespace around

                elements. PPs relied on this behavior, so we're stuck. """
            for br in xpath(header, '//xhtml:br'):
                if RE_NO_WS.match(str(br.tail)):
                    br.tail = '\n' + str(br.tail) if br.tail else '\n'

            text = gg.normalize(etree.tostring(header,
                                               method="text",
                                               encoding=six.text_type,
                                               with_tail=False))

            return header.get('title', text).strip()

        idg = id_generator()

        def get_id(elem):
            """ Get the id of the element or generate and set one. """
            if not elem.get('id'):
                elem.set('id', six.next(idg))
            return elem.get('id')

        toc = []

        for header in xpath(
                xhtml,
                '//xhtml:h1|//xhtml:h2|//xhtml:h3|//xhtml:h4|'
                # DP page number
                '//xhtml:*[contains (@class, "pageno")]|'
                # DocUtils contents header
                '//xhtml:p[contains (@class, "topic-title")]'
            ):

            previous = header.getprevious()
            if previous is not None and previous.tag == header.tag:
                # consecutive headers get combined
                continue

            text = get_header_text(header)

            if not text:
                # so
 may be used to suppress TOC entry
                continue

            if header.get('class', '').find('pageno') > -1:
                toc.append(["%s#%s" % (self.attribs.url, get_id(header)), text, -1])
            else:
                # header
                if ((text.lower().startswith('by ')
                     or text.lower() == ('by'))
                        and 'x-ebookmaker-important' not in header.get('class', '')):
                    # common error in PG:
by Lewis Carroll
 should
                    # yield no TOC entry
                    warning(f'dropping by-heading in {self.attribs.url}: {text.lower()}')
                    warning('use x-ebookmaker-important class if this heading should be in TOC')
                    continue

                try:
                    depth = int(header.tag[-1:])
                except ValueError:
                    depth = 2 # avoid top level

                #join consecutive headers
                next = header.getnext()
                while next is not None and next.tag == header.tag:
                    text = (text + ' ' + get_header_text(next)).strip()
                    next = next.getnext()

                # if <h*> is first element of a
 use
 instead
                parent = header.getparent()
                if (parent.tag == NS.xhtml.div and
                        parent[0] == header and
                        parent.text and
                        parent.text.strip() == ''):
                    header = parent

                toc.append(["%s#%s" % (self.attribs.url, get_id(header)), text, depth])

        return toc

    def serialize(self):
        """ Serialize to string. """
        if self.attribs.url.endswith('.xhtml'):
            # epub3
            doctype = ""
        else:
            # epub2
            doctype=gg.XHTML_DOCTYPE
        return etree.tostring(self.xhtml,
                              doctype=doctype,
                              xml_declaration=True,
                              encoding='utf-8',
                              pretty_print=True)


import cv2
import numpy as np
import config

# Get color ranges and noise removal kernels from config
ball_color_range = config.get("colors", config.get("vision", "ball_color"))
ball_noise_kernel = config.get("vision", "ball_noise_kernel")
# basket_color_range = config.get("colors", config.get("vision", "basket_color"))
edge_color_range = config.get("colors", config.get("vision", "bounds"))

def apply_ball_color_filter(hsv, basket=False, bounds = False, korv=None, piir=None):
    #print(ball_color_range)
    #print(hsv)
    height = 0
    w, h, x2, y2 = 0,0,0,0

    basket_color_range = config.get("colors", config.get("vision", "basket_color"))

    """
        args:
            hsv image
        returns:
            1) masked image of the ball
            2) masked image of the basket
            3) [x, y] for the coordinates of the ball
            4) [x, y] for the coordinates of the basket
    """
    # hsv = cv2.blur(hsv, (2,2))
    #print(ball_color_range)
    if basket:
        masked_img = cv2.inRange(hsv, basket_color_range["min"], basket_color_range["max"])
        #cv2.imshow("hsv", hsv)
        #print(basket_color_range["min"], basket_color_range["max"])
    elif bounds:
        masked_img = cv2.inRange(hsv, edge_color_range["min"], edge_color_range["max"])
        pass
    else:
        masked_img = cv2.inRange(hsv, ball_color_range["min"], ball_color_range["max"])
        #print(ball_color_range["min"], ball_color_range["max"])
    kernel = np.ones((5, 5), np.uint8)
    masked_img2 = cv2.morphologyEx(masked_img, cv2.MORPH_OPEN, kernel)
    erosion = cv2.erode(masked_img2, kernel, iterations=1)
    dilation = cv2.dilate(erosion, kernel, iterations=1)
    cont, hie = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # Get blob contour coordinates
    try:
        cnt = max(cont, key=cv2.contourArea)
        x2, y2, w, h = cv2.boundingRect(cnt)
        # Draw bounding rect to pic
        height = y2+h
        cv2.rectangle(hsv, (x2, y2), (x2 + w, y2 + h), (0, 255, 0), 2)
    except:
        #print("unable to draw contours")
        pass

    contour_img = cv2.drawContours(masked_img2, cont, -1, (255, 0, 255))
    # print("cont", cont)
    try:
        max_cont = max(cont, key=cv2.contourArea)
        (x, y), r = cv2.minEnclosingCircle(max_cont)
        x = int(x)
        y = int(y)
        r = int(r)
        # print("vision color filter: ", (x, y), r)
        print(korv)
        if korv is not None and korv > 190:
            print("liiga lähedal")
            x = None;
            y = None;
            r = None
            w = None
            h = None
            x2 = None
            y2 = None
        count = 0
        if piir is not None:
            try:
                for i in range(len(piir)-y):
                    alla = piir[y+i][x]
                    if alla > 0:
                        count += 1
                    elif alla == 0:
                        count = 0
                    if count == 7:
                        #print("pall on väljaspool")
                        x = None;
                        y = None;
                        r = None
                        w = None
                        h = None
                        x2 = None
                        y2 = None
                        count = 0
                        return x, y, r, contour_img
            except:
                pass

        if r < 3 and not basket:
            raise NotImplementedError
        if r < 10 and basket:
            raise NotImplementedError
    except Exception as e:
        # print("Nothing found, returning 0, 0, 0")
        x = None;
        y = None;
        r = None
        w = None
        h = None
        x2 = None
        y2 = None

    # Only return the blob of the largest objects of the same color
    #print(x,y)
    return x, y, r, contour_img, w, h, height, x2, y2


import numpy as np
import pandas as pd
import sys, os, pickle, keras, warnings

np.random.seed(43)
warnings.filterwarnings('ignore')

from scipy import stats
from time import time

import tensorflow as tf
from keras.models import Model
from keras.layers import Input, Dense,Dropout
from keras import optimizers, regularizers, backend as K

from sklearn.preprocessing import StandardScaler
from matplotlib import pyplot as plt
import seaborn as sn
# %matplotlib inline

from preprocessing import get_data
import Utils

# train ,test ,indx = get_data("multiclass")
train ,test = get_data("Binary")

train_label = train.label
train = train.drop(["label"],axis=1)

Scaler = StandardScaler()
train = Scaler.fit_transform(train.values)[np.where(train_label == 1)]

xtest , ytest = Scaler.transform(test.drop(["label"],axis=1)), test.label.values

def fit_model(params,X,latent=10,BS=250,ep = 100):
    input_dim = train.shape[1]
    latent_space_size = latent
    K.clear_session()
    input_ = Input(shape = (input_dim, ))

    layer_1 = Dense(100, activation=params[0])(input_)
    layer_2 = Dense(50, activation=params[0],kernel_regularizer=regularizers.l2(0.01))(layer_1)
    layer_3 = Dense(25, activation=params[0])(layer_2)

    encoding = Dense(latent_space_size,activation=None)(layer_3)

    layer_6 = Dense(25, activation=params[0])(encoding)
    layer_7 = Dense(50, activation=params[0],kernel_regularizer=regularizers.l2(0.01))(layer_6)
    layer_8 = Dense(100, activation=params[0])(layer_7)

    decoded = Dense(input_dim,activation=None)(layer_8)

    autoencoder = Model(inputs=input_ , outputs=decoded)
    opt = optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
    autoencoder.compile(metrics=['accuracy'],loss='mean_squared_error',optimizer=opt)

    print("Training Started ....")
    autoencoder.fit(X, X,epochs=ep,validation_split=0.2,batch_size=BS,shuffle=True,verbose=0)
    print("Training Finished ....")

    return autoencoder

if os.path.exists('models/nslkdd_reg_ep100_bs250_final.pickle'):
    with open('models/model_tanh_Adam_reg_ep95_bs250.pickle', 'rb') as fid:
        model = pickle.load(fid)

else:
    model = fit_model(["tanh","Adam"],X=train,latent=12,BS=250,ep=95)
    with open('models/nslkdd_reg_ep100_bs250_final.pickle', 'wb') as f:
                pickle.dump(model, f)

losses = Utils.get_losses(model, train)

thresholds = Utils.confidence_intervals(losses,0.95)
#choose the upper interval as threshold
threshold = thresholds[1]
pred = Utils.predictAnomaly(model,xtest,threshold)
Utils.performance(ytest,pred)


import numpy as np
import pandas as pd
import scipy.interpolate
from tqdm import tqdm

def gaussian_peak(x, amplitude, loc, scale):
    return amplitude * np.exp((-(x - loc)**2) / (2 * scale**2))

def asymmetrical_gaussian_peak(x, amplitude, loc, s0, s1, s2=0.0, eps=1e-7):
    # assymetrical_gaussian_peak(..., s1=0) is the same as gaussian_peak(...)
    # add additional asymmetries by adding to the denominator inside np.exp:
    #   s0 + s1*(x-loc) + s2*(x-loc)**2 ..., sN*(x-loc)**N

    peak = np.exp(-1/2*((x - loc)/(eps + s0 + s1*(x - loc) + s2*(x - loc)**2))**2)
    peak *= amplitude

    if s1 > 0:
        out = loc - 4 * s0
        idx = np.argmin(np.abs(x - out))
        peak[:idx] = 0.0
    else:
        out = loc + 4 * s0
        idx = np.argmin(np.abs(x - out))
        peak[idx:] = 0.0

    return peak

def apply_white_noise(chromatogram, apices, signal_to_noise_ratio):
    # obtain a stddev that approximately results in noise levels close to SNR
    stddev = apices.mean() / signal_to_noise_ratio / 4
    noise = np.random.normal(0, stddev, len(chromatogram))
    return chromatogram + noise

def apply_pink_noise(chromatogram, apices, signal_to_noise_ratio, num_sources=8):
    nrows = len(chromatogram)
    ncols = num_sources
    noise = np.full((nrows, ncols), np.nan)
    noise[0, :] = np.random.random(ncols)
    noise[:, 0] = np.random.random(nrows)

    cols = np.random.geometric(0.5, nrows)
    cols[cols >= ncols] = 0
    rows = np.random.randint(nrows, size=nrows)
    noise[rows, cols] = np.random.random(nrows)

    noise = pd.DataFrame(noise)
    noise.fillna(method='ffill', axis=0, inplace=True)
    noise = noise.sum(axis=1).to_numpy()
    noise = (noise - noise.mean())

    # make noise approximately match SNR
    noise = (apices.mean() / signal_to_noise_ratio) * noise / 2
    return chromatogram + noise

def apply_baseline_drift(chromatogram, resolution, multiplier_range):

    def sigmoid(x, a, b, multiplier):
        return 1 / (1 + np.exp( - (x * a + b) )) * multiplier

    x = np.linspace(-1, 1, resolution)
    baseline_drift = np.zeros(resolution, dtype='float32')
    n = 10
    for _ in range(n):
        multiplier = np.random.uniform(*multiplier_range)
        a = np.random.uniform(-20, 20)
        b = np.random.uniform(-20, 20)
        baseline_drift += sigmoid(x, a, b, multiplier) / n
    return chromatogram + baseline_drift

def random_truncated_normal(loc, scale, minimum, maximum, size):
    values = np.zeros(size)
    logical_test = values.copy().astype(bool)
    while not np.all(logical_test):
        logical_test = np.logical_and((minimum < values), (values < maximum))
        values = np.where(logical_test, values, scale * np.random.randn(size) + loc)
    return values

def random_logarithmic_uniform(minimum, maximum, size=None):
    return 10 ** np.random.uniform(np.log10(minimum), np.log10(maximum), size=size)

def random_logarithmic_randint(minimum, maximum, size=None):
    return np.round(random_logarithmic_uniform(minimum, maximum, size)).astype(int)

class Simulator:

    def __init__(
        self,
        remove_collision_fn=None,
        resolution=8192,
        num_peaks_range=(10, 100),
        snr_range=(3.0, 300.0),
        amplitude_range=(10, 100),
        loc_range=(0.05, 0.95),
        scale_range=(0.001, 0.002),
        asymmetry_range=(0.00, 0.30),
        baseline_drift_magnitude=(-5, 5), # Not used
        white_noise_prob=1.0,
    ):
        self.remove_collision_fn = remove_collision_fn
        self.resolution = resolution
        self.num_peaks_range = num_peaks_range
        self.snr_range = snr_range
        self.amplitude_range = amplitude_range
        self.loc_range = loc_range
        self.scale_range = scale_range
        self.asymmetry_range = asymmetry_range
        self.baseline_drift_magnitude = baseline_drift_magnitude
        self.white_noise_prob = white_noise_prob

    def sample_batch(self, indices, verbose=0):
        if verbose:
            indices = tqdm(indices)
        for i in indices:
            yield self._generate_example(i)

    def _get_random_scales(self, locs, n_peaks):
        scale_loc = np.random.uniform(*self.scale_range)
        scales = random_truncated_normal(
            scale_loc,                      # mean
            scale_loc/10,                   # std
            scale_loc - scale_loc/10 * 3,   # min (mean - 3std)
            scale_loc + scale_loc/10 * 3,   # max (mean + 3std)
            n_peaks                         # size
        )
        a = np.random.uniform(1, 3)
        b = 0.0 # np.random.uniform(0, 4)
        scales *= 1 + a*locs +  b*locs**2
        return scales, a, b

    def _get_random_amplitudes(self, locs, a, b, n_peaks):
        amplitudes = np.random.uniform(*self.amplitude_range, size=n_peaks)
        amplitudes /= (1 + a*locs + b*locs)
        return amplitudes

    def _get_random_locs(self, n_peaks):
        locs = np.random.uniform(*self.loc_range, size=n_peaks)
        return np.sort(locs)

    def _get_random_asymmetries(self, locs, n_peaks):
        asymmetry_loc = np.random.uniform(*self.asymmetry_range)
        s1 = random_truncated_normal(
            asymmetry_loc,                          # mean
            asymmetry_loc/10,                       # std
            asymmetry_loc - asymmetry_loc/10 * 3,   # min (mean - 3std)
            asymmetry_loc + asymmetry_loc/10 * 3,   # max (mean + 3std)
            n_peaks                                 # size
        )
        s1 *= (1 - locs)
        s2 = -np.random.uniform(np.abs(s1/2), np.abs(s1*2))
        return s1, s2

    def _generate_example(self, random_seed):

        np.random.seed(random_seed)

        n_peaks = random_logarithmic_randint(*self.num_peaks_range)

        # 1. Generate (noise-free) chromatogram
        # a. Obtain peak parameters
        locs = self._get_random_locs(n_peaks)
        scales, a, b = self._get_random_scales(locs, n_peaks)
        ampls = self._get_random_amplitudes(locs, a, b, n_peaks)
        s1s, s2s = self._get_random_asymmetries(locs, n_peaks)

        # b. Remove collisions:
        #    If two peaks fall inside the same window, remove one of the peaks
        #    Otherwise we will train the model to predict one peak (for the
        #    given heavily-overlapping peak) even though there are two peaks
        if self.remove_collision_fn is not None:
            locs, scales, s1s, s2s, ampls = self.remove_collision_fn(
                locs, scales, s1s, s2s, ampls
            )

        # 3. Generate (noise-free) chromatogram from peaks (and obtain areas)
        x = np.linspace(0, 1, self.resolution)
        areas = np.zeros([0], dtype='float32')
        chromatogram = np.zeros_like(x)
        for i, (ampl, loc, scale, s1, s2) in enumerate(zip(ampls, locs, scales, s1s, s2s)):
            peak = asymmetrical_gaussian_peak(x, ampl, loc, scale, s1, s2)
            areas = np.concatenate([areas, [np.trapz(peak, dx=x[1]-x[0])]])
            chromatogram += peak

        # 2. Apply noise to (noise-free) chromatogram
        # a. Obtain signal-to-noise ratio (levels of noise)
        snr = random_logarithmic_uniform(*self.snr_range)
        # b. Apply white noise or pink noise to chromatogram
        if np.random.random() <= self.white_noise_prob:
            chromatogram = apply_white_noise(chromatogram, ampls, snr)
        else:
            chromatogram = apply_pink_noise(chromatogram, ampls, snr)

        # distort baseline a bit
        chromatogram += np.random.randn() * 2

        # c. Apply baseline drift to chromatogram
        #chromatogram = apply_baseline_drift(
        #   chromatogram, self.resolution, self.baseline_drift_magnitude)

        return {
            'chromatogram': chromatogram,
            'loc': locs,
            'scale': scales,
            'amplitude': ampls,
            's1': s1s,
            's2': s2s,
            'area': areas,
        }


import yaml, os

def get_data():
    # 返回 yaml文件数据 [(),(),()]
    # 存储读取数据
    data_list = []
    with open('E:\\就业班\\20190125\\me\\app_code08_3\\Data\\book.yml', "r") as f:
        data = yaml.load(f)
        for i in data.get("data"):
            # 数据组装
            data_list.append(i)
    return data_list

# print(get_data())


#Assignment.Python1
#NAME : COREY A. JONES
#DATE: OCTOBER 30

#cubing numbers in a list up to output of 1000

rangelist=list(range(1,1000))
list_num = []
for i in rangelist:
    x=i**3
    v = x
    list_num.append(v)
    if x <= 1000:
        print(v)


import xlsxwriter
from constants import XLS_FILE

class Excel:
    def __init__(self):
        self.workbook = xlsxwriter.Workbook(XLS_FILE)
        self.worksheet = self.workbook.add_worksheet()
        self.actual_row = 0
        self.col_names = [
            "referencia",
            "nombre",
            "precio",
            "imagen",
            "descripcion",
        ]

        self.__write_headers()

    def __write_headers(self):
        row = 0
        col = 0

        for header in self.col_names:
            self.worksheet.write(row, col, header)
            col += 1

        self.actual_row = 1

    def __write_row(self, element: dict):
        print(element)
        col = 0
        for value in list(element.values()):
            self.worksheet.write(self.actual_row, col, value)
            col += 1

        self.actual_row += 1

    def write_data(self, item_list: list):
        print("\nEscribiendo datos en excel...")
        for element in item_list:
            self.__write_row(element)


def isJolly(a, n):
    diffSet = [False] * n
    for i in range(n):
        d = abs(a[i]-a[i + 1])
        if (d == 0 or d > n-1 or diffSet[d] == True):
            return False
        diffSet[d] = True
    return True

while True:
    s=input()
    if s=="STOP":
        break
    else:
        jolly=True
        new=s.split(" ")
        n=len(new)
        L1=[]
        for i in range(n):
            t=int(new[i])
            L1.append(t)
    V=L1
    N=len(V)
    if isJolly(V, N):
        print("UB Jumper")
    else:
        print("Not UB Jumper")


#!/usr/bin/python
import random
import time
import numpy as np

# Set global values
alpha = 0.9
gamma = 1.0
epsilon = 0.0
episodes = 25000 # Number of games to be played
mov_list = [-40,-20,20,40] # Possible changes to x or y position
initial_pos_x1 = 40
initial_pos_y1 = 80
initial_pos_x2 = 160
initial_pos_y2 = 200

fout = open("logfile.txt","w")

#Set up Q table
state_space = {} # Set of all possible states
temp_list = []
state_temp_list = []

#State description for 1 ball
for n in range(0,500,20):
	for m in range(0,360,20):
		temp_list.append((n,m))

#State for the whole 2 ball system
for j in temp_list:
	for k in temp_list:
		state_temp_list.append((j,k))

for k in range(202500):
	state_space[k] = state_temp_list[k]

print(state_space[19])

action_space = {} # Set of all possible actions
temp_list = []
for n in mov_list:
	for m in mov_list:
		temp_list.append((m,n))
for k in range(16):
	action_space[k] = temp_list[k]

q_table = np.zeros([len(state_space),len(action_space)]) # Use this for generating new Q table
#q_table = np.loadtxt("qtable.csv",delimiter=',') # Uncomment this to read from an existing q table

def movement(): # Movement of Green Ball

	# Set local variables
	steps = 0
	checkpoint = 0
	pos_x1 = initial_pos_x1 # x coordinate
	pos_y1 = initial_pos_y1 # y coordinate
	x1 = 20 # movement size in x direction
	y1 = 20 # movement size in y direction
	pos_x2 = initial_pos_x2 # x coordinate
	pos_y2 = initial_pos_y2 # y coordinate
	x2 = 20 # movement size in x direction
	y2 = 20 # movement size in y direction
	game = 0
	reward = 0
	win_counter = 0
	collision = 0
	green_collision_count = 0
	red_collision_count = 0
	tmp = 0

	end = 1
	while end == 1:
		reward = 0
		state = list(state_space.keys())[list(state_space.values()).index(((pos_x1, pos_y1),(pos_x2,pos_y2)))]
		steps += 1

		if game == episodes:
			end = 0
			print("Total games won : ",win_counter, "(",round(win_counter*100/episodes,2),"%)")
			print("collision_count : ",green_collision_count,red_collision_count)
			np.savetxt("qtable.csv", q_table, delimiter=",")
			fout.write("qtable saved at " + str(steps) + " steps\n")
			print("saved qtable after "+str(game)+" games")

		if game % 10000 == 0 and game != episodes and tmp == 0:
			np.savetxt("qtable.csv", q_table, delimiter=",")
			fout.write("qtable saved at " + str(steps) + " steps\n")
			print("saved qtable after "+str(game)+" games")
			tmp = 1

		if game % 10000 != 0:
			tmp = 0

		if steps % 200 == 0:
			checkpoint = steps
			game += 1
			print("Game : "+str(game) + " lost")
			fout.write(str(steps) + " adjusting, time up\n")
			fout.write("game "+str(game) + " lost\n")
			fout.flush()

			# Reset to initial position
			new_x1 = (initial_pos_x1 - pos_x1)
			new_y1 = (initial_pos_y1 - pos_y1)
			pos_x1 += new_x1
			pos_y1 += new_y1

			new_x2 = (initial_pos_x2 - pos_x2)
			new_y2 = (initial_pos_y2 - pos_y2)
			pos_x2 += new_x2
			pos_y2 += new_y2

			collision = 0

		if game < 20000000: # arbitrarily chosen high value to prevent exploitation ;
			#change above if exploitation is desired afterwards certain number of games
			x1 = random.choice(mov_list)
			y1 = random.choice(mov_list)
			action = list(action_space.keys())[list(action_space.values()).index((x1, y1))]
		else:
			# Exploit based on epsilon probability
			if random.random() < epsilon:
				x1 = random.choice(mov_list)
				y1 = random.choice(mov_list)
				action = list(action_space.keys())[list(action_space.values()).index((x1, y1))]
			else:
				action = np.argmax(q_table[state])
				x1, y1 = action_space[action]

		# Bounce back from boundaries
		if pos_x1 > 459:
			x1 = -20
		if pos_x1 < 41:
			x1 = 20
		if pos_y1 > 319:
			y1 = -20
		if pos_y1 < 41:
			y1 = 20

		# Update position
		pos_x1 += x1
		pos_y1 += y1

		# Check if green ball hit the red ball

		if (pos_x1 == pos_x2) and (pos_y1 == pos_y2):
			collision = 1
			reward = -200
			print("green collision", pos_x1, pos_y1, pos_x2, pos_y2)
			green_collision_count += 1

		# Move the red ball
		if collision != 1:
			x2 = random.choice(mov_list)
			y2 = random.choice(mov_list)
			if pos_x2 > 459:
				x2 = -20
			if pos_x2 < 41:
				x2 = 20
			if pos_y2 > 319:
				y2 = -20
			if pos_y2 < 41:
				y2 = 20

			pos_x2 += x2
			pos_y2 += y2

			if (pos_x1 == pos_x2) and (pos_y1 == pos_y2):
				collision = 1
				print("red collision", pos_x1, pos_y1, pos_x2, pos_y2)
				red_collision_count += 1

		if collision == 1:
			game += 1
			print("Game : "+str(game) + " lost due to collision")
			fout.write("game "+str(game) + " lost due to collision\n")
			fout.flush()
			steps = checkpoint # Reset number of steps to the start of the run

			# Reset to initial position
			new_x1 = (initial_pos_x1 - pos_x1)
			new_y1 = (initial_pos_y1 - pos_y1)
			pos_x1 += new_x1
			pos_y1 += new_y1

			new_x2 = (initial_pos_x2 - pos_x2)
			new_y2 = (initial_pos_y2 - pos_y2)
			pos_x2 += new_x2
			pos_y2 += new_y2

			collision = 0

		if pos_x1 == 240 and pos_y1 == 180:
			reward = 100
			game += 1
			print("Game : "+str(game) + " won")
			win_counter += 1
			steps = checkpoint # Reset number of steps to the start of the run
			fout.write("game "+str(game) + " won\n")
			fout.flush()

			# Reset to initial position
			new_x1 = (initial_pos_x1 - pos_x1)
			new_y1 = (initial_pos_y1 - pos_y1)
			pos_x1 += new_x1
			pos_y1 += new_y1

			new_x2 = (initial_pos_x2 - pos_x2)
			new_y2 = (initial_pos_y2 - pos_y2)
			pos_x2 += new_x2
			pos_y2 += new_y2

		# Update the Q table
		old_q_value = q_table[state, action]
		next_state = list(state_space.keys())[list(state_space.values()).index(((pos_x1, pos_y1),(pos_x2,pos_y2)))]
		next_max = np.max(q_table[next_state])
		q_target = reward + gamma * next_max
		q_delta = q_target - old_q_value
		q_table[state, action] = old_q_value + alpha * q_delta

movement()


import pandas as pd
from flask import Flask, request, render_template
import requests
import json
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
 	return render_template('home.html')
@app.route('/process',methods=['GET', 'POST'])
def nextFn():
    # Dataset from - https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection
    df = pd.read_table('smsspamcollection/SMSSpamCollection',
                   sep='\t',
                   header=None,
                   names=['label', 'sms_message'])
    df['label'] = df.label.map({'ham':0, 'spam':1})
    count_vector = CountVectorizer()

    X_train, X_test, y_train, y_test = train_test_split(df['sms_message'],
                                                    df['label'],
                                                    random_state=1)

    count_vector = CountVectorizer()

    # Fit the training data and then return the matrix
    training_data = count_vector.fit_transform(X_train)
    naive_bayes = MultinomialNB()
    naive_bayes.fit(training_data, y_train)
    user_text= request.form.get('raw')
    t_data= count_vector.transform([str(user_text)])
    p = naive_bayes.predict(t_data)
    if p[0]==0:
        result="Not Spam"
        return render_template('response.html', result=result)
    else:
        result="Spam"
        return render_template('response.html', result=result)

if __name__=='__main__':
    app.run()


from __future__ import division

import itertools
import random
import hexagonal as hex

from .incremental import ZobristKey
from .validate import validate_dict, validate_equal
from .util import zip_exact, window2

try: import cPickle as pickle
except ImportError: import pickle

# Every Rule has at least one kind; for those with one it is usually this:
# (appears as config key, and as a possible value in MoveCache)
DEFAULT_KIND = 'natural'

# These constants are for named for purposes of clarity, not for abstraction;
# Most of the code WILL assume that they have these numeric values,
#  and may use bitwise operations to manipulate them.
LAYERS = [1,2]   # possible values of "layers" for monovacancy
BOTH_LAYERS = 3  # value of "layers" for divacancy

# These namedtuples are used together with their type as a tagged union;
# e.g.  (type(obj), obj), where the type serves as the discriminator.
#
# (the explicit discriminator is because namedtuples are (unfortunately)
#  designed to be compatible with tuples, which means their __eq__ and
#  __hash__ methods do not care about the type)
from collections import namedtuple
Pristine = namedtuple('Pristine', [])
Vacancy = namedtuple('Vacancy', ['node', 'layers'])
Trefoil = namedtuple('Trefoil', ['nodes'])

# only need one instance
PRISTINE = Pristine()
PRISTINE_ENTRY = (Pristine, PRISTINE)

# ``State(zobrist=HASH)`` uses ``hash`` for zobrist diffs.
HASH = object()

class State:

	def __init__(self, dim, zobrist=None):
		self.grid = Grid(dim)
		self.__vacancies = set()
		self.__trefoils = set()
		self.__nodes = self.__compute_nodes_lookup()

		self.__zobrist = None
		if isinstance(zobrist, int): self.__zobrist = ZobristKey(bits=zobrist)
		elif zobrist is HASH:        self.__zobrist = ZobristKey(rng=None)
		elif zobrist is not None:    raise TypeError('zobrist')

	@classmethod
	def from_entity_lists(cls, dim, vacancies, trefoils, zobrist=None):
		self = cls(dim, zobrist=zobrist)
		for (node, layer) in vacancies:
			self.new_vacancy(node, layer)
		for (nodes,) in trefoils:
			self.new_trefoil(nodes)
		return self

	def dim(self):
		return self.grid.dim

	def clone(self):
		''' Creates a copy of the state (minus event bindings). '''
		return pickle.loads(pickle.dumps(self))

	#------------------------------------------
	# Serialization

	@classmethod
	def from_dict(cls, d):
		from itertools import starmap
		dim = tuple(d.pop('dim'))
		if len(dim) != 2: raise ValueError
		if not all(isinstance(x,int) for x in dim): raise ValueError
		if not all(x>0 for x in dim): raise ValueError

		vacancies = starmap(Vacancy, d.pop('vacancies'))
		trefoils  = starmap(Trefoil, d.pop('trefoils'))
		return cls.from_entity_lists(dim, vacancies, trefoils)

	def to_dict(self):
		return {
			'dim': list(self.dim()),
			'vacancies': list(map(tuple, self.vacancies())),
			'trefoils': list(map(tuple, self.trefoils())),
		}

	#------------------------------------------
	# THE __nodes CACHE:
	# A lookup of data for individual nodes.

	# The values of __nodes are like a tagged union.
	# They are of the form (status, data), where status serves as a descriminator
	#  for how to interpret the data.

	def validate(self):
		'''
		Validate incrementalized computations with an expensive test.

		Throws an exception or returns True (for use in assert).
		'''
		self.__validate_entity_invariants()
		self.__validate_nodes_lookup()
		self.__validate_zobrist_key()
		return True

	# This function is the "gold standard" for what __nodes should look like.
	# Rules must strive to preserve this definition.
	def __compute_nodes_lookup(self):
		''' generates __nodes from __vacancies and __trefoils '''
		cache = { x:PRISTINE_ENTRY for x in self.grid.nodes() }

		for vacancy in self.__vacancies:
			cache[vacancy.node] = (Vacancy, vacancy)

		for trefoil in self.__trefoils:
			for node in trefoil.nodes:
				cache[node] = (Trefoil, trefoil)

		return cache

	def __validate_nodes_lookup(self):
		validate_dict(
			self.__nodes,
			self.__compute_nodes_lookup(),
			name1='cached', name2='expected', key='node')

		return True

	def __validate_zobrist_key(self):
		if self.is_zobrist_enabled():
			expected = self.__zobrist.derive()
			expected.update((Vacancy,x) for x in self.__vacancies)
			expected.update((Trefoil,x) for x in self.__trefoils)
			validate_equal(self.__zobrist.value(), expected.value())
		return True

	def __validate_entity_invariants(self):
		for x in self.__vacancies:
			if not (1 <= x.layers <= 3):
				raise AssertionError('vacancy with bad layer: %s' % x.layers)

		return True

	#------------------------------------------
	# Accessors/iterators

	def pristine_nodes(self): return filter(self.is_pristine, self.grid.nodes())

	def vacancies(self): return self.__vacancies.__iter__()
	def divacancies(self): return (x for x in self.__vacancies if x.layers == BOTH_LAYERS)
	def monovacancies(self): return (x for x in self.__vacancies if x.layers != BOTH_LAYERS)

	def nodes(self): return self.grid.nodes()
	def node_status(self, node): return self.__nodes[node][0]
	def nodes_with_status(self): return [(n, self.node_status(n)) for n in self.nodes()]

	def trefoils(self): return self.__trefoils.__iter__()
	def trefoil_nodes_at(self, node):
		(status,trefoil) = self.__nodes[node]
		if status is not Trefoil:
			raise KeyError('node not a trefoil')
		return frozenset(trefoil.nodes)

	def vacant_layerset_at(self, node):
		''' Get the layers value (an int to manipulate as a bitset) of a node.
		0 = no vacancies, 1 or 2 = monovacancy, 3 = divacancy '''
		(status,vacancy) = self.__nodes[node]
		if status is Pristine: return 0
		elif status is Vacancy: return vacancy.layers
		else: raise KeyError('monovacancy layers not defined at node')

	#------------------------------------------
	# Public mutators
	# These are discrete actions which modify the State and perform
	# incrementalized updates to all caches, so that all objects
	# are left in a consistent state.

	# General flow is:
	# * Update the entity lists (__vacancies, __trefoils)
	# * Update the __nodes table.
	# * Update the __zobrist key.

	# NOTES on implementation constraints:
	# * These methods should be regarded as the primitive operations for
	#   modifying the State.  Any other operations are composed of these.
	# * They must be members of State so that they can modify private members.

	def new_divacancy(self, node):
		''' Turn a pristine node into a divacancy. '''
		self.new_vacancy(node, BOTH_LAYERS)

	def new_vacancy(self, node, layers):
		''' Turn a pristine node into a mono- or divacancy. '''
		node = tuple(node)
		assert self.is_pristine(node)

		vacancy = Vacancy(node, layers)
		self.__vacancies.add(vacancy)
		self.__nodes[node] = (Vacancy, vacancy)
		self.__zobrist_toggle((Vacancy, vacancy))

	def new_trefoil(self, nodes):
		''' Turn three pristine nodes into a trefoil. '''
		nodes = frozenset(map(tuple, nodes))
		assert len(nodes) == 3
		assert all(map(self.is_pristine, nodes))

		trefoil = Trefoil(nodes)
		self.__trefoils.add(trefoil)
		for node in nodes:
			self.__nodes[node] = (Trefoil, trefoil)
		self.__zobrist_toggle((Trefoil, trefoil))

	def pop_divacancy(self, node):
		''' Turn a divacancy into a pristine node. '''
		assert self.is_divacancy(node)
		self.pop_vacancy(node)

	def pop_vacancy(self, node):
		''' Turn a mono- or divacancy into a pristine node. '''
		vacancy = self.__find_vacancy(node)
		self.__vacancies.remove(vacancy)
		self.__nodes[node] = PRISTINE_ENTRY
		self.__zobrist_toggle((Vacancy, vacancy))
		return vacancy

	def pop_trefoil(self, nodes):
		''' Turn a trefoil into three pristine nodes. '''
		nodes = frozenset(map(tuple, nodes))
		assert len(nodes) == 3

		trefoil = self.__find_trefoil(nodes)
		self.__trefoils.remove(trefoil)
		for node in nodes:
			self.__nodes[node] = PRISTINE_ENTRY
		self.__zobrist_toggle((Trefoil, trefoil))
		return trefoil

	def __zobrist_toggle(self, value):
		if self.__zobrist:
			self.__zobrist.toggle(value)

	def __find_vacancy(self, node):
		(status,vacancy) = self.__nodes[node]
		assert status is Vacancy
		assert vacancy.node == node
		return vacancy

	def __find_trefoil(self, nodes):
		nodes = frozenset(nodes)
		(status,trefoil) = self.__nodes[next(iter(nodes))]
		assert status is Trefoil
		assert trefoil.nodes == nodes
		return trefoil

	#------------------------------------------
	def is_monovacancy(self, node):
		''' Test that a node is a monovacancy. '''
		tag, data = self.__nodes[node]
		assert tag in [Pristine, Vacancy, Trefoil], 'function not updated'
		return tag is Vacancy and data.layers in LAYERS

	def is_divacancy(self, node):
		''' Test that a node is a divacancy. '''
		tag, data = self.__nodes[node]
		assert tag in [Pristine, Vacancy, Trefoil], 'function not updated'
		return tag is Vacancy and data.layers == BOTH_LAYERS

	def is_vacancy(self, node):
		''' Test that a node is a mono or divacancy. '''
		tag, data = self.__nodes[node]
		assert tag in [Pristine, Vacancy, Trefoil], 'function not updated'
		return tag is Vacancy

	def is_trefoil(self, node):
		''' Test that a node is in a trefoil. '''
		tag, data = self.__nodes[node]
		assert tag in [Pristine, Vacancy, Trefoil], 'function not updated'
		return tag is Trefoil

	def is_pristine(self, node):
		''' Test that a node is pristine. (i.e. all atoms are present)'''
		tag, data = self.__nodes[node]
		assert tag in [Pristine, Vacancy, Trefoil], 'function not updated'
		return tag is Pristine

	def has_defined_layerset(self, node):
		''' Test that a node has a well-defined set of monovacancies.
		True for pristine nodes, monovacancies and divacancies. '''
		tag, data = self.__nodes[node]
		assert tag in [Pristine, Vacancy, Trefoil], 'function not updated'
		return tag is not Trefoil

	#------------------------------------------
	# FIXME Feels like a bit of a hack that code using State might need
	#       to check this.
	def is_zobrist_enabled(self):
		return self.__zobrist is not None
	def zobrist_key(self):
		'''
		Get the current value of the zobrist key, an incrementally
		computed hash for identifying previously visited states.

		In general, zobrist keys between two different instances of State
		are incompatible.  However, if one is ``clone``d from the other,
		then the two will always at least agree on the hashes for states
		visited *prior* to the ``clone``.)
		'''
		assert self.is_zobrist_enabled(), "shouldn't be called unless --zobrist is set..."
		return self.__zobrist.value()

#------------------------------------------------------------------

RANDOM_MODES =  ['exact','approx']
RANDOM_ASSIGN_FUNC = {
	'divacancy':   lambda s,n,rng: s.new_divacancy(n),
	'monovacancy': lambda s,n,rng: s.new_vacancy(n, layers=rng.choice(LAYERS)),
	'remainder':   lambda s,n,rng: None,
}
RANDOM_PARAMS = list(set(RANDOM_ASSIGN_FUNC) - set(['remainder']))

def gen_random_state(dim, mode, params, rng=random, **kw):
	state = State(dim, **kw)
	__populate_state(state, mode=mode, params=params, rng=rng)
	return state

def __populate_state(state, mode, params, rng=random):
	''' randomly populate an empty state '''
	params = dict(params)
	if mode == 'exact':    return __populate_state__exact(state, params, rng=rng)
	elif mode == 'approx': return __populate_state__approx(state, params, rng=rng)
	else: assert False, 'complete switch'

# interprets each rate as a probability of occurence for each individual site
def __populate_state__approx(state, params, rng=random):
	from math import fsum
	from .kmc import weighted_choice

	kw_pairs = list(params.items())

	remainder_prob = 1. - fsum(params.values())
	assert remainder_prob >= (-1e-10), 'already required sum() <= 1.'
	if remainder_prob > 0:
		kw_pairs.append(('remainder', remainder_prob))

	nodes = list(state.nodes())
	chosen = weighted_choice(kw_pairs, howmany=len(nodes), rng=rng)
	for (node,param) in zip_exact(nodes, chosen):
		RANDOM_ASSIGN_FUNC[param](state, node, rng)

# interprets each rate as a target frequency and tries to match them
#  as closely as possible
def __populate_state__exact(state, params, rng=random):
	from .util import partial_sums, differences

	nodes = list(state.nodes())
	rng.shuffle(nodes)

	# From the shuffled list, select intervals of lengths that best approximate
	# the specified rate distribution.
	(keys,rates) = zip(*sorted(params.items(), key=lambda kv:kv[1]))
	cumul = partial_sums(rates, with_zero=True)
	indices = list(round(r*len(nodes)) for r in cumul) # interval endpoints

	assert all(x >= 0 for x in differences(indices)), 'tested prior to this func'
	assert indices[-1] <= len(nodes), 'not possible through floating point error alone'

	for (key,(start,end)) in zip_exact(keys, window2(indices)):
		f = RANDOM_ASSIGN_FUNC[key]
		for node in nodes[start:end]:
			f(state, node, rng)

#------------------------------------------------------------------

# Periodic hexagonal grid, stored in axial coords.
class Grid:
	def __init__(self, dim):
		self.dim = dim
		assert len(self.dim) == 2

	def nodes(self):
		''' Iterate over all nodes. '''
		return itertools.product(*(range(d) for d in self.dim))

	def neighbors(self, node):
		''' The six neighbors of a node on a hexagonal lattice. '''
		return self.rotations_around(node, [-1, 0, 1])

	def trefoil_neighbors(self, node):
		''' The six nodes with which a node can form a trefoil defect.

		For one to actually form, three nodes must all mutually be
		trefoil neighbors. '''
		return self.rotations_around(node, [2, -2, 0])

	def nodes_in_distance_range(self, nodes, mindist, maxdist):
		'''
		Collect nodes in a range of distances from a set of nodes.

		Collects nodes at a distance from ``mindist`` to ``maxdist``, inclusive.
		The input nodes have distance 0, their neighbors (excluding themselves)
		are distance 1, et cetera.

		Designed for functions which need to invalidate a region of the grid
		after making several modifications.
		'''
		# structured to avoid unnecessarily computing an extra group
		if maxdist < mindist: return
		for (n,group) in enumerate(bfs_groups_by_distance(nodes, self.neighbors)):
			if n < mindist: continue
			yield from group
			if n >= maxdist: break

	def rotations_around(self, node, disp):
		''' Get the node at node+disp, together with the other 5 nodes
		related to it by the sixfold rotational symmetry around node. '''
		a,b = node
		for da, db, _ in hex.cubic_rotations_60(*disp):
			yield self.reduce((a + da, b + db))

	def rotations_around_threefold(self, node, disp):
		''' Get the node at node+disp, together with the other 2 nodes
		related to it by the threefold rotational symmetry around node. '''
		a,b = node
		for da, db, _ in hex.cubic_rotations_120(*disp):
			yield self.reduce((a + da, b + db))

	def can_form_trefoil(self, nodes):
		''' Determine if the three given nodes can form a trefoil defect. '''
		n1,n2,n3 = nodes
		return all(
			u in self.trefoil_neighbors(v)
			for (u,v) in [(n1,n2), (n2,n3), (n3,n1)]
		)

	def neighbors_and_mutuals(self, node):
		'''
		Get (nbr,near,far) triplets of neighbors and mutual neighbors of a node.

		``near`` and ``far`` are the two nodes that are mutual neighbors of ``node``
		and ``nbr``.  They are such that ``(node, nbr, near)`` are all attached to the
		same metal ion, and ``(node, nbr, far)`` are all on the same honeycomb cell.
		'''
		rotations = self.rotations_around_threefold
		nbrs  = rotations(node, [-1,  1,  0])
		nears = rotations(node, [ 0,  1, -1])
		fars  = rotations(node, [-1,  0,  1])
		yield from zip(nbrs, nears, fars)
		nbrs  = rotations(node, [ 0,  1, -1])
		nears = rotations(node, [-1,  1,  0])
		fars  = rotations(node, [ 1,  0, -1])
		yield from zip(nbrs, nears, fars)

	def reduce(self, node):
		''' Apply PBC to get a node's image in the unit cell. '''
		a, b = node
		return (a % self.dim[0], b % self.dim[1])

def bfs_groups_by_distance(roots, edge_func):
	seen = set()
	current = set(roots)
	while True:
		yield current
		seen |= current
		prev = current

		current = set()
		for x in prev:
			new = set(edge_func(x))
			new -= seen
			current.update(new)


import os
from blackjack import Blackjack

# classe do console principal
class Console():

    def __init__(self, pcard1=0, pcard2=0, pcard3=0, pcard4=0, pcard5=0, dcard1=0, dcard2=0, dcard3=0, dcard4=0, dcard5=0, qdecks=1):
        self.pcard1 = pcard1
        self.pcard2 = pcard2
        self.pcard3 = pcard3
        self.pcard4 = pcard4
        self.pcard5 = pcard5
        self.dcard1 = dcard1
        self.dcard2 = dcard2
        self.dcard3 = dcard3
        self.dcard4 = dcard4
        self.dcard5 = dcard5
        self.qdecks = qdecks

        self.main()

        self.blackjack = Blackjack(self.pcard1, self.pcard2, self.pcard3, self.pcard4, self.pcard5, self.dcard1, self.dcard2, self.dcard3, self.dcard4, self.dcard5, self.qdecks)

        self.inicio_partida()

    def clear(self):
        clear = 'cls' if os.name == 'nt' else 'clear'
        os.system(clear)

    def header(self):
        print("****************************")
        print("*** Análise de Blackjack ***")
        print("****************************")

    def main(self):
        self.clear()
        self.header()

    def inicio_partida(self):
        self.pcard1 = input('Digite a sua primeira carta: ')
        self.pcard2 = input('Digite a sua segunda carta: ')
        self.dcard1 = input('Digite a carta revelada do Dealer: ')
        self.qdecks = input('Digite a quantidade de baralhos: ')
        self.blackjack = Blackjack(self.pcard1, self.pcard2, self.pcard3, self.pcard4, self.pcard5, self.dcard1, self.dcard2, self.dcard3, self.dcard4, self.dcard5, self.qdecks)

        self.main()
        self.escolher_sugestao()

    def proxima_acao(self):
        self.main()
        self.blackjack.get_info()
        self.blackjack.get_suggestions()

        print('Escolha a próxima ação:')
        print('1 - Escolher sugestão')
        print('2 - Informar resultado')
        print('3 - Sair')
        self.acao_escolhida = input('Escolha a próxima ação: ')

        if (self.acao_escolhida == '1'):
            self.escolher_sugestao()
        elif (self.acao_escolhida == '2'):
            self.informar_resultado()
        else:
            pass

    def escolher_sugestao(self):
        self.main()
        self.blackjack.get_info()
        self.blackjack.get_suggestions()

        print("****************************")
        print('Informe a sugestão escolhida:')
        print('1 - Hit')
        print('2 - Stand')
        self.sugestao_escolhida = input('Sugestão escolhida: ')

        if (self.blackjack.player.busted == False and self.blackjack.dealer.busted == False):
            if (self.sugestao_escolhida == 'hit' or self.sugestao_escolhida == 'Hit' or self.sugestao_escolhida == '1'):
                self.informar_nova_carta_jogador()
                #self.proxima_acao()

            elif (self.sugestao_escolhida == 'stand' or self.sugestao_escolhida == 'Stand' or self.sugestao_escolhida == '2'):
                self.informar_resultado()
            else:
                pass

    def informar_resultado(self):
        self.main()

        print('Informe o resultado da rodada ou partida:')
        print('1 - Win')
        print('2 - Loss')
        print('3 - Draw')
        self.resultado_partida = input('Resultado da partida: ')

        if (self.resultado_partida == 'win' or self.resultado_partida == 'Win' or self.resultado_partida == '1'):
            self.blackjack.get_result(self.resultado_partida, self.sugestao_escolhida)
        elif (self.resultado_partida == 'loss' or self.resultado_partida == 'Loss' or self.resultado_partida == '2'):
            self.blackjack.get_result(self.resultado_partida, self.sugestao_escolhida)
        elif (self.resultado_partida == 'draw' or self.resultado_partida == 'Draw' or self.resultado_partida == '3'):
            self.blackjack.get_result(self.resultado_partida, self.sugestao_escolhida)
        else:
            pass

    def informar_cartas_dealer(self):
        pass

    def informar_nova_carta_jogador(self):

        # definindo a proxima carta a ser recebida
        if(self.pcard3 != 0):
            self.next_pcard = 3
            self.next_pcard_ordinal = "terceira"
            self.pcard3 = input('Digite a sua '+self.next_pcard_ordinal+' carta: ')
            self.blackjack.player.card3 = self.pcard3
        elif(self.pcard4 != 0):
            self.next_pcard = 4
            self.next_pcard_ordinal = "quarta"
            self.pcard4 = input('Digite a sua '+self.next_pcard_ordinal+' carta: ')
            self.blackjack.player.card4 = self.pcard4
        elif(self.pcard5 != 0):
            self.next_pcard = 5
            self.next_pcard_ordinal = "quinta"
            self.pcard5 = input('Digite a sua '+self.next_pcard_ordinal+' carta: ')
            self.blackjack.player.card5 = self.pcard5

    def informar_nova_carta_dealer(self):
        pass


# coding:utf-8

from flask import Flask,make_response,jsonify
from flask_restful import Api, Resource
from flask_restful import reqparse
from flask_restful import fields, marshal
from flask_httpauth import HTTPBasicAuth
from algorithm import KeywordExtraction

app = Flask(__name__,static_url_path="")
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False)) #保证输出为中文而不是Unicode码，默认为True，所有的非ascii字符在输出时都会被转义为\uxxxx的序列
api = Api(app)

# auth = HTTPBasicAuth()

# @auth.get_password
# def get_password(username):
#     if username == 'wzy':
#         return '123456'
#     return None

# @auth.error_handler
# def unauthorized():
#     return make_response(jsonify({'error': 'Unauthorized access'}), 403) #这里需要使用jsonify

class KnoAPI(Resource):
    # decorators = [auth.login_required]
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('text', type = str, required = True, help = 'No text provided', location = 'json')
        self.reqparse.add_argument('mode', type = int, default = 0, location = 'json')
        self.reqparse.add_argument('num', type = int, default = 5, location = 'json')
        self.reqparse.add_argument('weight', type = int, default = 0, location = 'json')
        super(KnoAPI, self).__init__()

    def post(self):
        args = self.reqparse.parse_args()
        inputDict = {}
        inputDict['text'] = args['text']
        if(args['mode'] == 0 or args['mode'] == 1 ):
            inputDict['mode'] = args['mode']
        else:
            inputDict['mode'] = 0
        if(args['weight'] == 0 or args['weight'] == 1 ):
            inputDict['weight'] = args['weight']
        else:
            inputDict['weight'] = 0
        inputDict['keywordNum'] = args['num']
        inputDict['url'] = None
        keywordResult = KeywordExtraction(inputDict)

        result = {
            'mode':args['mode'],
            'num':args['num'],
            'keyword':keywordResult
        }

        return {'result':result}

api.add_resource(KnoAPI, '/kno/api/v1.0/getKeyword', endpoint = 'keyword')

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


from pulp import *
import numpy as np
import matplotlib.pyplot as plt
from random import randrange
import pandas as pd

# # Funciones globales

# ## 0) Feasible solution:

def feasible_sets_2(A,B,h=10):
    control=False
    itera=0
    while (control!=True) and itera<10:
        #print("sol factible")
        y=[randrange(-10,10),randrange(-10,10)]
        y0=[randrange(-10,10),randrange(-10,10)]
        Ajs=[[]for i in range(0,len(y))]
        Bjs=[[]for i in range(0,len(y))]
        for i in range(0,len(list(A))):
            perdidas=[abs(B[i]-y[d]*A[i]+y0[d]) for d in range(0,len(y))]
            cambiar=np.argmin(perdidas)
            Ajs[cambiar]=Ajs[cambiar]+[A[i]]
            Bjs[cambiar]=Bjs[cambiar]+[B[i]]
        if (len(Ajs[0])>h and len(Ajs[1])>h):
            control=True
        itera=itera+1

    Res={"Ajs": Ajs,"Bjs":Bjs}
    return Res

def feasible_sets(A,B,h=10):
    Ajs=[[]for i in range(0,2)]
    Bjs=[[]for i in range(0,2)]
    for i in range(0,len(list(A))):
        if i <= (len(list(A))/h):
            Ajs[0]=Ajs[0]+[A[i]]
            Bjs[0]=Bjs[0]+[B[i]]
        else:
            Ajs[1]=Ajs[1]+[A[i]]
            Bjs[1]=Bjs[1]+[B[i]]
    #print(f"A1 {len(Ajs[0])}, A2 {len(Ajs[1])}")
    Res={"Ajs": Ajs,"Bjs":Bjs}
    return Res

## i) Submodel Fitting:

def submodel_fitting(Aj,Bj):

    #conjuntos
    conjuntoAj=Aj
    conjuntoBj=Bj
    mj=len(Aj)

    #Definimos variables
    d_vars = LpVariable.dicts("errorMilp",[(i) for i in range(0,mj)], cat='Continuous')
    wj_vars = LpVariable.dicts("coeficientesMilp",[(k) for k in range(0,n)], cat='continuous')
    wj0_vars = LpVariable.dicts("termIndependienteMilp",[(k) for k in range(0,n)], cat='Continuous')

    #Armamos problema y definimos función objetivo
    prob=LpProblem("Milp",LpMinimize)
    prob += lpSum(d_vars[(i)] for i in range(0,mj))

    #Agregamos restricciones

    for i in range(0,mj):
        prob += d_vars[(i)] >=conjuntoBj[(i)]-(wj_vars[(0)]*conjuntoAj[i])+ wj0_vars[(0)]
        prob += d_vars[(i)] >=-conjuntoBj[(i)]+(wj_vars[(0)]*conjuntoAj[i])- wj0_vars[(0)] #CAMBIE UN MENOS

    for i in range(0,mj):
        prob += d_vars[(i)]>=0

    resultado=prob.solve()

    if resultado==-1:
        print("infactible")

    elif resultado not in [-1,1]:
        print("me rompi")

    else:
        error=0
        for i in range(0,mj):
            error=error+d_vars[(i)].varValue

        Res={"coef":wj_vars[(0)].varValue, "termInd": wj0_vars[(0)].varValue,"error": error,"Aj": Aj}
        return Res

## Agregar supuesto continuidad

def submodel_fitting_2(A,Ajs,Bjs,punto,n):
    #Definimos variables
    d_vars = LpVariable.dicts("errorMilp",[(i,j) for i in range(0,len(A))for j in range(0,len(Ajs))], cat='Continuous')
    wj_vars = LpVariable.dicts("coeficientesMilp",[(k,j) for k in range(0,n) for j in range(0,len(Ajs))], cat='continuous')
    wj0_vars = LpVariable.dicts("termIndependienteMilp",[(k,j) for k in range(0,n) for j in range(0,len(Ajs))], cat='Continuous')

    #Armamos problema y definimos función objetivo
    prob=LpProblem("Milp",LpMinimize)
    prob += lpSum(d_vars[(i,j)] for i in range(0,len(A)) for j in range(0,len(Ajs)))

    #Agregamos restricciones
    for j in range(0,len(Ajs)):
        conjuntoAj=Ajs[j]
        conjuntoBj=Bjs[j]
        mj=len(conjuntoAj)
        for i in range(0,mj):
            prob += d_vars[i,j] >=conjuntoBj[i]-(wj_vars[0,j]*conjuntoAj[i])+ wj0_vars[0,j]
            prob += d_vars[i,j] >=-conjuntoBj[i]+(wj_vars[0,j]*conjuntoAj[i])- wj0_vars[0,j] #CAMBIE UN MENOS

    for j in range(0,len(Ajs)):
        for i in range(0,len(A)):
            prob += d_vars[(i,j)]>=0

    prob += ((wj_vars[(0,0)]*punto)- wj0_vars[(0,0)])==((wj_vars[(0,1)]*punto)- wj0_vars[(0,1)])

    #prob += sum([((wj_vars[(0,0)]*p)- wj0_vars[(0,0)])==((wj_vars[(0,1)]*p)- wj0_vars[(0,1)]) for p in A])==1

    resultado=prob.solve()

    if resultado==-1:
        print("infactible")

    else:
        error=0
        for j in range(0,len(Ajs)):
            conjuntoAj=Ajs[j]
            conjuntoBj=Bjs[j]
            mj=len(conjuntoAj)

            for i in range(0,mj):
                error=error+d_vars[(i,j)].varValue
        Res={"coef":[wj_vars[0,j].varValue for j in range(0,len(Ajs))], "termInd": [wj0_vars[(0,j)].varValue for j in range(0,len(Ajs))],"error": error}
        return Res

## ii) Point Partition:

def point_partition(dp,alpha,A,B,Ajs_dic):

    #Calculamos Rankings
    rankings=[[] for l in Ajs_dic]
    Ajs=[l["Aj"] for l in Ajs_dic]
    #print(Ajs)
    A_nuevo=Ajs[0]+Ajs[1]
    candidatos=[]

    for d in range(0,len(Ajs)):
        conjunto=Ajs[d]
        for a in conjunto:
            i=np.where(np.array(A)==a)[0][0]
            cual_Aj=d
            cual_no_Aj=np.where([True if A[i] not in l else False for l in Ajs])[0]

            perdidas=[abs(B[i]-Ajs_dic[cual_no_Aj[d]]["coef"]*A[i]+Ajs_dic[cual_no_Aj[d]]["termInd"]) for d in range(0,len(cual_no_Aj))]

            #print(f"a: {a}")
            #print(f"perdidas: {perdidas}")
            cambiar=min(perdidas)
            candidatos=candidatos+[cual_no_Aj[np.argmin(perdidas)]]

            if cambiar!=0:
                ra=abs(B[i]-Ajs_dic[cual_Aj]["coef"]*A[i]+Ajs_dic[cual_Aj]["termInd"])/cambiar
            else:
                ra=100000

            rankings[cual_Aj]=rankings[cual_Aj]+[ra]
            #print(f"error actual: {abs(B[i]-Ajs_dic[cual_Aj]['coef']*A[i]+Ajs_dic[cual_Aj]['termInd'])}")
            #print(f"ranking: {ra}")

    #Calculamos puntos criticos y no criticos

    scores=[sorted(l,reverse=True) for l in rankings]
    puntosCriticos=[]
    puntosNOCriticos=[]
    for i in range(0,len(Ajs)):
        puntosCriticos=puntosCriticos+[[x for x in Ajs[i] if rankings[i][np.where(np.array(Ajs[i])==x)[0][0]]
                      in scores[i][0:round(alpha*len(Ajs[i]))]]]
        #print(f"puntos criticos {puntosCriticos[i]}")
        if len(puntosCriticos[i])>0:#por si hay muchos con el mismo score
            puntosCriticos[i]=puntosCriticos[i][0:round(alpha*len(Ajs[i]))]
            #print(f"proporcion: {round(alpha*len(Ajs[i]))}")

        puntosNOCriticos=puntosNOCriticos+[[x for x in Ajs[i] if x not in puntosCriticos[i]]]

    #Forzamos la reasignacion de los puntos criticos y los no criticos van al su correspondiente Dj

    nuevosAjs=[[] for i in range(0,len(Ajs))]
    #print(f"La cantidad de puntos criticos es de A1 {len(puntosCriticos[0])}, de A2 {len(puntosCriticos[1])}")
    for p in range(0,len(puntosCriticos)):
        for punto in puntosCriticos[p]:
            punto_A=np.where(np.array(A_nuevo)==punto)[0][0]
            nuevosAjs[candidatos[punto_A]]=nuevosAjs[candidatos[punto_A]]+[punto]

    for p in range(0,len(puntosNOCriticos)):
        #l=nuevosAjs[p]+puntosNOCriticos[p] #Opcion de dejarlo donde esta

        for punto in puntosNOCriticos[p]:
            i=np.where(np.array(A)==punto)[0][0]
            perdida=[abs(B[i]-Ajs_dic[d]["coef"]*A[i]+Ajs_dic[d]["termInd"]) for d in range(0,len(Ajs))]
            ind=np.argmin(perdida)
            #if len(nuevosAjs[ind])>(len(A)*0.9):
            #    left=list(set(range(0,len(Ajs)))-set([ind]))[0]
            #    nuevosAjs[left]=nuevosAjs[left]+[punto]
            #else:
            nuevosAjs[ind]=nuevosAjs[ind]+[punto]

        #    try:
        #        indice= np.where([sum([(dp["y"][i][0]-dp["y"][j][0])*punto-(dp["y0"][i]-dp["y0"][j])>0
        #              for j in range(0,len(Ajs)) if j!=i])==(len(Ajs)-1) for i in range(0,len(Ajs))])[0][0]
        #        nuevosAjs[indice]=nuevosAjs[indice]+[punto]
        #    except:
        #        nuevosAjs[p]=nuevosAjs[p]+[punto]

    #print(nuevosAjs)
    return({"Ajs":nuevosAjs})

## iii) Domain Partition:

def domain_partition(A,Ajs,n):

    #Definimos variables
    e_vars = LpVariable.dicts("errorMilp",[(i) for i in range(0,len(A))], cat='Continuous')
    y_vars = LpVariable.dicts("coeficientesMilp",[(k,j) for k in range(0,n) for j in range(0,len(Ajs))],
                              cat='Continuous')
    y0_vars = LpVariable.dicts("termIndependienteMilp",[(k,j) for k in range(0,1) for j in range(0,len(Ajs))],
                              cat='Continuous')

    #Armamos problema y definimos función objetivo
    prob=LpProblem("Particion",LpMinimize)

    prob += lpSum(e_vars[(i)] for i in range(0,len(A)))

    #Agregamos restricciones

    for i in range(0,len(A)):
        for j in range(0,len(Ajs)):
            ji=np.where([True if A[i] in l else False for l in Ajs])[0][0]
            if j!=ji:
                prob += e_vars[(i)] >=-(y_vars[0,ji]-y_vars[0,j])*A[i]+y0_vars[0,ji]-y0_vars[0,j]+1

    for i in range(0,len(A)):
        prob += e_vars[(i)]>=0

    resultado=prob.solve()
    #print(resultado)

    if resultado==-1:
        print("infactible")

    elif resultado not in [-1,1]:
        print("me rompi")

    else:
        error=0
        error_completo=[]
        for i in range(0,len(A)):
            error=error+e_vars[(i)].varValue
            error_completo=error_completo+[e_vars[(i)].varValue]
        y=[]
        y0=[]
        for j in range(0,len(Ajs)):
            coef=[]
            for d in range(0,n):
                coef=coef+[y_vars[d,j].varValue]
            y=y+[coef]
            y0=y0+[y0_vars[0,j].varValue]

        Res={"error": error,"y": y,"y0":y0,"Ajs":Ajs,"error completo":error_completo}
        return Res

## iv) Partition Consistency:
# * Reasigna puntos a su Dj correcto

def partition_consistency(dp,A):

    Ajs_actuales=dp["Ajs"]
    Ajs_nuevos=[[] for i in range(0,len(Ajs_actuales))]

    for j in range(0,len(Ajs_actuales)):
        for punto in Ajs_actuales[j]:
            #if dp["error completo"][np.where(np.array(A)==punto)[0][0]]>0:
            pasa=np.where([True if punto not in l else False for l in Ajs_actuales])[0][0]
            if ((dp["y"][j][0]-dp["y"][pasa][0])*punto-(dp["y0"][j]-dp["y0"][pasa]))>0:#puse un mayor igual
                Ajs_nuevos[j]=Ajs_nuevos[j]+[punto]
            else:
                Ajs_nuevos[pasa]=Ajs_nuevos[pasa]+[punto]

    Res={"Ajs":Ajs_nuevos,"y":dp["y"],"y0":dp["y0"]}
    return Res

# ## Fin del proceso

# Estos 4 puntos se repiten hasta que $\alpha$ sea 0 o se alcance el tiempo máximo.
def FourStepCriterion(inputs,respuesta,alpha,rho,n):
    iteracion=1
    #Generamos solución factible

    fs=feasible_sets(inputs,respuesta,h=10)
    A1,A2,B1,B2=fs["Ajs"][0],fs["Ajs"][1],fs["Bjs"][0],fs["Bjs"][1]
    A=A1+A2
    B=B1+B2
    dp=domain_partition(A,[A1,A2],n)
    pc=partition_consistency(dp,A)
    if dp["y"][0][0]==0:
        dp["y"][0][0]=0.000001
    if dp["y0"][1]==0 and dp["y"][1][0]==0:
        try:
            punto=max([x for x in inputs if x<=(dp["y0"][0]/dp["y"][0][0])])
        except:
            punto=dp["y0"][0]/dp["y"][0][0]
    #punto=dp["y0"][0]/dp["y"][0][0]
    A_sol=submodel_fitting_2(A1+A2,[A1,A2],[B1,B2],punto,n)
    A1_ganador=A1
    A2_ganador=A2
    B1_ganador=B1
    B2_ganador=B2
    error=A_sol["error"]

    while (alpha>=0.001):

        for count in range(1,6):
            if [] in pc["Ajs"]:
                #print("entre")
                fs=feasible_sets(inputs,respuesta,h=10-count)
                A1,A2,B1,B2=fs["Ajs"][0],fs["Ajs"][1],fs["Bjs"][0],fs["Bjs"][1]
                dp=domain_partition(A,[A1,A2],n)
                pc=partition_consistency(dp,A)
            if [] not in pc["Ajs"]:
                break

        if [] in pc["Ajs"]:
            print("soy lineal asecas")
            break

        if dp["y"][0][0]==0:
            dp["y"][0][0]=0.000001
        if dp["y0"][1]==0 and dp["y"][1][0]==0:
            try:
                punto=max([x for x in inputs if x<=(dp["y0"][0]/dp["y"][0][0])])
            except:
                punto=dp["y0"][0]/dp["y"][0][0]
        else:
            try:
                punto=max([x for x in inputs if x<=(dp["y0"][1]/dp["y"][1][0])])
            except:
                punto=dp["y0"][1]/dp["y"][1][0]
        #punto=dp["y0"][0]/dp["y"][0][0]
        #print(punto)

        A_sol=submodel_fitting_2(A1+A2,[A1,A2],[B1,B2],punto,n)
        alpha=0.99*(rho**(iteracion))
        iteracion=iteracion+1
        A1_sol={"Aj":A1,"coef":A_sol["coef"][0],'termInd':A_sol['termInd'][0]}
        A2_sol={"Aj":A2,"coef":A_sol["coef"][1],'termInd':A_sol['termInd'][1]}
        pp=point_partition(dp,alpha,A,B,[A1_sol,A2_sol])
        dp=domain_partition(A,pp["Ajs"],n)
        pc=partition_consistency(dp,A)
        A1=pc["Ajs"][0]
        A2=pc["Ajs"][1]
        B1=[B[np.where(np.array(A)==a)[0][0]] for a in A1]
        B2=[B[np.where(np.array(A)==a)[0][0]] for a in A2]

        if A_sol["error"]<=error:
            A1_ganador=A1
            A2_ganador=A2
            B1_ganador=B1
            B2_ganador=B2
            error=A_sol["error"]

        #print(f"error: {error}")

        #print(iteracion)

    A1=A1_ganador
    A2=A2_ganador
    B1=B1_ganador
    B2=B2_ganador
    dp=domain_partition(A,[A1,A2],n)
    if dp["y"][0][0]==0:
        dp["y"][0][0]=0.000001
    if dp["y0"][1]==0 and dp["y"][1][0]==0:
        try:
            punto=max([x for x in inputs if x<=(dp["y0"][0]/dp["y"][0][0])])
        except:
            punto=dp["y0"][0]/dp["y"][0][0]
    else:
        try:
            punto=max([x for x in inputs if x<=(dp["y0"][1]/dp["y"][1][0])])
        except:
            punto=dp["y0"][1]/dp["y"][1][0]
    A_sol=submodel_fitting_2(A1+A2,[A1,A2],[B1,B2],punto,n)
    A1_sol={"Aj":A1,"coef":A_sol["coef"][0],'termInd':A_sol['termInd'][0]}
    A2_sol={"Aj":A2,"coef":A_sol["coef"][1],'termInd':A_sol['termInd'][1]}

    return A1_sol,A2_sol,A1,A2,punto

# Plots

def plot_separability(inputs,respuesta,A1_sol,A2_sol,A1,A2,x=[-0.4, 1],y=[-5, 8]):

    objective_A1 = np.vectorize(lambda x: A1_sol["coef"]*x-A1_sol["termInd"])
    objective_A2 = np.vectorize(lambda x: A2_sol["coef"]*x-A2_sol["termInd"])
    A_nuevo=A1+A2
    Prediccion = list(objective_A1(np.array(A1)))+list(objective_A2(np.array(A2)))
    dp=domain_partition(A_nuevo,[A1,A2])
    print(f"El error de mala clasificacion es {dp['error']}")
    print(dp["y0"])
    objective_LS = np.vectorize(lambda x: dp["y"][0][0]*x-dp["y0"][0])
    LS = list(objective_LS(np.array(A_nuevo)))
    plt.scatter(A_nuevo, Prediccion)
    plt.plot(A_nuevo,LS, '-o',color="red")
    plt.plot(A_nuevo,LS, '-o',color="red")
    plt.ylim(y)
    plt.xlim(x)
    plt.show()

def plot_prediccion(inputs,respuesta,A1_sol,A2_sol,A1,A2):
    objective_A1 = np.vectorize(lambda x: A1_sol["coef"]*x-A1_sol["termInd"])
    objective_A2 = np.vectorize(lambda x: A2_sol["coef"]*x-A2_sol["termInd"])

    A_nuevo=A1+A2
    Prediccion = list(objective_A1(np.array(A1)))+list(objective_A2(np.array(A2)))

    plt.figure(figsize=(10,10))
    plt.plot(inputs, respuesta, 'o',color="lightgreen", markersize=12)
    plt.plot(A_nuevo, Prediccion, 'o', markersize=6)
    plt.show()


# -*- coding: utf-8 -*-
"""
common settings and a bit of infrastructure
"""
from .options import getParser

program_version = "1.5.7"

# pubchem url for retrieving sdf for numerical IDs
pubchem_url = (
    r"http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=%s&disopt=DisplaySDF"
)

_version_blurb = """
%(program_name)s version %(version)s

mol2chemfig generates chemfig code from molfiles.
For more information, type '%(program_name)s --help'.
"""

_lua_version_blurb = """
This is version %(client_version)s of %(program_name)s,
the Lua web client for the mol2chemfig server. The
server is running version %(server_version)s of mol2chemfig;
server and client version may differ.

%(program_name)s generates chemfig code from molfiles.
For more information, type '%(program_name)s --help'.
"""

_help_blurb = """
%(program_name)s version %(version)s, originally by Eric Brefo-Mensah and Michael Palmer;
Re-written in python3 by Nianze A. TAO (Omozawa SUENO) in 2021.*
*Visit https://augus1999.github.io/mol2chemfigPy3/ for more details.
%(program_name)s generates chemfig code from molfiles. Usage example:

%(program_name)s --angle=45 --aromatic-circles somefile.mol

Options:
"""

def version_text(program_name="mol2chemfigPy3", version=program_version) -> str:
    return _version_blurb % locals()

def help_text(program_name="mol2chemfigPy3", version=program_version) -> str:
    msg = _help_blurb % locals()
    msg += getParser().format_help(indent=32, linewidth=75, separator="")
    return msg

def lua_version_text(program_name, client_version) -> str:
    server_version = program_version
    return _lua_version_blurb % locals()

# the settings dict contains a number of fixed settings that can not
# be overridden from the command line. A copy of this dict will
# augmented with command line options and passed around during processing.

settings = dict(
    # input mode: auto, molfile, molblock, smilesfile, smiles
    input_mode="auto",
    # use relative angles
    relative_angles=False,
    # round bond lengths to this many decimal digits
    bond_round=3,
    # round angles to this many digits
    angle_round=1,
    # tolerance for angle impingement on atom quadrants, range 0 to 1
    quadrant_tolerance=0.1,
)

class MCFError(Exception):
    """
    this flags an anticipated error due to faulty user input.
    """

    def __init__(self, text: any):
        self.text = str(text)

    def __str__(self):
        return self.text

class Counter:
    """
    a simple Counter class, just to remove the dependency on version 2.7
    (which provides one in module collections)
    """

    def __init__(self, lst: list):
        self._d = {}

        for val in lst:
            if not (val in self._d):
                self._d[val] = 0

            self._d[val] += 1

    def most_common(self) -> any:
        """
        return the most common object

        :return: an object (any type)
        """
        lst = list(self._d.items())
        lst.sort(key=lambda pair: pair[1])

        return lst[-1][0]


import urllib,urllib2,re,xbmcplugin,xbmcgui,socket,xbmc,base64

def CATS():
        addDir('1) Featured Movies','http://www.thepiratecity.org/',5,'')
        addDir('2) All Movies','http://www.thepiratecity.org/search.htm',1,'')
        addDir('3) Action','http://www.thepiratecity.org/search.htm?cat=29&type=',1,'')
        addDir('4) Drama ','http://www.thepiratecity.org/search.htm?cat=33&type=',1,'')
        addDir('5) Family','http://www.thepiratecity.org/search.htm?cat=31&type=',1,'')
        addDir('6) Horror','http://www.thepiratecity.org/search.htm?cat=34&type=',1,'')
        addDir('7) Comedy','http://www.thepiratecity.org/search.htm?cat=32&type=',1,'')
        addDir('8) Sci-fi','http://www.thepiratecity.org/search.htm?cat=36&type=',1,'')
        addDir('9) Others','http://www.thepiratecity.org/search.htm?cat=37&type=',1,'')

def INDEX(data):
                #req = urllib2.Request(data)
                #req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
                #lemon = urllib2.urlopen(req);response=lemon.read();lemon.close()
                #url=re.compile('<a class="anc"  href="(.+?)\"').findall(response)
                #name=re.compile('_(.+?).htm').findall(str(url))
                #for n in range(0,len(url)):
                #        addDir(name[n],'http://www.thepiratecity.org/'+url[n],2,'')
        req = urllib2.Request(data)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        lemon = urllib2.urlopen(req);response=lemon.read();lemon.close()
        url=re.compile('<a class="anc"  href="(.+?)\"').findall(response)
        nameclean=re.compile('_(.+?).htm').findall(str(url))
        #Tidy names
        code=re.sub('_',' ',str(nameclean))
        code2=re.sub('  ',' - ',code)
        code3=re.sub(''','',code2)
        code4=re.sub('&','&',code3)
        code5=re.sub('é','e',code4)
        name=re.compile("'(.+?)'").findall(code5)
        #small ammendment - Voinage.
        for n in range(0,len(url)):
                addDir(name[n],'http://www.thepiratecity.org/'+url[n],2,"")

def INDEXF(data):
                req = urllib2.Request(data)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
                lemon = urllib2.urlopen(req);response=lemon.read();lemon.close()
                url=re.compile('').findall(response)
                name=re.compile('_(.+?).htm').findall(str(url))
                for n in range(0,len(url)):
                        addDir(name[n],'http://www.thepiratecity.org/'+url[n],2,'')

def ExtractMediaUrl(data):
        if len(data) > 0:
        			videoPath = ""
        			storeMessage = ""
        			alphabet = "abcdefghijklmnopqrstuvwxyz"
        			randomAlpha = ""
        			randomNumber = 0
        			storeMessage = data
        			switchOverDecoded = ""
        			keyPosition = 0
        			i = 0
        			j = 0

        			while i < 26:
        				if data[0] == alphabet[i]:
        					keyPosition = i
        				i = i + 1

        			i = 0

        			while i < 26:
        				randomAlpha = randomAlpha + alphabet[keyPosition]
        				keyPosition = keyPosition + 1
        				if keyPosition == 26:
        					keyPosition = 0
        				i = i + 1

        			i = 0

        			while i < len(storeMessage):
        				if (storeMessage[i] > "`" and storeMessage[i] < "{"):
        					j = 0
        					while j < 26:
        						if (storeMessage[i] == randomAlpha[j]):
        							switchOverDecoded = switchOverDecoded + alphabet[j]
        						j = j + 1
        				else:
        					switchOverDecoded = switchOverDecoded + storeMessage[i]
        				i = i + 1

        			storeMessage = switchOverDecoded[1:]
        			randomAlpha = ""
        			switchOverDecoded = ""
        			videoPath = storeMessage

        			return videoPath

        else:
            return ""

def VIDEO(url,name):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        lemon = urllib2.urlopen(req);response=lemon.read();lemon.close()
        vpageurl=re.compile('<iframe scrolling="no" frameborder="0" src="(.+?)\"').findall(response)
        req = urllib2.Request('http://www.thepiratecity.org/'+vpageurl[0])
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        lemon = urllib2.urlopen(req);response=lemon.read();lemon.close()
        match=re.compile('\r\nflashvars="myURL=(.+?)"').findall(response)
        link=ExtractMediaUrl(match[0])
        addLink(name+' - Flv',link,'')

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]

        return param

def addLink(name,url,iconimage):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok

def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

params=get_params()
url=None
name=None
mode=None
try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
#print "Mode: "+ str(mode)
#print "URL: "+str(url)
#print "Name: "+str(name)
if mode==None or url==None or len(url)<1:
        #print "CATEGORY INDEX : "
        CATS()
elif mode==1:
        INDEX(url)
elif mode==2:
        VIDEO(url,name)
elif mode==5:
        INDEXF(url)

xbmcplugin.endOfDirectory(int(sys.argv[1]))


#https://networkx.github.io/
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.colors as mc

def gen_color(G):
    colors = []
    for n in G:
        d=nx.get_node_attributes(G,'description')[n]
        if d == "Station":
            colors.append(mc.to_rgba('red'))
        elif d == "Slow down Tag":
            colors.append(mc.to_rgba('green'))
        else:
            colors.append(mc.to_rgba('gray'))
    return colors

G=nx.DiGraph()

# adding just one node:
G.add_nodes_from([1,4,5,6], description="Station")
G.add_node(2, description="Slow down Tag")
G.add_node(3, description="Bifurcation", merge_to_node=2)

G.add_edge(1, 2, length=10 )
G.add_edge(2, 3, length=5 )
G.add_edge(3, 4, length=10 )
G.add_edge(3, 5, length=10 )
G.add_edge(4, 6, length=17 )
G.add_edge(5, 6, length=10 )

pos = {1:(0,0),2:(10,0),3:(20,0),4:(30,10),5:(30,-10), 6:(40,-10)}

#col=mc.to_rgba('red')
#nx.draw(G, with_labels=True, pos =pos)

#print(nx.shortest_path(G, source=1, target=6,weight="length"))

im = plt.imread("AGV.png")

nx.draw_networkx(G, with_labels=True, pos =pos,node_color=gen_color(G))
#implot = plt.imshow(im, extent=[1,9,-5,5])
#plt.plot([0,25],[0,15])
plt.xlim((-5,45))
plt.ylim((-15,15))
plt.savefig("Map.png") # save as png
plt.show() # display

Prev Tests/Graph tests/00 Generate map.py


from __future__ import absolute_import

from datetime import datetime, timedelta
import time
import uuid

from sentry.testutils import APITestCase
from django.core.urlresolvers import reverse
from sentry.testutils import SnubaTestCase

class OrganizationDiscoverTest(APITestCase, SnubaTestCase):
    def setUp(self):
        super(OrganizationDiscoverTest, self).setUp()

        now = datetime.now()

        self.login_as(user=self.user)

        self.org = self.create_organization(owner=self.user, name='foo')

        self.project = self.create_project(
            name='bar',
            organization=self.org,
        )

        events = [{
            'event_id': uuid.uuid4().hex,
            'primary_hash': uuid.uuid4().hex,
            'project_id': self.project.id,
            'message': 'message!',
            'platform': 'python',
            'datetime': now.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
            'data': {
                'received': time.mktime(now.timetuple()),
                'exception': {
                    'values': [
                        {
                            'type': 'ValidationError',
                            'value': 'Bad request',
                            'mechanism': {
                                'type': '1',
                                'value': '1',
                            },
                            'stacktrace': {
                                'frames': [
                                    {
                                        'function': '?',
                                        'filename': 'http://localhost:1337/error.js',
                                        'lineno': 29,
                                        'colno': 3,
                                        'in_app': True
                                    },
                                ]
                            },
                        }
                    ]
                },
            },

        }]

        self.snuba_insert(events)

    def test(self):
        url = reverse('sentry-api-0-organization-discover', args=[self.org.slug])
        response = self.client.post(url, {
            'projects': [self.project.id],
            'fields': ['message', 'platform'],
            'start': (datetime.now() - timedelta(seconds=10)).strftime('%Y-%m-%dT%H:%M:%S'),
            'end': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
            'orderby': '-timestamp',
        })

        assert response.status_code == 200, response.content
        assert len(response.data['data']) == 1
        assert response.data['data'][0]['message'] == 'message!'
        assert response.data['data'][0]['platform'] == 'python'

    def test_array_join(self):
        url = reverse('sentry-api-0-organization-discover', args=[self.org.slug])
        response = self.client.post(url, {
            'projects': [self.project.id],
            'fields': ['message', 'exception_stacks.type'],
            'start': (datetime.now() - timedelta(seconds=10)).strftime('%Y-%m-%dT%H:%M:%S'),
            'end': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
            'orderby': '-timestamp',
        })
        assert response.status_code == 200, response.content
        assert len(response.data['data']) == 1
        assert response.data['data'][0]['exception_stacks.type'] == 'ValidationError'


kitapListesi=list()

menü ="""
[1] Kitap Ekle
[2] Kitap Çıkar
[3] Kitapları Listele
[Q] Çıkış

"""
def kitapEkle(kitap,liste):
    liste+=[kitap]
    print("Kitap Eklendi'")
    input("Ana menüye dönmek için 'enter' e basınız.")

def kitapCikar():
    pass

def listele(liste):
    for i in liste:
        print("Kitap Adı ----->>>>>    {}".format(i))
    input("Ana menüye dönmek için 'enter' e basınız. ")

def cik():
    quit()

while True:
    print(menü)
    secim=input("Seçiminiz: ")

    if secim=="1":
        kitapAdi=input("Kitap Adi: ")
        kitapEkle(kitapAdi,kitapListesi)

    elif secim=="2":
        kitapCikar()

    elif secim=="3":
        listele(kitapListesi)

    elif secim=="q" or secim=="Q":
        cik()

    else:
        print("Hatalı Girdiniz !")
        print("Ana menüye dönmek için 'enter' e basınız!")


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

def erosion(img, se):
    img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]

    rows, columns = img.shape
    output_img = np.zeros((rows, columns), dtype=np.uint8)

    for i in range(0, rows-se.shape[0]):
        for j in range(0, columns-se.shape[1]):
            cut_img = img[i:i + se.shape[0], j:j + se.shape[1]]
            nh_img = (cut_img * se)
            output_img[i, j] = np.min(nh_img)

    return output_img

def dilation(img, se):
    img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]

    rows, columns = img.shape
    output_img = np.zeros((rows, columns), dtype=np.uint8)

    for i in range(0, rows-se.shape[0]):
        for j in range(0, columns-se.shape[1]):
            cut_img = img[i:i + se.shape[0], j:j + se.shape[1]]
            nh_img =  (cut_img * se)
            output_img[i, j] = np.max(nh_img)

    return output_img

def Task_5a():
    # Load image
    img = cv2.imread('im.png', cv2.IMREAD_GRAYSCALE)

    # Structuring element
    se = np.ones((3,3), dtype=np.uint8)

    # Erosion and Dilation
    eroded_img = erosion(img, se)
    dilated_img = dilation(img, se)

    # Display results
    plt.figure(figsize=(10, 8))

    plt.subplot(2, 2, 1)
    plt.imshow(cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1], cmap='gray')
    plt.title('Before Erosion')

    plt.subplot(2, 2, 2)
    plt.imshow(eroded_img, cmap='gray')
    plt.title('After Erosion')

    plt.subplot(2, 2, 3)
    plt.imshow(dilated_img, cmap='gray')
    plt.title('After Dilation')

def Task_5b():
    # Load image
    img = cv2.imread('fingerprint.png', cv2.IMREAD_GRAYSCALE)

    # Structuring element
    se = np.ones((5,5), dtype=np.uint8)

    # cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]

    # Erosion and Dilation
    erosion_img = erosion(img, se)
    opening = dilation(erosion_img, se)

    dilation_img = dilation(opening, se)
    closing = erosion(dilation_img, se)

    # Display results
    plt.figure(figsize=(10, 8))

    plt.subplot(2, 2, 1)
    plt.imshow(cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1], cmap='gray')
    plt.title('Before Erosion')

    plt.subplot(2, 2, 2)
    plt.imshow(opening, cmap='gray')
    plt.title('After Opening')

    plt.subplot(2, 2, 3)
    plt.imshow(closing, cmap='gray')
    plt.title('After Closing')

def Task_5c():
    # Load image
    img = cv2.imread('boundary.png', cv2.IMREAD_GRAYSCALE)

    # Structuring element
    se = np.ones((10,10), dtype=np.uint8)

    # Erosion and Dilation
    erosion_img = erosion(img, se)
    boundary = img-erosion_img

    # Display results
    plt.figure(figsize=(10, 8))

    plt.subplot(2, 1, 1)
    plt.imshow(cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1], cmap='gray')
    plt.title('Original image')

    plt.subplot(2, 1, 2)
    plt.imshow(boundary, cmap='gray')
    plt.title('The boundary')

def main():
    # Task_5a()
    # Task_5b()
    Task_5c()
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    main()


import sys
sys.stdin = open('bj11724.txt','r')

def BFS(y,x,t):
    Que=[[y,x]]
    Map[y]=t
    Map[x]=t
    while Que:
        Q=[]
        for q in Que:
            for n in range(N):
                if m[q[1]][n] and not Map[n]:
                    Map[n]=t
                    Q.append([q[1],n])
        Que=Q

N,M=map(int,input().split())
Map=[0]*N
m=[[0]*N for _ in range(N)]
for i in range(M):
    y,x=map(int,input().split())
    m[y-1][x-1]=1
    m[x-1][y-1]=1
T,tmp=1,0
for i in range(N):
    Check=0
    for j in range(N):
        if m[i][j] and not Map[j]:
            Check=1
            BFS(i,j,T)
    if Check:T+=1
    if Map[i]==0:tmp+=1
print(T+tmp-1)

algoritm/20상반기 코딩테스트/연결 요소의 개수(BFS)/bj11724.py