import psutil
import time
import platform_detector

import logging
logger = logging.getLogger("please_logger.invoker")

class ResultInfo:
    '''
    This class represents all the information we have to get from the execution:
    * verdict:
        possible values are:
          OK (program executed succesfully);
          TL (CPU time limit exceeded);
          real TL (real time limit exceeded)
          ML (memory limit exceeded);
          RE (program has returned non-zero code).
    * cpu time:
        cpu time in seconds, used by the program
    * real time:
        time in seconds, passed since the call of this method
    * used memory:
        memory in megabytes, used by the program
    * return code:
        code returned by the program
    '''
    def __init__(self, verdict, return_code, real_time, cpu_time, used_memory):
        self.verdict = verdict
        self.return_code = return_code
        self.real_time = real_time
        self.cpu_time = cpu_time
        self.used_memory = used_memory

    def __str__(self):
        return ("verdict: {0}\n" \
                + "return code: {1}\n" \
                + "real time: {2:.2f} sec, cpu time: {3:.2f} sec\n" \
                + "used memory: {4:.3f} Mb").format(self.verdict, self.return_code,
                                                    self.real_time, self.cpu_time,
                                                    self.used_memory)

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        return (self.verdict == other.verdict and
                self.return_code == other.return_code and
                self.real_time == other.real_time and
                self.cpu_time == other.cpu_time and
                self.used_memory == other.used_memory)

class ExecutionLimits:
    '''
    This class represents constraints of the execution.
    '''
    def __init__(self, cpu_time=10, memory=512, real_time=None):
        real_time = real_time or cpu_time * 5
        self.real_time, self.memory, self.cpu_time = \
            real_time, memory, cpu_time
        self.real_time = float(self.real_time)
        self.memory = float(self.memory)
        self.cpu_time = float(self.cpu_time)

    def __str__(self):
        return "cpu_time=%s, memory=%sMb, real_time=%s" % (
                self.cpu_time, self.memory, self.real_time)

    def __repr__(self):
        return self.__str__()

'''
This function controls the execution of the program.
It looks after memory limit, time limit (cpu and real),
that means that program will be terminated if it exeeds any of constraints.

It returns ResultInfo, showing result of execution.

Example of using:
  import psutil
  from subprocess import PIPE

  handler = psutil.Popen(["program.exe", "--arg1=first", "/arg2=second"],
                         stdout = PIPE) # read help(psutil.Popen)
  limits = ExecutionLimits(real_time=3, memory=128, cpu_time=10)
                           # cpu_time can be omitted; by default it equals
                           # to real_time.
                           # Warning: don't use this value if you don't
                           # know what is it

  result = invoke(handler, limits)
  print(str(result))
  if (result.verdict != "OK"):
      print("42")
  else:
      raise Exception(":-(")
'''
def invoke(handler, limits):
    CHECK_PERIOD = 0.05
    MEGABYTE = 1 << 20

    used_memory = 0
    cpu_time = 0
    verdict = None

    start_time = time.time()
    real_time = 0
    pid = handler.pid
    return_code = None
    while return_code is None:
        #wait some time before checking process information,
        #because in darwin it is access denied raised in first moment
        try:
            return_code = handler.wait(CHECK_PERIOD)
        except psutil.TimeoutExpired:
            pass

        try:
            cpu_time = sum(list(handler.get_cpu_times()))
            real_time = time.time() - start_time
            used_memory = max(used_memory, __get_memory_info(handler))
        except psutil.error.NoSuchProcess as e:
            #logger.warning("Couldn't check limits: NoSuchProcess")
            continue#sometimes it happens for unknown reasons
        except psutil.error.AccessDenied as e:
            try:#wait some time, in darwin process is steel running, but already not exists
                return_code = handler.wait(CHECK_PERIOD)
            except psutil.TimeoutExpired:
                pass
            #logger.warning("Couldn't check limits: AccessDenied")
            continue#sometimes it happens for unknown reasons

        if real_time > limits.real_time:
            handler.kill()
            verdict = "real TL"
            return_code = None
            break
        elif cpu_time > limits.cpu_time:
            handler.kill()
            verdict = "TL"
            return_code = None
            break
        elif used_memory > MEGABYTE * limits.memory:
            handler.kill()
            verdict = "ML"
            return_code = None
            break

    real_time = time.time() - start_time
    if real_time > limits.real_time:
        verdict = "real TL"
        return_code = None

    verdict = verdict or ("OK" if return_code == 0 else "RE")
    return ResultInfo(verdict, return_code, real_time, cpu_time, used_memory / MEGABYTE)

__current_platform = platform_detector.get_platform()

def __get_memory_info(handler):
    return handler.get_memory_info()[0]


import sys
import pdb
import svgfig
import json
import math

argv = {}
argv["json"] = 0
argv["max-time"] = 0
argv["max-nodes"] = 0
argv["silent"] = False
g = svgfig.SVG("g")
nodes = set()
nodes_index = {}

offset = 15
groups = {}

# BEGIN FUNCTIONS
def ask_args():
	sys.stderr.write(" Input number of nodes[" + str(argv["max-nodes"]) + "]:\n")
	user_maxnodes = raw_input()
	if user_maxnodes != '':
		argv["max-nodes"] = int(user_maxnodes)
	sys.stderr.write(" Input maximum time [" + str(argv["max-time"]) + "]:\n")
	user_maxtime = raw_input()
	if user_maxtime != '':
		argv["max-time"] = int(user_maxtime)

def infer_args():
	cpt = 1
	if argv["json"] == 0:
		inputfile = open(sys.argv[1])
		for line in inputfile.readlines():
			contents = line.split(" ")
			t = int(contents[0])
			u = contents[1].strip()
			v = contents[2].strip()

			if t > argv["max-time"]:
				argv["max-time"] = t

			nodes.add(u)
			nodes.add(v)

			if not u in nodes_index:
				nodes_index[u] = cpt
				cpt += 1
			if not v in nodes_index:
				nodes_index[v] = cpt
				cpt += 1

			#if u > argv["max-nodes"]:
			#	argv["max-nodes"] = u
			#if v > argv["max-nodes"]:
			#	argv["max-nodes"] = v
		inputfile.close()
		argv["max-nodes"] = len(nodes)
	else:
		json_struct = json.loads(open(sys.argv[1], "r").read())
		cpt = 1
		for link in json_struct:
			argv["max-time"] = max(argv["max-time"], json_struct[link]["time"])
			nodes.add(str(json_struct[link]["from"]))
			nodes.add(str(json_struct[link]["to"]))

			if not json_struct[link]["from"] in nodes_index:
				nodes_index[json_struct[link]["from"]] = cpt
				cpt += 1
			if not json_struct[link]["to"] in nodes_index:
				nodes_index[json_struct[link]["to"]] = cpt
				cpt += 1

			argv["max-nodes"] = max(argv["max-nodes"], nodes_index[json_struct[link]["from"]], nodes_index[json_struct[link]["to"]])

def show_help():
	print("Usage: main.py input_file [--silent] [--json=1] [--output=<out.svg>]")
	print("Input file is either a text file containing t u v, or a JSON file where the following properties are available:")
	print("    from")
	print("    to")
	print("    time")
	print("    color: to be chosen in http://www.december.com/html/spec/colorsvg.html")
	# print("    group: Group ID (any number) offers the opportunity to color groups of links identically")

def read_argv():
	for arg in sys.argv:
		if "=" in arg:
			content = arg.split("=")
			arg_name = content[0].replace("--", "")
			argv[arg_name] = content[1]
		elif "silent" in arg:
			argv["silent"] = True

def version():
	sys.stderr.write("\tTempNetSVG 1.0 -- Jordan Viard 2015\n")
# END FUNCTIONS

# BEGIN MAIN PROGRAM
if len(sys.argv) < 2 or "--help" in sys.argv or "-h" in sys.argv :
	show_help()
	sys.exit()
if "-v" in sys.argv or "--version" in sys.argv:
	version()
	exit()

read_argv()

## Infer max-nodes/times from input file, and confirm
infer_args()
if not argv["silent"]:
	ask_args()
	sys.stderr.write(" I will now generate a drawing of file " + str(sys.argv[1]) + ", containing " + str(argv["max-nodes"]) + " nodes over " + str(argv["max-time"]) + " instants of time."+ "\n")

max_node_length = 0
# Manage node labels
for i in range(1, int(argv["max-nodes"]) + 1):
	if(len(list(nodes)[i-1]) > max_node_length):
		max_node_length = len(list(nodes)[i-1])

# Define dimensions
width = 5*max_node_length + 10*int(argv["max-time"]+5)
svgfig._canvas_defaults["width"] = str(width) + 'px'

height = 2 + 10*int(argv["max-nodes"])
svgfig._canvas_defaults["height"] = str(height) + 'px'

origleft = max_node_length*5+5
origtop = 0

#For groups only
hoffset = 0
voffset = 10
################
# Draw background lines
for i in range(1, int(argv["max-nodes"]) + 1):
	g.append(svgfig.SVG("text", str(list(nodes)[i-1]), x=str(max_node_length*5), y=10*i+origtop+2, fill="black", stroke_width=0, text_anchor="end", font_size="6"))
	g.append(svgfig.SVG("line", stroke_dasharray="2,2", stroke_width=0.5, x1=str(origleft), y1=10*i+origtop, x2=width - 5, y2=10*i + origtop))

# Add timearrow
# g.append(svgfig.SVG("line", stroke_width=0.5, x1=10, y1=10+10*int(argv["max-nodes"]) , x2=25+10*int(argv["max-time"]), y2=10+10*int(argv["max-nodes"])))
# g.append(svgfig.SVG("line", stroke_width=0.5, x1=22+10*int(argv["max-time"]), y1=7+10*int(argv["max-nodes"]) , x2=25+10*int(argv["max-time"]), y2=10+10*int(argv["max-nodes"])))
# g.append(svgfig.SVG("line", stroke_width=0.5, x1=22+10*int(argv["max-time"]), y1=13+10*int(argv["max-nodes"]) , x2=25+10*int(argv["max-time"]), y2=10+10*int(argv["max-nodes"])))
# g.append(svgfig.SVG("text", str("Time"), x=25+10*int(argv["max-time"]) , y=-4+10*int(argv["max-time"]) , fill="black", stroke_width=0, style="font-size:4"))
#
# # Add time ticks
# for i in range(0, int(argv["max-time"])):
# 	if i % 5 == 0:
# 		if i == 0:
# 			g.append(svgfig.SVG("line", stroke_width=0.5, x1=10 , y1=10+10*int(argv["max-nodes"]), x2=10 , y2=12+10*int(argv["max-nodes"])))
# 			g.append(svgfig.SVG("text", str(i), x=10 , y=-2+10*int(argv["max-time"]) , fill="black", stroke_width=0, style="font-size:6"))
# 		else:
# 			g.append(svgfig.SVG("line", stroke_width=0.5, x1=offset*i , y1=10+10*int(argv["max-nodes"]), x2=offset*i , y2=12+10*int(argv["max-nodes"])))
# 			g.append(svgfig.SVG("text", str(i), x=offset*i , y=-2+10*int(argv["max-time"]) , fill="black", stroke_width=0, style="font-size:6"))

# Transform file of triplets into JSON structure, or load JSON structure
links_to_json = []
# If we are reading from a JSON file
if int(argv["json"]) is 1:
	json_struct = json.loads(open(sys.argv[1], "r").read())
	for link in json_struct:
		new_link = {}
		new_link["time"] = int(json_struct[link]["time"])
		new_link["from"] = min(nodes_index[json_struct[link]["from"]], nodes_index[json_struct[link]["to"]])
		new_link["to"] = max(nodes_index[json_struct[link]["from"]], nodes_index[json_struct[link]["to"]])
		if json_struct[link].get("color") is not None:
			new_link["color"] = json_struct[link]["color"]
		else:
			new_link["color"] = "black"

		if json_struct[link].get("curved") is not None:
			new_link["curved"] = json_struct[link]["curved"]
		else:
			new_link["curved"] = 1

		if json_struct[link].get("group") is not None:
			new_link["group"] = json_struct[link]["group"]
			groupID = json_struct[link]["group"]
			groups[groupID] = {}
			groups[groupID]["timeStart"] = 100000
			groups[groupID]["timeEnd"] = 0
			groups[groupID]["nodeStart"] = 100000
			groups[groupID]["nodeEnd"] = 0
		else:
			new_link["group"] = None

		links_to_json.append(new_link)
# Otherwise, we have to transform the file into a dict structure
else:
	with open(sys.argv[1], 'r') as infile:
		for line in infile:
			link = {}
			contents = line.split(" ")
			link["time"] = int(contents[0])
			link["from"] = min(nodes_index[contents[1].strip()],nodes_index[contents[2].strip()])
			link["to"] = max(nodes_index[contents[1].strip()],nodes_index[contents[2].strip()])
			link["color"] = "black"
			link["curved"] = 1
			link["group"] = None
			links_to_json.append(link)

