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

import ispformat.schema as _schema
from jsonschema import Draft4Validator, RefResolver, draft4_format_checker
from jsonschema.exceptions import RefResolutionError, ValidationError
from urlparse import urlsplit

class MyRefResolver(RefResolver):
    def resolve_remote(self, uri):
        # Prevent remote resolving
        raise RefResolutionError("LOL NOPE")

geojson_allowed_types=('Polygon', 'MultiPolygon')
def validate_geojson_type(d):
    """
    Make sure a geojson dict only contains allowed geometry types
    """
    type_=d.get('type')
    if type_ not in geojson_allowed_types:
        return False
    return True

def validate_geojson(geodict):
    """
    Convenience function to validate a geojson dict
    """
    _version = 0.1
    schema = _schema.load_schema(_version, 'geojson/geojson')
    v = Draft4Validator(
        schema,
        resolver=MyRefResolver.from_schema(schema, store=_schema.deps_for_version(_version)),
        format_checker=draft4_format_checker,
    )

    for err in v.iter_errors(geodict):
        return False

    if not validate_geojson_type(geodict):
        return False

    return True

def validate_isp(jdict):
    """
    Validate a json-object against the isp json-schema
    """
    if not 'version' in jdict:
        raise ValidationError(u'version is a required property')
    try:
        schema=_schema.versions[jdict['version']]
    except (AttributeError, TypeError, KeyError):
        raise ValidationError(u'version %r unsupported'%jdict['version'])

    v=Draft4Validator(
        schema,
        resolver=MyRefResolver.from_schema(schema, store=_schema.deps_for_version(jdict['version'])),
        format_checker=draft4_format_checker,
    )

    for err in v.iter_errors(jdict):
        yield err

    def is_valid_url(u):
        try:
            pu=urlsplit(u)
        except:
            return False
        if pu.scheme not in ('', 'http', 'https'):
            return False
        if not pu.netloc:
            return False
        return True

    if 'website' in jdict and not is_valid_url(jdict['website']):
        yield ValidationError(u'%r must be an absolute HTTP URL'%u'website',
                              instance=jdict[u'website'], schema=schema[u'properties'][u'website'],
                              path=[u'website'], schema_path=[u'properties', u'website', u'description'],
                              validator=u'validate_url', validator_value=jdict['website'])

    if 'logoURL' in jdict and not is_valid_url(jdict['logoURL']):
        yield ValidationError(u'%r must be an absolute HTTP URL'%u'logoURL',
                              instance=jdict[u'logoURL'], schema=schema[u'properties'][u'logoURL'],
                              path=[u'logoURL'], schema_path=[u'properties', u'logoURL', u'description'],
                              validator=u'validate_url', validator_value=jdict['logoURL'])

    sch=schema[u'properties'][u'otherWebsites'][u'patternProperties'][u'^.+$']
    for name, url in jdict.get('otherWebsites', {}).iteritems():
        if is_valid_url(url):
            continue
        yield ValidationError(u'%r must be an absolute HTTP URL'%name,
                              instance=url, schema=sch, path=[u'otherWebsite', name],
                              schema_path=[u'properties', u'otherWebsites', u'patternProperties', u'^.+$', 'description'],
                              validator=u'validate_url', validator_value=url)

    for i, ca in enumerate(jdict.get('coveredAreas', [])):
        area=ca.get('area')
        if area and validate_geojson_type(area):
            continue
        elif not area:
            continue

        yield ValidationError(
            u'GeoJSON can only contain the following types: %s'%repr(geojson_allowed_types),
            instance=ca, schema=schema[u'definitions'][u'coveredArea'][u'properties'][u'area'],
            path=['coveredAreas', i, 'area'],
            schema_path=[u'properties', u'coveredAreas', u'items', u'properties', u'area'],
            validator=u'validate_geojson_type', validator_value=ca
        )


'''
Find the nearest smaller numbers on left side in an array
Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.
Examples:

Input:  arr[] = {1, 6, 4, 10, 2, 5}
Output:         {_, 1, 1,  4, 1, 2}
First element ('1') has no element on left side. For 6,
there is only one smaller element on left side '1'.
For 10, there are three smaller elements on left side (1,
6 and 4), nearest among the three elements is 4.

Input: arr[] = {1, 3, 0, 2, 5}
Output:        {_, 1, _, 0, 2}
Expected time complexity is O(n).

https://www.geeksforgeeks.org/find-the-nearest-smaller-numbers-on-left-side-in-an-array/
'''

array = [1, 6, 4, 10, 2, 5]
stack = []

for element in array:

    while (stack and stack[-1] > element):
        stack.pop()

    print(stack[-1] if stack else "_")

    stack.append(element)


# version: python 3.7
# zID: z5052292

from socket import *
from datetime import datetime
import time
import sys

serverIP = sys.argv[1]
serverPort = int(sys.argv[2])
clientSocket = socket(AF_INET, SOCK_DGRAM)
list_rtts = []
packets_lost = 0

for i in range(10):
	time_stamp = datetime.now().isoformat(sep=' ')[:-3]
	ping_message = "PING" + str(i) + ' ' + time_stamp + '\r\n'
	time_send = datetime.now()
	clientSocket.sendto(ping_message.encode(), (serverIP, serverPort))

	try:
		clientSocket.settimeout(1)
		response, severAddress = clientSocket.recvfrom(2048)
		time_receive = datetime.now()
		rtt = round((time_receive - time_send).total_seconds() * 1000)
		list_rtts.append(rtt)
		print(f'Ping to {serverIP}, seq = {i}, rtt = {rtt} ms')
		clientSocket.settimeout(None)

	except timeout:
		packets_lost += 1
		print(f'Ping to {serverIP}, seq = {i}, rtt = time out')

print("\n")
print(f'Minimun RTT = {min(list_rtts)} ms')
print(f'Maximun RTT = {max(list_rtts)} ms')
print(f'Average RTT = {round(float(sum(list_rtts)/len(list_rtts)))} ms')
print(f'10 packets transmitted, {10 - int(packets_lost)} packets received, {float(packets_lost) / 10 * 100}% of packets loss.')
clientSocket.close()


"""Conceptual model page."""

from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel

class CMPage(Page):

    template = "ecos_cm/cm_page.html"

    ECOLOGICAL_PROCESSES = "ecological processes"
    TARGET_SPECIES = "target species"

    CONCELTUAL_MODEL_TYPE_CHOICES = [
        (ECOLOGICAL_PROCESSES,'ecological processes'),
        (TARGET_SPECIES, 'target species'),
    ]
    conceptual_model_type = models.CharField(
      choices=CONCELTUAL_MODEL_TYPE_CHOICES,
      max_length=100,
      default=ECOLOGICAL_PROCESSES,
    )

    cm_title = models.CharField(max_length=300, null=True, blank=True)
    cm_image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=False,
        on_delete=models.SET_NULL,
        related_name="+"
    )

    cm_human_interactions = RichTextField( null=True, blank=True)
    cm_ecolagical_processes = RichTextField( null=True, blank=True)
    cm_oceanographic_variables = RichTextField( null=True, blank=True)
    cm_performance_indicators = RichTextField( null=True, blank=True)

    content_panels = Page.content_panels + [
        FieldPanel("conceptual_model_type"),
        FieldPanel("cm_title"),
        ImageChooserPanel("cm_image"),
        FieldPanel("cm_human_interactions"),
        FieldPanel("cm_ecolagical_processes"),
        FieldPanel("cm_oceanographic_variables"),
        FieldPanel("cm_performance_indicators"),
    ]


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

import SPARQLWrapper

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def select_example():
	sparql = SPARQLWrapper.SPARQLWrapper("http://vocabs.ardc.edu.au/repository/api/sparql/csiro_international-chronostratigraphic-chart_geologic-time-scale-2020")
	sparql.setReturnFormat(SPARQLWrapper.JSON)

	# Gets the first 3 geological ages from a Geological Timescale database, via a SPARQL endpoint.
	sparql.setQuery("""
PREFIX gts: <http://resource.geosciml.org/ontology/timescale/gts#>

SELECT *
WHERE {
	?a a gts:Age .
}
ORDER BY ?a
LIMIT 3
"""
	)

	try:
		ret = sparql.queryAndConvert()

		for r in ret["results"]["bindings"]:
			print(r)
	except Exception as ex:
		print(ex)

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def ask_example():
	sparql = SPARQLWrapper.SPARQLWrapper("http://dbpedia.org/sparql")
	sparql.setQuery("""
ASK WHERE {
	<http://dbpedia.org/resource/Asturias> rdfs:label "Asturias"@es
}
"""
	)
	sparql.setReturnFormat(SPARQLWrapper.XML)

	try:
		results = sparql.query().convert()
		print(results.toxml())
	except Exception as ex:
		print(ex)

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def construct_example():
	sparql = SPARQLWrapper.SPARQLWrapper("http://dbpedia.org/sparql")

	sparql.setQuery("""
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX sdo: <https://schema.org/>

CONSTRUCT {
	?lang a sdo:Language ;
	sdo:alternateName ?iso6391Code .
}
WHERE {
	?lang a dbo:Language ;
	dbo:iso6391Code ?iso6391Code .
	FILTER (STRLEN(?iso6391Code)=2)  # To filter out non-valid values.
}
LIMIT 3
"""
	)

	try:
		results = sparql.queryAndConvert()
		print(results.serialize())
	except Exception as ex:
		print(ex)

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def describe_example():
	sparql = SPARQLWrapper.SPARQLWrapper("http://dbpedia.org/sparql")
	sparql.setQuery("DESCRIBE <http://dbpedia.org/resource/Asturias>")

	try:
		results = sparql.queryAndConvert()
		print(results.serialize(format="json-ld"))
	except Exception as ex:
		print(ex)

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def update_example():
	sparql = SPARQLWrapper.SPARQLWrapper("https://example.org/sparql")
	sparql.setHTTPAuth(SPARQLWrapper.DIGEST)
	sparql.setCredentials("some-login", "some-password")
	sparql.setMethod(SPARQLWrapper.POST)

	sparql.setQuery("""
PREFIX dbp:  <http://dbpedia.org/resource/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

WITH <http://example.graph>
DELETE {
	dbo:Asturias rdfs:label "Asturies"@ast
}
"""
	)

	try:
		results = sparql.query()
		print(results.response.read())
	except Exception as ex:
		print(ex)

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def SPARQLWrapper2_example():
	sparql = SPARQLWrapper.SPARQLWrapper2("http://dbpedia.org/sparql")
	sparql.setQuery("""
PREFIX dbp:  <http://dbpedia.org/resource/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT ?label
WHERE {
	dbp:Asturias rdfs:label ?label
}
LIMIT 3
"""
	)

	try:
		for result in sparql.query().bindings:
			print(f"{result['label'].lang}, {result['label'].value}")
	except Exception as ex:
		print(ex)

# REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html
def partial_interpretation_of_results():
	sparql = SPARQLWrapper.SPARQLWrapper2("http://example.org/sparql")
	sparql.setQuery("""
SELECT ?subj ?prop
WHERE {
	?subj ?prop ?obj
}
"""
	)

	try:
		ret = sparql.query()
		print(ret.variables)  # This is an array consisting of "subj" and "prop".
		for binding in ret.bindings:
			# Each binding is a dictionary. Let us just print the results.
			print(f"{binding['subj'].value}, {binding['subj'].type}")
			print(f"{binding['prop'].value}, {binding['prop'].type}")
	except Exception as ex:
		print(ex)

	#-----
	sparql.setQuery("""
SELECT ?subj ?obj ?opt
WHERE {
	?subj <http://a.b.c> ?obj .
	OPTIONAL {
		?subj <http://d.e.f> ?opt
	}
}
"""
	)

	try:
		ret = sparql.query()
		print(ret.variables)  # This is an array consisting of "subj", "obj", "opt".
		if ("subj", "prop", "opt") in ret:
			# There is at least one binding covering the optional "opt", too.
			bindings = ret["subj", "obj", "opt"]
			# Bindings is an array of dictionaries with the full bindings.
			for b in bindings:
				subj = b["subj"].value
				o = b["obj"].value
				opt = b["opt"].value

				# Do something nice with subj, o, and opt.

		# Another way of accessing to values for a single variable: take all the bindings of the "subj", "obj", "opt".
		subjbind = ret.getValues("subj")  # An array of Value instances.
		objbind = ret.getValues("obj")  # An array of Value instances.
		optbind = ret.getValues("opt")  # An array of Value instances.
	except Exception as ex:
		print(ex)

def dbpedia_test():
	sparql = SPARQLWrapper.SPARQLWrapper("http://dbpedia.org/sparql")
	sparql.setReturnFormat(SPARQLWrapper.JSON)

	if True:
		sparql.setQuery("""
SELECT ?uri ?name ?page ?nick
WHERE {
	?uri a foaf:Person ;
	foaf:name ?name;
	foaf:page ?page;
	foaf:nick ?nick.
}
LIMIT 100
"""
		)
	elif False:
		sparql.setQuery("""
SELECT ?name ?birth ?role
WHERE{
	?x a foaf:Person ;
	dbpprop:fullname ?name;
	dbpprop:countryofbirth ?birth;
	dbpprop:role ?role.

	FILTER regex(?birth, "land$").
	FILTER regex(?birth, "^Eng").
	FILTER regex(?birth, "England").
} LIMIT 100
"""
		)

	try:
		ret = sparql.queryAndConvert()
		print(ret["results"]["bindings"])
	except Exception as ex:
		print(ex)

def dbpedia_ko_test():
	sparql = SPARQLWrapper.SPARQLWrapper("http://ko.dbpedia.org/sparql")
	sparql.setReturnFormat(SPARQLWrapper.JSON)

	if False:
		sparql.setQuery("""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://ko.dbpedia.org/property/>

SELECT DISTINCT ?comment
WHERE {
	?s foaf:name ?name;
	rdfs:comment ?comment;
	dbp:occupation ?occupation.
	FILTER(REGEX(STR(?occupation), '정치'))
}
LIMIT 30
"""
		)
	elif False:
		sparql.setQuery("""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://ko.dbpedia.org/property/>

SELECT ?comment, ?relative, ?parent
WHERE {
	?s foaf:name ?name;
	rdfs:comment ?comment.
	FILTER(STR(?name) = '하정우')
	OPTIONAL{?relative dbo:relative ?s.}
	OPTIONAL{?parent dbo:child ?s.}
}
LIMIT 30
"""
		)
	elif True:
		sparql.setQuery("""
select * where {
	?s <http://ko.dbpedia.org/property/장소> ?o
} LIMIT 100
"""
		)
	elif False:
		sparql.setQuery("""
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://ko.dbpedia.org/property/>
PREFIX res: <http://ko.dbpedia.org/resource/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

select * where {
	?s rdf:type foaf:Person.
	?s <http://ko.dbpedia.org/property/국가> '대한민국'@ko.
}
"""
		)
	elif False:
		sparql.setQuery("""
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://ko.dbpedia.org/property/>
PREFIX res: <http://ko.dbpedia.org/resource/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
select count(*) where {
	?s rdf:type foaf:Person.
	{?s dbp:출생일 ?Bdate.} UNION {?s dbp:사망일 ?Ddate.}
	?s dbo:abstract ?abstract.
	?s dbp:국적 ?nation.
}
"""
		)

	try:
		ret = sparql.queryAndConvert()
		print(ret["results"]["bindings"])
	except Exception as ex:
		print(ex)

def main():
	#select_example()
	#ask_example()
	#construct_example()
	#describe_example()
	#update_example()

	#SPARQLWrapper2_example()

	#partial_interpretation_of_results()

	#-----
	dbpedia_test()
	dbpedia_ko_test()

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

if "__main__" == __name__:
	main()


import numpy as np
import matplotlib.pyplot as plt
from tqdm.auto import tqdm

"""
Reads Siemens rawdata file and returns the DICOs values
Author: Ali Aghaeifar <ali.aghaeifar@tuebingen.mpg.de>
"""

def read_dico(twixObj):
    mdb_vop = [mdb for mdb in twixObj[-1]['mdb'] if mdb.is_flag_set('MDH_VOP')]
    # concatenate segments of RFs longer than 1ms
    DICO_comb = []
    for mdb in tqdm(mdb_vop, desc='Reading DICO'):
        if mdb.mdh.Counter.Ide == 0:
            DICO_comb.append(mdb.data)
        else:
            DICO_comb[-1] = np.concatenate((DICO_comb[-1],mdb.data), axis=1)

    DICO = []
    shapes = [dico.shape for dico in DICO_comb]  # all shapes
    shapes = sorted(set(shapes), key=shapes.index)  # unique shapes
    for i, shape in enumerate(shapes):
        temp = [dico for dico in tqdm(DICO_comb, desc=f'RF Pulse {i}') if dico.shape == shape]
        DICO.append(np.stack(temp, axis=-1))

    forward = [dico_frw[::2] for dico_frw in DICO]
    reflect = [dico_rfl[1::2] for dico_rfl in DICO]

    return forward, reflect

# memory optimized version, but slower. Only save integral of forward signal
def read_dico_memOpt(twixObj):
    mdb_vop = [mdb for mdb in twixObj[-1]['mdb'] if mdb.is_flag_set('MDH_VOP')]
    forward_integral = []
    forward_length = []
    for mdb in tqdm(mdb_vop, desc = 'Reading DICO'):
        DICO_integral = np.sum(np.abs(mdb.data[::2]), axis=1)
        DICO_length = mdb.data.shape[1]
        if mdb.mdh.Counter.Ide == 0:
            forward_integral.append(DICO_integral)
            forward_length.append(DICO_length)
        else:
            forward_integral[-1] = forward_integral[-1] + DICO_integral
            forward_length[-1] = forward_length[-1] + DICO_length

    forward_integral = np.stack(forward_integral, axis=-1)

    # split RFs with different lengths
    forward_length_unq = sorted(set(forward_length), key=forward_length.index)
    forward_integral   = [forward_integral[:, np.where(np.array(forward_length) == l)[0]] for l in forward_length_unq]

    return forward_integral, forward_length_unq

def plot_drift(twixObj):
    forward_integral, _ = read_dico_memOpt(twixObj)
    for dico in forward_integral:
        _, ax = plt.subplots()
        ax.plot(forward_integral[0].squeeze().T)
    plt.show()


from tkinter import Tk, StringVar, Label, Button, Entry, filedialog, W
from os.path import exists
import generator as gp

def cmdExec():
    if checkFileExist(textIn.get()) and checkFileExist(textOut.get()):
        result.set("Gerando planilha de presença ...")
        isSuccess = gp.main(textIn.get(), textOut.get())
        if isSuccess:
            result.set("Planilha de presença gerada com successo")
        else:
            result.set("Ocorreu um erro ao tentar gerar a planilha de presença")

def checkFileExist(file):
    if(file != ""):
        name  = file.split('/')
        if exists(file):
            return True
        result.set(f"Erro: Arquivo de {name[-1]} não encontrado")
        return False
    result.set("Erro: Campo vazio")
    return False

def cmdSearchFileIn():
    filename = filedialog.askopenfilename()
    result.set("")
    textIn.set(filename)

def cmdSearchFileOut():
    filename = filedialog.askopenfilename()
    result.set("")
    textOut.set(filename)

screen = Tk()
screen.title("Gerador de Lista de Presença")
textIn = StringVar()
textOut = StringVar()
result = StringVar()

# pos screen
width, height = 500, 200
widthScreen = screen.winfo_screenwidth()
heightScreen = screen.winfo_screenheight()

posX = int(widthScreen/2 - width/2)
posY = int(heightScreen/2 - height/2)

screen.geometry(f"{width}x{height}+{posX}+{posY}")

# Labels
labelFileIn = Label(screen, text="Escolha o arquivo de entrada:").grid(row=0, sticky=W)
labelFileOut = Label(screen, text="Escolha o arquivo de saída:").grid(row=2, sticky=W)
labelResult = Label(screen, textvariable=result).grid(row=5, pady=10)

# Text box
textBoxFileIn = Entry(screen, textvariable=textIn).grid(row=1, padx=5, pady=5 ,ipadx=120)
textBoxFileOut = Entry(screen, textvariable=textOut).grid(row=3, padx=5, pady=5, ipadx=120)
# Butões
btnSearchFileIn = Button(screen, text= "Buscar", command=cmdSearchFileIn).grid(row=1, column=1)
btnSearchFileOut = Button(screen, text= "Buscar", command=cmdSearchFileOut).grid(row=3, column=1)
btnExec = Button(screen, text= "Executar", command=cmdExec).grid(row=4, pady=10)

screen.mainloop()


# accepted on codewars.com
import random
import math
import time

conflicts_threshold = 3

# main method
def solve_n_queens(size, mandatory_coords):

    # here we use the simple bactracking
    if size <= 10:
        answer = queens_backtrack(size, mandatory_coords)
        return get_string_of_queens(size, answer) if answer is not None else None

    attempts_made = 1

    while True:

        partial_sol = generate_greed(size, mandatory_coords)
        solution = conflicts_solver(partial_sol, size, mandatory_coords)

        if not solution and (attempts_made <= 15):
            # print(str(size) + ": no solution been found", sep='')
            attempts_made += 1
        else:
            if attempts_made <= 15:
                # print(str(size) + ": SOLUTION BEEN FOUND!!!", sep='')
                # print("Time elapsed: ", time.time() - start, "seconds.")
                return get_string_of_queens(size, solution)
            else:
                # print(str(size) + ": Tries ended up", sep='')
                # print("Time elapsed", time.time() - start, "seconds.")
                return None

# here we are building a partial solution for the task given
def generate_greed(n, mandatory: list[int]):
    # initializating
    positions = [-1] * n
    verticals = [-1] * n
    diagonals = [[0 for x in range((2 * n) - 1)] for y in range(2)]

    # mandatory queen
    positions[mandatory[0]] = mandatory[1]
    verticals[mandatory[1]] = 1
    diagonals[0][mandatory[0] + mandatory[1]] = 1
    diagonals[1][n - 1 + mandatory[0] - mandatory[1]] = 1

    marked_rows = []
    cols = set()

    for c in range(n):
        if c == mandatory[1]:
            continue
        cols.add(c)

    for row in range(n):
        if row == mandatory[0]:
            continue

        for col in cols:

            if (diagonals[0][row + col] == 0) and (diagonals[1][row + ((n - 1) - col)] == 0):
                positions[row] = col
                verticals[col] = 1
                diagonals[0][row + col] = 1
                diagonals[1][row + ((n - 1) - col)] = 1
                cols.remove(col)
                break

        if positions[row] == -1:
            marked_rows.append(row)

    for row in marked_rows:
        col = cols.pop()
        positions[row] = col
        verticals[col] = 1
        diagonals[0][row + col] += 1
        diagonals[1][row + ((n - 1) - col)] += 1

    return [positions, verticals, diagonals]