# Read JSON structure
for link in links_to_json:
	ts = link["time"]
	node_1 = link["from"]
	node_2 = link["to"]
	offset = ts*10 + 15

	# Add nodes
	g.append(g.append(svgfig.SVG("circle", cx=origleft + offset, cy=10*node_1, r=1, fill=link["color"])))
	g.append(g.append(svgfig.SVG("circle", cx=origleft + offset, cy=10*node_2, r=1, fill=link["color"])))

	# Draw path between nodes according to specified curving -- links can be curved or not.
	if link["curved"] is 1:
		x = 0.2*((10*node_2 - 10*node_1)/math.tan(math.pi/3)) + origleft + offset
		y = (10*node_1 + 10*node_2) / 2

		g.append(svgfig.SVG("path", stroke=link["color"],d="M" + str(origleft + offset) + "," + str(10*node_1) + " C" + str(x) + "," + str(y) + " " + str(x) + "," + str(y) + " " + str(origleft + offset) + "," + str(10*node_2)))
	else:
		g.append(svgfig.SVG("line", x1=offset, y1=10*node_1, x2=offset, y2=10*node_2, stroke=link["color"]))

	if link["group"] is not None:
		groupID = int(link["group"])
		if groups[groupID]["timeStart"] > link["time"]:
			groups[groupID]["timeStart"] = link["time"]

		if groups[groupID]["timeEnd"] < link["time"]:
			groups[groupID]["timeEnd"] = link["time"]

		if groups[groupID]["nodeStart"] > min(link["from"], link["to"]):
			groups[groupID]["nodeStart"] = min(link["from"], link["to"])

		if groups[groupID]["nodeEnd"] < max(link["from"], link["to"]):
			groups[groupID]["nodeEnd"] = max(link["from"], link["to"])

# Draw groups
# for group in groups:
# 	print "Time start : " + str(groups[group]["timeStart"]*hoffset)
# 	print "Time end : " + str(groups[group]["timeEnd"]*hoffset)
# 	print "Node start : " + str(groups[group]["nodeStart"])
# 	print "Node end : " + str(groups[group]["nodeEnd"])

	# g.append(svgfig.SVG("rect", x=str(groups[group]["timeStart"]*hoffset), y=str(groups[group]["nodeStart"]*voffset), width=str(groups[group]["timeEnd"]*hoffset - groups[group]["timeStart"]*hoffset - 21), height=str(groups[group]["nodeEnd"]*voffset - groups[group]["nodeStart"]*voffset), style="fill:blue;stroke:blue;stroke-width:1;fill-opacity:0;stroke-opacity:0.9"))

# Save to svg file
if argv.get("output") is not None:
	svgfig.canvas(g, viewBox="0 0 " + str(width) + " " + str(height)).save(argv["output"])
	if not argv["silent"]:
		sys.stderr.write("Output generated to "+ str(argv["output"]) + ".\n")
else:
	svgfig.canvas(g, viewBox="0 0 " + str(width) + " " + str(height)).save("out.svg")
	if not argv["silent"]:
		sys.stderr.write(" Output generated to out.svg.\n")