# now fixing the prev solution, the way is: min conflicts algorithm
def conflicts_solver(queens, size, mandatory):
    diagonals = queens.pop()
    verticals = queens.pop()
    positions = queens.pop()
    length = len(positions)

    problem_cols = get_conflicts([positions, verticals, diagonals], mandatory)

    swaps_counter = 0
    err_flag = False

    def place(r, c):
        verticals[c] -= 1
        diagonals[0][r + c] -= 1
        diagonals[1][r + ((length - 1) - c)] -= 1

    def displace(r, new_c):
        verticals[new_c] += 1
        diagonals[0][r + new_c] += 1
        diagonals[1][r + ((length - 1) - new_c)] += 1

    while problem_cols:

        random.shuffle(problem_cols)
        row = problem_cols.pop()
        conflicts = []
        min_conflicts = []
        the_min = math.inf

        for col in range(length):

            if col == mandatory[1]:
                conflicts.append(0)
                continue

            conflicts.append(0)
            conflicts[col] += verticals[col]
            conflicts[col] += diagonals[0][row + col]
            conflicts[col] += diagonals[1][row + ((length - 1) - col)]

            if col == positions[row]:
                conflicts[col] = math.inf

            if conflicts[col] < the_min:
                min_conflicts = []
                the_min = conflicts[col]

            if conflicts[col] == the_min:
                min_conflicts.append(col)

        # now let's swap
        random.shuffle(min_conflicts)
        swap = min_conflicts.pop()
        col = positions[row]

        place(row, col)

        displace(row, swap)

        positions[row] = swap

        # restriction for no solution or bad variation
        if swaps_counter < size * conflicts_threshold:
            problem_cols = get_conflicts([positions, verticals, diagonals], mandatory)
        else:
            err_flag = True
            break

        swaps_counter += 1

    return [] if err_flag else positions

# getting all the queens in conflicts:
def get_conflicts(array, mandatory):
    diagonals = array.pop()
    verticals = array.pop()
    positions = array.pop()

    length = len(positions)
    conflicts = []

    for col in range(length):

        if col != mandatory[1]:

            row = positions[col]

            if verticals[row] > 1 or diagonals[0][row + col] > 1 or diagonals[1][col + ((length - 1) - row)] > 1:
                conflicts.append(col)  # col

    return conflicts

# translating the coords to string
def get_string_of_queens(size, sol):
    res = ''

    for coords in sol:
        res += '.' * coords + 'Q' + '.' * (size - 1 - coords) + '\n'

    return res

flag_of_rec_stop: bool  # 36 366 98 989
result: list

# bactracking auxiliary method
def queens_backtrack(n: int, mandatory):
    global flag_of_rec_stop, result

    result = []
    flag_of_rec_stop = False

    def recursive_seeker(row: int, vertical_set: list[int],
                         diag1_set: set[int], diag2_set: set[int],
                         board_size: int) -> None:
        global flag_of_rec_stop, result

        # jumping over the mandatory queen
        if row == mandatory[0]:
            recursive_seeker(row + 1, vertical_set + [mandatory[1]], diag1_set, diag2_set, board_size)

        # finishing all the branches of recursion tree
        if flag_of_rec_stop:
            return

        # catching the result
        if row == board_size:
            for i in range(board_size):
                if i == mandatory[0]:
                    result.append(mandatory[1])
                else:
                    result.append(vertical_set[i])

            flag_of_rec_stop = True
            return

        # cycling all over the possible vertical coords:
        for i in range(board_size):
            if i not in (vertical_set + [mandatory[1]]) and row + i not in diag1_set and row - i not in diag2_set:
                new_vertical_set = list(vertical_set)
                new_diag1_set = set(diag1_set)
                new_diag2_set = set(diag2_set)

                new_vertical_set.append(i)
                new_diag1_set.add(row + i)
                new_diag2_set.add(row - i)

                recursive_seeker(row + 1, new_vertical_set, new_diag1_set, new_diag2_set, board_size)
                # no need to bactrack coz of creating new sets

    recursive_seeker(0, [], {mandatory[0] + mandatory[1]}, {mandatory[0] - mandatory[1]}, n)

    return result if len(result) > 0 else None

start = time.time_ns()

print(solve_n_queens(100, [1, 2]))

finish = time.time_ns()

print(f'Time costs: {(finish - start) // 10 ** 6} milliseconds')


# 피보나치 수열
import sys

input = sys.stdin.readline

n = int(input())

# 1번과 2번 더하면 3번, 2번과 3번 더하면 4번.. 이러한 방법이므로
# A는 B의 값을 받고, B는 A의 값을 더해서 받는다.
# 최종 결과값은 A
A = 0
B = 1

for i in range(n):
    A, B = B, B+A

print(A)


import os, sys
import multiprocessing as mp

def pipeline(config, genome, protocol, cells, minreads, name, fq1, fq2, dir,
             top_million_reads, step, parallel):
    """
    Run the Data Processing Pipeline...

    #. Stats and count the barcode from pair-end 1 sequences;
    #. Read the barcode counts files;
    #. Correct the barcode with 1bp mismatch;
    #. Stats the mismatch barcode reads and sequences;
    #. Determine wheather mutate on the last base (show A/T/C/G with similar ratio at the last base);
    #. Filter by whitelist;
    #. Filter by read counts (>=min_reads);
    #. Print the number of barcode and reads retained after each steps.

    Usage:
    ::
        from baseqDrops import pipeline
        pipeline("", "hg38", "10X", 1000, minreads, name, fq1, fq2, dir, top_million_reads, step, parallel)

        #specify the length of UMI and barcodes
        pipeline("", "hg38", "10X", 1000, minreads, name, fq1, fq2, dir, top_million_reads, step, parallel)

        #Run in command line
        baseqdrops

    Protocols:

    #. For 10X: 16bp Barcode and 10 bp UMI => 10X (most commonly used)
    #. For 10X: 14bp Barcode and 5/10 bp UMIs => 10X_14_10 / 10X_14_5 (For some old version data)
    #. For DropSeq ==> dropseq
    #. For inDrop ==> indrop

    Args:
        config: The path of configuration file;
        genome: Genome version (hg38, mm10, hg38_mm10);
        cells: Max number of cells;
        minreads: Minimum number of reads for a cell barcode (10000);
        name: Samplename;
        fq1, fq2: Path to fastq reads;
        dir: The folder for processing, a folder with samplename will be created;
        top_million_reads: Number of reads used for processing in Million;
        step: Steps to run;
        parallel: How many thread to use;

    Steps:
        count
        stats
        split
        star
        tagging
        table
    """

    from . import count_barcode
    from . import valid_barcode
    from . import split_by_barcode
    from .barcode.split_fast import split_by_barcode_faster
    from .tagging.prime3 import check_reference_files

    #Set Config Files...
    if config:
        if not os.path.exists(config):
            sys.exit("[error] The config file does not exist in: {}!".format(config))
        os.environ["BASEQCFG"] = config

    #Check Annotation Files
    print('[info] Checking Reference Files...')
    check_reference_files(genome)

    print('[info] Start Processing Your RNA-Seq Dataset ...')

    dir = os.path.abspath(os.path.join(dir, name))
    bc_counts = os.path.join(dir, "barcode_count_{}.csv".format(name))
    bc_stats = os.path.join(dir, "barcode_stats_{}.csv".format(name))
    bc_splits_dir = os.path.join(dir, "barcode_splits")
    align_dir = os.path.join(dir, "star_align")
    tagging_dir = os.path.join(dir, "read_tagging")
    tpm_table = os.path.join(dir, "Result.UMIs.{}.txt".format(name))
    reads_table = os.path.join(dir, "Result.Reads.{}.txt".format(name))

    from itertools import product
    barcode_prefix = [x[0] + x[1] for x in list(product('ATCG', repeat=2))]

    dirs = [dir, align_dir, tagging_dir, bc_splits_dir]

    for dir in dirs:
        if not os.path.exists(dir):
            os.mkdir(dir)

    #Check the existance of the files
    if not os.path.exists(fq1):
         sys.exit("[error] Fastq-1 does not exist!")

    if not os.path.exists(fq2):
         sys.exit("[error] Fastq-2 does not exist!")

    #count barcode
    if step in ["all", "count"]:
        print("[info] Counting the barcodes ...")
        count_barcode(fq1, bc_counts, protocol, min_reads=50, topreads=int(top_million_reads))

    #aggregate
    if step in ["all", "stats"]:
        print("[info] Aggregating the barcodes errors and get valid ones ...")
        valid_barcode(protocol, bc_counts, max_cell=cells, min_reads=minreads, output=bc_stats)

    #barcode split
    if step in ["all", "split"]:
        print("[info] Split the barcode for each Barcode Prefix ...")
        split_by_barcode_faster(name, protocol, bc_stats, fq1, fq2,
            bc_splits_dir, int(top_million_reads))

    #run alignment
    if step in ["all", "star"]:
        from .star import star_align
        star_align(bc_splits_dir, align_dir, name, genome, parallel=int(parallel))

    #run reads tagging
    if step in ["all", "tagging"]:
        from .tagging.prime3 import tagging_reads
        print('[info] Tagging the reads to genes...')
        pool = mp.Pool(processes=int(parallel))
        result = []
        for bc in barcode_prefix:
            bamfile = os.path.join(align_dir, "{}/{}.sort.bam".format(bc, bc))
            outfile = os.path.join(tagging_dir, "tagging.{}.txt".format(bc))
            #tagging_reads(genome, bamfile, outfile)
            result.append(pool.apply_async(tagging_reads, (genome, bamfile, outfile,)))
        pool.close()
        pool.join()

    #run Table aggragation
    if step in ["all", "table"]:
        print('[info] Build gene expression table from the tagging files...')

        from .aggregate import read_barcode_gene_file, write_to_table
        pool = mp.Pool(processes=int(parallel))
        result = []
        for bc in barcode_prefix:
            filepath = os.path.join(tagging_dir, "tagging.{}.txt".format(bc))
            result.append(pool.apply_async(read_barcode_gene_file, (filepath, 1)))
        pool.close()
        pool.join()

        from itertools import chain
        barcodes_all = [x.get()[0] for x in result]
        barcodes_lists = list(chain(*barcodes_all))

        exp = {}
        UMIs_all = [x.get()[1] for x in result]
        for UMI in UMIs_all:
            for gene in UMI:
                if gene in exp:
                    exp[gene].update(UMI[gene])
                else:
                    exp[gene] = UMI[gene]
        write_to_table(barcodes_lists, exp, tpm_table, "UMI Table")

        exp = {}
        Reads_all = [x.get()[2] for x in result]
        for UMI in Reads_all:
            for gene in UMI:
                if gene in exp:
                    exp[gene].update(UMI[gene])
                else:
                    exp[gene] = UMI[gene]
        write_to_table(barcodes_lists, exp, reads_table, "Read Count Table")

if __name__ == "__main__":
    print("begin running pipeline")


from ast import Tuple
from app.screen.titled_screen import TitledScreen
from app.globals import State, MovieService, TheatreService, BookingService
from core.viewmodels import Ticket
from core.utils import TheatreUtils

class TicketManagementScreen(TitledScreen):
    def __init__(self):
        super().__init__("Ticket", "Management")
        self.options = [self.change_owner, self.change_time]
        self.option_names = ["Change owner", "Select new time"]

    def fetch_ticket(self) -> Tuple(Ticket, bool):
        ticket = None
        while True:
                t_id = input("Enter ticket id (Enter 0 to exit): ")
                if not t_id.isdigit():
                    print("Enter a valid ticket id")
                    continue
                t_id = int(t_id)
                if t_id == 0:
                    return ticket, True
                ticket = BookingService.get(t_id)
                if ticket.id != t_id:
                    print("Ticket #", t_id, " does not exist")
                    continue
                break
        return ticket, False

    def deregister_ticket(self, ticket):
        TheatreService.deregister_ticket(ticket)

    def register_ticket(self, ticket):
        TheatreService.register_ticket(ticket)
        BookingService.update(ticket)

    def change_owner(self, ticket):
        while True:
            name = input("Enter your name (Enter \"exit\" to cancel): ")
            confirm = input(f"Are you sure you want to change {ticket.owner} to {name}? (Enter \"yes\" to confirm): ")
            if confirm != "yes":
                continue
            self.deregister_ticket(ticket)
            ticket.owner = name
            self.register_ticket(ticket)
            print("Ticket Successfully registered")
            return
        pass

    def check_if_seats_available(self, ticket: Ticket, date: str, time: str) -> bool:
        theatreB = TheatreService.get(ticket.movie, date, time)
        seats = theatreB.seats
        for seat in ticket.seats:
            row, col = TheatreUtils.split_seat(seat)
            r_int = TheatreUtils.letter_to_index(row)
            c_int = col - 1
            if seats[r_int][c_int] == True:
                return False
        return True

    def change_time(self, ticket: Ticket):
        times = ["2PM", "5PM", "8PM"]
        print("Available times")
        for idx, time in enumerate(times):
            print(idx + 1, time)

        while True:
            user_choice = input("Select a time (Enter \"exit\" to cancel): ")
            if user_choice == "exit":
                return

            if not user_choice.isdigit():
                print("Enter a valid number")
                continue

            user_choice = int(user_choice)
            if user_choice > len(times) or user_choice <= 0:
                print("Enter a valid option")
                continue
            time = times[user_choice - 1]
            if time == ticket.time:
                print("Select a different time than displayed on the ticket")
                continue

            if not self.check_if_seats_available(ticket, ticket.date, time):
                print("Seats displayed on the ticket are unavailable for the time selected")
                continue

            confirm = input(f"Are you sure you want to change from {ticket.time} to {time} (Enter \"yes\" to confirm): ")
            if confirm == "yes":
                break

        time = times[user_choice - 1]
        self.deregister_ticket(ticket)
        ticket.time = time
        self.register_ticket(ticket)

    def start(self):
        super().start()
        ticket, exit = self.fetch_ticket()

        if exit:
            return self.goBack()
        while True:
            print("Ticket details:", ticket)
            print("Select an option")
            for idx, option in enumerate(self.option_names):
                print(f"{idx + 1}: {option}")
            user_choice = 0
            while True:
                user_choice = input("Enter a number (Enter 0 to exit): ")
                if user_choice == "exit":
                        return

                if not user_choice.isdigit():
                    print("Enter a valid number")
                    continue

                user_choice = int(user_choice)
                if user_choice > len(self.options) or user_choice < 0:
                    print("Enter a valid option")
                    continue
                break
            if user_choice == 0:
                break
            self.options[user_choice-1](ticket)

        return self.goBack()


'''
Source code modified from https://github.com/budzianowski/PyTorch-Beam-Search-Decoding/blob/master/decode_beam.py
implementation of beam search on GPT-2's logits
'''

import operator
import torch
import torch.nn as nn
import torch.nn.functional as F
from queue import PriorityQueue
import sys

class BeamSearchNode(object):
    def __init__(self, hiddenstate, previousNode, wordId, logProb, length):
        '''
        :param hiddenstate:
        :param previousNode:
        :param wordId:
        :param logProb:
        :param length:
        '''
        self.h = hiddenstate
        self.prevNode = previousNode
        self.wordid = wordId
        self.logp = logProb
        self.leng = length

    def eval(self, alpha=1.0):
        reward = 0
        # Add here a function for shaping a reward

        return self.logp / float(self.leng - 1 + 1e-6) + alpha * reward

    def __lt__(self, x):
        if(self.eval() < x.eval()):
            return True

        else:
            return False

def beam_decode_sentence(hidden_X, config,num_generate=1, beam_size = 5, batch_size = 1):
    '''
    generate a sentence based on beam search
    :param hidden_X: hidden_X of sentence embedding  (1024) with/without projection
    :param model: GPT-2 model
    :param tokenizer: GPT-2 tokenizer
    :return: decoded_batch
    '''
    #SOS_token = tokenizer.encode("<|endoftext|>")
    beam_width = beam_size
    topk = num_generate  # how many sentence do you want to generate

    past = None
    model = config['model']
    tokenizer =config['tokenizer']
    eos = [tokenizer.encode(tokenizer.eos_token)]
    EOS_token = eos
    hidden_X_unsqueeze = torch.unsqueeze(hidden_X, 0)
    hidden_X_unsqueeze = torch.unsqueeze(hidden_X_unsqueeze, 0)  #[1,1,embed_dim]

    decoded_batch = []

    # decoding goes sentence by sentence
    for idx in range(batch_size):

        # Number of sentence to generate
        endnodes = []
        number_required = min((topk + 1), topk - len(endnodes))

        # starting node -  hidden vector, previous node, word id, logp, length              hiddenstate, previousNode, wordId, logProb, length
        node = BeamSearchNode(past, None, torch.tensor([[220]]).cuda(), 0, 1)                    # 220 refers to single space ' ' on GPT
        nodes = PriorityQueue()

        # start the queue
        nodes.put((-node.eval(), node))
        qsize = 1

        # start beam search
        for text_len in range(50):
            # give up when decoding takes too long
            if qsize > 2000: break

            # fetch the best node
            try:
                score, n = nodes.get()
            except:
                print('Cannot get nodes')
                while not nodes.empty():
                    next_item = nodes.get()
                    print(next_item)
            prev_input = n.wordid
            past = n.h

            if n.wordid.item() == EOS_token[0] and n.prevNode != None:
                endnodes.append((score, n))
                # if we reached maximum # of sentences required
                if len(endnodes) >= number_required:
                    break
                else:
                    print('continue')
                    continue
            # decode for one step using decoder
            if(text_len == 0):
                logits, past = model(inputs_embeds=hidden_X_unsqueeze,past_key_values  = past,return_dict=False)

            else:
                logits, past = model(prev_input,past_key_values = past, attention_mask=None, return_dict=False)
            logits = logits[:, -1, :]
            probs = torch.softmax(logits, dim=-1)
            # PUT HERE REAL BEAM SEARCH OF TOP
            log_prob, indexes = torch.topk(probs, beam_width)
            nextnodes = []

            for new_k in range(beam_width):
                decoded_t = indexes[0][new_k].view(1, -1)
                log_p = log_prob[0][new_k].item()
                #### hiddenstate, previousNode, wordId, logProb, length
                node = BeamSearchNode(past, n, decoded_t, n.logp + log_p, n.leng + 1)
                score = -node.eval()
                nextnodes.append((score, node))

            # put them into queue
            for i in range(len(nextnodes)):
                score, nn = nextnodes[i]
                try:
                    nodes.put((score, nn))
                except:
                    print('Cannot put nodes')
                    print(score)
                    print(nn)
                # increase qsize
            qsize += len(nextnodes) - 1
        # for loop ends here
        # choose nbest paths, back trace them
        if len(endnodes) == 0:
            endnodes = [nodes.get() for _ in range(topk)]

        utterances = []
        text = []
        for score, n in sorted(endnodes, key=operator.itemgetter(0)):
            utterance = []
            utterance.append(n.wordid.item())
            # back trace
            while n.prevNode != None:
                n = n.prevNode
                utterance.append(n.wordid.item())

            utterance = utterance[::-1]
            utterances.append(utterance)
            decode_process = tokenizer.decode(utterance[1:-1])
            text.append(decode_process)
        decoded_batch.append(utterances)

    return text

def greedy_decode(decoder_hidden, encoder_outputs, target_tensor):
    '''
    :param target_tensor: target indexes tensor of shape [B, T] where B is the batch size and T is the maximum length of the output sentence
    :param decoder_hidden: input tensor of shape [1, B, H] for start of the decoding
    :param encoder_outputs: if you are using attention mechanism you can pass encoder outputs, [T, B, H] where T is the maximum length of input sentence
    :return: decoded_batch
    '''

    batch_size, seq_len = target_tensor.size()
    decoded_batch = torch.zeros((batch_size, MAX_LENGTH))
    decoder_input = torch.LongTensor([[SOS_token] for _ in range(batch_size)], device=device)

    for t in range(MAX_LENGTH):
        decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs)

        topv, topi = decoder_output.data.topk(1)  # get candidates
        topi = topi.view(-1)
        decoded_batch[:, t] = topi

        decoder_input = topi.detach().view(-1, 1)

    return decoded_batch


import numpy as np
import matplotlib.pyplot as plt

def sigmoid(Z):
	"""sigmoid

	Arguments:
		Z {[np.array]} -- [Wx + b]

	Returns:
		A - [np.array] -- [1 / 1+exp(- Wx + b)]
		cache - Z
	"""
	A = 1/(1+np.exp(-Z))
	cache = Z

	return A, cache

def relu(Z):
	"""rectified linear unit

	Arguments:
		Z {[np.array]} -- [Wx + b]

	Returns:
		A - [np.array] -- [max(0,Z)]
		cache - Z
	"""
	A = np.maximum(0,Z)

	assert(A.shape == Z.shape)

	cache = Z
	return A, cache

def relu_backward(dA, cache):
    """
    Implement the backward propagation for a single RELU unit.

    Arguments:
		dA - the activated gradient
		cache - Z

    Returns:
    	dZ - Gradient of the cost with respect to Z
    """

    Z = cache
    dZ = np.array(dA, copy=True) # just converting dz to a correct object.

    # for z <= 0, set dz to 0
    dZ[Z <= 0] = 0

    assert (dZ.shape == Z.shape)

    return dZ

def sigmoid_backward(dA, cache):
    """
    Implement the backward propagation for a single SIGMOID unit.

    Arguments:
    dA - the acitvated gradient
    cache - Z

    Returns:
    	dZ - Gradient of the cost with respect to Z
    """

    Z = cache

    s = 1/(1+np.exp(-Z))
    dZ = dA * s * (1-s)

    assert (dZ.shape == Z.shape)

    return dZ

def print_mislabeled_images(classes, X, y, p):
    """
    Plots images where predictions and truth were different.
    X -- dataset
    y -- true labels
    p -- predictions
    """
    a = p + y
    mislabeled_indices = np.asarray(np.where(a == 1))
    print(mislabeled_indices)
    num_images = len(mislabeled_indices[0])
    for i in range(num_images):
        index = mislabeled_indices[1][i]

        plt.subplot(2, num_images, i + 1)
        plt.imshow(X[:,index].reshape(64,64,3))
        plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
        plt.show()