"""
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
For example, the sum of the proper divisors of 28 would
be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant
if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written
as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all
integers greater than 28123 can be written as the sum of two abundant numbers.
However, this upper limit cannot be reduced any further by analysis even though it is known that
the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
def sumDivisors(number):
	somme=0
	for i in range(1,number//2+1):
		if number%i==0:
			somme+=i
	return somme

def main():
	abundantNumbers=[]
	for x in range(1,28123):
		if x < sumDivisors(x):
			abundantNumbers.append(x)

	sumTwoAbundant=set()
	for i in range(0,len(abundantNumbers)):
		for j in range(0,len(abundantNumbers)):
			while abundantNumbers[i]+abundantNumbers[j] < 28123:
				sumTwoAbundant.add(abundantNumbers[i]+abundantNumbers[j])
				break

	somme=0
	for i in range(1,28123):
		if i in sumTwoAbundant:
			pass
		else :
			somme+=i
	print(somme)

if __name__ == '__main__':
	main()


import time
import networkx as nx

GWASoverlap=open('GeneOverlap.txt','r')

GeneMapfile=open('hugogenelist.txt','r')

GeneMap=[]
allgenenames=[]
DataCombos=[]

posEntrez={}
posEntrez=set()

G = nx.Graph()

# class Gene:
#     def __init__(self, name, aliases=None, entrez=None, UID=None, ens=None):
#         self.name=name
#         self.aliases=aliases
#         self.entrez=entrez
#         self.UID=UID
#         self.ens=ens
#         if self.ens==None:
#             self.ens=''

class DataCombo:
    def __init__(self, name, genes=None):
        self.name=name
        self.genes=genes

for i in GeneMapfile:
    i=i.split('\t')
    iname=i[0]

    if iname!='Approved Symbol':
        iUID=i[4]
        ientrez=i[3]

        ialiases=i[1]+','+i[2]

        ialiases=ialiases.split(',')
        for j in range(len(ialiases)):
            if ialiases[j]!='':
                if ialiases[j][0]==' ':
                    ialiases[j]=ialiases[j][1:]
        if ialiases[0]=='' and ialiases[1]=='':
            ialiases=['']
        if len(ialiases)>1:
            if ialiases[0]=='' and ialiases[1]!='':
                ialiases=ialiases[1:]
        iens=i[5]

        print(iname,ialiases,ientrez,iUID, iens)
        igene=[iname,ientrez]
        GeneMap.append(igene)
        G.add_node(ientrez, positive=False)

def geneLister(superstring):
    length=len(superstring)
    superstring=superstring[1:length-2]
    superstring=superstring.replace('\'','')
    superstring=superstring.split(',')
    GeneList=superstring
    return GeneList

def geneobjectifier(GeneList):
    SuperGeneList=[]
    for i in range(len(GeneList)):
        found=False
        if GeneList[i]=='':
            continue

        if GeneList[i][0]==' ':
            GeneList[i]=GeneList[i][1:]
        for supergene in GeneMap:
            if supergene[0]==GeneList[i]:
                found=True
                GeneList[i]=supergene
                posEntrez.add(supergene[1])
                G.nodes[supergene[1]]['positive']=True

    return GeneList

for combo in GWASoverlap:
    combo=combo.split(';')
    comboname=combo[0]
    print('----------------')
    print(comboname)
    genes=combo[1]
    # print genes
    genes=geneLister(genes)
    genes=geneobjectifier(genes)
    DataCombos.append(DataCombo(comboname,genes))

for DataCombo in DataCombos:
    print(DataCombo.name)
    print(DataCombo.genes)

GIANTbrain=open('brain_top.txt','r')

start=time.time()
# GIANTentrez={}
# GIANTentrez=set()
# GIANTentrez5={}
# GIANTentrez5=set()
# GIANTentrez75={}
# GIANTentrez75=set()
# GIANTentrez9={}
# GIANTentrez9=set()
# GIANTentrez25={}
# GIANTentrez25=set()
# GIANTentrez10={}
# GIANTentrez10=set()
x=0
for line in GIANTbrain:

    timepassedSinceStart=time.time()-start
    x=x+1
    done=x*100.0/41668864.0
    if x%50000==0:
        print()
        print(done, 'percent completed')
        print('time remaining:', (100-done)*timepassedSinceStart/done, 'seconds')

    line=line.split('\t')
    line[2]=float(line[2][:len(line[2])-2])

    if line[2]>0.5:

        G.add_edge(line[0],line[1], weight=line[2])

GIANTbrain.close()

print(G.number_of_edges())
print(G.number_of_nodes())
print()
HasPositiveNeighbors=[]
weightedHasPositiveNeighbors=[]

start=time.time()
x=0
for node in G:
    x=x+1
    done=x*100.0/G.number_of_nodes()
    if x%1==0:
        print()
        print(done, 'percent completed')
        print('time remaining:', (100-done)*timepassedSinceStart/done, 'seconds')
    if len(G.nodes[node])>0:
        if G.nodes[node]['positive']==False:

            positiveNeighborCount=0
            weightedCount=0.0
            for adjacent,datadict in G.adj[node].items():
                if len(G.nodes[adjacent])>0:
                    if G.nodes[adjacent]['positive']==True:
                        positiveNeighborCount=positiveNeighborCount+1
                        weightedCount=weightedCount+datadict['weight']
            if positiveNeighborCount>0:
                HasPositiveNeighbors.append([node,positiveNeighborCount])
                weightedHasPositiveNeighbors.append([node,weightedCount])

    # for gene in GeneMap:

SortedHasPositiveNeighbors=sorted(HasPositiveNeighbors, key=lambda student: student[1], reverse=True)
SortedWeighted=sorted(weightedHasPositiveNeighbors, key=lambda student: student[1], reverse=True)

for gene in SortedHasPositiveNeighbors:
    for supergene in GeneMap:
        if supergene[1]==gene[0]:
            gene[0]=supergene[0]

for gene in SortedWeighted:
    for supergene in GeneMap:
        if supergene[1]==gene[0]:
            gene[0]=supergene[0]

output=open('genesWithAdjacentPositivesSansPositives0.5.txt','w')

for i in SortedHasPositiveNeighbors:
    output.write(str(i)+'\n')

output.write('\n\n\n')

for i in SortedWeighted:
    output.write(str(i)+'\n')


from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Profile(models.Model):
    nickname = models.CharField(verbose_name='昵称',max_length=50, blank=True)
    user = models.OneToOneField(User)

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


import torch
# from tensorboardX import SummaryWriter

import sys
import torch.optim as optim
import os

def add_path(path):
    if path not in sys.path:
        print('Adding {}'.format(path))
        sys.path.append(path)

abs_current_path = os.path.realpath('./')
root_path = os.path.join('/', *abs_current_path.split(os.path.sep)[:-3])
lib_dir = os.path.join(root_path, 'lib')
add_path(root_path)

from experiments.cifar10.preres18_yopo_5_3.config import config, args
from experiments.dataset import create_train_dataset, create_test_dataset
from experiments.cifar10.preres18_yopo_5_3.network import create_network

from lib.utils.misc import save_checkpoint, load_checkpoint
from lib.training.train import eval_one_epoch
from experiments.cifar10.preres18_yopo_5_3.loss import Hamiltonian
from experiments.cifar10.preres18_yopo_5_3.training_function import train_one_epoch, FastGradientLayerOneTrainer

def main():
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    torch.backends.cudnn.benchmark = True

    # writer = SummaryWriter(log_dir=config.log_dir)

    net = create_network()
    net.to(device)
    criterion = config.create_loss_function().to(device)
    # criterion = CrossEntropyWithWeightPenalty(net.other_layers, DEVICE, config.weight_decay)#.to(DEVICE)
    # ce_criterion = nn.CrossEntropyLoss().to(DEVICE)
    optimizer = config.create_optimizer(net.other_layers.parameters())
    lr_scheduler = config.create_lr_scheduler(optimizer)

    # Make Layer One trainer  This part of code should be writen in config.py

    Hamiltonian_func = Hamiltonian(net.layer_one, config.weight_decay)
    layer_one_optimizer = optim.SGD(net.layer_one.parameters(), lr=lr_scheduler.get_last_lr()[0], momentum=0.9,
                                    weight_decay=5e-4)
    layer_one_optimizer_lr_scheduler = optim.lr_scheduler.MultiStepLR(layer_one_optimizer,
                                                                      milestones=[55, 75, 95], gamma=0.1)
    LayerOneTrainer = FastGradientLayerOneTrainer(Hamiltonian_func, layer_one_optimizer,
                                                  config.inner_iters, config.sigma, config.eps)

    ds_train = create_train_dataset(args.batch_size)
    ds_val = create_test_dataset(args.batch_size)

    # TrainAttack = config.create_attack_method(DEVICE)
    eval_attack = config.create_evaluation_attack_method(device)

    now_epoch = 0

    if args.auto_continue:
        args.resume = os.path.join(config.model_dir, 'last.checkpoint')
    if args.resume is not None and os.path.isfile(args.resume):
        now_epoch = load_checkpoint(args.resume, net, optimizer, lr_scheduler)

    for i in range(now_epoch, config.num_epochs):

        descrip_str = 'Epoch:{}/{} -- lr:{}'.format(i, config.num_epochs,
                                                    lr_scheduler.get_last_lr()[0])
        acc, yofoacc = train_one_epoch(net, ds_train, optimizer, criterion, LayerOneTrainer, config.K,
                                       device, descrip_str)
        tb_train_dic = {'Acc': acc, 'YofoAcc': yofoacc}
        print('Train: {}'.format(tb_train_dic))

        if config.eval_interval > 0 and i % config.eval_interval == 0:
            acc, advacc = eval_one_epoch(net, ds_val, device, eval_attack)
            tb_val_dic = {'Acc': acc, 'AdvAcc': advacc}
            print('Eval: {}'.format(tb_val_dic))

        lr_scheduler.step()
        layer_one_optimizer_lr_scheduler.step()

    save_checkpoint(i, net, optimizer, lr_scheduler,
                    file_name=os.path.join(config.model_dir, 'epoch-{}.checkpoint'.format(i)))
    acc, advacc = eval_one_epoch(net, ds_val, device, eval_attack)
    tb_val_dic = {'Acc': acc, 'AdvAcc': advacc}
    print('Eval: {}'.format(tb_val_dic))

if __name__ == '__main__':
    main()


import turtle
from create_board import create_board
window_width = 450
window_hight = 450

def collect_empty(i, j, board,empties):
    if board[i][j][3] == 0 and (not board[i][j][0]):
        empties.append([i,j])

def uncover_nearby(i, j, board,empties):
    if i != 0:
        collect_empty(i-1,j,board,empties)
        board[i-1][j][0] = True
    if i != len(board)-1:
        collect_empty(i+1,j,board,empties)
        board[i+1][j][0] =True
    if j != 0:
        collect_empty(i,j-1,board,empties)
        board[i][j-1][0] = True
    if j != len(board[0])-1:
        collect_empty(i,j+1,board,empties)
        board[i][j+1][0] = True
    if i != 0 and j != 0:
        collect_empty(i-1,j-1,board,empties)
        board[i-1][j-1][0] = True
    if i != 0 and j != len(board[0])-1:
        collect_empty(i-1,j+1,board,empties)
        board[i-1][j+1][0] = True
    if i != len(board)-1 and j != 0:
        collect_empty(i+1,j-1,board,empties)
        board[i+1][j-1][0] = True
    if i != len(board)-1 and j != len(board[0])-1:
        collect_empty(i+1,j+1,board,empties)
        board[i+1][j+1][0] = True

def uncover_field(board,x,y):
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j][4] <= x < board[i][j][4]+window_width/len(board[0])\
                    and board[i][j][5] <= y < board[i][j][5]+window_hight/len(board):
                board[i][j][0] = True
                if board[i][j][3] == 0:
                    empties = []
                    empties.append([i,j])
                    while len(empties) != 0:
                        i, j = empties[0]
                        uncover_nearby(i,j,board,empties)
                        del empties[0]

board = create_board(5,5,4)
for line in board:
    print(line)
x = int(input("x"))
y = int(input("y"))
uncover_field(board,x,y)
for i in range(len(board)):
    print(board[i])


import cv2
import os
import moviepy.editor as mp

video = "00046"
#input_imgs
im_dir = '/home/cai/Desktop/yolo_dataset/t1_video/t1_video_'+video+'/'
#im_dir =
#output_video
video_dir = '/home/cai/Desktop/yolo_dataset/t1_video/test_video/det_t1_video_'+video+'_test_q.avi'
#fps
fps = 50
#num_of_imgs
num = 310
#img_size
img_size = (1920,1080)
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
#opencv3

videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)
for i in range(0,num):
    #im_name = os.path.join(im_dir,'frame-' + str(i) + '.png')
    im_name = os.path.join(im_dir,'t1_video_'+video+'_' + "%05d" % i + '.jpg')
    frame = cv2.imread(im_name)
    #frame = cv2.resize(frame, (480, 320))
    #frame = cv2.resize(frame,(520,320), interpolation=cv2.INTER_CUBIC)
    videoWriter.write(frame)
    print (im_name)
videoWriter.release()
print('finish')


from datetime import datetime, timedelta

from podiomirror.transport import call_endpoint, POST

class Token:
    def __init__(self, client_id, client_secret, app_id, access_token, token_type, expires_in, refresh_token, auto_refresh=True):
        self.client_id = client_id
        self.client_secret = client_secret
        self.app_id = app_id
        self.access_token = access_token
        self.token_type = token_type
        self.expiry_time = datetime.now() + timedelta(seconds=expires_in)
        self.refresh_token = refresh_token
        self.auto_refresh = auto_refresh

    def is_token_valid(self):
        return datetime.now() < self.expiry_time

    def perform_token_refresh(self):
        refresh_data = {
            'grant_type': 'refresh_token',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'refresh_token': self.refresh_token
        }
        response = call_endpoint('/oauth/token', POST, refresh_data)
        response.raise_for_status()

        data = response.json()
        self.access_token = data['access_token']
        self.expiry_time = datetime.now() + timedelta(seconds=int(data['expires_in']))
        self.refresh_token = data['refresh_token']

    def get_valid_token(self):
        if not self.is_token_valid():
            if self.auto_refresh:
                self.perform_token_refresh()
            else:
                raise RuntimeError('Failed to retrieve a valid token')

        return self.access_token


lista =[['Diego', '566','Anivia Supp','(21)9999999'],
        ['Clara', '566','Geek','(21)9999999'],
        ['Samara', '566','Otaka','(21)9999999'],
        ['Vitória', '566','Gamer','(21)9999999']]

def busca(setor,matriz):
    '''essa função recebe uma matriz e retorna somente o nome daqueles que são de determinado setor'''
    '''str, list -> list'''
    setor = str.lower(setor)
    funcionarios_encontrados = []

    for i in range(len(matriz)) :
     if setor in str.lower(matriz[i][2]):
        cargo = matriz[i]
        del cargo[2]
        funcionarios_encontrados.append(cargo)
    return funcionarios_encontrados

print(busca('Geek',lista))


import math

class Solution(object):
	def findMedianSortedArrays(self, nums1, nums2):
		l1 = len(nums1) # length 1
		l2 = len(nums2) # length 2

		# check ending conditions
		# if list 1 is empty, return the median of list 2
		if nums1 == [] and nums2 != [] > 0: return median(nums2)
		# if list 2 is empty, return the median of list 1
		if nums2 == [] and nums1 != []: return median(nums1)
		# if list 1 and list 2 have the same median, return it
		if median(nums1) == median(nums2): return median(nums1)
		# if list 1 = [x] and list 2 = [y], return (x+y)/2
		if l1 == 1 and l2 == 1: return (nums1[0] + nums2[0])/2

		m1 = median(nums1)
		m2 = median(nums2)

		if m1 > m2:
			i = l1 - (l1//2)
			del nums1 [(l1//2):l1]
			del nums2 [0:i]

		else:
			i = l2 - (l2//2)
			del nums2 [(l2//2):l2]
			del nums1 [0:i]

		return Solution.findMedianSortedArrays(self, nums1,nums2)

def median(x):
	if len(x) % 2 == 0:
		return (x[len(x) // 2] + x[(len(x)//2)-1]) / 2
	return x[len(x)//2]


import requests
import time
import logging
import threading

from tiempo import Contador

logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(threadName)s] - %(message)s', datefmt='%H:%M:%S', level=logging.INFO)

img_urls = [
    'https://images.unsplash.com/photo-1516117172878-fd2c41f4a759',
    'https://images.unsplash.com/photo-1532009324734-20a7a5813719'

]

def bajar_imagen(img_url):

        img_bytes = requests.get(img_url).content
        img_name = img_url.split('/')[3]
        img_name = f'{img_name}.jpg'
        with open(img_name, 'wb') as img_file:
            img_file.write(img_bytes)
        # print(f'{img_name} fue bajada...')

#tiempo.iniciar()

# una por una
#for url in img_urls:
 #   bajar_imagen(url)

#tiempo.finalizar()
#tiempo.imprimir()

# Pero ahora con threads
def run():
    dato=img_urls.pop()
    bajar_imagen(dato)

tiempo = Contador()

tiempo.iniciar()

lista = [] #crea una lista vacía

for i in range(2):
    #crear un thead
    imag = threading.Thread(target=run)
    #lanzarlo
    lista.append(imag)
    imag.start()

for thread in lista:
    thread.join()

tiempo.finalizar()
tiempo.imprimir()


# -*- coding: utf-8 -*-
import numpy as np
import cv2
import xlrd
import config as cfg
import os
import random as rd

class ADE20K():
    txt_names = []

    def findfile(self,rootdir):
        for dir in os.listdir(rootdir):
            nrootdir = os.path.join(rootdir, dir)
            if os.path.isdir(nrootdir):
                self.findfile(nrootdir)
            else:
                if os.path.splitext(dir)[1] == '.txt':
                    self.txt_names.append(nrootdir)

    def __init__(self,rootdir,excel_file):
        self.findfile(rootdir)
        rd.shuffle(self.txt_names)

        self.force_data = xlrd.open_workbook(excel_file)
        self.force_table = self.force_data.sheets()[0]
        self.names = self.force_table.col_values(0)
        self.names_indexs_dict = {}
        self.force_list = []
        for i in range(0, self.force_table.nrows):
            self.force_list.append(self.force_table.row_values(i))

        for i in range(1, len(self.names)):
            self.names_indexs_dict[self.names[i]] = i + 1

        self.index = 0
        self.num_images = len(self.txt_names)

    def get_labelmask(self, txt_name):

        txt_file = open(txt_name)
        lines = txt_file.readlines()
        lei_dict = {}
        lei_dict[' 0 '] = []
        lei_dict[' 1 '] = []
        lei_dict[' 2 '] = []

        for line in lines:
            try:
                line_s = line.split('#')
                lei_dict[line_s[1]].append(line_s[3])
            except:
                pass

        lei_dict[' 0 '] = list(set(lei_dict[' 0 ']))
        lei_dict[' 1 '] = list(set(lei_dict[' 1 ']))
        lei_dict[' 2 '] = list(set(lei_dict[' 2 ']))

        lei_dict_all = {}

        for i in lei_dict:
            tempdict = {}
            for name in lei_dict[i]:
                index = self.names_indexs_dict[name.strip()]
                tempdict[index] = self.force_list[index - 1]
            lei_dict[i] = tempdict
            lei_dict_all.update(tempdict)

        def hecheng(seg_index, part_index, mask, level):
            temp_maskhc_bl = np.zeros(seg_index.shape, dtype=np.int)
            temp_maskhc_xc = np.ones(seg_index.shape, dtype=np.int)
            level_lei_dict = lei_dict[level]
            for i in level_lei_dict:
                # i为类别id
                if level_lei_dict[i][10] == 0:
                    temp_maskhc_xc[part_index == i] = 0
                    temp_maskhc_bl[temp_maskhc_xc == 0] = 1
                    seg_index = seg_index * temp_maskhc_xc + part_index * temp_maskhc_bl
                else:
                    lei_dict_all.pop(i)
                    if level_lei_dict[i][8] == 1:
                         mask[part_index == i] = 0

            return seg_index, mask

        seg_png = cv2.resize(cv2.imread(txt_name[:-7] + 'seg.png', 1), cfg.IMG_SIZE, interpolation=cv2.INTER_NEAREST)
        seg_index = seg_png[:, :, 2] / 10 * 256 + seg_png[:, :, 1]
        mask = np.ones(cfg.IMG_SIZE, dtype=np.int)

        if lei_dict[' 2 '] != {}:
            part2_name = txt_name[:-7] + 'parts_2.png'
            part2_png = cv2.resize(cv2.imread(part2_name, 1), cfg.IMG_SIZE)
            part2_index = part2_png[:, :, 2] / 10 * 256 + part2_png[:, :, 1]
            seg_index, mask = hecheng(seg_index, part2_index, mask, ' 2 ')

        if lei_dict[' 1 '] != {}:
            part1_name = txt_name[:-7] + 'parts_1.png'
            part1_png = cv2.resize(cv2.imread(part1_name, 1), cfg.IMG_SIZE)
            part1_index = part1_png[:, :, 2] / 10 * 256 + part1_png[:, :, 1]
            seg_index, mask = hecheng(seg_index, part1_index, mask, ' 1 ')

        # 查看seg图是否正常

        paper_elaster = np.ones(cfg.IMG_SIZE, dtype=np.float32)
        paper_parken = np.zeros(cfg.IMG_SIZE, dtype=np.float32)
        paper_slg = np.ones(cfg.IMG_SIZE, dtype=np.float32)
        # 固体1,流体-1

        for i in lei_dict_all:
            temp_b = seg_index == i
            if lei_dict_all[i][10] == 0:
                temp_bf = (temp_b).astype(np.float32)
                paper_elaster = paper_elaster + temp_bf * lei_dict_all[i][6]
                paper_parken = paper_parken + temp_bf * lei_dict_all[i][7]

            elif lei_dict_all[i][11] == 0:
                paper_slg[temp_b] = -1
        mask[paper_elaster == 0] = 0

        return np.dstack((paper_elaster, paper_parken, paper_slg, mask))

    def next_batch(self):
        if self.index+cfg.BATCH_SIZE>self.num_images:
            self.index = 0
            rd.shuffle(self.txt_names)
        imgs = []
        labels = []
        loop_times = cfg.BATCH_SIZE
        i = 0
        while i < loop_times:
            try:
                txt_name = self.txt_names[self.index + i]
                img = cv2.resize(cv2.imread(txt_name[:-8] + '.jpg'), cfg.IMG_SIZE)
                label_mask = self.get_labelmask(txt_name)
                imgs.append(img)
                labels.append(label_mask)
            except:
                print('error')
                loop_times = loop_times + 1
            i = i + 1
        batch_imgs = np.array(imgs)
        batch_labels = np.array(labels)
        self.index+=cfg.BATCH_SIZE
        return (batch_imgs,batch_labels)

ad = ADE20K('./ADETEST','./fcs.xlsx')

for iii in range(100):
    nb = ad.next_batch()

    limg = nb[0].reshape((512, 512, 3))
    cv2.imshow('img', limg)
    label_mask = nb[1].reshape(512, 512, 4)

    p = np.zeros(cfg.IMG_SIZE, dtype=np.uint8)
    p[label_mask[:, :, 3] == 0] = 255
    cv2.imshow('mask', p)

    p = np.zeros(cfg.IMG_SIZE, dtype=np.uint8)
    p[label_mask[:, :, 2] == -1] = 255
    cv2.imshow('lg', p)

    t0 = np.zeros(cfg.IMG_SIZE, dtype=np.uint8)
    t1 = np.floor(label_mask[:, :, 0]).astype(np.uint8)
    t2 = ((label_mask[:, :, 0] * 100) % 100).astype(np.uint8)
    cv2.imshow('ei', np.dstack((t0, t1, t2)))

    maxv = label_mask[:, :, 1].max()
    cv2.imshow('pi', (label_mask[:, :, 1] * 255 / maxv).astype(np.uint8))

    cv2.waitKey(0)


# importerer nodvnedige libraryer

import sys
import os
import platform
import ipaddress
import asyncio
from datetime import datetime as dt
import speedtest

# erklerer globale variabler
my_list_of_tasks = []
my_tasks = []
nbr_host_found = 0
list_of_hosts_found = []

# asynkron funksjon for aa send ping til spesifiser ip paa lokalt nettverk
async def ping_coroutine(cmd, ip):

   global nbr_host_found, list_of_hosts_found

   running_coroutine = await asyncio.create_subprocess_shell(
      cmd,
      stdout=asyncio.subprocess.PIPE,
      stderr=asyncio.subprocess.PIPE)

   # vent for svar paa ping
   stdout = await running_coroutine.communicate()

   # hvis svar inneholder time to live inkluder ip i liste
   # og inkrementer antall enheter funnet
   if "ttl=" in str(stdout).lower():

      nbr_host_found += 1
      list_of_hosts_found.append(ip)

async def ping_loop():

   global my_tasks, my_list_of_tasks

   for each_task_list in my_list_of_tasks:
      for each_coroutine in asyncio.as_completed(each_task_list):
         await each_coroutine

class Networkscan:

   def __init__(self, ip_and_prefix):
      # deklarere verdier brukt i objekt
      self.nbr_host_found = 0
      self.list_of_hosts_found = []

      # fil hvor lokale ip adresser funnet blir lagret
      self.filename = "hosts.txt"

      # tester om ip adresse er riktig
      try:
            self.network = ipaddress.ip_network(ip_and_prefix)
      except:
            sys.exit("Incorrect network/prefix " + ip_and_prefix)

      self.nbr_host = self.network.num_addresses

      if self.network.num_addresses > 2:
            self.nbr_host -= 2

      # kommando som skrives inn i terminal
      self.one_ping_param = "ping -n 1 -l 1 -w 1000 " if platform.system().lower() == "windows" else "ping -c 1 -s 1 -w 1 "

   # funksjon for aa skrive inn data i csv fil
   def write_file(self, filename="speedtest.csv"):
      ret = 0
      now = dt.now()
      time = now.strftime("%d/%m/%Y,%T")
      try:
         with open(filename, "a") as f:
               if os.stat(filename).st_size == 0:
                  f.write("Date,Time,Ping (ms),Download (Mbit/s),Upload (Mbit/s),number of hosts online, url, latitude, longitude, location, country, countrycode, ISP, id, host, d, latency \n")
               f.write(f"{time},{self.download},{self.upload},{self.ping},{self.nbr_host_found},{self.server}\n")

      except Exception:
         ret = 1

      return ret

   def run(self):
      global my_tasks, nbr_host_found, list_of_hosts_found, my_list_of_tasks

      # kjorer speedtest
      st = speedtest.Speedtest()
      # lagrer resultater
      # merk download og upload i multithread mode
      self.download = st.download()
      self.upload = st.upload()
      self.ping = st.results.ping
      # self.server = str(st.get_best_server()).replace(",", "     ")
      self.server = list(st.get_best_server().values())

      # check for hosts
      self.nbr_host_found = 0
      self.list_of_hosts_found = []
      my_tasks = []
      nbr_host_found = 0
      list_of_hosts_found = []

      i = 128

      my_list_of_tasks = []

      my_list_of_tasks.append(my_tasks)

      if self.network.num_addresses != 1:
         for host in self.network.hosts():

            cmd = self.one_ping_param + str(host)
            my_tasks.append(ping_coroutine(cmd, str(host)))
            i -= 1
            if i <= 0:
                  i = 128
                  my_tasks = []
                  my_list_of_tasks.append(my_tasks)
            else:
               host = str(self.network.network_address)
               cmd = self.one_ping_param + host
               my_tasks.append(ping_coroutine(cmd, host))

         # hvis kjores paa vindows kjor asyncio loop'er med IOCP
         if platform.system().lower() == "windows":
            asyncio.set_event_loop_policy(
            asyncio.WindowsProactorEventLoopPolicy())

         asyncio.run(ping_loop())

         self.list_of_hosts_found = list_of_hosts_found
         self.nbr_host_found = nbr_host_found

if __name__ == '__main__':

   # lokal ip adresse og cidr notasjon for subnet maske
   my_network = "192.168.10.0/24"

   my_scan = Networkscan(my_network)

   # skriv inn data i csv fil og  print ut masse data for debugging
   print("Network to scan: " + str(my_scan.network))
   print("Prefix to scan: " + str(my_scan.network.prefixlen))
   print("Number of hosts to scan: " + str(my_scan.nbr_host))
   print("Scanning hosts...")

   my_scan.run()

   print("List of hosts found:")

   for i in my_scan.list_of_hosts_found:
      print(i)

   print("Number of hosts found: " + str(my_scan.nbr_host_found))

   res = my_scan.write_file()

   if res:
      print("Write error with file " + my_scan.filename)

   else:
      print("Data saved into file " + my_scan.filename)

   # print object properties
   my_scan.tail = 1
   temp = vars(my_scan)
   for item in temp:
      print(item, ':', temp[item])


from logging import getLogger

import tensorflow as tf

logger = getLogger(__name__)

def set_gpu_memory_growth():
    """
    Reference:
      Use a GPU | TensorFlow Core
      https://www.tensorflow.org/guide/gpu
    """
    gpus = tf.config.experimental.list_physical_devices("GPU")
    if gpus:
        try:
            # Currently, memory growth needs to be the same across GPUs
            for gpu in gpus:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices("GPU")
            logger.info(
                f"Physical GPUs: {len(gpus)}, Logical GPUs: {len(logical_gpus)}"
            )
        except RuntimeError as e:
            # Memory growth must be set before GPUs have been initialized
            logger.warning(e)

if __name__ == "__main__":
    set_gpu_memory_growth()


from mecmon2 import *
import time
import gensim

class lda_wk(mecmon2):
    def lda_input(self):
        self.twelist = test.mongofind()

        self.nlist = []

        for self.twe in self.twelist:
            self.text = self.twe["tweet"]
            self.mecabres = self.exeMecab2(test.text)
            self.list = list(self.mecabres)

            self.nlist.append(self.list)

        return self.nlist

#LDAによるクラスタリング
if __name__ == "__main__":

    stime = time.time()

    #topicnum = float(20)
    #alpha = float(50)/topicnum

    #print(alpha)
    test = lda_wk("ht","insht")#collection選択

    test.nounlist = list(test.insco.distinct("name",{"func":"名詞"}))#名詞の要素抽出

    test.lda_input()

    test.dict = gensim.corpora.Dictionary(test.nlist)
    test.dict.filter_extremes(no_below = 20,no_above=0.3)

    print(test.dict)

    test.corpus = [test.dict.doc2bow(doc) for doc in test.nlist]

    #print(test.corpus)

    #print(test.corpus)

    lda = gensim.models.LdaModel(corpus=test.corpus, id2word=test.dict, num_topics=20,alpha='auto')
    #lda = gensim.models.LdaModel(corpus=test.corpus, id2word=test.dict, num_topics=topicnum,alpha=alpha)

    for topic in lda.show_topics(-1):
        print(topic)

    etime = time.time()
    print(etime - stime)


import time
import gzip
import pickle
import math
from math import acos,sin,cos,pow,sqrt
import numpy as np
import csv
import random

from OpenGLContext import testingcontext
BaseContext = testingcontext.getInteractive()

PI = math.pi

def mod(a,b):
	# return a%b
	return (a%b + b)%b

def spiral_points(N,a,f1,f2,f3,f4):

	theta = range(N);
	phi =  range(N);
	h =  range(N);
	phi[0] = 0;
	phi[N-1] = 0;
	for k in range(N):
		h[k] = -1 + (2.0*(k))/(N-1.0);
		theta[k] = acos(h[k]);

	count = 0
	for k in  range(1,N):
		if sqrt(1.0 - pow(h[k],2.0)) == 0:
			phi[k] = 0
			count+=1
		else:
			# print(phi[k-1] + (3.6/sqrt(N*1.0))* (1.0/sqrt(1.0 - pow(h[k],2.0))))
			phi[k] = mod(phi[k-1] + (3.6/sqrt(N*1.0))* (1.0/sqrt(1.0 - pow(h[k],2.0))),2.0*PI);
	for i in range(N):
		theta[i] = theta[i] - (PI/2);
		theta[i] /= 1
		phi[i]/= 1

	x = range(N)
	y = range(N)
	z = range(N)
	r = 1.0
	for i in range(N):
		x[i] = r*cos(phi[i]+(a*f1))*sin(theta[i]+(a*f2))
		# x[i] = r*cos(phi[i])
		y[i] = r*sin(phi[i]+(a*f3))*sin(theta[i])
		z[i] = r*cos(theta[i]+a*f4)

	return x,y,z

def spiral_points_sph(N):

	theta = range(N);
	phi =  range(N);
	h =  range(N);
	phi[0] = 0;
	phi[N-1] = 0;
	for k in range(N):
		h[k] = -1 + (2.0*(k))/(N-1.0);
		theta[k] = acos(h[k]);

	count = 0
	for k in  range(1,N):
		if sqrt(1.0 - pow(h[k],2.0)) == 0:
			phi[k] = 0
			count+=1
		else:
			# print(phi[k-1] + (3.6/sqrt(N*1.0))* (1.0/sqrt(1.0 - pow(h[k],2.0))))
			phi[k] = mod(phi[k-1] + (3.6/sqrt(N*1.0))* (1.0/sqrt(1.0 - pow(h[k],2.0))),2.0*PI);
	for i in range(N):
		theta[i] = theta[i] - (PI/2);
		theta[i] /= 1
		phi[i]/= 1

	for i in range(N):
		phi[i] += PI/2
		theta[i] += PI/2
		phi[i] = mod(phi[i],PI*2)
		theta[i] = mod(theta[i],PI*2)

	return phi,theta

def sph2cart(phi,theta):
	N = len(phi)
	x = range(N)
	y = range(N)
	z = range(N)
	r = 1.0

	for i in range(N):
		x[i] = r*cos(phi[i])*sin(theta[i])
		y[i] = r*sin(phi[i])*sin(theta[i])
		# x[i] = 1
		# x[i] = r*cos(phi[i])

		z[i] = r*cos(theta[i])
	return x,y,z

def cart2sph(x,y,z):
	N = len(x)
	theta = range(N)
	phi = range(N)
	for i in range(N):
		theta[i]=acos(z[i])
		phi[i]=atan2(y[i],x[i])

	# for i in range(N):
	#     x[i] = r*sin(phi[i])*cos(theta[i])
	#     y[i] = r*cos(phi[i])*cos(theta[i])
	#     # x[i] = 1
	#     # x[i] = r*cos(phi[i])

	#     z[i] = r*sin(theta[i])

	return phi,theta

def rotate_fun(a,f1,f2,f3,f4):
	def tmp(phi,theta):
		return rotate_point(phi,theta,a,f1,f2,f3,f4)
	return tmp;

def rotate_point(phi,theta,a,f1,f2,f3,f4):
	r = 1.0
	x = r*cos(phi+(a*f1))*sin(theta+(a*f2))
	y = r*sin(phi+(a*f3))*sin(theta)
	z = r*cos(theta+a*f4)

	return x,y,z

def write_points(x,y,z):
	with open('data_stream', 'wb') as f:
		f.write("points "+repr(len(x))+"\n")
		# for i,_ in enumerate(x):
		# 	# print(repr(x[i])+" "+repr(y[i])+" "+repr(z[i])+"\n")
		# 	f.write(repr(x[i])+" "+repr(y[i])+" "+repr(z[i])+"\n")
		writer = csv.writer(f, delimiter=' ')
		writer.writerows(zip(x,y,z))
		f.write("draw\n")

def clear():
	with open('data_stream', 'wb') as f:
		f.write("clear\n");

# i = 1
# a = i*1.0/time_steps
# a = 1
# x,y,z = rotate_points(phi,theta,a,f1,f2,f3,f4)
# p = np.array([x,y,z]).T
global SPACE_PRESSED
SPACE_PRESSED = False
def keyboard_fun(e):
	global SPACE_PRESSED
	if e.name == 'space':
		SPACE_PRESSED = True

from OpenGL.arrays import vbo
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import serial
import os
import threading
import colorsys
from PIL import Image
import keyboard
import colour
from colour import Color

keyboard.hook(keyboard_fun)

x = []
y = []
z = []

height = 1600
width = 800

def get_colors(N):
	c1 = Color(rgb=(1.0, 0.0, 0.0))
	c2 = Color(rgb=(1.0, .5, 0.0))
	c3 = Color(rgb=(1.0, 1.0, 0.0))
	colors1 = list(c1.range_to(c2,N/2))
	colors2 = list(c2.range_to(c3,N/2))

	colors = colors1+colors2
	if len(colors) < N:
		colors.append(c3)
	if len(colors) < N:
		colors.append(c3)
	# print(colors)
	# colors = range(N)
	for i in range(N):
		c = colors[i].rgb

		colors[i] = [c[0],c[1],c[2],1.0]
		# h = i*1.0/N
		# c = colorsys.hsv_to_rgb(h/2, 1.0, 1.0)
		# colors[i] = [c[0],c[1],c[2],1.0]
		# # colors[i] = [1.0-h,h,1.0]
	return colors

def get_colors_rainbow(N):
	colors = range(N)
	for i in range(N):
		h = i*1.0/N
		c = colorsys.hsv_to_rgb(h/2, 1.0, 1.0)
		colors[i] = [c[0],c[1],c[2],1.0]
		# colors[i] = [1.0-h,h,1.0]
	return colors

ESCAPE = '\033'

window = 0

#rotation
X_AXIS = 0.0
Y_AXIS = 0.0
Z_AXIS = 0.0

DIRECTION = 1

def InitGL(Width, Height):

	glClearColor(0.5, 0.5, 0.5, 0.5)
	glClearDepth(1.0)
	glDepthFunc(GL_LESS)
	glEnable(GL_DEPTH_TEST)
	glShadeModel(GL_SMOOTH)
	glMatrixMode(GL_PROJECTION)
	glLoadIdentity()
	gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
	glMatrixMode(GL_MODELVIEW)

def keyPressed(*args):
	if args[0] == ESCAPE:
		sys.exit()

def rotate_points(phi,theta,a,rf,f1,f2,f3,f4,f5):
	r = rf(a)
	a1 = f1(a)
	a2 = f2(a)
	a3 = f3(a)
	a4 = f4(a)
	a5 = f5(a)
	x = r*(np.cos(phi+a1)*np.sin(theta+a2)+np.sin(a)*2)/1.5#+np.cos(theta*a)/10
	y = r*(np.sin(phi+a3)*np.sin(theta+a5)+np.cos(a*.5)*2)/1.5#+np.sin(phi*a)/10
	z = r*(np.cos(theta+a4))#+np.cos(theta+a1)/10

	return x,y,z

N = 100
phi,theta = spiral_points_sph(N)
# colors = get_colors(N)
colors = get_colors_rainbow(N)

time_steps = 100;
phi = np.array(phi)
theta = np.array(theta)

def linear(a):
	return lambda x : a*x*1.0
global a
a = PI
f1 = linear(1)
f2 = linear(2)
f3 = linear(3)
f4 = linear(4)
f5 = linear(1)
f1 = lambda x : 1
f2 = lambda x : 1
f3 = lambda x : 1
f4 = lambda x : 1
f5 = lambda x : 1
rf = lambda x : .2+x/10

# f1 = lambda x : 1+np.sin(x*5)
# f2 = lambda x : 1+np.cos(x*20)
# f4 = lambda x : 1+np.cos(x*9)
# f5 = lambda x : np.sin(x)

speed = 1.0
point_size = 1.0
intensity = 4.0*speed
rotate_color = False
# tmp = phi
# phi = theta
# theta = tmp
global frame_num
frame_num = 0
def DrawGLScene():
	global X_AXIS,Y_AXIS,Z_AXIS
	global DIRECTION
	global a, SPACE_PRESSED, frame_num
	frame_num+=1

	start = time.time()
	a += .001*speed
	x,y,z = rotate_points(phi,theta,a,rf,f1,f2,f3,f4,f5)
	points = np.array([x,y,z]).T*1.5
	t = time.time()-start;
	# print("Move time: "+repr(t))

	glClear(GL_DEPTH_BUFFER_BIT)
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

	glLoadIdentity()
	glTranslatef(0.0,0.0,-6.0)

	glRotatef(X_AXIS,1.0,0.0,0.0)
	glRotatef(Y_AXIS,0.0,1.0,0.0)
	glRotatef(Z_AXIS,0.0,0.0,1.0)
	glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
	glPointSize(1*point_size);
	# Draw Cube (multiple quads)
	start = time.time()
	glBegin(GL_POINTS)

	glColor4f(0.0,1.0,0.0,0.1)

	for i,p in enumerate(points):
		if rotate_color:
			ci = (N/2) + np.sin(a+i*2*PI/N)*N/2
			ci = max(0,min(int(ci),N))
			c = colors[ci]
		else:
			c = colors[i]
		glColor4f(c[0],c[1],c[2],.01*intensity)
		glVertex3f( p[0], p[1], p[2])
	glEnd()
	glPointSize(2*point_size);
	glBegin(GL_POINTS)
	for i,p in enumerate(points):
		if rotate_color:
			ci = (N/2) + np.sin(a+i*2*PI/N)*N/2
			ci = max(0,min(int(ci),N))
			c = colors[ci]
		else:
			c = colors[i]
		glColor4f(c[0],c[1],c[2],.005*intensity*(p[2]))
		glVertex3f( p[0], p[1], p[2])

	glEnd()
	t = time.time()-start;
	# print("Draw time: "+repr(t))

	# X_AXIS = X_AXIS - 0.01
	# Z_AXIS = Z_AXIS - 0.30
	img = []

	glReadBuffer(GL_BACK);
	if SPACE_PRESSED:
		print("Taking screenshot")
		buffer = glReadPixels(0, 0, width, height, GL_RGB,
		                         GL_UNSIGNED_BYTE)
		image = Image.frombytes(mode="RGB", size=(width, height),
		                         data=buffer)
		image = image.transpose(Image.FLIP_TOP_BOTTOM)

		image.save("output-"+repr(time.time())+".png",'PNG')
		SPACE_PRESSED = False

	glutSwapBuffers()

	# time.sleep(.01)

def main():

	global window

	glutInit(sys.argv)
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE)
	glutInitWindowSize(width,height)
	glutInitWindowPosition(0,0)

	window = glutCreateWindow('OpenGL Python Cube')

	glutDisplayFunc(DrawGLScene)
	glutIdleFunc(DrawGLScene)
	glutKeyboardFunc(keyPressed)
	InitGL(width, height)
	# glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);

	glEnable( GL_BLEND);
	glEnable(GL_POINT_SMOOTH)
	glutMainLoop()

if __name__ == "__main__":
	main()


class HashTable:

    def __init__(self, buckets = 11):
        self.buckets = buckets
        self.table = [[] for i in range(self.buckets)]

    def buckets_str(self):
        """
        Returns a string representing the various buckets of this table.
        The output looks like:
          0000->
          0001->
          0002->
          0003->key:value
          0004->
        where key:value indicates an association of (key:value) in bucket 3.
        """
        buckets_index = ""
        counter = 0
        for bucket in self.table:
            buckets_index += "%04d->" % counter

            pairs = []
            for key_value in bucket:
                pairs.append(":".join([str(key_value[0]), str(key_value[1])]))
            buckets_index += ", ".join(pairs) + '\n'
            counter += 1
        return buckets_index

    def __str__(self):
        """
        Return what str(table) would return for a regular
        Python dict such as {key:value}.
        The order should be bucket order and then insertion
        order in the bucket.
        The insertion order is guaranteed when you append
        to the buckets in put.
        """
        b = []
        if len(self.table) == 0:
            return "{}"

        for buck in self.table:
            for key_value in buck:
                pairs = str(key_value[0]) + ":" + str(key_value[1])
                b.append(pairs)
        result = ', '.join(b)
        result = "{" + result + "}"
        if result == "":
            return "{" + result + "}"
        return result

    def get(self, key):
        """
        Return table[key].
        Find the appropriate bucket indicated by the key and
        look for the association with the key.
        Return the value (not the key and not the association!)
        Return None if key not found.
        """
        index, exists, buck_num = self.bucket_indexof(key)
        if exists is False:
            return set()
        else:
            return self.table[buck_num][index][1]

    def put(self, key, value):
        """
        Perform table[key] = value
        Find the appropriate bucket indicated by key and then append
        a value to the bucket. If the bucket for key already has a key,
        value pair with that key then replace it.
        Make sure that you are only adding (key, value) associations
        to the buckets.
        """
        index, exists, buck_num = self.bucket_indexof(key)

        if exists is True:
            index, exists, buck_num = self.bucket_indexof(key)
            self.table[buck_num][index] = (key, set([value]))
            return None

        elif exists is False:
            self.table[buck_num].append((key, value))
            return None

    def bucket_indexof(self, key):
        """
        Return the element within a specific bucket; the bucket is table[key].
        You have to search the bucket linearly.
        """
        tuple_index = 0
        if type(key) == int:
            hashcode = key

        elif type(key) == str:
            hashcode = 0
            for i in key:
                hashcode = hashcode * 31 + ord(i)

        else:
            hashcode = None

        buck_number = hashcode % len(self.table)
        buck = self.table[buck_number]

        exists = False
        for elem in buck:
            if key == elem[0]:
                tuple_index = buck.index(elem)
                exists = True
        return tuple_index, exists, buck_number

    def __setitem__(self, key, item):
        self.put(key, item)

    def __getitem__(self, key):
        return self.get(key)


#!/usr/bin/python
# -*- coding: utf-8 -*-
# forked from https://github.com/DaikiMaekawa/neovim.cpp/blob/master/gen_api.py

from jinja2 import Environment, FileSystemLoader
import msgpack
import os
import subprocess
import re
from typing import Dict, Any

class InvalidType(Exception):
    pass

class NativeType:
    def __init__(self, name, regex=""):
        self.name = name
        self.container = False
        self.regex = regex

t_types = {
    "Boolean": NativeType("Boolean"),
    "String": NativeType("String"),
    "void": NativeType("Unit"),
    "Integer": NativeType("Int"),
    "Window": NativeType("Window"),
    "Buffer": NativeType("Buffer"),
    "Tabpage": NativeType("TabPage"),
}

# For now Dicts and Objects excluded. Most of the core functions have been covered.
excluded_types = {"Dictionary": "", "Object": "", "Array": ""}
excluded_methods = {"get_api_info": "", "vim_get_api_info": ""}

ext_types = ["Buffer", "Window", "Tabpage"]
derived_types = {"ArrayOf": NativeType("T[]", r"\w+\((\w+)(.*?(\d+))?\)")}

def type_to_native(str_t):
    if str_t in t_types:
        return t_types[str_t].name
    for key in derived_types.keys():
        if key in str_t:
            t = derived_types[key]
            m = re.match(t.regex, str_t)
            if m:
                return "ArrayBuffer[{}]".format(type_to_native(m.group(1)))
    raise InvalidType({"type": str_t})

def gen_tmpl_arg(ret_type):
    tmpl_val = ret_type
    # nested substring matching
    for item in ext_types:
        if item in ret_type:
            tmpl_val = tmpl_val.replace(item, "ExtValue")
    return tmpl_val

def snake_to_camel(str_input):
    res = ""
    words = str_input.split("_")
    res = words[0]
    for word in words[1:]:
        res += word.capitalize()
    return res

def gen_func(f_name, name, return_type, tmpl_arg, is_async, args):
    return {
        "name": name,
        "f_name": f_name,
        "return": return_type,
        "tmpl_arg": tmpl_arg,
        "is_async": is_async,
        "args": args,
    }

def gen_api(pre_print=False, post_print=False, gen_file=True):
    file_name = "Api.scala"
    source_dir = os.path.join("src", "main", "scala", "nvimhost")
    env = Environment(loader=FileSystemLoader("templates", encoding="utf8"))
    tpl = env.get_template(file_name.split(".")[0].lower() + ".j2")

    api_info = subprocess.check_output(["nvim", "--api-info"])
    unpacked_api = msgpack.unpackb(api_info, raw=False)

    functions: Dict[str, Any] = {}
    for f in unpacked_api["functions"]:
        name = f.get("name", "")
        if name in excluded_methods:
            continue
        f_name = snake_to_camel(name.replace("nvim_", ""))
        if f_name in functions:
            continue
        try:
            if pre_print:
                print(f, "\n")
            is_async = False
            return_type = type_to_native(f.get("return_type", ""))
            tmpl_arg = gen_tmpl_arg(return_type)
            args = [
                {"type": type_to_native(arg[0]), "name": arg[1]}
                for arg in f["parameters"]
            ]
            parsed_funcs: Dict[str, Any] = {}
            func_def = gen_func(f_name, name, return_type, tmpl_arg, is_async, args)
            parsed_funcs[f_name] = func_def
            # Ignored for now since all functions are wrapped in a Future
            if return_type == "void":
                f_name = f_name + "Async"
                is_async = True
                func_def = gen_func(f_name, name, return_type, tmpl_arg, is_async, args)
                parsed_funcs[f_name] = func_def
            if post_print:
                [print(f, "\n") for k, f in parsed_funcs.items()]
            functions.update(parsed_funcs)
        except InvalidType as e:
            if e.args[0]["type"] in excluded_types:
                pass
            else:
                print("Invalid func = " + str(f))

    api = tpl.render({"functions": list(functions.values())})

    if gen_file:
        if not os.path.isdir(source_dir):
            os.makedirs(source_dir)
        with open(os.path.join(source_dir, file_name), "w+") as f:
            f.write(api)

def main():
    gen_api(pre_print=True, post_print=True, gen_file=True)

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from std_msgs.msg import Float64
from std_msgs.msg import String
from sensor_msgs.msg import LaserScan
from sensor_msgs.msg import Image
from tut_ibx0020.msg import Diag

import tf  # for a function to transform quaternion into euler
import math  # for sqrt and atan2 functions
import array as arr

# utility function to normalyze angles (-pi <= a <= pi)
def normalizeAngle(a):
    while a < -math.pi:
        a += 2.0 * math.pi
    while a > +math.pi:
        a -= 2.0 * math.pi
    return a

# global variable to store the last received odometry reading
lastOdomReading = None

# Minimum distances to obstacles set coliders true ( for easy editing)

f_min = 1.0
l_min = 1.50
r_min = 1.50
l45_min= 1.50
r45_min=1.50

def rgb2hsv(r, g, b):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    return h, s, v

# callback function to process data from subscribed Odometry topic
def odometryReceived(data):
    global lastOdomReading
    lastOdomReading = data

# global variable to store the last received odometry reading
LaserReading = None

# callback function to process data from subscribed Odometry topic
def LaserReceived(data):
    global LaserReading
    LaserReading = data

callback = None #Global variable to store odometry
def Odom(data):
    global callback
    callback = data

def GetOdometry():
    global callback

    rospy.Subscriber("base_pose_ground_truth", Odometry, Odom)
    r = rospy.Rate(10)

    while not rospy.is_shutdown():
        if callback is None:

            r.sleep()
            continue

        pose = callback.pose.pose
        #rospy.loginfo('NU SHO TAM'+ str(pose))
        break

    return pose

def LaserColliders(): #returns two arrays 1) boolean coliders F,L,R,l45,R45
    #2) Distances at those those angles

    global LaserReading
    global f_min,r_min,l_min,r45_min,l45_min

    rospy.Subscriber("base_scan", LaserScan, LaserReceived)
    r = rospy.Rate(10)

    while not rospy.is_shutdown():

        if LaserReading is None:
            r.sleep()
            continue
            ###########LASER functions ###############
        number_of_readings= len(LaserReading.ranges)
        view_angle_min = LaserReading.angle_min

        view_angle_max = LaserReading.angle_max
        #angle_per_reading= (view_angle_max -view_angle_min )/number_of_readings
        angle_per_reading=LaserReading.angle_increment

        #now find distances to objects measuring frontal , left right orientations

        f_angl=view_angle_max  # frontal distance measurement angle
        r_angl = 0
        l_angl =view_angle_min
        l45_angl = view_angle_max+0.5
        r45_angl = 0.5

#DEBUG
        #rospy.loginfo(str(LaserReading))

        #rospy.loginfo("NUM OF READINGS "+str(angle_per_reading))

        #END DEBUG

        #find correcponding indexes of ranges array for angles

        f_indx = f_angl / angle_per_reading
        f_indx = int(f_indx)

        #f_indx = abs(f_indx)

        l_indx = l_angl / angle_per_reading
        l_indx = int(l_indx)

        r_indx = r_angl / angle_per_reading
        r_indx = int(r_indx)

        l45_indx = l45_angl / angle_per_reading
        l45_indx = int(l45_indx)

        r45_indx = r45_angl / angle_per_reading
        r45_indx = int(r45_indx)

        f_indx = 6
        r_indx = 0
        l_indx = 12
        l45_indx = 9
        r45_indx = 3

        #find correcponding distances to obstacles

        f_dist = LaserReading.ranges[f_indx]
        l_dist = LaserReading.ranges[l_indx]
        r_dist = LaserReading.ranges[r_indx]
        l45_dist = LaserReading.ranges[l45_indx]
        r45_dist = LaserReading.ranges[r45_indx]

        f_colider= False
        l_colider= False
        r_colider= False
        l45_colider= False
        r45_colider= False

        if f_dist < f_min:
            f_colider=True

        if l_dist < l_min:
            l_colider=True
        if r_dist < r_min:
            r_colider=True

        if l45_dist < l45_min:
            l45_colider=True

        if r45_dist < r45_min:
            r45_colider=True

        collider_array = [f_colider,r_colider,l_colider,l45_colider,r45_colider]
        distance_array = [f_dist,r_dist,l_dist,l45_dist,r45_dist]

        break
    return collider_array,distance_array
    ##END OF LASER COLIDERS FUNCTION

def gotogoal(x,y,th,disable_goal_th,stop_before_obstacle):
    global lastOdomReading
    global LaserReading
    global callback

    # subscribing to odometry and announcing published topics
    #rospy.Subscriber("base_pose_ground_truth", Odometry, odometryReceived)

    ##############################
    #rospy.Subscriber("base_scan", LaserScan, LaserReceived)

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

    pub = rospy.Publisher('cmd_vel', Twist)

    ############################
    pub_Diag = rospy.Publisher('diag', Diag)

    DiagMsg = Diag()  # create diag message object
    ####################################

    r = rospy.Rate(10)  # an object to maintain specific frequency of a control loop - 10hz

    # goal pose: coordinates (x,y) in metres and orintation (th) in radians
    goal_x = x
    goal_y = y
    goal_th = th

    #goal_x = rospy.get_param('~x', 0)
    #goal_y = rospy.get_param('~y', 0)
    #goal_th = rospy.get_param('~th', 0)

    rospy.loginfo('Goal: x=' + str(goal_x) + ', y=' + str(goal_y) + ', th=' + str(goal_th))

    cmd = Twist()  # command that will be sent to Stage (published)

    while not rospy.is_shutdown():
        #if lastOdomReading is None:  # we cannot issue any commands until we have our position
            #print
            #'waiting for lastOdomReading to become available'
            #r.sleep()
            #continue

        # current robot 2D coordinates and orientation
        #pose = lastOdomReading.pose.pose  # robots current pose (position and orientation)

        pose = GetOdometry()
        x = pose.position.x
        y = pose.position.y

        # euler_from_quaternion returns array of [pitch, roll, yaw], we need only yaw (rotation around Z axis)
        th = tf.transformations.euler_from_quaternion(
            [pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w])[2]

        #rospy.loginfo('MOVIG LINEARLY . Position x=' + str(x) + ', y=' + str(y) + ', th=' + str(th))

        #rospy.loginfo('LASER debugs angle min '+ str(LaserReading.angle_min) +'anglemax'+str(LaserReading.angle_max))
        #rospy.loginfo('range of array '+str(len(LaserReading.ranges)))
        # deltas
        dx = goal_x - x
        dy = goal_y - y
        dth = goal_th - th  # angle between current orientation and goal orientation

        #########DEBUG TEST##########

        #image = GetImage()
        #rospy.loginfo(str(image))

        ######END OF TEST DEBUG
        ###########LASER functions ###############

        colider_array,distance_array = LaserColliders()
        image = GetImage()

        '''

        number_of_readings= len(LaserReading.ranges)
        view_angle_min = LaserReading.angle_min
        view_angle_max = LaserReading.angle_max
        angle_per_reading= (view_angle_max -view_angle_min )/number_of_readings

        #now find distances to objects measuring frontal , left right orientations

        f_angl=view_angle_max  # frontal distance measurement angle
        l_angl = view_angle_max+1.57
        r_angl =view_angle_max -1.57
        l45_angl = view_angle_max+ 0.785
        r45_angl = view_angle_max - 0.785

        #find correcponding indexes of ranges array for angles

        f_indx = f_angl / angle_per_reading
        f_indx = int(f_indx)

        #f_indx = abs(f_indx)

        l_indx = l_angl / angle_per_reading
        l_indx = int(l_indx)

        r_indx = r_angl / angle_per_reading
        r_indx = int(r_indx)

        l45_indx = l45_angl / angle_per_reading
        l45_indx = int(l45_indx)

        r45_indx = r45_angl / angle_per_reading
        r45_indx = int(r45_indx)

        #find correcponding distances to obstacles

        f_dist = LaserReading.ranges[f_indx]
        l_dist = LaserReading.ranges[l_indx]
        r_dist = LaserReading.ranges[r_indx]
        l45_dist = LaserReading.ranges[l45_indx]
        r45_dist = LaserReading.ranges[r45_indx]

        #rospy.loginfo('front index '+str(f_indx))

        #rospy.loginfo('INITIALISING LASER angle_per_reading = '+ str(angle_per_reading))
        #rospy.loginfo('INITIALISING LASER view_angle_max = '+ str(view_angle_max))
        #rospy.loginfo('INITIALISING LASER view_angle_min = '+ str(view_angle_min))
        rospy.loginfo('Laser distance readings F ='+ str(f_dist)+' l='+ str(l_dist)+' r='+ str(r_dist)+' l45='+ str(l45_dist)+' r45='+ str(r45_dist))
        '''
        ############END OF LASER FUNCTIONS#######################

        if(image != False and stop_before_obstacle == True):
            rospy.loginfo("Red light ahead")
            break

        if((colider_array[0] == True or colider_array[1]== True or colider_array[2]== True and colider_array[3]== True and colider_array[4]==True ) and stop_before_obstacle == True ):
            rospy.loginfo("Obstacle ahead : STOP!!!!!!!!!!!!!!!!!!")
            break

        if math.fabs(dx) < 0.01 and math.fabs(dy) < 0.01 and math.fabs(dth) < 0.10:
            # if we are acceptably close to the goal, we can exit
            rospy.loginfo('Destination Reached !!')
            break

        if math.fabs(dx) < 0.01 and math.fabs(dy) < 0.01 and disable_goal_th == True:
            rospy.loginfo('Destination Reached !!')
            rospy.loginfo('No Orientation corrections were applied upon arrival !!')
            break

        # control equations
        p = math.sqrt(dx * dx + dy * dy)  # linear distance to goal
        a = normalizeAngle(-th + math.atan2(dy, dx))  # angle between current orientation th and p(dx,dy) vector
        b = normalizeAngle(-th - a)
        # control equations

        Kp = 0.5
        Ka = 0.5
        Kb = 0.5
        v = Kp * p  # translational speed in m/s

        # w = normalizeAngle(Ka*a + Kb*b)  # rotational speed in rad/s
        w = 0

        if math.fabs(dx) > 0.01 and math.fabs(dy) > 0.01 and math.fabs(a) > 0.1:
            #rospy.loginfo(' Setting proper orientation before linear movement dA = ' + str(a))
            v = 0
            w = 0.5 * a

        if math.fabs(dx) < 0.01 and math.fabs(dy) < 0.01 and math.fabs(dth) > 0.03 and disable_goal_th == False:

            #rospy.loginfo(' X ,Y goal reached  , Applying TH orientation corrections')
            v = 0
            w = 0.5 * dth

        # setting command fields
        cmd.linear.x = v
        cmd.angular.z = w
        # publishing command to a robot
        pub.publish(cmd)

        # publishing Diag message
        # pub_Diag.

        DiagMsg.a = a
        DiagMsg.b = goal_th - th
        DiagMsg.dx = dx
        DiagMsg.dy = dy
        DiagMsg.Ka = Ka
        DiagMsg.Kp = Kp
        DiagMsg.Kb = Kb
        DiagMsg.x = x
        DiagMsg.y = y
        DiagMsg.student_name = "Jevgeni Potulov"
        DiagMsg.p = p
        DiagMsg.th = th
        DiagMsg.v = v
        DiagMsg.w = w
        DiagMsg.dth = dth

        DiagMsg.f_d = distance_array[0]
        DiagMsg.r_d = distance_array[1]
        DiagMsg.l_d = distance_array[2]
        DiagMsg.l45_d = distance_array[3]
        DiagMsg.r45_d = distance_array[4]

        pub_Diag.publish(DiagMsg)

        # sleeping so, that the loop won't run faster than r's frequency
        r.sleep()
        # end of loop
    # end of function

# main function of the node

callbackImage = None #Global variable to store odometry
def Imgcallback(data):
    global callbackImage
    callbackImage = data

def GetImage():
    global callbackImage
    #pixels = ["str","str"]
    pose = GetOdometry()
    th = tf.transformations.euler_from_quaternion(
            [pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w])[2]
    pixels = []
    i = None

    rospy.Subscriber("image", Image , Imgcallback)
    r = rospy.Rate(10)

    while not rospy.is_shutdown():
        if callbackImage is None:

            rospy.loginfo('WHatt?%!@')
            ##DEBUG

            ##

            r.sleep()
            continue

        image = callbackImage
        #rospy.loginfo('NU SHO TAM'+ str(image))
        break

    for index in range(image.width):
        pixel = image.data[index*4:index*4+4]
        r=ord(pixel[0])
        g=ord(pixel[1])
        b=ord(pixel[2])
        a= ord(pixel[3])

        #rospy.loginfo('R = '+str(r)+ ' G= '+str(g)+ ' B= '+str(g)+ ' a ='+str(a))

        if(r==128 and g==0 and b==0):
            pixels +="R"
            i= index #if red pixel found record value of index

        else:
            pixels +=" "

    if i==None:
        rospy.loginfo("red pixel NOT FOUND ")
        return False
    #rospy.loginfo("%s",pixels)
    rospy.loginfo(pixels)
    #Now calculate angle , based on index of red pixel
    angl= 2.0944* i*4/480
    # recalculate angle with respect to global frame
    if angl <=1.0472:
        red_pixel_angle = th+ (1.0472 -angl)
        rospy.loginfo("TYT")
    if angl >  1.0472:
        red_pixel_angle = th-(angl-1.0472)
    red_pixel_angle = normalizeAngle(red_pixel_angle)
    rospy.loginfo("RED PIXEL FOUND angle = "+str(red_pixel_angle))
    #rospy.loginfo(" angle = "+str(angl))
    #rospy.loginfo(" i = "+str(i*4))
    return red_pixel_angle

def obstacle_avoid(goal_x,goal_y,goal_th,enable_goal_th): #HARDCODED FOR 45 DEG bearing goal x,y, th disregarded
    r = rospy.Rate(10)

    while not rospy.is_shutdown():
        colider_array,distance_array = LaserColliders()
        front_colider = colider_array[0]
        right_colider = colider_array[1]
        left_colider = colider_array[2]
        r45_colider = colider_array[3]
        l45_colider = colider_array[4]

        red_pixel_angl= GetImage()

        #rospy.loginfo('FRONT ='+str(front_colider)+ ' RIGHT = '+str(right_colider)+ " LEFT= "+str(left_colider) )

        rospy.loginfo(str( colider_array))
        #rospy.loginfo(str( distance_array))
        ###
        pose = GetOdometry()

        x=pose.position.x
        y = pose.position.y
        th = tf.transformations.euler_from_quaternion(
            [pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w])[2]
        dx = goal_x-x
        dy= goal_y-y
        dth = goal_th-th
        if(red_pixel_angl != False):
            rospy.loginfo('RED LIGHT')
            break

        if math.fabs(dx) < 0.01 and math.fabs(dy) < 0.01 and enable_goal_th== False:
            # if we are acceptably close to the goal, we can exit
            rospy.loginfo('Destination Reached with obstacle avoidance!!')
            rospy.loginfo('Goal TH disregarded')
            break

        if math.fabs(dx) < 0.01 and math.fabs(dy) < 0.01 and enable_goal_th == True:
            # if we are acceptably close to the goal, we can exit
            gotogoal(goal_x,goal_y,goal_th,False,False)
            rospy.loginfo('Destination Reached with obstacle avoidance!!')
            break

        '''
        if(front_colider == False):
            gotogoal(goal_x,goal_y,goal_th,True,True) # if nothing blocks way - go to goal
            # (x,y,goal_th,False,True)   4th parameter(True) - disables goal_th
            # 5 parameter(True) means stop in front of obstacle
            rospy.loginfo('GOING TO A GOAL')

        '''
        if (front_colider == True and right_colider == True and left_colider == False): # DEVIATE LEFT
            #gotogoal(x,y,th+0.3,False,False) #rotate and change orientation
            #untill alligned with the wall
            #Enable goal_th orientation , Disregard obstacles
            RotateLeft()
            rospy.loginfo('DEVIATE LEFT')

        if (left_colider == True and front_colider== True and right_colider== False): # DEVIATE RIGHT
            #gotogoal(x,y,th-0.3,False,False)
            RotateRight()
            rospy.loginfo('DEVIATE RIGHT')

        if(front_colider == False and right_colider == True and left_colider == False):# GO LEFT ALONG THE WALL (GO TO GOAL
            #gotogoal(goal_x,goal_y,goal_th,True,True)
            #gotogoal(x-0.4,y,th,True,True) #Disable goal orientation , Enable collider
            GoForwardRight()
            rospy.loginfo('coliderRight go ALONG THE WALL ')

        if(front_colider == False and left_colider == True and right_colider==False):# GO RIGHT ALONG THE WALL
            #gotogoal(goal_x,goal_y,goal_th,True,True)
            #gotogoal(x+0.4,y,th,True,True) #Disable goal orientation , Enable collider
            GoForwardLeft()
            rospy.loginfo('coliderLeft go ALONG THE WALL/')
        if(front_colider == True and right_colider == False and left_colider == False):
            #TURN LEFT
            #gotogoal(x,y,th+1.57,False,False)
            GoBackRIGHT()
            rospy.loginfo('F=t R=f L =f  Right')

        if(front_colider == True and right_colider == True and left_colider == True):
            #BACK
            GoBackRIGHT()
            #gotogoal(x,y,th+1.57,False,False)
            rospy.loginfo('F=t R=t L =t  GO BACK LEFT')

        if(front_colider == False and right_colider == False and left_colider == False):
            rospy.loginfo('Clear way - go to goal')
            gotogoal(x+3,y+3,goal_th,True,True) # GO to 45 deg bearing

        if (front_colider == False and right_colider == True and left_colider == True):

            GoForwardCMD()
            rospy.loginfo('WALLs on both right and left side => going straight')

        if(front_colider == True and right_colider == True and left_colider == True):

            GoBackLEFT()
            rospy.loginfo('CORNER - turn arround')

        if(front_colider == False and right_colider == False and left_colider == False and r45_colider == True and l45_colider == False):
            GoBackRIGHT()

        if(front_colider == False and right_colider == False and left_colider == False and r45_colider == False and l45_colider == True):
            GoBackLEFT()

        '''
        else:
            colider_array,distance_array = LaserColliders()
            front_colider = colider_array[0]
            right_colider = colider_array[1]
            left_colider = colider_array[2]
            #RotateLeft()
            rospy.loginfo('CONDITIONS NOT SET')
            rospy.loginfo('FRONT ='+str(front_colider)+ ' RIGHT = '+str(right_colider)+ " LEFT= "+str(left_colider) )
          '''

        r.sleep()

    ###

def GoBackCMD():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x =-0.2
    cmd.angular.z = 0

    pub.publish(cmd)

def GoBackLEFT():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x =-0.5
    cmd.angular.z = 0.6

    pub.publish(cmd)

def GoBackRIGHT():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x =-0.2
    cmd.angular.z = -0.6

    pub.publish(cmd)

def GoForwardCMD():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x = 0.2
    cmd.angular.z = 0

    pub.publish(cmd)

def GoForwardRight():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x = 0.2
    cmd.angular.z = 0.4
    pub.publish(cmd)

def GoForwardLeft():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x = 0.2
    cmd.angular.z = -0.4
    pub.publish(cmd)

def RotateLeft():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x = 0
    cmd.angular.z = 0.4
    pub.publish(cmd)

def RotateRight():
    pub = rospy.Publisher('cmd_vel', Twist)
    cmd = Twist()
    cmd.linear.x = 0
    cmd.angular.z = -0.4
    pub.publish(cmd)
# entry point of the executable
# calling the main node function of the node only if this .py file is executed directly, not imported
if __name__ == '__main__':

    #############MAIN FUNCTION######################
    rospy.init_node('control')

    rate = rospy.Rate(10) # 10hz
    test = 1

    #gotogoal(3,3,1.57,False,False)
    ##########################

    '''
    #gotogoal(10,16,0,False,False)
    obstacle_avoid(10,10,0,True)

    GoForwardCMD()

    red_pixel_angl = float(GetImage())
    pose = GetOdometry()
    x = pose.position.x
    y= pose.position.y

    #gotogoal(x,y,red_pixel_angl,False,False)

    rospy.loginfo(str( red_pixel_angl))

'''

    #gotogoal(3.5,2,red_pixel_angl,False)
    #colider_array,distance_array = LaserColliders()
    #rospy.loginfo(str( colider_array))
    #rospy.loginfo(str( distance_array))

    #obstacle_avoid()
    '''

    image = GetImage()
    rospy.loginfo('Height '+str(image.height))
    rospy.loginfo('width '+ str(image.width))
    rospy.loginfo('length of array '+ str(len(image.data)))
    '''

    '''
    for index in range(len(image.data)):
        pixel = image.data[index:index+3]
        r= ord(pixel[0])
        g=ord(pixel[1])
        b=ord(pixel[2])
        rospy.loginfo('index ='+ str(index))

        if r==255 and g==0 and b == 0:
            rospy.loginfo('RED FOUND !!! index ='+ str(index))

        #rospy.loginfo('r = '+str(r)+ ' g= '+str(g)+ ' b= '+str(g))

    '''

    #colider_array,distance_array = LaserColliders()
    #rospy.loginfo(str( colider_array))
    #poss = GetOdometry()

    #rospy.loginfo('MAIN LOOP GetODOMETRY'+str(poss))

    while not rospy.is_shutdown():

        ########MAIN WHILE LOOP ######
        ###### DO STUFF HERE ################
        #image = GetImage()
        #rospy.loginfo(str(image))

        #gotogoal(test,test,0,True)
        #rospy.loginfo('alala')

        colider_array,distance_array = LaserColliders()
        rospy.loginfo(str( distance_array))

        #poss = GetOdometry()

        #rospy.loginfo('MAIN LOOP GetODOMETRY'+str(poss))

        #obstacle_avoid()

        #gotogoal(9,-5,1.57,False)

        red_pixel_angl = float(GetImage())

        pose = GetOdometry()
        x = pose.position.x
        y= pose.position.y

        if(red_pixel_angl == False ):
            obstacle_avoid(10,10,0,True)

        if(red_pixel_angl != False):
            gotogoal(x,y,red_pixel_angl,False,False)

        #gotogoal(x,y,red_pixel_angl,False)

        #rospy.loginfo(str( red_pixel_angl))

        test = test+0.5
        rate.sleep()
        ## END OF MAIN WHILE LOOP

  ############END OF MAIN#################


import random
money= 5000#金额数
num =random.randint(1,30)#随机数的取值范围
count = 0#次数初始为零
while True:#循环
    count=count+1#执行后次数自动跳到下一次
    if count>10:#限制次数
        print("余额不足 ")
        break#结束
    chose = input("请输入你要猜的数字：")
    chose = int(chose)
    if chose > num:#输入的数字大于随机的数字
        print("大了!")
        money = money - 500#金额减10
        print("当前金币为：", money)
    elif chose < num:
        print("小了！")
        money=money-10
        print("当前金币为：",money)

    else:
        money = money + 5000
        print("恭喜猜中了， 你本次数字为：",num,"你本次输入了",count,"次","你的金额为：",money)

        #跳出循环
        break


import datetime

year = int(input("Введіть рік: "))

if year % 4 != 0:
    leap = False
elif year % 100 == 0:
    if year % 400 == 0:
        leap = True
    else:
        leap = False
else:
    leap = True

month = int(input("Введiть мiсяць: "))

if month in (1, 3, 5, 7, 8, 10, 12):
    length = 31
elif month == 2:
    if leap:
        length = 29
    else:
        length = 28
else:
    length = 30
day = int(input("Введiть день: "))

if day < length:
    day += 1
else:
    day = 1
    if month == 12:
        month = 1
        year += 1
    else:
        month += 1
print("Наступний день:", str(year), "-", str(month), "-", str(day))

for year in (year, month, day,):
     if day > length:
        break

def printTimeStamp(name):

	print('Автори програми: ' + name)

	print('Час компіляції: ' + str(datetime.datetime.now()))

printTimeStamp("Омельченко Олександр & Белавiн Данило")


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

from time import time

import pylab as pl
import numpy as np

from scipy.misc import lena as get_lena

from sklearn.decomposition import MiniBatchDictionaryLearning
from sklearn.feature_extraction.image import extract_patches_2d
from sklearn.feature_extraction.image import reconstruct_from_patches_2d

###############################################################################
# Load Lena image and extract patches

lena = get_lena() / 256.0
height, width = lena.shape

# Distort the the image
print('Distorting image...')
lena_copy = lena.copy()

from PIL import Image, ImageDraw, ImageFont
import numpy
im = Image.fromarray((lena_copy*256).astype(numpy.uint8))
#TEXT = 'En realidad, Remedios, la bella, no era un ser de este mundo. Hasta muy avanzada la pubertad, Santa Sofía de la Piedad tuvo que bañarla y ponerle la ropa, y aún cuando pudo valerse por sí misma había que vigilarla para que no pintara animalitos en las paredes con una varita embadurnada de su propia caca. Llegó a los veinte años sin aprender a leer y escribir, sin servirse de los cubiertos en la mesa, paseándose desnuda por la casa, porque su naturaleza se resistía a cualquier clase de convencionalismos'
TEXT = 'Muchos años después, frente al pelotón de fusilamiento, el coronel Aureliano Buendía había de recordar aquella tarde remota en que su padre lo llevó a conocer el hielo'
font_path = '/Library/Fonts/Arial.ttf'
font = ImageFont.truetype(font_path, 42, encoding='unic')
text = TEXT.decode('utf-8')
draw = ImageDraw.Draw(im)

import textwrap
h, w = 25, 34
lines = textwrap.wrap(text, width = w)
y_text = h
x_text = 0
for line in lines:
    width2, height2 = font.getsize(line)
    draw.text((x_text, y_text), line, font = font, fill = 'white')
    y_text += height2 * 2

im.save('distorted.png')

from scipy import misc
#distorted = misc.imread('distorted.png') / 256.0
distorted = numpy.asarray(im) / 256.0

# Extract all reference patches from the left half of the image
print('Extracting reference patches...')
t0 = time()
patch_size = (8, 8)
data = extract_patches_2d(distorted[:, :height / 2], patch_size)
data = data.reshape(data.shape[0], -1)
data -= np.mean(data, axis=0)
data /= np.std(data, axis=0)
print('done in %.2fs.' % (time() - t0))

###############################################################################
# Learn the dictionary from reference patches

print('Learning the dictionary...')
t0 = time()
dico = MiniBatchDictionaryLearning(n_components=100, alpha=1, n_iter=500)
V = dico.fit(data).components_
dt = time() - t0
print('done in %.2fs.' % dt)

pl.figure(figsize=(4.2, 4))
for i, comp in enumerate(V[:100]):
    pl.subplot(10, 10, i + 1)
    pl.imshow(comp.reshape(patch_size), cmap=pl.cm.gray_r,
              interpolation='nearest')
    pl.xticks(())
    pl.yticks(())
pl.suptitle('Dictionary learned from Lena patches\n' +
            'Train time %.1fs on %d patches' % (dt, len(data)),
            fontsize=16)
pl.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)

###############################################################################
# Display the distorted image

def show_with_diff(image, reference, title):
    """Helper function to display denoising"""
    pl.figure(figsize=(5, 3.3))
    pl.subplot(1, 2, 1)
    pl.title('Image')
    pl.imshow(image, vmin=0, vmax=1, cmap=pl.cm.gray, interpolation='nearest')
    pl.xticks(())
    pl.yticks(())
    pl.subplot(1, 2, 2)
    difference = image - reference

    pl.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference ** 2)))
    pl.imshow(difference, vmin=-0.5, vmax=0.5, cmap=pl.cm.PuOr,
              interpolation='nearest')
    pl.xticks(())
    pl.yticks(())
    pl.suptitle(title, size=16)
    pl.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2)

show_with_diff(distorted, lena, 'Distorted image')

###############################################################################
# Extract noisy patches and reconstruct them using the dictionary

print('Extracting noisy patches... ')
t0 = time()
data = extract_patches_2d(distorted[:, height / 2:], patch_size)
data = data.reshape(data.shape[0], -1)
intercept = np.mean(data, axis=0)
data -= intercept
print('done in %.2fs.' % (time() - t0))

transform_algorithms = [
    ('Orthogonal Matching Pursuit\n1 atom', 'omp',
     {'transform_n_nonzero_coefs': 1}),
    ('Orthogonal Matching Pursuit\n2 atoms', 'omp',
     {'transform_n_nonzero_coefs': 2}),
    ('Least-angle regression\n5 atoms', 'lars',
     {'transform_n_nonzero_coefs': 5}),
    ('Thresholding\n alpha=0.1', 'threshold', {'transform_alpha': .1})]

reconstructions = {}
for title, transform_algorithm, kwargs in transform_algorithms:
    print(title + '...')
    reconstructions[title] = lena.copy()
    t0 = time()
    dico.set_params(transform_algorithm=transform_algorithm, **kwargs)
    code = dico.transform(data)
    patches = np.dot(code, V)

    if transform_algorithm == 'threshold':
        patches -= patches.min()
        patches /= patches.max()

    patches += intercept
    patches = patches.reshape(len(data), *patch_size)
    if transform_algorithm == 'threshold':
        patches -= patches.min()
        patches /= patches.max()
    reconstructions[title][:, height / 2:] = reconstruct_from_patches_2d(
        patches, (width, height / 2))
    dt = time() - t0
    print('done in %.2fs.' % dt)
    show_with_diff(reconstructions[title], lena,
                   title + ' (time: %.1fs)' % dt)

pl.show()


import logging
LOG_FILENAME = 'murder.log' # this is my log file name

logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO) #starting my logging

def inspected():
  logging.info('inside inspected')
  print('As we sent the blood to be inspected we have found that it directly connects to a man named Nicholas')
  chance5 =str(input('Do you want to bring him in for questioning, Yes or No: '))
  if chance5 == 'Yes' or chance5 =='yes':
    print('You bring him in for questioning and he breaks down confessing that he murdered the earl for money.')
    final = str(input('Do you want to arrest him? yes or no: '))
    if final == 'Yes' or final == 'yes':
      print('Excellent job Detective! You are promoted')
    else:
      print('Game Over')
  else:
    print('Are u crazy? You cannot be a detective')


#============= enthought library imports =======================
from enthought.traits.api import HasTraits, Instance, on_trait_change, Str, Int, Float, Button
from enthought.traits.ui.api import View, Item, Group, HGroup, VGroup
from enthought.tvtk.pyface.scene_model import SceneModel
from enthought.tvtk.pyface.scene_editor import SceneEditor
from enthought.tvtk.pyface.api import Scene
from enthought.mayavi.core.ui.mayavi_scene import MayaviScene
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
#============= standard library imports ========================
from numpy import linspace, ones, asarray
from threading import Thread
from enthought.pyface.timer.do_later import do_after
import time
import random
#============= local library imports  ==========================

def point_generator(padding, cx, cy):
    offset = 1
    #nrows should be calculates so  result is a square
    nrows = int(padding * 2 / offset) + 1

    for i in range(nrows):
        y = cy - padding + i * offset
        if i % 2:
            p1 = cx - padding, y
            p2 = cx + padding, y
        else:
            p2 = cx - padding, y
            p1 = cx + padding, y

        yield p1, p2

class Graph3D(HasTraits):
    scene = Instance(MlabSceneModel, ())
#    def _scene_default(self):
#        s = MlabSceneModel()
#        pt_gen = point_generator(5, 0, 0)
#        j = 0
#        xx = []
#        yy = []
#        zz = []
#        for p1, p2 in [((-5, 0), (5, 0)), ((5, 1), (-5, 1))]:
##        for p1, p2 in pt_gen:
#
#            #move to p1
#            #move to p2
#            moving = True
#            i = 0
#            zs = []
#            xs = []
#            ys = []
#            while moving:
#                if i == 11:
#                    break
#
#                x = p1[0] - i if j % 2 else p1[0] + i
#                mag = 40 - x * x
#                zs.append(mag)
#
#                xs.append(x)
#                ys.append(p1[1])
#
#                if j % 2:
#                    data = sorted(zip(xs, ys, zs), key = lambda d:d[0])
#
#                    xs = [d[0] for d in data]
#                    ys = [d[1] for d in data]
#                    zs = [d[2] for d in data]
#
#                i += 1
#            j += 1
#            xx.append(xs)
#            yy.append(ys)
#            zz.append(zs)
#
#        s.mlab.mesh(asarray(xx), asarray(yy), asarray(zz))
##        s.mlab.plot3d(asarray(xx)[0], asarray(yy)[0], asarray(zz)[0], asarray(zz)[0])
#        return s

#        xs = []
#        ys = []
#        zs = []
#        for i in range(5):
#
#            x = linspace(-5, 5, 100)
#            y = ones(100) * i
#            z = 10 - 0.2 * x * x
#            xs.append(x)
#            ys.append(y)
#            zs.append(z)
#
#        s.mlab.mesh(asarray(xs), asarray(ys), asarray(zs)
#                        #z,
##                          line_width = 50,
##                          tube_radius = None,
#                          #representation = 'wireframe'
#                          )
#        return s

    def traits_view(self):
#        self.scene.mlab.points3d(x, y, z)
        kw = dict()
        klass = Scene

        use_mayavi_toolbar = True
        use_raw_toolbar = False
        if use_mayavi_toolbar:
            klass = MayaviScene
        elif use_raw_toolbar:
            klass = None

        if klass is not None:
            kw['scene_class'] = klass

        v = View(Item('scene', show_label = False,
                      height = 400,
                      width = 400,
                      resizable = True,
                      editor = SceneEditor(**kw

                                           )))
        return v

class FastScan(HasTraits):
    scan = Button
    graph = Instance(Graph3D, ())
    def _scan_(self):
        padding = 20
        s = self.graph.scene
        pt_gen = point_generator(padding, 0, 0)
        j = 0
        xx = []
        yy = []
        zz = []
#        for p1, p2 in [((5, -5), (-5, 5)), ((-5, -4), (5, -4))]:
#            print p1, p2, pt_gen.next()
        for p1, p2 in pt_gen:

            #move to p1
            #move to p2
            moving = True
            i = 0
            zs = []
            xs = []
            ys = []
            while moving:
                if i == 2 * padding + 1:
                    break

                x = p1[0] - i if j % 2 == 0 else p1[0] + i
                if i == 0 or i == 2 * padding:
                    mag = 0
                else:
                    mag = (-0.1 * (j - padding) ** 2) + padding * 4 - 0.1 * x * x
                zs.append(mag)

                xs.append(x)
                ys.append(p1[1])

                if j % 2 == 0:
                    data = sorted(zip(xs, ys, zs), key = lambda d:d[0])

                    xs = [d[0] for d in data]
                    ys = [d[1] for d in data]
                    zs = [d[2] for d in data]

                i += 1
            j += 1
            xx.append(xs)
            yy.append(ys)
            zz.append(zs)
#            do_after(1, s.mlab.plot3d, asarray(xs), asarray(ys), asarray(zs), asarray(zs))#, asarray(zz)[0])
            do_after(1, s.mlab.mesh, asarray(xx), asarray(yy), asarray(zz))
            time.sleep(0.1)

    def _scan_fired(self):
        t = Thread(target = self._scan_)
        t.start()

    def traits_view(self):
        v = View(

                 Item('scan', show_label = False),
                 Item('graph', show_label = False, style = 'custom'))
        return v

if __name__ == '__main__':
    g = FastScan()
    g.configure_traits()
#============= EOF ====================================


import pyautogui as p

# p.moveTo(41, 234, duration=1)
# p.click(41, 234)

p.hotkey('Win','r')
p.sleep(1)
p.typewrite('Notepad')
p.sleep(2)
p.press('enter')
p.sleep(2)
p.typewrite('Oi!!! eu sou um bot!!')
p.sleep(2)
valor = p.getActiveWindow()
valor.close()
p.press('right')
p.sleep(2)
p.press('enter')

# p.sleep(2)
# print(p.position())


import json
from pylib import common_module as cm

def deleteComment(event):

    status = "Success"
    message = "Successfully Deleted"
    returnJson = {}

    try:
        if event and ('userid' in event and event["userid"]) and 'postid' in event and event["postid"] and 'id' in event and event['id']:
            deleteCommentsQry = """DELETE FROM blogcomments WHERE POST_ID=%s and USER_ID=%s and ID=%s"""
            deleteCommentsVal = (event["postid"], event["userid"], event['id'])
            cm.queryIUD(deleteCommentsQry, deleteCommentsVal)

        else:
            status = "Failure"
            message = "Pleae try again!"

    except Exception as e:
        status = "Failure"
        message = str(e)

    returnJson = {"status":status, "message":message}
    print(returnJson)
    return returnJson

# event = {"userid":1, "postid":6, 'id':2}
# deleteBlog(event)