# This file is part of "Junya's self learning project about Neural Network."
#
# "Junya's self learning project about Neural Network"
# is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "Junya's self learning project about Neural Network"
# is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
#
# (c) Junya Kaneko <jyuneko@hotmail.com>

import numpy as np
from matplotlib import pyplot
import logging

__author__ = 'Junya Kaneko <jyuneko@hotmail.com>'

def sigmoid(z, alpha=1, theta=0):
    return 1 / (1 + np.exp(-alpha * (z - theta)))

def draw_sigmoid_graphs():
    dom = np.array([x / 100 for x in range(-300, 300)])
    alphas = [1, 10, 50, 100]

    nrows = 2
    ncols = int(len(alphas)/2)
    for i, alpha in enumerate(alphas):
        values = np.array([0.0] * len(dom))
        for j, x in enumerate(dom):
            values[j] = sigmoid(x, alpha=alpha)
        pyplot.subplot(nrows, ncols, i + 1)
        pyplot.title('Alpha = %s' % alpha)
        pyplot.xlabel('x')
        pyplot.ylabel('sigmoid(x)')
        pyplot.plot(dom, values)
    pyplot.tight_layout()
    pyplot.show()

class Element:
    def __init__(self, w, alpha, theta):
        self._w = w if isinstance(w, np.ndarray) else np.array(w)
        self._alpha = alpha
        self._theta = theta

    def out(self, input, alpha=None, theta=None):
        _input = input if isinstance(input, np.ndarray) else np.array(input)
        _alpha = alpha if alpha else self._alpha
        _theta = theta if theta else self._theta
        logging.debug('PARAMETERS (alpha, theta): (%s, %s)' % (_alpha, _theta))
        logging.debug('INPUT: (%s), SIGMOID: %s' % (','.join([str(i) for i in _input]), sigmoid(self._w.dot(_input), _alpha, _theta)))
        if sigmoid(self._w.dot(_input), _alpha, _theta) > 0.5:
            logging.debug('OUTPUT: %s' % 1)
            return 1
        else:
            logging.debug('OUTPUT: %s' % 0)
            return 0

    def __call__(self, input, alpha=None, theta=None):
        return self.out(input, alpha, theta)

class AndElement(Element):
    def __init__(self):
        super().__init__(w=[1, 1], alpha=1, theta=1.5)

class OrElement(Element):
    def __init__(self):
        super().__init__(w=[1, 1], alpha=1, theta=0.5)

class XorElement:

    def out(self, input):
        or_element = OrElement()

        i1 = np.array([input[0], -input[1]])
        i2 = np.array([-input[0], input[1]])

        o1 = or_element(i1)
        o2 = or_element(i2)
        return or_element([o1, o2])

    def __call__(self, input):
        return self.out(input)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    draw_sigmoid_graphs()

    and_element = AndElement()
    or_element = OrElement()
    xor_element = XorElement()

    assert and_element([1, 1])
    assert not and_element([1, 0])
    assert not and_element([0, 1])
    assert not and_element([0, 0])

    assert or_element([1, 1])
    assert or_element([1, 0])
    assert or_element([0, 1])
    assert not or_element([0, 0])

    assert not xor_element([1, 1])
    assert xor_element([1, 0])
    assert xor_element([0, 1])
    assert not xor_element([0, 0])


# Code courtesy: https://towardsdatascience.com/support-vector-machine-python-example-d67d9b63f1c8
# Theory: https://www.youtube.com/watch?v=_PwhiWxHK8o
import numpy as np
import cvxopt
from sklearn.datasets.samples_generator import make_blobs
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from sklearn.svm import LinearSVC
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score

class SVM:
    """

    """
    def __init__(self):
        self.alpha = None
        self.w = None
        self.b = None
        self.support_vectors = None
        self.support_vector_y = None

    def fit(self, X_train, y_train):
        n_samples, n_features = X_train.shape
        # P = X_train^T X_train
        K = np.zeros((n_samples, n_samples))
        for i in range(n_samples):
            for j in range(n_samples):
                K[i, j] = np.dot(X_train[i], X_train[j])

        P = cvxopt.matrix(np.outer(y_train, y_train) * K)
        # q = -1 (1xN)
        q = cvxopt.matrix(np.ones(n_samples) * -1)
        # A = y_train^T
        A = cvxopt.matrix(y_train, (1, n_samples))
        # b = 0
        b = cvxopt.matrix(0.0)
        # -1 (NxN)
        G = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))
        # 0 (1xN)
        h = cvxopt.matrix(np.zeros(n_samples))

        solution = cvxopt.solvers.qp(P, q, G, h, A, b)
        # Lagrange multipliers
        a = np.ravel(solution['x'])
        # Lagrange have non zero lagrange multipliers
        sv = a > 1e-5
        ind = np.arange(len(a))[sv]
        self.alpha = a[sv]
        self.support_vectors = X_train[sv]
        self.support_vector_y = y_train[sv]
        # Intercept
        self.b = 0
        for n in range(len(self.alpha)):
            self.b += self.support_vector_y[n]
            self.b -= np.sum(self.alpha * self.support_vector_y * K[ind[n], sv])
        self.b /= len(self.alpha)
        # Weights
        self.w = np.zeros(n_features)
        for n in range(len(self.alpha)):
            self.w += self.alpha[n] * self.support_vector_y[n] * self.support_vectors[n]

    def predict(self, X_test):
        return self.sign(np.dot(X_test, self.w) + self.b)

    def f1_score(self, X_test, y_test):
        pass

if __name__ == '__main__':
    X, y = make_blobs(n_samples=250, centers=2, random_state=100, cluster_std=1)
    y[y == 0] = -1
    tmp = np.ones(len(X))
    y = tmp * y

    plt.scatter(X[:, 0], X[:, 1], c=y, cmap='winter')
    plt.show()

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

    svm = SVM()
    svm.fit(X_train, y_train)

    def f(x, w, b, c=0):
        return (-w[0] * x - b + c) / w[1]

    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='winter')
    # w.x + b = 0
    a0 = -4
    a1 = f(a0, svm.w, svm.b)
    b0 = 4;
    b1 = f(b0, svm.w, svm.b)
    plt.plot([a0, b0], [a1, b1], 'k')
    # w.x + b = 1
    a0 = -4;
    a1 = f(a0, svm.w, svm.b, 1)
    b0 = 4;
    b1 = f(b0, svm.w, svm.b, 1)
    plt.plot([a0, b0], [a1, b1], 'k--')
    # w.x + b = -1
    a0 = -4;
    a1 = f(a0, svm.w, svm.b, -1)
    b0 = 4;
    b1 = f(b0, svm.w, svm.b, -1)
    plt.plot([a0, b0], [a1, b1], 'k--')
    plt.show()


"""Wrapper a los proceso de scrapping
"""
import tempfile
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

# pylint: disable=unused-import
from scrapper.procesos.patentes_inpi_novedades import patentes_inpi_novedades
from scrapper.procesos.zonaprop import zonaprop
from scrapper.procesos.dummy import dummy_download_file
from scrapper.procesos.inpi_novedades import inpi_novedades

def get_chrome_driver(download_folder, show=False):
    """Configura y retorna el driver chrome

    Args:
        download_folder (str): Carpeta de descarga deseada
        show (bool): Establece si se muestra la operación en el navegador

    Returns:
        driver: retorna el objeto driver
    """

    chrome_options = Options()
    if not show:
        chrome_options.add_argument("--headless=new")

    chrome_options.add_argument(f"--download-directory={download_folder}")
    chrome_options.add_argument("--start-maximized")
    chrome_options.add_experimental_option("prefs", {
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "download.default_directory": download_folder,
        "safebrowsing.enabled": True,
        'safebrowsing.disable_download_protection': True
    })
    chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])

    caps = DesiredCapabilities().CHROME
    #caps["pageLoadStrategy"] = "normal"  #  complete
    #caps["pageLoadStrategy"] = "eager"  #  interactive
    caps["pageLoadStrategy"] = "none"

    driver = webdriver.Chrome(options=chrome_options, desired_capabilities=caps)

    return driver

def scrap(proceso,
          config,
          log,
          inputparam=None,
          inputfile=None,
          outputpath = None,
          show_browser=False):
    """Ejecución generica de un proceso  modelo de scrapping

    Args:
        proceso (str): Nombre del proceps
        config (Config): Objeto de Configuración
        log (Log): Objeto de Logging
        inputparam (str, optional): Cadena variable de parámetros dada por el usuario.
                                    Defaults to None.
        inputfile (str, optional): Archivo de entrada. Defaults to None.
        outputpath (str, optional): Carpeta de salida de los resultados. Defaults to None.
        show_browser (bool, optional): Se muestra muestra el navegador durante el proceso
                                       de scrapping.
                                       Defaults to False.

    Returns:
        List: Lista de valores capturados
    """

    if outputpath is None:
        workpath = tempfile.mkdtemp()
    else:
        workpath = outputpath

    temp_download_folder = os.path.join(workpath, "tmp")
    os.makedirs(temp_download_folder, exist_ok=True)

    log.info(f"Carpeta de descarga: {temp_download_folder}")
    driver = get_chrome_driver(download_folder=temp_download_folder, show=show_browser)

    section         = "proc:" + proceso
    function_name   = config[section]["function"]
    datos           = []
    if function_name in globals():
        function = globals()[function_name]
        log.info(f"Invocando a: {function_name}")

        try:
            datos = function(driver=driver,
                            log=log,
                            parametros=config[section],
                            inputfile=inputfile,
                            tmpdir=workpath,
                            inputparam=inputparam,
                            outputpath=outputpath,
                            show_browser = show_browser)

        # pylint: disable=broad-except
        except Exception as err:
            log.exception("General en la invocación a la función de scrapping")
            log.exception(str(err))

    else:
        log.error(f"proceso {function_name} no implementado")

    return datos


# import torch
# import torch.nn as nn
# from torch.autograd import Variable
import tensorflow as tf

class reparameterize(tf.keras.Model):
    def __init__(self):
        super(reparameterize, self).__init__()

    @tf.function
    def call(self, mu, logvar, sample_num=1, phase='training'):
        if phase == 'training':
            std = tf.math.exp(logvar*0.5)
            eps = tf.keras.backend.random_normal(shape=[1]+std.get_shape().as_list()[1:], mean=0., stddev=1.)
            return (eps*std)+mu
        else:
            raise ValueError('Wrong phase. Always assume training phase.')
        # elif phase == 'test':tf.math.exp(
        #  return mu
        # elif phase == 'generation':
        #  eps = Variable(logvar.data.new(logvar.size()).normal_())
        #  return eps
def run():
  x1 = tf.random.normal([16,64])
  x2 = tf.random.normal([16,64])
  import time
  s = time.time()
  sample(x1,x2)
  print(time.time() - s)
if __name__ =="__main__":
    sample = reparameterize()
    for i in range(20):
        run()
    print(len(sample.trainable_variables))


from typing import *

# ref https://leetcode.cn/problems/naming-a-company/solution/by-endlesscheng-ruz8/
from collections import defaultdict
class Solution:
    def distinctNames(self, ideas: List[str]) -> int:
        group = defaultdict(int)
        for s in ideas:
            group[s[1:]] |= 1 << (ord(s[0]) - ord('a'))
        ans = 0
        # 定义 \textit{cnt}[i][j]cnt[i][j] 表示组中首字母不包含 ii 但包含 jj 的组的个数。枚举每个组，统计 \textit{cnt}cnt，
        # 同时枚举该组的首字母 ii 和不在该组的首字母 jj，答案即为 \textit{cnt}[i][j]cnt[i][j] 的累加值
        cnt = [[0] * 26 for _ in range(26)]
        for mask in group.values():
            for i in range(26):
                if mask >> i & 1 == 0:
                    for j in range(26):
                        if mask >> j & 1:
                            cnt[i][j] += 1
                else:
                    for j in range(26):
                        if mask >> j & 1 == 0:
                            ans += cnt[i][j]
        return ans * 2


def two_split(nums,target,lo,high):
    while(lo<=high):
        middle = (lo + high)/2
        if(nums[middle] < target):
            lo = middle+1
        elif(nums[middle]>target):
            high = middle-1
        else:
            return middle
    return lo
class Solution(object):

    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        n = len(nums) -1
        lo = 0
        high=n
        if(n<0):
            return -1
        while(nums[lo]> nums[high]):
            middle = (lo+high)/2
            if(nums[middle]>nums[high]):
                lo = middle+1
            else:
                high = middle
        print(lo)
        if(nums[n]<target<=nums[lo-1]):
            m = two_split(nums,target,0,lo-1)
        elif(nums[lo]<target<=nums[n]):
            m = two_split(nums,target,lo,n)
        else:
            m = lo
        if(nums[m]==target):
            return m
        else:
            return -1


import requests
from common.log import GetLogger

log = GetLogger().get_logger()

class BaseRequest():
    def __init__(self):
        pass

    def get(self,url,params=None,**kwargs):
        try:
            response=requests.get(url,params=params,**kwargs)
            log.info("==========接口API请求开始===========")
            log.info("请求URL：{}/n请求参数：{}".format(url,params))
            log.info("接口请求成功！返回参数:{}".format(response.text))
            log.info("===========结束===========")
        except Exception as e:
            log.error("接口请求异常！{0}".format(e))

    def post(self,url,data=None,json=None,headers=None,**kwargs):

        try:
            respose = requests.post(url=url,data=data.encode("utf-8"),json=json,headers=headers,**kwargs)
            log.info("===========接口API请求开始===========")
            log.info("请求URL：{}".format(url))
            log.info("请求参数：{}".format(data,json))
            log.info("响应参数：{}".format(respose.text))
            log.info("响应时间：{}ms".format(respose.elapsed.total_seconds()*1000))
            log.info("===========结束===========")
            return respose
        except Exception as e:
            log.error("接口请求异常！{0}".format(e))

# if __name__ == '__main__':
#     Headers = {
#         "content-type": "application/json"
#         }
#     a=BaseRequest()
#     a.get("http://192.168.122.105:9900/basic-user/web/business/system/list")
#     data={
# 	"businessSystemCode": "DAC",
# 	"businessSystemId": 0,
# 	"businessSystemKey": "DAC",
# 	"businessSystemName": "基础配置中心"
# }
#     a.post("http://192.168.122.105:9900/basic-user/web/business/system/save",data=data,headers=Headers)


#!/usr/bin/env python3

import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import PoseWithCovarianceStamped
#from nav_msgs.msg import Odometry
from math import floor
import matplotlib.pyplot as plt

import numpy as np
#teste

#This node receives topic 'scanner' and 'poser' and adds noise to them

#--------------------------------------------------------------------------------
# NOISE
# 68% of the observations lie within 1 standard deviation of the mean;
# 95% lie within two standard deviation of the mean;
# 99.9% lie within 3 standard deviations of the mean
SCAN_NOISE = 0.0  # percentagem
POSE_NOISE = 0.0  # metros
ANG_NOISE = 0.0   # percentagem
#--------------------------------------------------------------------------------

# Import your custom code to implement your algorithm logic here
# for example:

class Noiser_Node:
    def __init__(self):

        # Initialize some necessary variables here
        self.node_frequency = None
        self.pub_scan = None
        self.pub_pose = None
        self.scan_sensor = LaserScan
        self.position = PoseWithCovarianceStamped

        # Initialize the ROS node
        rospy.init_node('noiser_node')
        rospy.loginfo_once('Noiser Node has started')

        # Load parameters from the parameter server
        self.load_parameters()

        # Initialize the publishers and subscribers
        self.initialize_subscribers()
        self.initialize_publishers()

        # Initialize the timer with the corresponding interruption to work at a constant rate
        #self.initialize_timer()

    def initialize_publishers(self):

        # Initialize the publisher to the topic '/output_topic'
        self.pub_scan = rospy.Publisher('scan', LaserScan, queue_size=10)
        self.pub_pose = rospy.Publisher('amcl_pose', PoseWithCovarianceStamped, queue_size=10)

    def load_parameters(self):
        """
        Load the parameters from the configuration server (ROS)
        """

        # Node frequency of operation
        self.node_frequency = rospy.get_param('node_frequency', 30)
        rospy.loginfo('Node Frequency: %s', self.node_frequency)

    def initialize_subscribers(self):
        """
        Initialize the subscribers to the topics. You should subscribe to
        sensor data and odometry (if applicable) here
        """

        # Subscribe to the topic '/fake_sensor_topic'
        rospy.Subscriber('/scanner', LaserScan, self.callback_scan)
        rospy.Subscriber('/poser', PoseWithCovarianceStamped, self.callback_pose)

    def callback_scan(self, msg):
        self.scan_sensor = msg

        scan_noise = abs(np.random.normal(1,SCAN_NOISE,360))
        self.scan_sensor.ranges *= scan_noise

        self.pub_scan.publish(self.scan_sensor)

    def callback_pose(self,msg):
        self.position = msg

        pose_noise = np.random.normal(0,POSE_NOISE,2)

        self.position.pose.pose.position.x += pose_noise[0]
        self.position.pose.pose.position.y += pose_noise[1]
        ang = 2*np.arcsin(msg.pose.pose.orientation.z)
        self.position.pose.pose.orientation.z = np.sin((ang + np.pi*np.random.normal(0,ANG_NOISE,1))/2)
        rospy.loginfo('NOISED at: %s', rospy.get_time())

        self.pub_pose.publish(self.position)

def main():
    # Create an instance of the DemoNode class
    node = Noiser_Node()

    # Spin to keep the script for exiting
    rospy.spin()

if __name__ == '__main__':
    main()


from statuspage.forms import StatusPageModelForm
from utilities.forms import StaticSelect
from ..models import Component, ComponentGroup

__all__ = (
    'ComponentForm',
    'ComponentGroupForm',
)

class ComponentForm(StatusPageModelForm):
    fieldsets = (
        ('Component', (
            'name', 'link', 'description', 'component_group', 'status', 'show_historic_incidents', 'visibility',
            'order',
        )),
    )

    class Meta:
        model = Component
        fields = (
            'name', 'link', 'description', 'component_group', 'status', 'show_historic_incidents', 'visibility', 'order'
        )
        widgets = {
            'component_group': StaticSelect(),
            'status': StaticSelect(),
        }

class ComponentGroupForm(StatusPageModelForm):
    fieldsets = (
        ('Component Group', (
            'name', 'description', 'visibility', 'order', 'collapse'
        )),
    )

    class Meta:
        model = ComponentGroup
        fields = (
            'name', 'description', 'visibility', 'order', 'collapse'
        )
        widgets = {
            'collapse': StaticSelect(),
        }


import os
class Event_Controler:
    def __init__(self, rede_p1, rede_p2):
        self.need_objects = True
        self.comandos = []
        self.redep1 = rede_p1
        self.redep2 = rede_p2

    def set_objects(self, bola, player_1, player_2, partida):
        self.bola = bola
        self.player_1 = player_1
        self.player_2 = player_2
        self.p1_controler = player_1.controle
        self.p2_controler = player_2.controle
        self.partida = partida

    def atualiza_lista(self):
        self.comandos = []
        a = self.bola.get_posicao()
        r1 = self.redep1.run([self.bola.get_posicao()[0], self.bola.get_posicao()[1], self.player_1.posicao.x])
        r2 = self.redep2.run([self.bola.get_posicao()[0], self.bola.get_posicao()[1], self.player_2.posicao.x])
        if r1 < 0.5:
            self.comandos.append(self.p1_controler.esquerda)
        else:
            self.comandos.append(self.p1_controler.direita)

        if r2 < 0.5:
            self.comandos.append(self.p2_controler.esquerda)
        else:
            self.comandos.append(self.p2_controler.direita)

    def get_eventos_list(self):
        self.atualiza_lista()
        return self.comandos

    def finalizar(self):
        self.salvar()

    def salvar(self):

        placar = self.partida.placar_p1 - self.partida.placar_p2
        salvar = self.redep1
        sufixo = '-P1'
        if placar < 0:
            salvar = self.redep2
            sufixo = '-P2'
            placar = -placar

        file = open('Redes' + sufixo + '.txt', 'a')

        file.write(str(placar) + ',')

        # Salva Pesos das Camadas Ocultas

        for a in range(len(salvar.hlw)):

            for b in range(len(salvar.hlw[a])):
                for c in range(len(salvar.hlw[a][b])):
                    if c is not len(salvar.hlw[a][b])-1:
                        file.write(str(salvar.hlw[a][b][c]) + ';')
                    else:
                        file.write(str(salvar.hlw[a][b][c]))
                if b is not len(salvar.hlw[a])-1:
                    file.write('_')

            if a is not len(salvar.hlw) - 1:
                file.write(':')

        #Salva Pesos da Camada de Saida
        file.write(',')
        for a in range(len(salvar.output_weights)):
            file.write('')
            for b in range(len(salvar.output_weights[a])):
                if b is not len(salvar.output_weights[a])-1:
                    file.write(str(salvar.output_weights[a][b]) + ';')
                else:
                    file.write(str(salvar.output_weights[a][b]))
            if a is not len(salvar.output_weights) - 1:
                file.write('_')

        # Salva os bias das Camadas ocultas
        file.write(',')
        for a in range(len(salvar.hlb)):
            file.write('')
            for b in range(len(salvar.hlb[a])):
                if b is not len(salvar.hlb[a]) - 1:
                    file.write(str(salvar.hlb[a][b]) + ';')
                else:
                    file.write(str(salvar.hlb[a][b]))
            if a is not len(salvar.hlb) - 1:
                file.write('_')

        # Salva os bias da Camada de Saida

        file.write(',')
        for a in range(len(salvar.output_bias)):
            if a is not len(salvar.output_bias) - 1:
                file.write(str(salvar.output_bias[a]) + ';')
            else:
                file.write(str(salvar.output_bias[a]))

        file.write('\n')
        file.close()


"""
Revised Monitor for screen addition, removing logging & LED
Author: Howard Webb
Date: 10/09/2018

Controller to collect GPS and Sonar data and integrate into a single record
May also collect non-serial data (ie. turbidity)
Store to a file, incrementing for each new run
"""
from __future__ import print_function
from GPS import GPS
from Sonar import Sonar
# from oneWireTemp import getTempC
# from Turbidity import Turbidity
import serial
# Routine to check serial ports for GPS or Sonar messages
# No guarantee which device is on which port
from PortScan import PortScan
from i2c_lcd_util import lcd
from time import sleep
from datetime import datetime

class Monitor(object):

    def __init__(self):
        """
        Build monitor with GPS and Sonar
        :param logger:
        """
        # Object level holders for data

        # used for recording
        self._time = None
        self._lat = None
        self._lon = None
        self._depth = None
        self._temp = None
        # used for dispaly
        self._time_msg = ""
        self._lat_msg = ""
        self._lon_msg = ""
        self._depth_msg = ""
        self._temp_msg = ""

        self._lcd = lcd()
        self._lcd.lcd_display_string("Waiting GPS", 1)
        # Option to use test logger or recording logger
        #        self._tur = Turbidity()
        # Get file for logging data
        self._file = self.getFile()
        self.writeHeader()
        self._GPS = None
        self._Sonar = None
        # Get list of ports and check who is using
        #  avoids problems when switch USB location
        ps = PortScan()
        port_list = ps.getPorts()
        print(port_list)
        if 'GPS' in port_list.keys():

            self._GPS = GPS(self.recorder, port_list['GPS'])
        else:
            # Fail gracefully
            self._GPS = None
            self._lcd.lcd_display_string("No GPS port found", 1)
            raise SystemExit

        self._lcd.lcd_display_string("Waiting Sonar", 1)
        if 'Sonar' in port_list.keys():
            self._Sonar = Sonar(self.recorder, port_list['Sonar'])
        else:
            # Fail
            self._Sonar = None
            self._lcd.lcd_display_string("No Sonar found", 1)
            raise SystemExit
        self._lcd.lcd_display_string(" "*15)
        self._lcd.lcd_display_string("Data", 1, 1)
        while True:
            self._GPS.get()
            self._Sonar.get()
            #sleep(0.5)

    def getFile(self):
        name = self.getFileName()
        return self.openFile(name)

    def getFileName(self):
        """
        Create file name for next log
            Assumes format 'Log_000.csv'
            Will incriment the number for the next file
        :return: the filename
        """
        import glob
        filename = '/home/pi/Data/Log_000.csv'
        files = glob.glob("/home/pi/Data/*.csv")
        if len(files) > 0:
            files.sort()
            last_file = files[-1]
            next_nbr = int(last_file.split('.')[0].split('_')[1])
            next_nbr += 1
            filename = "{}{}{}".format('/home/pi/Data/Log_', format(next_nbr, '0>3'), '.csv')
        return filename

    def openFile(self, name):
        """
        Open a file for logging data
        :return: the file descriptor
        """
        return open(name, 'a')

    def writeHeader(self):
        # write header
        rec = "{}, {}, {}, {}, {}".format('Time', 'Latitude', 'Longitude', 'Depth', 'Temperature')
        self.save(rec)

    def save(self, rec):
        """
        appandes the characters in rec into the file
        :param rec: the characters to be saved
        :return: None, but also prints the rec
        """
        self._file.write(rec)
        self._file.flush()

    def recorder(self, values):
        """
        Callback to get messages, when have all three - save them as one record. A log value is printed
        when all measurement values have non None values.
        :param values:
        :return: None
        """
        #        print "Values", values
        # gets data from GPS and Sonar
        #print(values)
        #print(values["name"])
        if values['name'] is None:
            print("No Msg Name")
        if values['name'] == 'GPRMC':  # Time and velocity
            #print("GPRMC", values)
            self._time = values["data"]["time"]
            self._lat = values["data"]["lat"]
            self._lon = values["data"]["lon"]

            self._lat_msg = '{:.6f}'.format(self._lat)
            self._lon_msg = '{:.6f}'.format(self._lon)

        if values['name'] == 'GPGLL':  # Time and location
            print("GPGLL", values)
            self._time = values["data"]["time"]
            self._lat = values["data"]["lat"]
            self._lon = values["data"]["lon"]

            self._lat_msg = '{:.6f}'.format(self._lat)
            self._lon_msg = '{:.6f}'.format(self._lon)

        elif values['name'] == 'SDDBT':  # Depth
            #print("SDDBT", values)
            depth = values["data"]["depth"]
            # check for missing data
            if depth == '':
                depth = 0
            self._depth = depth
            #print(type(self._depth), self._depth)
            self._depth_msg = 'D{:04.1f}'.format(float(self._depth))

        elif values['name'] == 'YXMTW':  # Temperature
            #print("YXMTW", values)
            self._temp = values["data"]["temp"]
            #print(type(self._temp), self._temp)
            self._temp_msg = 'T{}'.format(self._temp)

       # Save record when have all parts
        #print(datetime.now().strftime("%S"))
        #print(values["name"], self._lat, self._depth, self._time)
        if (self._lat is not None) and (self._depth is not None):
            print(values["name"], self._lat, self._depth, self._time)
            self.finishLogging()

            # display data
            self._lcd.lcd_display_string(self._lat_msg, 1, 1)
            self._lcd.lcd_display_string(self._depth_msg, 1, 11)

            self._lcd.lcd_display_string(self._lon_msg, 2)
            self._lcd.lcd_display_string(self._temp_msg, 2, 11)

            # clear data for next round of sentences
            self._time = None
            self._lat = None
            self._lon = None
            self._depth = None
            self._temp = None

    def finishLogging(self):
        """
        save the logging data to the file
        :return: None
        """
        rec = "\n{}, {}, {}, {}, {}".format(self._time, self._lat, self._lon, self._depth, self._temp)
        self.save(rec)

def test():
    """ Quick test with dummy logger """
    print("Test Monitor")
    main()

def main():
    mon = Monitor()

if __name__ == "__main__":
        main()


"""
 A Module for Encrypt and Decrypt message
"""

import ReadWriteFileManagement
# Import the Fernet module
from cryptography.fernet import Fernet

DATABASE_DIR_PATH = "../../databases/chat_db/"
FILE_NAME = "encryptKey.key"

"""
A function for generating an encryption key.
the function generate the using Fernet class,
and saves the key into file in a specific path
"""

def generate_encryption_key():
    # generate a random key for encryption
    encrypt_key = Fernet.generate_key()
    # Writing the key into a file in order to decode the messages when needed
    if ReadWriteFileManagement.create_chat_file(FILE_NAME) is not None:
        ReadWriteFileManagement.create_chat_file(FILE_NAME)
    # Stores the encryption key into the encryption file
    with open(DATABASE_DIR_PATH + FILE_NAME, 'wb') as encryptKey:
        encryptKey.write(encrypt_key)

"""
A function for Encrypt a text message
"""

def message_encrypt(message_to_encrypt):
    # Opening the file that stores the encrypt key
    with open(DATABASE_DIR_PATH + FILE_NAME, 'rb') as en_Key:
        key = en_Key.read()
    # Creating an instant of the Fernet class with encrypt_key,
    # so we can encrypt each message using Fernet methods
    fernet = Fernet(key)

    # E ncrypt message
    enc_message = fernet.encrypt(message_to_encrypt.encode())
    return enc_message

"""
A function for Decrypt a text message
"""

def message_decrypt(message_to_decrypt):
    # Opening the file that stores the encrypt key
    with open(DATABASE_DIR_PATH + FILE_NAME, 'rb') as encryptKey:
        key = encryptKey.read()
    # Creating an instant of the Fernet class with encrypt_key,
    # so we can encrypt each message using Fernet methods
    fernet = Fernet(key)
    decode_message = fernet.decrypt(message_to_decrypt.decode())
    return decode_message

if __name__ == "__main__":
    generate_encryption_key()
    message = "Hello"
    enc_m = message_encrypt(message)
    print(enc_m.decode())
    dec_m = message_decrypt(enc_m)
    print(dec_m.decode())


import cv2 as cv
import copy
import numpy as np
from matplotlib import pyplot as plt

img  = cv.imread("/home/arkaprabha/CViiing/photos/cameron.jpeg")
cv.imshow("image",img)

def reframe(frame=None,scale=0.75):
    width= int(frame.shape[1] + scale)
    height = int(frame.shape[0] + scale)
    dimen = (width,height)
    return cv.resize(frame,dimen,cv.INTER_AREA)

def drawshapes(frame,n1,m1,n2,m2):
    cv.rectangle(frame,(n1,m1),(n2,m2),(0,255,0),thickness=2)
    cv.circle(frame,(n2//2,m2 + m2//2),40,(0,0,255),thickness = 3)
    cv.putText(frame,"Didn't meant to put the circle there :)",(0,m2+10),cv.FONT_HERSHEY_TRIPLEX,0.25,(255,255,255),1)
    cv.imshow("Bound",frame)

def translate(img, x,y):
    # -x -> Left
    # -y -> Up
    # x -> Right
    # y -> Down
    transMat =  np.float32([[1,0,x],[0,1,y]])
    dimensions = (img.shape[1],img.shape[0])
    return cv.warpAffine(img, transMat, dimensions)

def rotate(img,angle,rotPoint = None,scale=1.0):
    (height,width)= img.shape[:2]
    if (rotPoint is None):
        rotPoint= (width//2,height//2)
    rotmat = cv.getRotationMatrix2D(rotPoint, angle,scale) #third factor is scale here we pass 1.0 as we dont need to scale for rotation
    dimens = (width,height)
    return cv.warpAffine(img,rotmat,dimens)

#basically shows our hot Dr.Cameron magnified/zoomed 50 times
im2 = reframe(img,500)
cv.imshow("image2",im2)

#draw shapes on the image
x = copy.copy(img)
drawshapes(x,10,10,img.shape[0]//2,img.shape[1]//2)

#grayscale
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow("Gray",gray)

# blur
# gaussian blurr
x = copy.copy(im2)
blurrr = cv.GaussianBlur(x,(41,41),cv.BORDER_DEFAULT)
cv.imshow("Blur",blurrr)
# median blurr
mblur = cv.medianBlur(x,3)
cv.imshow("Median blur",mblur)
# bilateral
bilateral = cv.bilateralFilter(x, 5 ,15,15)
cv.imshow("Bilateral",bilateral)

#edge cascade
canny = cv.Canny(x,90,100)
cv.imshow("canny",canny)

#dilating the image
dilated = cv.dilate(x,(40,40),iterations=5)
cv.imshow("Dilated",dilated)

#eroding the image
eroded = cv.erode(x,(10,10),iterations = 5)
cv.imshow("eroded",eroded)

#translate
translated = translate(x,-100,10)
cv.imshow("Translated",translated)

#rotate
rotated = rotate(x,45)
cv.imshow("Rotated",rotated)

#resize
resized = cv.resize(x,(1000,1000), interpolation = cv.INTER_CUBIC)
cv.imshow("Resized", resized)

#flipping
flip = cv.flip(x,0)
cv.imshow('Flipped',flip)

#thresholding
gray2 =  cv.cvtColor(im2,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray2,100,125,cv.THRESH_BINARY)
cv.imshow("Thresholded",thresh)  #produces a really hot image
print(ret)

#contours
#RETR_LIST = list of all contours
#RETR_EXTERNAL = list of all external contours
#RETR_TREE = list of all heirarchical contours
#Contour approximations
#CHAIN_APPROX_NONE = No approximations
#CHAIN_APPROX_SIMPLE = Compresses all contours into simpler ones(layman explanation)

contours, heirarchies = cv.findContours(thresh,cv.RETR_LIST,cv.CHAIN_APPROX_SIMPLE)
print(f'{len(contours)} contours found')

blank = np.zeros(x.shape[:2],dtype='uint8')
cv.drawContours(blank,contours,-1,(255,0,0),1)
cv.imshow("Contours",blank)

#color spaces
hsv = cv.cvtColor(x, cv.COLOR_BGR2HSV)
cv.imshow("HSV",hsv)

#rgb
rgb = cv.cvtColor(x, cv.COLOR_BGR2RGB)
cv.imshow("RGB",rgb)

#lab
lab = cv.cvtColor(x, cv.COLOR_BGR2LAB)
cv.imshow("LAB",lab)

#color_channels
b,g,r = cv.split(im2)

blank = np.zeros(im2.shape[:2],dtype='uint8')
blue = cv.merge([b,blank,blank])
green = cv.merge([blank,g,blank])
red = cv.merge([blank,blank,r])

cv.imshow("Blue",blue)
cv.imshow("Green",green)
cv.imshow("red",red)

#edge detection
#laplacian
lap  = cv.Laplacian(gray, cv.CV_64F)
lap = np.uint8(np.absolute(lap))
cv.imshow("Laplacian edge",lap)

#sobel
sobelx = cv.Sobel(gray, cv.CV_64F,1,0)
sobely = cv.Sobel(gray, cv.CV_64F,0,1)

cv.imshow("Sobelx gray",sobelx)
cv.imshow("Sobely gray",sobely)

#histogram
#grayscale histogram
gray_hist = cv.calcHist([gray],[0],None,[256],[0,256])
plt.plot(gray_hist)
plt.title("HISTORGRAM")

#color histogram
colors = ('b','g','r')
for i,col in enumerate(colors):
    hist = cv.calcHist([img],[i],None,[256],[0,256])
    plt.plot(hist , color = col)
plt.show()

cv.waitKey(0)


from fastapi import APIRouter, Depends
from app.dependencies import verify_api_key
from app.libraries.libpoller import Poller
from app.schemas.poller import PollerModel, PollerUpdateModel, PollerCreateModel

router = APIRouter(tags=["poller"])
oPoller = Poller()

# Poller Requests ( API_KEY required )

@router.get("/poller/devices")
async def get_poller_devices(poller = Depends(verify_api_key)):
    return await oPoller.get_poller_devices(poller)

# CRUID Poller Requests ( JWT required )

@router.get("/poller/schema")
async def get_poller_schema(joined: bool = False):
  return await oPoller.get_poller_schema(joined=joined)

@router.get("/poller")
async def get_poller_list(joined: bool = False, limit: int = 100, offset: int = 0, sortField: str = None, sortOrder: str = "asc", search: str = ""):
    return await oPoller.get_poller_list(joined=joined, limit=limit, offset=offset, sortField=sortField, sortOrder=sortOrder, search=search)

@router.get("/poller/{pollerid}")
async def get_poller(pollerid: int, joined: bool = False):
    return await oPoller.get_poller(pollerid, joined=joined)

@router.post("/poller")
async def create_poller(poller: PollerCreateModel):
    return await oPoller.create_poller(poller)

@router.put("/poller/{pollerid}")
async def update_poller(pollerid: int, poller: PollerUpdateModel):
    return await oPoller.update_poller(pollerid, poller)

@router.delete("/poller/{pollerid}")
async def delete_poller(pollerid: int):
    return await oPoller.delete_poller(pollerid)


import random
import csv
import time

from src.world import World
from src.user import User
from src.euclidregion import EuclidRegion
from src.regionprovider import GreedyRegionProvider
from src.userprofile import UserProfile
from src.gridregion import GridRegion

region_provider = GreedyRegionProvider.unmodified_generator(None)
world = World(None, region_provider)

MAX_AREA = 100
MAP_SIZE = 300

default_profile = UserProfile(10, MAX_AREA, 3)

def add_random_user(world):
    x = random.uniform(0, MAP_SIZE)
    y = random.uniform(0, MAP_SIZE)

    world.add_user(x, y, default_profile)

def coords_in_bounds(user:User):
    x_in = MAX_AREA <= user.xcoord <= MAP_SIZE - MAX_AREA
    y_in = MAX_AREA <= user.ycoord <= MAP_SIZE - MAX_AREA

    return x_in and y_in

USER_COUNT = 7500
GENERATIONS = 1

for _ in range(0, USER_COUNT):
    add_random_user(world)

with open('bias.csv', 'w', newline='') as results:
    writer = csv.writer(results)
    writer.writerow(["Generation #",
    "Region Anonymity",
    "Distance to Boundary",
    "Probability of distrance to boundary",
    "Is corner",
    "area",
    "user x",
    "user y",
    "x1",
    "x2",
    "y1",
    "y2"])

    for gen in range(0, GENERATIONS):
        user:User

        start = int(round(time.time() * 1000))

        middler_users = [u for u in world.users if coords_in_bounds(u)]
        print(len(middler_users))
        for user in middler_users:
            print(int(round(time.time() * 1000)) - start)
            start = int(round(time.time() * 1000))

            user.update_region()
            region:EuclidRegion
            region = user.current_region()

            data = [gen,
            region.privacy,
            region.user_dist_to_boundary,
            region.user_location_likelihoods[region.user_dist_to_boundary],
            region.is_corner,
            region.area(),
            user.xcoord,
            user.ycoord,
            region.x_min,
            region.x_max,
            region.y_min,
            region.y_max]

            writer.writerow(data)

            #print(f"privacy: {region.privacy} \
            #\n Distance: {region.user_dist_to_boundary} Expected: {region.user_location_likelihood} \
            #\n size: {region.area()} \
            #\n location:({user.xcoord}, {user.ycoord}) with region {user.current_region()}")


import boto3, datetime, time

region = 'us-west-2'
accesskey = os.environ['ACCESSKEY']
secretkey = os.environ['SECRET_ACCESSKEY']

def send_firehose(message: str):
  client = boto3.client('firehose', aws_access_key_id=accesskey, aws_secret_access_key=secretkey, region_name=region)

  # Send message to firehose
  response = client.put_record(
    DeliveryStreamName=os.environ['FIREHOSE_NAME'],
      Record={
        'Data': message
          }
        )

  return response


from typing import Dict
from network.api.base import BaseRepository
import re
from http.cookies import SimpleCookie
import dukpy
import requests
import http.client
from network.api.base_mainpage_cookies_loader import BaseMainPageCookiesLoader

IPP_JS_PATH = 'resources/ipp.js'

class PagesRepository(BaseRepository, BaseMainPageCookiesLoader):
    def __init__(self, user_agent: str, cookies: Dict[str, str] = None):
        super().__init__(user_agent=user_agent, cookies=cookies)

    def get_main_page_cookies(self):
        # first we get ipp cookies
        self.get_ipp_cookies()
        # then we load main page with ipp cookies
        # and get more cookies
        self.load_main_page()

    def get_cookies(self):  # override BaseMainPageCookiesLoader's method
        return self.get_main_page_cookies()

    def get_ipp_cookies(self):
        # send request to main page
        response = self.load_main_page(False)
        # get js for tokens generation
        js_code_regex_result = \
            re.findall(r'<script type=\"text/javascript\">(.*)</script>', response.text, flags=re.S | re.M)
        assert len(js_code_regex_result) > 0
        js_code = js_code_regex_result[0]

        # edit js to extract cookies from script's result
        with open(IPP_JS_PATH, encoding='utf8') as f:
            part_of_code = f.read()
        js_code = part_of_code + '\r\n' + js_code + '\r\n' + 'document.cookie'

        # evaluate js
        ipp_cookies_string = dukpy.evaljs(js_code, user_agent=self.user_agent)

        # update cookies
        ipp_cookies = SimpleCookie()
        ipp_cookies.load(ipp_cookies_string)
        for k, v in ipp_cookies.items():
            self.cookies[k] = v.value

    def load_main_page(self, update_cookies=True) -> requests.Response:
        http.client._MAXHEADERS = 1000
        # send request to main page
        response = requests.get(
            'https://dns-shop.ru/',
            headers={
                'accept': '*/*',
                'user-agent': self.user_agent,
                'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
            },
            cookies=self.cookies,
        )

        if update_cookies:
            self.update_cookies(response.cookies)

        return response


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: GAN.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>

import tensorflow as tf
import numpy as np
from tensorpack import (QueueInputTrainerBase, TowerContext,
        get_global_step_var)
from tensorpack.tfutils.summary import summary_moving_average, add_moving_summary
from tensorpack.dataflow import DataFlow

class GANTrainer(QueueInputTrainerBase):
    def __init__(self, config, g_vs_d=3):
        super(GANTrainer, self).__init__(config)
        self._build_enque_thread()
        if g_vs_d > 1:
            self._opt_g = g_vs_d
            self._opt_d = 1
        else:
            self._opt_g = 1
            self._opt_d = int(1.0 / g_vs_d)

    def _setup(self):
        with TowerContext(''):
            actual_inputs = self._get_input_tensors_noreuse()
            self.model.build_graph(actual_inputs)
        self.gs_incr = tf.assign_add(get_global_step_var(), 1, name='global_step_incr')
        self.g_min = self.config.optimizer.minimize(self.model.g_loss,
                var_list=self.model.g_vars, name='g_op')
        self.d_min = self.config.optimizer.minimize(self.model.d_loss,
                var_list=self.model.d_vars)
        self.d_min = tf.group(self.d_min, summary_moving_average(), name='d_op')

    def run_step(self):
        for _ in range(self._opt_g):
            self.sess.run(self.g_min)
        for _ in range(self._opt_d):
            self.sess.run(self.d_min)
        self.sess.run(self.gs_incr)

class RandomZData(DataFlow):
    def __init__(self, shape):
        super(RandomZData, self).__init__()
        self.shape = shape
    def get_data(self):
        while True:
            yield [np.random.uniform(-1, 1, size=self.shape)]

def build_GAN_losses(vecpos, vecneg):
    sigmpos = tf.sigmoid(vecpos)
    sigmneg = tf.sigmoid(vecneg)
    tf.histogram_summary('sigmoid-pos', sigmpos)
    tf.histogram_summary('sigmoid-neg', sigmneg)

    d_loss_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
        vecpos, tf.ones_like(vecpos)), name='d_loss_pos')
    d_loss_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
        vecneg, tf.zeros_like(vecneg)), name='d_loss_neg')

    d_pos_acc = tf.reduce_mean(tf.cast(sigmpos > 0.5, tf.float32), name='pos_acc')
    d_neg_acc = tf.reduce_mean(tf.cast(sigmneg < 0.5, tf.float32), name='neg_acc')

    g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
        vecneg, tf.ones_like(vecneg)), name='g_loss')
    d_loss = tf.add(d_loss_pos, d_loss_neg, name='d_loss')
    add_moving_summary(d_loss_pos, d_loss_neg,
            g_loss, d_loss,
            d_pos_acc, d_neg_acc)
    return g_loss, d_loss


import os
import sys
import shutil

if not os.path.exists("build"):
    os.mkdir("build")

os.chdir("build")

code = os.system("cmake .. -DPK_USE_CJSON=ON -DPK_USE_BOX2D=ON")
assert code == 0
code = os.system("cmake --build . --config Release")
assert code == 0

if sys.platform == "win32":
    shutil.copy("Release/main.exe", "../main.exe")
    shutil.copy("Release/pocketpy.dll", "../pocketpy.dll")
elif sys.platform == "darwin":
    shutil.copy("main", "../main")
    shutil.copy("libpocketpy.dylib", "../libpocketpy.dylib")
else:
    shutil.copy("main", "../main")
    shutil.copy("libpocketpy.so", "../libpocketpy.so")