##
# Authors: Scott Towne and Jeriah Caplinger
# Version: May 2019
# Description: This file contains the functions used to manipulate images in the
#              Spike program
##
from PIL import Image
import PIL.ImageOps
import subprocess
import sys

def mirror_image(copyLocation):
    """
    Mirror the image and calls display_image so that the edited version is displayed
    @param: copyLocation - the location to which the edited image is saved
    """
    image_obj = Image.open(copyLocation)
    rotated_image = image_obj.transpose(Image.FLIP_LEFT_RIGHT)
    rotated_image.save(copyLocation)

def rotate_image(copyLocation):
    """
    Rotate the given photo 90 degrees and calls display_image
    @param: copyLocation - the location to which the edited image is saved
    """
    image = Image.open(copyLocation)
    image = image.transpose(Image.ROTATE_90)
    image.save(copyLocation)

def grayscale_image(copyLocation):
    """
    Convert image to grayscale using PIL
    @param: copyLocation - the location to which the edited image is saved
    """
    img_obj = Image.open(copyLocation)
    img_obj = img_obj.convert("L")
    img_obj.save(copyLocation)

def invert_image(copyLocation):
    """
    Inverts colors of image using PIL
    @param: copyLocation - the location to which the edited image is saved
    """
    image = Image.open(copyLocation)
    inverted_image = PIL.ImageOps.invert(image)
    inverted_image.save(copyLocation)

def compare_image(copyLocation, copy_array, copy_count):
    """
    Creates a SecondaryWindow with the most recent and directly previous image using the SecondaryWindow.py file.
    @param: copyLocation - the location to which the edited image is saved
            copy_array - array of past edits to the image
            copy_count - where in the array the current edit is located
    """
    if(copy_count > 1):
        #runs SecondaryWindow.py executable
        pid = subprocess.Popen([sys.executable, "SecondaryWindow.py", copy_array[copy_count%5-2], copyLocation])

def undo(copy_array, copy_count, undo_count, copyLocation):
    """
    Implements functionality of the undo button by displaying the image from
    the previous edit and saving it to the copyLocation.
    @param: copyLocation - the location to which the edited image is saved
            copy_array - array of past edits to the image
            copy_count - where in the array the current edit is located
            undo_count - how many times the undo function has been performed
    """
    if(undo_count > 0 and copy_count >= 0):
        image_location = copy_array[copy_count%5 - 2]
        copy_count = copy_count - 1
        image = Image.open(image_location)
        image.save(copyLocation)
        copy_count = copy_count - 1 #copy_count decremented twice to account
                                    #for increment in save_copy
        undo_count = undo_count - 2 #undo_count decremented by 2 to account
                                    #for increment in save_copy
    return copy_count, undo_count


import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout

previsores = pd.read_csv('entradas-breast.csv')
classes = pd.read_csv('saidas-breast.csv')

classificador= Sequential()

classificador.add(Dense(units=10,activation='relu',
                        kernel_initializer='normal',
                        input_dim=30))

#Adicionando dropout para evitar overfitting
classificador.add(Dropout(0.2)) #20%

#Adicionando mais 1 camada oculta
classificador.add(Dense(units=10,activation='relu',
                        kernel_initializer='normal'))
#Adicionando dropout para evitar overfitting
classificador.add(Dropout(0.4)) #20%

#Saida = sigmoid (entre 1 e 0)
classificador.add(Dense(units=1, activation='sigmoid'))

classificador.compile(optimizer='adam', loss='binary_crossentropy',
                      metrics=['binary_accuracy'])

classificador.fit(previsores,classes,batch_size=10,epochs=100)

#Salvar os parametros em disco do classificador

classificador_json = classificador.to_json()

with open('classificador_breast.json','w') as json_file:
    json_file.write(classificador_json)

#Salvar pesos
classificador.save_weights('classificador_breast.h5')

resulto = classificador.evaluate(previsores,classes)


import sys
import random
import numpy as np
from strutils import words

def selection_sort(array):
    array = np.array(array)
    for i, e in enumerate(array):
        # elem_min, index_min = min((array[j], j) for j in range(i, len(array)))
        index_min = i + np.argmin(array[i:])
        elem_min = array[index_min]
        array[i], array[index_min] = elem_min, e
    return array

if __name__ == "__main__":
    a = [random.randrange(10) for i in range(1000)]
    print(a)
    print(selection_sort(a))
    filename = sys.argv[1]
    with open(filename) as lines:
        wordslist = [word for line in lines for word in words(line)]
    np.set_printoptions(threshold=np.nan)
    print(selection_sort(wordslist))


from networkAnalyzer import NetworkAnalyzer

def main():
    handler= NetworkAnalyzer("./Pcaps/arppoison.pcap")

    for i,user in enumerate(handler.userList):
        print("User {} : {}".format(i+1,user.macAddr))
        print("Nombre de trames émises : {}".format(len(user.userTramesList)))
    print("Nombre de trames totales du pcap : {}".format(handler.nbFrame))
main()


import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

link1 = "http://suninjuly.github.io/registration1.html"
link2 = "http://suninjuly.github.io/registration2.html"

class TestMain():
    @pytest.fixture
    def browser(self):
        print("\nstart browser for test..")
        browser = webdriver.Chrome()
        yield browser
        print("\nquit browser..")
        browser.quit()
    def form_test(self, browser, link):
        browser.get(link)
        firstname = browser.find_elements(By.XPATH, "//input[@placeholder='Input your first name']")
        lastname = browser.find_elements(By.XPATH, "//input[@placeholder='Input your last name']")
        email = browser.find_elements(By.XPATH, "//input[@placeholder='Input your email']")
        phone = browser.find_elements(By.XPATH, "//input[@placeholder='Input your phone:']")
        adress = browser.find_elements(By.XPATH, "//input[@placeholder='Input your address:']")
        assert len(firstname) == 1, "First name input not found"
        firstname[0].send_keys("Rapolas")
        assert len(lastname) == 1, "Last name input not found"
        lastname[0].send_keys("Kubaitis")
        assert len(email) == 1, "Email input not found"
        email[0].send_keys("email.com")
        assert len(phone) == 1, "Phone input not found"
        phone[0].send_keys("123")
        assert len(adress) == 1, "Adress input not found"
        adress[0].send_keys("home 123")
        browser.find_element_by_class_name("btn").click()
        assert browser.find_element_by_tag_name('h1').text == "Congratulations! You have successfully registered!"
    def test1(self, browser):
        print("start test1")
        self.form_test(browser, link1)
        print("finish test1")
    def test2(self, browser):
        print("start test2")
        self.form_test(browser, link2)
        print("finish test2")


from lecture_7.chapter_11_1_classes_and_objects_the_basics import Point5 as Point

# 11.2.1 - Rectangles
class Rectangle:
    """ A class to manufacture rectangle objects """

    def __init__(self, posn, w, h):
        """ Initialize rectangle at posn, with width w, height h """
        self.corner = posn  # Corner of the rectangle
        self.width = w
        self.height = h

    def __str__(self):
        return "({0}, {1}, {2})"\
            .format(self.corner, self.width, self.height)

    def grow(self, delta_width, delta_height):
        """ Grow (or shrink) this object by the deltas """
        self.width += delta_width
        self.height += delta_height

    def move(self, dx, dy):
        """ Move this object by the deltas """
        self.corner.x += dx
        self.corner.y += dy

box = Rectangle(Point(0, 0), 100, 200)
bomb = Rectangle(Point(100, 80), 5, 10)  # In my video game
print("box: ", box)
print("bomb: ", bomb)

# 11.2.2 - Objects are mutable
box.width += 50
box.height += 100

# In order to provide a method that encapsulates the above inside a class we
# add the "grow" and "move" function

r = Rectangle(Point(10, 5), 100, 50)
print(r)
r.grow(25, -10)  # Now I can grow the rectangle by calling the functions inside the class. Pretty cool.
print(r)
r.move(-10, 10)  # Same
print(r)

# 11.2.3 - Sameness
p1 = Point(3, 4)
p2 = Point(3, 4)
print(p1 is p2)  # Even tho they contain the same coordinates, they are not the same object

p3 = p1
print(p1 is p3)  # The two variables are aliases of the same object

def same_coordinates(p1, p2):  # Finds if two points have the same coordinates
    return (p1.x == p2.x) and (p1.y == p2.y)

print(same_coordinates(p1, p2))  # If the two variables refer to the same object, they have
# both shallow and deep quality

# 11.2.4 - Copying
import copy
p1 = Point(3, 4)
p2 = copy.copy(p1)  # I think copying does the same as if we did p2 = p1
print(p1 is p2)
print(same_coordinates(p1, p2))


from flask import Blueprint, render_template, g, redirect, jsonify
from asmlearner.middleware import *
from asmlearner.library.pagination import Pagination

history = Blueprint('history', __name__)

@history.route('/histories')
@login_required
def history_list():
    page = int(request.args.get('p') if 'p' in request.args else '1')
    div = 20
    user_id = session['user']['id']
    histories = g.db.query('SELECT s.id, s.status, s.problem, (SELECT p.name FROM problem as p WHERE p.id = s.problem) AS probname FROM solved AS s WHERE owner=? ORDER BY time DESC LIMIT ?, ?', (user_id, (page-1)*div, div))
    history_count = g.db.query('SELECT COUNT(1) AS cnt FROM solved WHERE owner=?', (user_id, ), isSingle=True)['cnt']
    pagination = Pagination(page, div, history_count)

    return render_template('history.html', histories=histories, pagination=pagination)

def get_history(history_id):
    history = g.db.query('SELECT * FROM solved AS s WHERE s.id=?', (history_id, ),
            isSingle=True)
    return history

@history.route('/api/history/<int:history_id>')
@login_required
def history_api(history_id):
    user_id = session['user']['id']
    history = get_history(history_id)
    if history is not None and history['owner'] != user_id:
        history = None

    return jsonify(history if history is not None else {})

@history.route('/history/<int:history_id>')
@login_required
def history_(history_id):
    user_id = session['user']['id']
    history = get_history(history_id)
    snippet = {}

    if history is not None:
        snippet['code'] = history['answer']
        snippet['id'] = history['id']

    if history is not None and history['owner'] != user_id:
        history = None

    history = history if history is not None else {}

    return render_template('history_form.html', snippet=snippet)


class Drug(object):
    def __init__(self,antibiotic,pmc,ean1,ean2,restriction,product_name,apresentation,classe,type_product,tarja,register,pharm,can_sell):
        self.ean1=ean1
        self.ean2=ean2
        self.restriction=restriction
        self.product_name=product_name
        self.apresentation=apresentation
        self.classe=classe
        self.type_product=type_product
        self.tarja=tarja
        self.register=register
        self.pharm=pharm
        self.can_sell=can_sell
        self.pmc=pmc
        self.is_antibiotic=antibiotic


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('reviews', '0046_auto_20190717_2301'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='articleevaluation',
            options={'ordering': ('status',), 'verbose_name': 'ArticleEvaluation', 'verbose_name_plural': 'ArticleEvaluations'},
        ),
        migrations.AddField(
            model_name='article',
            name='status',
            field=models.CharField(default='U', max_length=1, choices=[('U', 'Unclassified'), ('W', 'Waiting'), ('R', 'Rejected'), ('A', 'Accepted'), ('D', 'Duplicated'), ('C', 'Conflict')]),
        ),
    ]


#coding:utf-8

from random import shuffle, choice

__metaclass__= type

__all__= [ u'merge_forest', u'tree_flat', u'tree_format', u'tree_depth' ]

# def is_complete( node )
# def could_attach( child, parent )
def merge_forest( forest, is_complete, could_attach ) : # return complete_forest, incomplete_forest
    forest= forest[:]
    shuffle( forest )
    while len( forest ) > 1 :
        child= None
        parents= []
        for index, root in enumerate( forest ) :
            assert not parents
            if not is_complete( root ) :
                continue
            def fetch_parent( node ) :
                if could_attach( root, node ) :
                    parents.append( node )
                for node_child in node[1:] :
                    fetch_parent( node_child )
            for parent in forest :
                if parent is root :
                    continue
                fetch_parent( parent )
            if parents :
                child= root
                forest.pop( index )
                break
        assert ( child is None ) == ( len( parents ) == 0 )
        if child is None :
            break
        parent= choice( parents )
        assert parent is not None
        assert parent is not child
        parent.append( child )
    complete_forest= []
    incomplete_forest= []
    for root in forest :
        if is_complete( root ) :
            complete_forest.append( root )
        else :
            incomplete_forest.append( root )
    return complete_forest, incomplete_forest

def tree_flat( datas, root ) :
    datas.append( root[0] )
    for node_child in root[1:] :
        tree_flat( datas, node_child )

# def node2str( node )
def tree_format( node2str, root ) : # return lines
    lines= []
    lines.append( node2str( root ) )
    ancestor_prefix_list= []
    def format_children( parent ) :
        children= parent[1:]
        children_len= len( children )
        ancestor_prefix= u''.join( ancestor_prefix_list )
        for index, child in enumerate( children ) :
            if index < children_len - 1 :
                self_prefix= u'├'
                child_prefix= u'│  '
            else :
                self_prefix= u'└'
                child_prefix= u'    '
            pattern= u'{ancestor_prefix}{self_prefix}{node_str}'
            s= pattern.format( ancestor_prefix= ancestor_prefix,
                                                self_prefix= self_prefix,
                                                node_str= node2str( child ) )
            lines.append( s )
            ancestor_prefix_list.append( child_prefix )
            try :
                format_children( child )
            finally :
                ancestor_prefix_list.pop()
    format_children( root )
    return lines

def tree_depth( root ) :
    if not root :
        return 0
    children= root[1:]
    if not children :
        return 1
    children_depth= max( ( tree_depth( child ) for child in children ) )
    return children_depth + 1


import io
import json

from layout.models import Section
from .util import build_font_choices, try_wrap
from .items import Part, build_document, build_inner_table, build_styles, build_outer_table

def extract_section(all, loc, styles):
    sections = [Part(d, styles) for d in all if d['location'] == loc]
    sections.sort(key=lambda s: s.order)
    return sections

def count_columns(sections):
    c1, c2, c3 = 0, 0, 0
    for s in sections:
        if s['location'] == Section.Location.COL1: c1 = 1
        if s['location'] == Section.Location.COL2: c2 = 1
        if s['location'] == Section.Location.COL3: c3 = 1
    return c1 + c2 + c3

def create_pdf(definition):
    build_font_choices()

    output = io.BytesIO()
    doc = build_document(definition['layout'], output)
    styles = build_styles(definition['styles'])
    sections = definition['sections']
    pad = definition['layout']['padding']

    n_columns = max(1, count_columns(sections))

    if n_columns == 1:
        main_table = build_content(pad, sections, styles, doc.width, [doc.width])
    if n_columns == 2:
        table_height = 9e99
        for s in [0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8]:
            colWidths = [doc.width * s, doc.width * (1 - s)]
            table = build_content(pad, sections, styles, doc.width, colWidths)
            table_h = try_wrap(table, doc.width, s - 0.5)
            if table_h < table_height:
                table_height = table_h
                main_table = table

    doc.build([main_table])
    return output.getvalue()

def build_content(pad, sections, styles, total_width, colWidths):
    top = extract_section(sections, Section.Location.TOP, styles)
    bottom = extract_section(sections, Section.Location.BOTTOM, styles)
    middle = list(filter(None, [
        extract_section(sections, Section.Location.COL1, styles),
        extract_section(sections, Section.Location.COL2, styles),
        extract_section(sections, Section.Location.COL3, styles),
    ]))

    mid_list = [build_inner_table(item, i == 0 or i < len(middle) - 1, pad, colWidths[i])
                for i, item in enumerate(middle)]

    main_table = build_outer_table(
            build_inner_table(top, False, pad, total_width),
            mid_list,
            build_inner_table(bottom, False, pad, total_width),
            pad, colWidths
    )
    return main_table

def create_txt(definition):
    return json.dumps(definition, indent=4)


def multiply_ll(first, second):
    n1 = 0
    n2 = 0
    MOD = 10**9+7

    while (first or second):
        if (first):
            n1 = ((n1*10)+first.data)%MOD
            first = first.next
        if (second):
            n2 = (n2 * 10 + second.data) % MOD
            second = second.next

    g = ((n1 % MOD) * (n2 % MOD)) % MOD
    return g


from __future__ import division
from bokeh.plotting import figure
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Slider, Button, Toggle, Arrow, OpenHead, RadioGroup, Div
from bokeh.io import curdoc
from math import pi, sin, cos, radians, sqrt, atan2
from os.path import dirname, join, split

## Create all required variables
circle_axis_phi=[]
circle_axis_source=ColumnDataSource(data=dict(x=[[],[]],y=[[],[]]))
room_axis_phi=[]
room_axis_source=ColumnDataSource(data=dict(x=[[],[]],y=[[],[]]))
mass_source=ColumnDataSource(data=dict(x=[],y=[]))
mass_path_circ_coords=dict(rho=[],phi=[])
mass_path_source=ColumnDataSource(data=dict(x=[],y=[]))
mass_lab_path_source=ColumnDataSource(data=dict(x=[],y=[]))
mass_lab_path_circ=dict(rho=[],phi=[])
mass_pos=[8,3.0*pi/4.0];
Omega=radians(2)
speed=[2,-2];
OSpeed=[2,-2];
v0_source=ColumnDataSource(data=dict(xStart=[],xEnd=[],yStart=[],yEnd=[]))
startPos=[]
Active=False
OnTable=False
AtStart=True

## Functions
# give initial values (called by stop and reset, therefore does not re-initialise arrow)
def initialise ():
    global mass_source, mass_pos, mass_lab_path_source, mass_path_circ_coords, mass_path_source, mass_lab_path_circ
    global circle_axis_source, startPos, circle_axis_phi, room_axis_phi, room_axis_source, speed, OSpeed, AtStart
    # give room axis coordinates
    room_axis_phi=[0,pi/2.0]
    room_axis_source.data=dict(x=[[-12, 12], [0,0]],y=[[0,0], [-12,12]])
    # give mass position in circular coordinates
    mass_pos=[8,3.0*pi/4.0];
    # give mass position in cartesian coordinates (stored in startPos to prevent unnecessary function calls)
    mass_source.data=dict(x=[startPos[0]],y=[startPos[1]])
    # clear old paths
    mass_path_source.data=dict(x=[startPos[0]],y=[startPos[1]])
    mass_lab_path_source.data=dict(x=[startPos[0]],y=[startPos[1]])
    mass_lab_path_circ=dict(rho=[8],phi=[3.0*pi/4.0])
    mass_path_circ_coords=dict(rho=[8],phi=[3.0*pi/4.0])
    # reset disk orientation in circular and cartesian coordinates
    circle_axis_phi=[0,pi/2.0]
    circle_axis_source.data=dict(x=[[-8,8],[0,0]],y=[[0,0],[8,-8]])
    # reset speed if it has moved with the room
    speed=OSpeed
    # set up directional arrow
    v0_source.data=dict(xStart=[startPos[0]-speed[0]],xEnd=[startPos[0]],
        yStart=[startPos[1]-speed[1]],yEnd=[startPos[1]])
    AtStart=True

# convert 1 cartesian coordinate to a circular coordinate
def cart_to_circ (x,y):
    rho=sqrt(x**2+y**2)
    phi=atan2(y,x)
    return rho,phi

# convert 1 circular coordinate to a cartesian coordinate
def circ_to_cart_coord (rho,phi):
    X=rho*cos(phi)
    Y=rho*sin(phi)
    return X,Y

# convert circular coordinates to cartesian coordinates
def circ_to_cart (rho,phi):
    X=[]
    Y=[]
    for i in range(0,len(rho)):
        X.append(rho[i]*cos(phi[i]))
        Y.append(rho[i]*sin(phi[i]))
    return X,Y

def move():
    global mass_source, mass_pos, speed, mass_lab_path_source, mass_lab_path_circ, mass_path_circ_coords
    # use mass_pos because bokeh was occasionally modifying mass_source
    # no idea why!
    [X,Y]=circ_to_cart_coord(mass_pos[0],mass_pos[1])
    # update mass position
    X+=0.1*speed[0]
    Y+=0.1*speed[1]
    # save new position
    [mass_pos[0],mass_pos[1]]=cart_to_circ(X,Y)
    # if in table referential spin
    if (OnTable):
        end=[X+0.1*speed[0],Y+0.1*speed[1]]
        [rho,phi]=cart_to_circ(end[0],end[1])
        phi-=Omega
        mass_pos[1]-=Omega
        [X,Y]=circ_to_cart_coord(mass_pos[0],mass_pos[1])
        [X2,Y2]=circ_to_cart_coord(rho,phi)
        speed=[10*(X2-X),10*(Y2-Y)]
    mass_source.data=dict(x=[X],y=[Y])
    # copy mass_lab_path_source so the update works
    X2=list(mass_lab_path_source.data['x'])
    Y2=list(mass_lab_path_source.data['y'])
    # add new coordinates
    X2.append(X)
    Y2.append(Y)
    # update path in laboratory referential system
    mass_lab_path_source.data=dict(x=X2,y=Y2)
    mass_lab_path_circ['rho'].append(mass_pos[0])
    mass_lab_path_circ['phi'].append(mass_pos[1])
    # update path in disk referential system
    mass_path_circ_coords['rho'].append(mass_pos[0])
    mass_path_circ_coords['phi'].append(mass_pos[1])
    # spin the disk and all associated objects
    if (OnTable):
        spinRoom(mass_pos)
    else:
        spinTable(mass_pos)

def spinTable(mass_pos):
    global Omega, mass_path_source, Active, circle_axis_phi
    # give appearance of rotating main disk by rotating axes
    circle_axis_phi[0]+=Omega
    circle_axis_phi[1]+=Omega
    # calculate cartesian coordinates after rotation from cylindrical coordinates
    [X1,Y1]=circ_to_cart_coord(8,circle_axis_phi[0])
    [X2,Y2]=circ_to_cart_coord(8,circle_axis_phi[1])
    circle_axis_source.data=dict(x=[[X1,-X1], [X2,-X2]],y=[[Y1,-Y1], [Y2,-Y2]])
    # rotate old positions of mass with disk
    for i in range(0,len(mass_path_circ_coords['phi'])-1):
        mass_path_circ_coords['phi'][i]+=Omega
    # calculate cartesian coordinates after rotation from cylindrical coordinates
    [X,Y]=circ_to_cart(mass_path_circ_coords['rho'],mass_path_circ_coords['phi'])
    mass_path_source.data=dict(x=X,y=Y)
    # if ball has exited disk stop the animation
    if (mass_pos[0]>8):
        curdoc().remove_periodic_callback(move)
        Active=False

def spinRoom (mass_pos):
    global room_axis_phi, Omega, room_axis_source, mass_path_source, Active, circle_axis_phi#, speed
    # give appearance of rotating room by rotating axes
    room_axis_phi[0]-=Omega
    room_axis_phi[1]-=Omega
    # calculate cartesian coordinates after rotation from cylindrical coordinates
    [X1,Y1]=circ_to_cart_coord(15,room_axis_phi[0])
    [X2,Y2]=circ_to_cart_coord(15,room_axis_phi[1])
    room_axis_source.data=dict(x=[[X1,-X1], [X2,-X2]],y=[[Y1,-Y1], [Y2,-Y2]])
    # calculate cartesian coordinates on disk
    [X,Y]=circ_to_cart(mass_path_circ_coords['rho'],mass_path_circ_coords['phi'])
    mass_path_source.data=dict(x=X,y=Y)
    # rotate old positions of mass with room
    for i in range(0,len(mass_lab_path_circ['phi'])-1):
        mass_lab_path_circ['phi'][i]-=Omega
    # calculate cartesian coordinates after rotation from cylindrical coordinates
    [X,Y]=circ_to_cart(mass_lab_path_circ['rho'],mass_lab_path_circ['phi'])
    mass_lab_path_source.data=dict(x=X,y=Y)
    # move v0 arrow
    [rho,phi]=cart_to_circ(v0_source.data['xStart'][0],v0_source.data['yStart'][0])
    start=circ_to_cart_coord(rho,phi-Omega)
    [rho,phi]=cart_to_circ(v0_source.data['xEnd'][0],v0_source.data['yEnd'][0])
    end=circ_to_cart_coord(rho,phi-Omega)
    v0_source.data=dict(xStart=[start[0]],xEnd=[end[0]],
            yStart=[start[1]],yEnd=[end[1]])
    # if ball has exited disk stop the animation
    if (mass_pos[0]>8):
        curdoc().remove_periodic_callback(move)
        Active=False

## Slider functions
# Set rotation speed
def rotation_speed(attrname, old, new):
    global Omega
    Omega=radians(new)

# Set v0
def particle_speed_x (attrname,old,new):
    global speed, OSpeed, AtStart
    if (AtStart):
        speed=[new,OSpeed[1]];
        OSpeed=speed
        v0_source.data=dict(xStart=[startPos[0]-speed[0]],xEnd=[startPos[0]],
            yStart=[startPos[1]-speed[1]],yEnd=[startPos[1]])
    elif (new!=OSpeed[0]):
        global v0_input_x
        v0_input_x.value=OSpeed[0]

# Set v0
def particle_speed_y (attrname,old,new):
    global speed, OSpeed, AtStart
    if (AtStart):
        speed=[OSpeed[0],new];
        OSpeed=speed
        v0_source.data=dict(xStart=[startPos[0]-speed[0]],xEnd=[startPos[0]],
            yStart=[startPos[1]-speed[1]],yEnd=[startPos[1]])
    elif (new!=OSpeed[1]):
        global v0_input_y
        v0_input_y.value=OSpeed[1]

## Button functions
def reset_situation ():
    global pause_button, Active
    # only stop callback if there is a callback
    if (Active):
        curdoc().remove_periodic_callback(move)
        Active=False
    # put everything back to initial position
    initialise()

def BackToInitial ():
    global pause_button, Active
    # only stop callback if there is a callback
    if (Active):
        curdoc().remove_periodic_callback(move)
        Active=False
    # put speed back to original value
    v0_input_x.value=2.0
    v0_input_y.value=-2.0
    Omega_input.value=2.0
    # put everything back to initial position
    initialise()

def pause (toggled):
    global Active
    # When active pause animation
    if (toggled):
        curdoc().remove_periodic_callback(move)
        Active=False
    # only restart if still on table
    elif(mass_pos[0]<=8):
        curdoc().add_periodic_callback(move, 100)
        Active=True

def play ():
    global Active, AtStart
    # if inactive, reactivate animation
    if (pause_button.active==True):
        # deactivating pause button reactivates animation
        # (calling add_periodic_callback twice gives errors)
        pause_button.active=False
    # only restart if still on table
    elif (not Active and mass_pos[0]<=8):
        curdoc().add_periodic_callback(move, 100)
        Active=True
        AtStart=False

def chooseRef (attrname, old, new):
    global OnTable
    OnTable = (new==1);

# initialise the start position of the ball
# (these lines are not in initialise() as it is unnecessary to call "circ_to_cart" at every "stop" or "reset")
[X,Y]=circ_to_cart([mass_pos[0]],[mass_pos[1]]);
startPos=[X[0],Y[0]];
# initialise object positions
initialise()

## Create slider to rotate plate
Omega_input = Slider(title=u"\u03C9", value=2.0, start=0.0, end=10.0, step=0.1)
Omega_input.on_change('value',rotation_speed)

## Create slider to select v0-x
v0_input_x = Slider(title=u"v\u2092-x", value=2.0, start=-5.0, end=5.0, step=0.5)
v0_input_x.on_change('value',particle_speed_x)

## Create slider to select v0-y
v0_input_y = Slider(title=u"v\u2092-y", value=-2.0, start=-5.0, end=5.0, step=0.5)
v0_input_y.on_change('value',particle_speed_y)

## Create reset button
reset_button = Button(label="Reset", button_type="success")
reset_button.on_click(reset_situation)

## Create pause button
pause_button = Toggle(label="Pause", button_type="success")
pause_button.on_click(pause)

## Create re-initialise button
reinit_button = Button(label="Re-initialise", button_type="success")
reinit_button.on_click(BackToInitial)

## Create play button
play_button = Button(label="Play", button_type="success")
play_button.on_click(play)

## Create choice of referential button
Referential_button = RadioGroup(labels=["Reference frame: Room",
    "Reference frame: Disk"], active=0)
Referential_button.on_change('active',chooseRef)

## create drawing
p=figure(title="Rotating disk with non accelerated particle", tools="", x_range=(-12,12), y_range=(-12,12))
p.title.text_font_size="25px"
p.axis.visible = False
p.grid.visible = False
p.outline_line_color = None
# draw room
p.multi_line('x','y',source=room_axis_source,line_color="#003359")
# draw disk
p.ellipse(0,0,16,16,fill_color="#98C6EA",line_color=None)
p.multi_line('x','y',source=circle_axis_source,line_color="#0065BD")
# draw old positions of the ball in circular and cartesian coordinates
p.line(x='x',y='y',source=mass_path_source,line_color="#E37222")
p.line(x='x',y='y',source=mass_lab_path_source,line_color="#A2AD00")
# draw ball
p.ellipse(x='x',y='y',width=0.5,height=0.5,source=mass_source,fill_color="#E37222",line_color=None)
# draw directional arrow
arrow_glyph = Arrow(end=OpenHead(line_color="black",line_width=2),
    x_start='xStart', y_start='yStart', x_end='xEnd', y_end='yEnd',source=v0_source)
p.add_layout(arrow_glyph)

# add app description
description_filename = join(dirname(__file__), "description.html")

description = Div(text=open(description_filename).read(), render_as_text=False, width=900)

## Send to window
curdoc().add_root(column(description,
                         row(p,column(Omega_input,v0_input_x,v0_input_y,play_button,pause_button,reset_button,reinit_button,Referential_button))
                         )
                  )
curdoc().title = split(dirname(__file__))[-1].replace('_',' ').replace('-',' ')  # get path of parent directory and only use the name of the Parent Directory for the tab name. Replace underscores '_' and minuses '-' with blanks ' '


# -*- coding: utf-8 -*-
import cv2
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('C:\\Users\\nct20\\Documents\\GitHub\\man-hole-Taka\\python\\TubeDiameter\\image_input\\real_tube.jpg',1)

def save_image(image,param1,param2):
    cv2.imwrite(
        'C:\\Users\\nct20\\Documents\\GitHub\\man-hole-Taka\\python\\TubeDiameter\\image_output\\hough_test\\' + 'real_tube' + str(
            param1) +'-'+ str(param2) +'.jpg', image)
    cv2.destroyAllWindows()

#キー処理＆画面終了＆保存
def key_action(image,param2):

  k = cv2.waitKey(0)
  # ESC:プログラム終了,s:セーブ＋プログラム終了
  if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
  elif k == ord('s'): # wait for 's' key to save and exit
   cv2.imwrite('C:\\Users\\nct20\\Documents\\GitHub\\man-hole-Taka\\python\\TubeDiameter\\image_output\\'+ 'test' + str(param2) + '.jpg',image)
   cv2.destroyAllWindows()

  # 終了処理
  cv2.destroyAllWindows()

def Hough(img,param1,param2):
    # グレースケールに変換
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 認識の精度を上げるために画像を平滑化
    gray = cv2.GaussianBlur(gray, (33, 33), 1)
    # ガウシアンフィルタ
    # gray = cv2.medianBlur(gray, 5)

    plt.imshow(gray, cmap='gray')
    plt.axis('off')
    plt.show()

    # ハフ変換による円検出
    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
                               param1=param1, param2=param2)
    circles = np.squeeze(circles, axis=0)  # (1, N, 3) -> (N, 3)
    cv2.imshow('Hough'+'-'+str(param1)+'-'+str(param2),img)
    #key_action(img,param2)

    # 描画する。
    if circles is not None:
        for x, y, radius in np.rint(circles).astype(int):
            print('center: ({}, {}), radius: {}'.format(x, y, radius))
            cv2.circle(img, (x, y), radius, (0, 255, 0), 5)
            cv2.circle(img, (x, y), 2, (0, 0, 255), 5)

    save_image(img,param1,param2)

if __name__ == '__main__':
    for i in range(200, 202):
        for j in range(50,51):
            Hough(img,i,j)
            print('Hello')


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import sorl.thumbnail.fields

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0003_auto_20150819_1322'),
    ]

    operations = [
        migrations.AlterField(
            model_name='background',
            name='background',
            field=sorl.thumbnail.fields.ImageField(upload_to=b'backgrounds/%Y/%m', verbose_name='\u0424\u043e\u043d \u0441\u0430\u0439\u0442\u0430'),
        ),
        migrations.AlterField(
            model_name='photo',
            name='is_cover_photo',
            field=models.BooleanField(default=False, verbose_name='\u041e\u0431\u043b\u043e\u0436\u043a\u0430'),
        ),
    ]


#!/usr/bin/python3
import os
import sys
import argparse

def help (message) :
    print(message)
    sys.exit(os.EX_USAGE)

def execute_command (command, change) :
    command = command.replace('::file', change['file'])
    command = command.replace('::change', change['change'])

    os.system(command)

def dir_changes (dirpath = None, prev_files = None, current_files = None) :
    changes = []

    if not dirpath or prev_files == None or current_files == None :
        return changes

    for file in current_files :
        if file not in prev_files :
            changes.append({'file': os.path.join(dirpath, file), 'change': 'CREATE'});

    for file in prev_files :
        if file not in current_files :
            changes.append({'file': os.path.join(dirpath, file), 'change': 'DELETE'});

    return changes

def close () :
    print('Stop watching.')
    sys.exit(os.EX_OK)

def get_args () :
    parser = argparse.ArgumentParser()
    parser.add_argument('--dir', help = 'Directory to watch', type = str)
    parser.add_argument('--on', help = 'Events type to react on, seperated by comma, no spaces. Types : ALL,CREATE,DELETE', type = str)
    parser.add_argument('--command', help = 'Command to run on event type detection. Use flags ::file and ::change to get filepath and change type event.', type = str)

    args = parser.parse_args(sys.argv[1:])

    if args.dir == None or args.on == None or args.command == None :
        help(parser.format_help());

    return args

def main () :
    args = get_args()

    directory = os.path.abspath(args.dir)
    command = args.command
    on_events = args.on.split(',')

    if not os.path.exists(directory) :
        print('Error: File {} does not exist.'.format(directory), file=sys.stderr)
        sys.exit(os.EX_OSFILE)

    try:
        prev_files = None
        current_files = None

        while True:
            prev_files = current_files
            current_files = os.listdir(directory)

            changes = dir_changes(directory, prev_files, current_files)

            for change in changes :
                if change['change'] in on_events or 'ALL' in on_events :
                    execute_command(command, change)

    except KeyboardInterrupt:
        close()

if __name__ == "__main__":
    main()


import torch.optim as optim
import torch

def calc_batch_mse(noisy_images, clean_images, lens):
    h, w = noisy_images.size()[1:3]
    masks = (torch.arange(h)[None, :].to(lens.device) < lens[:, None]).unsqueeze(-1)
    mse_batch = torch.sum(((noisy_images - clean_images) * masks) ** 2)
    mse_batch /= w * lens.sum()
    return mse_batch

def test_model(model, test_loader, device):
    model.eval()
    mse_loss = 0
    with torch.no_grad():
        for imgs_noisy, imgs_clean, lens in test_loader:

            imgs_noisy = imgs_noisy.to(device)
            imgs_clean = imgs_clean.to(device)
            lens = lens.to(device)

            answers = model(imgs_noisy)

            mse_loss += calc_batch_mse(answers, imgs_clean, lens).item()

    mse_loss /= len(test_loader)
    return mse_loss

def train_model(model, train_loader, val_loader, num_epochs, lr,
                device, log=False):

    optimizer = optim.Adam(model.parameters(), lr=lr)

    val_mse = []
    for i in range(num_epochs):
        model.train()

        if log:
            print("Epoch {}".format(i))

        running_loss = 0.0

        for i_batch, (imgs_noisy, imgs_clean, lens) in enumerate(train_loader):

            imgs_noisy = imgs_noisy.to(device)
            imgs_clean = imgs_clean.to(device)
            lens = lens.to(device)

            optimizer.zero_grad()

            answers = model(imgs_noisy)

            loss = calc_batch_mse(answers, imgs_clean, lens)
            loss.backward()
            optimizer.step()
            running_loss += loss.item()

        mse_loss = test_model(model, val_loader, device)

        val_mse.append(mse_loss)

        if log:
            print("Train MSE: {:.4f}".format(running_loss / len(train_loader)))
            print("Validation MSE: {:.4f}".format(mse_loss))

    return val_mse


from flask import Flask, render_template, request
import numpy as np
import cv2
import json

from mnist_classifier import classify

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/success/<int:number>")
def success(number):
    return render_template("success.html", res=number)

@app.route('/recognize', methods = ['POST'])
def upldfile():
    if request.method == "POST":
       file_val = request.data

       fig = cv2.imdecode(np.fromstring(request.data, np.uint8), cv2.IMREAD_UNCHANGED) #Convert from string to cv2 image
       img = cv2.cvtColor(fig, cv2.COLOR_RGB2GRAY) # Convert to grayscale

       prediction = classify(img)

       number = int(prediction)
       return \
           json.dumps({'num': number}), 200, {'ContentType': 'application/json'}

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


# Python
# $ presence.py <-skipBlast> <-skipDomain>
# skipBlast - skips the BLAST step, skipDomain - skips the domain checking step
# Script for determinining if a given protein is present in a genome

from subprocess import call
import sys, glob, requests, time, re, os
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
from Bio import Phylo, AlignIO, SeqIO
from Bio.Phylo.Applications import PhymlCommandline

############
# Settings #
############
"""
        These variables should be set by the user
"""
query = '../test/rnap.fa' # A FASTA file of the DNA or protein sequence of the transcription factor
output = 'output/rnap2/' # This directory is where all the results will be output to
pathway = 'acetate' # This should be the name of the directory under ../test/ where FASTA files of pathway enzymes are stored
bluGenome = '../db/blumeria/latest/Bgt_genome_v2_1.fa' # Not really necessary
bluGenes = '../db/blumeria/latest/bluGenes.fa' # The source of Blumeria genes

# Loading modules on the msc server
# if '-modules' in sys.argv:
#     call('module load clustal', shell=True)       Doesn't work
#     call('module load hmmer', shell=True)
#     call('module load phyml/3.1', shell=True)

# Allow user to repeat the same search (mostly for testing)
if '-skipBlast' in sys.argv: #or '-skipDomain' in sys.argv:
    repeatFile = open('output/repeat.txt', 'r')
    repeatData = repeatFile.readlines()
    repeatFile.close()
else:
    newRepeat = open('output/repeat.txt', 'w')

# newRepeat = open('output/repeat.txt', 'w')

if not os.path.exists(output):
    os.makedirs(output)

#############################################
# BLAST query sequences (genes of interest) #
#############################################
def blasterMaster(query):
    # This function handles the BLAST search (through the CLI) and the results
    searched_genomes = []
    with open(query,'r') as filey:
        for seq in SeqIO.parse(filey, 'fasta'):
            testing = str(seq.seq)
    if testing.strip('ACGTRYSWKMBHVN.-') == '':
        protein = False
    else:
        protein = True
    global output
    for genome in glob.iglob('../db/*genes.fasta'):
        searched_genomes.append(genome)
        print (genome.split('/')[-1][0:4] + query.split('/')[-1][:-3])
        # tblastx search for the best hits among the genomes present in /db
        if protein:
            call('tblastn -db ' + genome + ' -query ' + query + ' -out '+ output + genome.split('/')[-1][0:4] + query.split('/')[-1][:-3] + '.blast' + ' -num_threads 4 -max_target_seqs 1 -outfmt "7 sseqid evalue"', shell=True)
        else:
            call('tblastx -db ' + genome + ' -query ' + query + ' -out '+ output + genome.split('/')[-1][0:4] + query.split('/')[-1][:-3] + '.blast' + ' -num_threads 4 -max_target_seqs 1 -outfmt "7 sseqid evalue"', shell=True)
        #-evalue 0.0001 Shouldn't matter because we're only going to look at the best hit anyway

    matches = []
    print ('Searched ' + ','.join(searched_genomes[:-1]) + ', and ' + searched_genomes[-1] + ' for ' + query)

    # Read through BLAST output and return the seqid of any hits with an e-value less than 1e-4
    for outpot in glob.iglob(output + '*' + query.split('/')[-1][:-3] + '.blast'):
        infile = open(outpot, 'r')
        i = 0
        for line in infile.readlines():
            i += 1
            if i==1 or i==2 or i==4 or i==5:
                # Skip over some irrelevant lines output by BLAST
                continue
            if line[0] == '#':
                genome = line.split('/')[-1].rstrip()
                continue
            seqid, e_val = line.split()
            if float(e_val) < float(1e-04):
                matches.append(['../db/' + genome, seqid])
                break
        infile.close()

    print (matches)
    return (matches)

if '-skipBlast' in sys.argv:
    # Use data from output/repeat.txt instead of running BLAST (to save time while testing)
    print ('Skipping BLAST search')
    exec('hits = ' + repeatData[0].rstrip())
else:
    print('BLASTing...')
    hits = blasterMaster(query)
    newRepeat.write(str(hits) + '\n')

#################################################
# Retrieve sequences of best hit in each genome #
#################################################
def fastaFinder(lines, seqid):
    # Collects all of the sequence after a desired FASTA header
    i = 0
    seqs = []
    collect = False
    while i < len(lines):
        if lines[i][0] == '>':
            #if lines[i].find(seqid) >= 0:
            if re.search(seqid + r'\s', lines[i]):
                collect = True
                print('Found ' + seqid + ' in ' + lines[i])
            elif collect:
                break
        elif collect:
            seqs.append(lines[i].rstrip().upper())
        i += 1

    return ''.join(seqs)

def seqRetriever(seqinfo):
    # Not really a necessary function, but it calls fastaFinder() on all the items in a list of lists
    output = []
    for genome, seqid in seqinfo:
        print ('Retrieving ' + seqid + ' from ' + genome + '...')
        infile = open(genome, 'r')
        seq = fastaFinder(infile.readlines(), seqid)
        output.append([genome, seqid, seq])
    return output

print (hits)
nucSeqs = seqRetriever(hits)

# print (nucSeqs)

#######################
# Translate sequences #
#######################

def domainSpotter(seq):
    # Searches the NCBI's online CDD for any conserved domains within a given ORF
    r = requests.post('https://www.ncbi.nlm.nih.gov/Structure/bwrpsb/bwrpsb.cgi?', data=(('db','cdd'), ('queries',seq), ('tdata','hits')))
    # print (r.text)
    searchID = r.text.split('#')[2].split()[1].rstrip()
    # print (searchID)
    tick = True
    done = False
    print ('Searching for domains...', end='', flush=True)
    patience = 30
    while not done:
        # Ping the website every 2 seconds to see if it's done
        result = requests.post('https://www.ncbi.nlm.nih.gov/Structure/bwrpsb/bwrpsb.cgi?', data={'cdsid':searchID, 'cddefl':'true'})
        status = result.text.split('#')[4].split()[1].rstrip()
        if status == '3':
            # A 3 here indicates that the search is still in progress
            done = False
        else:
            done = True
        time.sleep(2)
        print ('.', end = '', flush=True)
        patience -= 1
        if patience < 1:
            print('Giving up')
            return []

    lines = result.text.split('\n')

    tags = []
    for line in lines:
        # if line[0] == '#' or line[0] == '' or line[:5] == 'Query':
        #     continue
        # print (line)
        if line[:2] == 'Q#':
            tags.append(line.split('\t')[8])
    return tags

if '-skipDomain' in sys.argv:
    # Uses data from output/repeat.txt instead of prompting the user to select which ORFs he wants
    print ('Skipping Domain search')
    #exec('protSeqs = ' + repeatData[1])
else:
    protSeqs = []
    for genome, seqid, seq in nucSeqs:
        # Using the Seq class from Biopython to perform the translation
        bioSeq = Seq(seq, generic_dna)
        protSeq = str(bioSeq.translate())
        # print (seq)
        # print (protSeq)
        sprote = protSeq.split('*')
        prote = ''.join(sprote)
        tags = domainSpotter(prote)
        if len(tags) == 0:
            print ('No tags found, trying other reading frames')
            for start in range(1,3):
                print ('Trying RF ' + str(start))
                bioSeq = Seq(seq[start:], generic_dna)
                protSeq = str(bioSeq.translate())
                sprote = protSeq.split('*')
                prote = ''.join(sprote)
                tags = domainSpotter(prote)
                if len(tags) > 0:
                    print('\nFound an RF of ' + seqid + ' containing:\n- ' + '\n- '.join(tags))
                    break
                else:
                    print('No domains found')
            if len(tags) == 0:
                revSeq = seq[::-1]
                for start in range(0,3):
                    print ('Trying RF -' + str(start))
                    bioSeq = Seq(revSeq[start:], generic_dna)
                    protSeq = str(bioSeq.translate())
                    sprote = protSeq.split('*')
                    prote = ''.join(sprote)
                    tags = domainSpotter(prote)
                    if len(tags) > 0:
                        break
                    else:
                        print('No domains found')
        print('\nProtein sequence of ' + seqid + ' contains:\n- ' + '\n- '.join(tags))
        # for orf in protSeq.split('*'):
        #     print(orf)
        #     # Splitting on stop codons to iterate through each ORF
        #     if len(orf) <= 50:
        #         print ('Skipping short ORF (<50 residues)')
        #         continue
        #
        #     tags = domainSpotter(orf)
        #     if len(tags) == 0:
        #         print ('No tags found, skipping ORF')
        #         continue
        #     # Give the user some information and allow him to decide if this ORF looks acceptable
        #     print('\nORF of length ' + str(len(orf)))
        #     print('With domain tags:\n' + '\n-'.join(tags))
        #     if input('\nKeep this ORF? (y/n)  ') == 'y':
        #         protSeqs.append([genome, seqid, orf])
        #         break
        #     else:
        #         print('#' * 80)
        # if genome == '../db/m_o_genes.fasta':

        #print (protSeqs)

    newRepeat.write(str(protSeqs) + '\n')
###################
# Align sequences #
###################
print ('Aligning sequences...')
seqFile = open(output + 'unaligned.fa', 'w')
# for genome, seqid, seq in protSeqs:
#     seqFile.write('>' + seqid + ' ORF | \n')      Protein sequence
#     seqFile.write(seq + '\n')

for genome, seqid, seq in nucSeqs:
    seqFile.write('>' + seqid + ' Whole gene | \n')      #Nucleotide sequence
    seqFile.write(seq + '\n')
seqFile.close()

# Use Clustal Omega to align the sequences
call('clustalo -i ' + output + 'unaligned.fa -o ' + output + 'aligned.aln --force --outfmt=clu', shell=True)

#######################################
# Look for query sequence in Blumeria #
#######################################
place = 1
thisContig = False
def genomeSlicer(start, end, line, contig):
    # Call this on iterating lines of a genome file and it will return all of the sequence that falls between start and end in the relevant contig/sequence/FASTA header
    # Global variables to persist through multiple calls to the function
    global place
    global thisContig
    if thisContig and place >= end:
        # Cut off the function if we've got all the desired sequence
        thisContig = False
        return
    if line[0] == '>':
        # Check if this FASTA header is the one we want
        if contig in line:
            thisContig = True
        return
    if thisContig:
        # Each line has 50 characters on it, only initialise the list if we're going to need it here
        if place > start - 50:
            output = []
        else:
            place += 50
            return
        for nuc in line.rstrip():
            # Grab every nucleotide that falls between start and end
            if place >= start and place < end:
                output.append(nuc)
            place += 1
        return ''.join(output)
    else:
        return

# First create an HMM profile based on the alignment
print ('Building HMM profile...')
call('hmmbuild -o /dev/null ' + output + 'query.hmm ' + output + 'aligned.aln', shell=True)

# Now search it (with nhmmer for nucleotides) against the whole Blumeria genome
# call('hmmsearch --tblout output/hmmertbl.tsv -o output/hmmer.txt output/query.hmm ' + bluGenome, shell=True)
print ('Running HMMER search...')
call('nhmmer --tblout ' + output + 'hmmertbl.tsv -o ' + output + 'nhmmer.txt ' + output + 'query.hmm ' + bluGenes, shell=True)

# The result is saved in this tabular file, we're interested in only the best hit
result = open(output + 'hmmertbl.tsv', 'r')
lines = result.readlines()
result.close()

if lines[2][0] == '#':
    # If there are no hits, then let the user know and don't run the follow up analysis
    print ('No equivalent found in Blumeria graminis')
    foundBlu = False
else:
    foundBlu = True

# Extract the matched gene from bluGenes.fa
if foundBlu:
    name = lines[2].split()[0]
    print ('Best hit in Blumeria is ' + name)
    bluFile = open(output + 'b_g_GOI.fa', 'w')
    gener = open('../db/blumeria/latest/bluGenes.fa', 'r')
    bluSeq = fastaFinder(gener.readlines(), name)
    bluFile.write('>Blumeria graminis candidate gene | ' + name + '\n')
    bluFile.write(bluSeq)
    bluFile.close()

    # And counter-search to check if it's really a good match, the top hit should be the query sequence
    call('tblastx -db ../db/a_n_genes.fasta -query ' + output + 'b_g_GOI.fa -out ' + output + 'counterBlast.blast -num_threads 4 -max_target_seqs 1 -outfmt "7 sseqid evalue"', shell=True)

################################
# Identify motifs in sequences #
################################

# Do we need to do this?

#################################
# Make a phylogeny of sequences #
#################################
if foundBlu:
    unaln = open(output + 'unaligned.fa', 'a')
    bluFile = open(output + 'b_g_GOI.fa', 'r')
    addition = bluFile.read()
    unaln.write(addition)
    unaln.close()
    bluFile.close()
    print ('Creating phylogenetic tree...')
    call('clustalo -i ' + output + 'unaligned.fa -o ' + output + 'alignedAll.aln --force --outfmt=clu', shell=True)
    AlignIO.convert(output + 'alignedAll.aln', 'clustal', output + 'phyAlign.phy', 'phylip-relaxed')
    cmdline = PhymlCommandline(input=output + 'phyAlign.phy', alpha='e', bootstrap=1, sequential=False)
    call(str(cmdline), shell=True)
    my_tree = Phylo.read(output + "phyAlign.phy_phyml_tree.txt", "newick")
    Phylo.draw(my_tree, show_confidence=False)

# Got to print 'Done' at the end
print ('Done')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 16 19:40:32 2018

@author: pedrohames
"""

import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
gi.require_version('GdkX11', '3.0')
from gi.repository import GdkX11
import contiudo
import sipp
import siptrans

import vlc

class ApplicationWindow(Gtk.Window):

    def __init__(self):
        self.my_IP = '192.168.1.231'
        self.my_number = 6032
        self.video_port = 4000
        self.audio_port = 4001
        self.cam_IP = '192.168.1.211'
        self.cam_number = '6002'
        self.port_reg = 5060
        self.ip_server = '192.168.1.1'
        self.port_reg_dest = 5060

        self.obj_sip = sipp.sipp(self.my_IP, self.port_reg, self.ip_server, self.port_reg_dest, self.my_number, self.cam_number)
        #self.reg_str = self.obj_sip.register(self.my_number)
        #self.obj_sip.send(self.reg_str, self.ip_server)
        self.invite_str = self.obj_sip.invite(self.my_number, self.cam_number, self.ip_server)
        self.obj_sip.send(self.invite_str, self.ip_server)
        #print (resposta)
        #if resposta == 200:
        #
        Gtk.Window.__init__(self, title="Python-Vlc Media Player")
        self.player_paused=False
        self.is_player_active = False
        self.connect("destroy", Gtk.main_quit)
        self.bye_str = None

    def show(self):
        self.show_all()

    def set_call_id(self, call_id):
        self.cid = call_id

    def setup_objects_and_events(self):
        self.playback_button = Gtk.Button()
        self.stop_button = Gtk.Button()

        self.play_image = Gtk.Image.new_from_icon_name(
                "gtk-media-play",
                Gtk.IconSize.MENU
            )
        self.pause_image = Gtk.Image.new_from_icon_name(
                "gtk-media-pause",
                Gtk.IconSize.MENU
            )
        self.stop_image = Gtk.Image.new_from_icon_name(
                "gtk-media-stop",
                Gtk.IconSize.MENU
            )

        self.playback_button.set_image(self.play_image)
        self.stop_button.set_image(self.stop_image)

        self.playback_button.connect("clicked", self.toggle_player_playback)
        self.stop_button.connect("clicked", self.stop_player)

        self.draw_area = Gtk.DrawingArea()
        self.draw_area.set_size_request(300,300)

        self.draw_area.connect("realize",self._realized)

        self.hbox = Gtk.Box(spacing=6)
        self.hbox.pack_start(self.playback_button, True, True, 0)
        self.hbox.pack_start(self.stop_button, True, True, 0)

        self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.add(self.vbox)
        self.vbox.pack_start(self.draw_area, True, True, 0)
        self.vbox.pack_start(self.hbox, False, False, 0)

    def do_delete_event(self, event):
        #self.bye_str = self.obj_sip_reg.bye(self.cam_IP, self.cid);
        #self.obj_sip_reg.send(self.bye_str, self.cam_IP)
        self.reg_str = self.obj_sip.deregister(self.my_number)
        self.obj_sip.send(self.reg_str, self.ip_server)

    def stop_player(self, widget, data=None):
        self.player.stop()
        self.is_player_active = False
        self.playback_button.set_image(self.play_image)

    def toggle_player_playback(self, widget, data=None):

        """
        Handler for Player's Playback Button (Play/Pause).
        """

        if self.is_player_active == False and self.player_paused == False:
            self.player.play()
            self.playback_button.set_image(self.pause_image)
            self.is_player_active = True

        elif self.is_player_active == True and self.player_paused == True:
            self.player.play()
            self.playback_button.set_image(self.pause_image)
            self.player_paused = False

        elif self.is_player_active == True and self.player_paused == False:
            self.player.pause()
            self.playback_button.set_image(self.play_image)
            self.player_paused = True
        else:
            pass

    def _realized(self, widget, data=None):
        self.vlcInstance = vlc.Instance("--no-xlib")
        self.player = self.vlcInstance.media_player_new()
        win_id = widget.get_window().get_xid()
        self.player.set_xwindow(win_id)
#        self.player.set_mrl(MRL)
        media = self.vlcInstance.media_new(MRL)
        self.player.set_media(media)
        self.player.play()
        self.playback_button.set_image(self.pause_image)
        self.is_player_active = True

if __name__ == '__main__':
    window = ApplicationWindow()

    my_IP = '192.168.1.231'
    my_IP = '192.168.1.225'
    my_number = 6032
    video_port = 4000
    audio_port = 4001
    cam_IP = '192.168.1.211'
    cam_number = '6002'
    port_reg = 5060
    ip_server = '192.168.1.1'
    port_reg_dest = 5060
    #cont = contiudo.contiudo(my_IP, str(my_number), video_port, audio_port, cam_IP, cam_number, ip_server)
    #window.set_call_id(cont.call_id())
    #open('stream.sdp','w').write(cont.getSDP())
    # MRL = 'rtp://239.255.12.42:5004'
    MRL = 'stream.sdp'
    # MRL = 'rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov'
    window.setup_objects_and_events()
    window.show()
    Gtk.main()
    window.player.stop()
    window.vlcInstance.release()


from flask import (
    request, render_template, redirect,
    session, flash, url_for)
from SteamScout import app, db, login_manager, flask_bcrypt
from SteamScout.forms import LoginForm, SignUpForm, AmountPref, GamesSearch, ContactForm
from SteamScout.models import Games, Preferences, User
from SteamScout.helpers import (
    percent_to_price, format_price, get_price_info,
    generate_email_token, confirm_email_token, send_mail)
from flask.ext.login import login_user, logout_user, login_required
import datetime

@login_manager.user_loader
def load_user(id):
    return User.query.get(id)

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

@app.route('/games', methods=['GET', 'POST']) # <int:page>
def games(page=1):

    game_search_form = GamesSearch()
    # all_games = Games.query.order_by(Games.game_name).paginate(page, 10, False)

    if request.method == "POST" and game_search_form.validate():
        search_term = game_search_form.search_term.data
        games_found = Games.query.filter(Games.game_name.ilike("%{}%".format(search_term)))
        found_count = games_found.count()
        game_search_form = GamesSearch()
        return render_template(
            'games_search.html', game_search_form=game_search_form,
            games_found=games_found, found_count=found_count)
    else:
        return render_template(
            'games.html', game_search_form=game_search_form)
            # add all_games here if pagination is wanted.

@app.route('/games/<game_name>', methods=['GET', 'POST'])
def game_name(game_name):
    title = game_name
    game = Games.query.filter_by(game_name=game_name).first()

    id_num = game.game_id
    amount_form = AmountPref()
    if 'user_id' in session.keys():
        try:
            preference = Preferences.query.filter_by(
                game_name=game_name, user_id=session['user_id']).first()
            existing_treshold = "{:.2f}".format(preference.threshold_amount)
        except:
            existing_treshold = None
    else:
        existing_treshold = None

    price_info = get_price_info(id_num)
    if price_info != None:
        current_price = format_price(price_info['current_price'])
        initial_price = format_price(price_info['initial_price'])
        discount = price_info['discount_percent']
        header_image = price_info['header_image']
    else:
        current_price, initial_price, discount, header_image = None, None, None, None
    if amount_form.validate_on_submit():
        user = User.query.filter_by(id=session['user_id']).first()
        if not user.validated:
            flash("You will not receieve any email alerts until you activate your account.", "danger")
        if preference:
            old_preference = Preferences.query.filter_by(
                game_name=game_name).first()
            db.session.delete(old_preference)
            db.session.commit()

        new_preference = Preferences(
            session['user_id'], id_num, title, amount_form.threshold_amount.data)
        db.session.add(new_preference)
        db.session.commit()
        return redirect(url_for('settings'))

    return render_template(
        'game_page.html', current_price=current_price, initial_price=initial_price,
        discount=discount, game_title=title, id_num=id_num, header_image=header_image,
        amount_form=amount_form, preference=existing_treshold)

@app.route('/developers')
def show_developors():
    # page that shows all the games.
    return render_template('developers.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        steam_email = app.config["MAIL_USERNAME"]
        html = render_template(
            "email/contact.html", message=form.message.data)
        subject = form.header.data
        send_mail(steam_email, subject, html, form.email.data, sender=form.email.data)
        flash("Message Sent!", "success")
        return redirect(url_for('games'))
    else:
        return render_template('contact.html', form=form)

@login_required
@app.route('/settings', methods=['GET', 'POST'])
def settings():
    pref_data = Preferences.query.filter_by(user_id=session['user_id'])
    preferences_count = pref_data.count()
    return render_template(
        'settings.html', pref_data=pref_data, preferences_count=preferences_count)

@login_required
@app.route('/delete', methods=['POST'])
def delete():
    preference = Preferences.query.filter_by(
        user_id=session['user_id'], game_name=request.form['delete']).first()
    db.session.delete(preference)
    db.session.commit()
    flash("That scout has been dismissed.", "success")
    return redirect(url_for('settings'))

# Log in / Log out
@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data.lower()).first()
        if user is None:
            flash("User not found", "danger")
            return render_template('login.html', form=form)
        if flask_bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user)
            session['logged_in'] = True
            session['username'] = user.username
            session['user_id'] = user.id
            return redirect(url_for('home'))
        else:
            return render_template('login.html', form=form)
    else:
        return render_template('login.html', form=form)

@login_required
@app.route('/logout')
def logout():
    logout_user()
    session.pop('username')
    session.pop('logged_in', None)
    flash("You have successfully logged out", "success")
    return redirect(url_for('login'))

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignUpForm(request.form)
    if request.method == 'POST' and form.validate():
        new_user = User(form.username.data.lower(), form.email.data, form.password.data)
        db.session.add(new_user)
        db.session.commit()

        token = generate_email_token(form.email.data)
        confirmation_url = url_for('.confirm_user', token=token, _external=True)
        html = render_template(
            "email/email_confirmation.html", confirmation_url=confirmation_url)
        subject = "Confirm your email"
        send_mail(new_user.email, subject, html)

        flash('We sent you an email to activate your account!', 'info')
        return redirect(url_for('login'))
    else:
        return render_template('signup.html', form=form)

@app.route('/confirm/<token>')
def confirm_user(token):
    try:
        email = confirm_email_token(token)
    except:
        flash('The confirmation link is invalid or has expired.', 'danger')
    current_user = User.query.filter_by(email=email).first_or_404()
    if current_user.validated:
        flash('Your account has already been validated!', 'info')
    else:
        current_user.validated = True
        current_user.validated_on = datetime.datetime.now()
        db.session.add(current_user)
        db.session.commit()
        flash('You have confirmed your account', 'success')
    return redirect(url_for('login'))


from datetime import datetime, timedelta, timezone
from unittest.mock import patch

import asf_search
import pytest

import subscription_worker

def get_asf_product(properties: dict) -> asf_search.ASFProduct:
    product = asf_search.ASFProduct()
    product.properties.update(properties)
    return product

def test_get_unprocessed_granules(tables):
    items = [
        {
            'job_id': 'job1',
            'request_time': '2021-01-01T00:00:00+00:00',
            'user_id': 'my_user',
            'job_type': 'INSAR_GAMMA',
            'name': 'my_name',
            'job_parameters': {
                'granules': ['processed', 'not_processed'],
            },
        },
        {
            'job_id': 'job2',
            'request_time': '2021-01-01T00:00:00+00:00',
            'user_id': 'different_user',
            'job_type': 'INSAR_GAMMA',
            'name': 'subscription1',
            'job_parameters': {
                'granules': ['not_processed', 'not_processed'],
            },
        },
        {
            'job_id': 'job3',
            'request_time': '2021-01-01T00:00:00+00:00',
            'user_id': 'user1',
            'job_type': 'INSAR_GAMMA',
            'name': 'different_name',
            'job_parameters': {
                'granules': ['not_processed', 'not_processed'],
            },
        },
        {
            'job_id': 'job4',
            'request_time': '2021-01-01T00:00:00+00:00',
            'user_id': 'my_user',
            'job_type': 'RTC_GAMMA',
            'name': 'my_name',
            'job_parameters': {
                'granules': ['not_processed'],
            },
        },
    ]
    for item in items:
        tables.jobs_table.put_item(Item=item)

    subscription = {
        'user_id': 'my_user',
        'job_specification': {
            'job_type': 'INSAR_GAMMA',
            'name': 'my_name',
        },
        'search_parameters': {
            'foo': 'bar',
        },
    }

    products = [
        get_asf_product({'sceneName': 'processed'}),
        get_asf_product({'sceneName': 'not_processed'}),
    ]

    def mock_search(**kwargs) -> asf_search.ASFSearchResults:
        assert kwargs == subscription['search_parameters']
        results = asf_search.ASFSearchResults(products)
        results.searchComplete = True
        return results

    def mock_search_incomplete(**kwargs) -> asf_search.ASFSearchResults:
        results = mock_search(**kwargs)
        results.searchComplete = False
        return results

    with patch('asf_search.search', mock_search):
        assert subscription_worker.get_unprocessed_granules(subscription) == products[1:]

    with patch('asf_search.search', mock_search_incomplete), \
            pytest.raises(asf_search.ASFSearchError, match=r'.*Results are incomplete.*'):
        subscription_worker.get_unprocessed_granules(subscription)

def test_get_processed_granules():
    def mock_job(granule_name: str) -> dict:
        return {
            'job_parameters': {
                'granules': [granule_name],
            }
        }

    def mock_query_jobs(**kwargs):
        assert kwargs['user'] == 'my_user'
        assert kwargs['name'] == 'my_name'
        assert kwargs['job_type'] == 'RTC_GAMMA'

        if 'start_key' not in kwargs:
            job = mock_job('granule0')
            next_token = 0
        elif kwargs['start_key'] == 0:
            job = mock_job('granule1')
            next_token = 1
        else:
            assert kwargs['start_key'] == 1
            job = mock_job('granule2')
            next_token = None

        return [job], next_token

    expected = ['granule0', 'granule1', 'granule2']
    with patch('dynamo.jobs.query_jobs', mock_query_jobs):
        assert subscription_worker.get_processed_granules('my_user', 'my_name', 'RTC_GAMMA') == expected

def test_get_neighbors():
    granule = get_asf_product({'sceneName': 'granule'})

    def mock_stack_from_product(payload) -> asf_search.ASFSearchResults:
        assert payload == granule
        results = asf_search.ASFSearchResults([
            get_asf_product({'sceneName': 'S1A_A', 'temporalBaseline': -3}),
            get_asf_product({'sceneName': 'S1B_B', 'temporalBaseline': -2}),
            get_asf_product({'sceneName': 'S1A_C', 'temporalBaseline': -1}),
            get_asf_product({'sceneName': 'S1B_D', 'temporalBaseline': 0}),
            get_asf_product({'sceneName': 'S1A_E', 'temporalBaseline': 1}),
            get_asf_product({'sceneName': 'S1B_F', 'temporalBaseline': 2}),
            get_asf_product({'sceneName': 'S1A_G', 'temporalBaseline': 3}),
        ])
        results.searchComplete = True
        return results

    def mock_stack_from_product_incomplete(payload) -> asf_search.ASFSearchResults:
        results = mock_stack_from_product(payload)
        results.searchComplete = False
        return results

    with patch('asf_search.baseline_search.stack_from_product', mock_stack_from_product):
        neighbors = subscription_worker.get_neighbors(granule, 1, 'S1')
        assert neighbors == ['S1A_C']

        neighbors = subscription_worker.get_neighbors(granule, 2, 'S1')
        assert neighbors == ['S1B_B', 'S1A_C']

        neighbors = subscription_worker.get_neighbors(granule, 2, 'S1A')
        assert neighbors == ['S1A_A', 'S1A_C']

        neighbors = subscription_worker.get_neighbors(granule, 5, 'S1B')
        assert neighbors == ['S1B_B']

    with patch('asf_search.baseline_search.stack_from_product', mock_stack_from_product_incomplete), \
            pytest.raises(asf_search.ASFSearchError, match=r'.*Results are incomplete.*'):
        subscription_worker.get_neighbors(granule, 1, 'S1')

def test_get_jobs_for_granule():
    granule = get_asf_product({'sceneName': 'GranuleName'})
    granule2 = get_asf_product({'sceneName': 'GranuleName2'})

    subscription = {
        'subscription_id': 'f00b731f-121d-44dc-abfa-c24afd8ad542',
        'user_id': 'subscriptionsUser',
        'search_parameters': {
            'start': '2020-01-01T00:00:00+00:00',
            'end': '2020-01-01T00:00:00+00:00',
        },
        'job_specification': {
            'job_type': 'RTC_GAMMA',
            'name': 'SubscriptionName',
            'job_parameters': {
                'speckle_filter': True,
            }
        }
    }
    payload = subscription_worker.get_jobs_for_granule(subscription, granule)
    payload2 = subscription_worker.get_jobs_for_granule(subscription, granule2)
    assert payload == [
        {
            'subscription_id': 'f00b731f-121d-44dc-abfa-c24afd8ad542',
            'job_type': 'RTC_GAMMA',
            'name': 'SubscriptionName',
            'job_parameters': {
                'granules': ['GranuleName'],
                'speckle_filter': True,
            },
        }
    ]
    assert payload2 == [
        {
            'subscription_id': 'f00b731f-121d-44dc-abfa-c24afd8ad542',
            'job_type': 'RTC_GAMMA',
            'name': 'SubscriptionName',
            'job_parameters': {
                'granules': ['GranuleName2'],
                'speckle_filter': True,
            },
        }
    ]

    subscription = {
        'subscription_id': '51b576b0-a89b-4108-a9d8-7ecb52aee950',
        'user_id': 'subscriptionsUser',
        'search_parameters': {
            'start': '2020-01-01T00:00:00+00:00',
            'end': '2020-01-01T00:00:00+00:00',
            'platform': 'foo',
        },
        'job_specification': {
            'job_type': 'INSAR_GAMMA',
            'name': 'SubscriptionName'
        }
    }
    mock_granules = ['granule2', 'granule3']
    with patch('subscription_worker.get_neighbors', lambda x, y, z: mock_granules):
        payload = subscription_worker.get_jobs_for_granule(subscription, granule)
        assert payload == [
            {
                'subscription_id': '51b576b0-a89b-4108-a9d8-7ecb52aee950',
                'job_type': 'INSAR_GAMMA',
                'name': 'SubscriptionName',
                'job_parameters': {
                    'granules': ['GranuleName', 'granule2'],
                }
            },
            {
                'subscription_id': '51b576b0-a89b-4108-a9d8-7ecb52aee950',
                'job_type': 'INSAR_GAMMA',
                'name': 'SubscriptionName',
                'job_parameters': {
                    'granules': ['GranuleName', 'granule3'],
                },
            }
        ]

    subscription = {
        'subscription_id': '51b576b0-a89b-4108-a9d8-7ecb52aee950',
        'job_specification': {
            'job_type': 'FOO',
        }
    }
    with pytest.raises(ValueError):
        subscription_worker.get_jobs_for_granule(subscription, granule)

def test_get_jobs_for_subscription():
    def mock_get_unprocessed_granules(subscription):
        assert subscription == {}
        return ['a', 'b', 'c']

    def mock_get_jobs_for_granule(subscription, granule):
        return [{'granule': granule}]

    with patch('subscription_worker.get_unprocessed_granules', mock_get_unprocessed_granules):
        with patch('subscription_worker.get_jobs_for_granule', mock_get_jobs_for_granule):

            result = subscription_worker.get_jobs_for_subscription(subscription={}, limit=20)
            assert result == [
                {'granule': 'a'},
                {'granule': 'b'},
                {'granule': 'c'},
            ]

            result = subscription_worker.get_jobs_for_subscription(subscription={}, limit=1)
            assert result == [
                {'granule': 'a'},
            ]

            result = subscription_worker.get_jobs_for_subscription(subscription={}, limit=0)
            assert result == []

def test_lambda_handler(tables):
    items = [
        {
            'subscription_id': 'sub1',
            'creation_date': '2020-01-01T00:00:00+00:00',
            'job_type': 'INSAR_GAMMA',
            'search_parameters': {
                'start': datetime.now(tz=timezone.utc).isoformat(timespec='seconds'),
                'end': (datetime.now(tz=timezone.utc) + timedelta(days=5)).isoformat(timespec='seconds'),
            },
            'user_id': 'user1',
            'enabled': True,
        },
        {
            'subscription_id': 'sub2',
            'creation_date': '2020-01-01T00:00:00+00:00',
            'job_type': 'INSAR_GAMMA',
            'user_id': 'user1',
            'enabled': False
        },
        {
            'subscription_id': 'sub3',
            'creation_date': '2020-01-01T00:00:00+00:00',
            'job_type': 'INSAR_GAMMA',
            'search_parameters': {
                'start': (datetime.now(tz=timezone.utc) - timedelta(days=15)).isoformat(timespec='seconds'),
                'end': (datetime.now(tz=timezone.utc) - timedelta(days=5)).isoformat(timespec='seconds'),
            },
            'user_id': 'user1',
            'enabled': True,
        },
        {
            'subscription_id': 'sub4',
            'creation_date': '2020-01-01T00:00:00+00:00',
            'job_type': 'INSAR_GAMMA',
            'search_parameters': {
                'start': (datetime.now(tz=timezone.utc) - timedelta(days=15)).isoformat(timespec='seconds'),
                'end': (datetime.now(tz=timezone.utc) - timedelta(days=5)).isoformat(timespec='seconds'),
            },
            'user_id': 'user1',
            'enabled': True,
        },
    ]
    for item in items:
        tables.subscriptions_table.put_item(Item=item)

    def mock_get_unprocessed_granules(subscription):
        if subscription['subscription_id'] == 'sub4':
            return ['notempty']
        else:
            return []

    with patch('subscription_worker.handle_subscription') as mock_handle_subscription:
        with patch('subscription_worker.get_unprocessed_granules', mock_get_unprocessed_granules):
            subscription_worker.lambda_handler({'subscription': items[0]}, None)

            with pytest.raises(ValueError, match=r'subscription sub2 is disabled'):
                subscription_worker.lambda_handler.__wrapped__({'subscription': items[1]}, None)

            subscription_worker.lambda_handler({'subscription': items[2]}, None)
            subscription_worker.lambda_handler({'subscription': items[3]}, None)

        assert mock_handle_subscription.call_count == 3

    response = tables.subscriptions_table.scan()['Items']

    sub1 = [sub for sub in response if sub['subscription_id'] == 'sub1'][0]
    assert sub1['enabled'] is True

    sub3 = [sub for sub in response if sub['subscription_id'] == 'sub3'][0]
    assert sub3['enabled'] is False

    sub4 = [sub for sub in response if sub['subscription_id'] == 'sub4'][0]
    assert sub4['enabled'] is True


""" Basic API integration for ordr.

    Can render replays and fetch replays by ID
"""
import json
import logging
from datetime import datetime

import socketio
from aiohttp import FormData

from pcbot import utils, config, Config

host = "https://apis.issou.best/ordr/"
ws_link = "https://ordr-ws.issou.best"
requested_renders = {}

ordr_client = socketio.AsyncClient()

ordr_config = Config("ordr", pretty=True, data=dict(
    verificationKey="change to your API key",
    resolution="1280x720",  # The resolution of the replay
    globalVolume=80,  # The global volume of the replay
    musicVolume=80,  # The music volume of the replay
    hitsoundVolume=80,  # The hitsound volume of the replay
    showHitErrorMeter="true",  # Whether or not to show the hiterror meter
    showUnstableRate="true",  # Whether or not to display the UR
    showScore="true",  # Whether or not to display the score
    showHPbar="true",  # Whether or not to display the HP bar
    showComboCounter="true",  # Whether or not to display the combo counter
    showPPCounter="true",  # Whether or not to display the PP counter
    showScoreboard="false",  # Whether or not to display the scoreboard (This might
    showBorders="false",  # Whether or not to display playfield borders
    showMods="true",  # Whether or not to display mod icons
    showResultScreen="false",  # Whether or not to show the results screen
    skin="heckin",  # The name or ID of the skin to use
    useSkinCursor="true",  # Whether or not to use the skin cursor
    useBeatmapColors="false",  # Whether or not to use beatmap colors instead of skin colors
    useSkinColors="true",  # Whether or not to use skin colors instead of beatmap colors
    useSkinHitsounds="false",  # Whether or not to use skin hitsounds instead of beatmap hitsounds
    cursorScaleToCS="false",  # Whether or not the cursor should scale with CS
    cursorRainbow="false",  # Whether or not the cursor should rainbow, only works if useSkinCursor is False
    cursorTrailGlow="false",  # Whether or not the cursor trail should have a glow
    drawFollowPoints="true",  # Whether or not followpoints should be shown
    scaleToTheBeat="false",  # Whether or not objects should scale to the beat
    sliderMerge="false",  # Whether or not sliders should be merged
    objectsRainbow="false",  # Whether or not objects should rainbow. This overrides beatmap or skin colors
    objectsFlashToTheBeat="false",  # Whether or not objects should flash to the beat
    useHitCircleColor="false",  # Whether or not the slider body should have the same color as the hitcircles
    seizureWarning="false",  # Whether or not to display the 5 second seizure warning before the render
    loadStoryboard="false",  # Whether or not to load the beatmap storyshow
    loadVideo="false",  # Whether or not to load the beatmap video
    introBGDim=80,  # How dimmed the intro BG should be in percentage from 0 to 100
    inGameBGDim=90,  # How dimmed the ingame BG should be in percentage from 0 to 100
    breakBGDim=80,  # How dimmed the break BG should be in percentage from 0 to 100
    BGParallax="false",  # Whether or not the BG should have parralax
    showDanserLogo="true",  # Whether or not to show the danser logo before the render
    skip="false",  # Whether or not to skip the intro
    cursorRipples="false",  # Whether or not to show cursor ripples
    cursorSize=1,  # The size of the cursor from 0.5 to 2
    cursorTrail="true",  # Whether or not to show the cursortrail
    drawComboNumbers="true",  # Whether or not to show combo number in hitcircles
    sliderSnakingIn="true",  # Whether or not sliders should snake in
    sliderSnakingOut="false",  # Whether or not sliders should snake out
    showHitCounter="true",  # Whether or not the hit counter (100s, 50s, misses) should be shown
    showKeyOverlay="true",  # Whether or not the key overlay should be shown
    showAvatarsOnScoreboard="false",  # Whether or not to show avatars on the scoreboard. May break some skins
    showAimErrorMeter="false",  # Whether or not to show an aim error meter
))

@ordr_client.event()
async def render_done_json(data: json):
    render_id = data["renderID"]
    video_url = data["videoUrl"]
    if render_id in requested_renders:
        await requested_renders[render_id]["message"].edit(video_url)
        requested_renders.pop(render_id)

@ordr_client.event()
async def render_failed_json(data: json):
    render_id = data["renderID"]
    error_code = data["errorCode"]
    error_message = data["errorMessage"]
    if render_id in requested_renders:
        if error_code == 1:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 2:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 3:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 4:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 5:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 6:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 7:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 8:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 9:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 10:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 11:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 12:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 13:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 14:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 15:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 16:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 17:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 18:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 19:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 20:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 21:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 22:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 23:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 24:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 25:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)
        elif error_code == 26:
            await requested_renders[render_id]["message"].edit(error_message)
            requested_renders.pop(render_id)

@ordr_client.event()
async def render_progress_json(data: json):
    render_id = data["renderID"]
    progress = data["progress"]
    renderer = data["renderer"]
    if render_id in requested_renders:
        if (datetime.utcnow() - requested_renders[render_id]["edited"]).total_seconds() > 5:
            await requested_renders[render_id]["message"].edit("{}\nRendered by: {}".format(progress, renderer))
            requested_renders[render_id]["edited"] = datetime.utcnow()

@ordr_client.event()
async def connect():
    logging.info("Client successfully connected to ordr websocket.")

@ordr_client.event()
async def disconnect():
    logging.info("Disconnected from ordr websocket. Attempting to reconnect.")

@ordr_client.event()
async def connect_error(data):
    logging.info("Connection to ordr websocket failed.")

async def get_render(render_id: int):
    """ Return an ordr render by it's ID """
    params = {
        "renderID": render_id
    }

    results = await utils.download_json(url=host + "renders", **params)
    if not results:
        return None
    result = results["renders"][0]
    return result

async def send_render_job(option):
    """ Send a replay to be rendered by ordr.
    """
    replay = None
    replay_url = None

    if isinstance(option, (bytes, bytearray)):
        replay = option
    elif utils.http_url_pattern.match(option):
        replay_url = option

    params = {
        "username": config.name,
        "resolution": ordr_config.data["resolution"],
        "globalVolume": ordr_config.data["globalVolume"],
        "musicVolume": ordr_config.data["musicVolume"],
        "hitsoundVolume": ordr_config.data["hitsoundVolume"],
        "showHitErrorMeter": ordr_config.data["showHitErrorMeter"],
        "showUnstableRate": ordr_config.data["showUnstableRate"],
        "showScore": ordr_config.data["showScore"],
        "showHPbar": ordr_config.data["showHPbar"],
        "showComboCounter": ordr_config.data["showComboCounter"],
        "showPPCounter": ordr_config.data["showPPCounter"],
        "showScoreboard": ordr_config.data["showScoreboard"],
        "showBorders": ordr_config.data["showBorders"],
        "showMods": ordr_config.data["showMods"],
        "showResultScreen": ordr_config.data["showResultScreen"],
        "skin": ordr_config.data["skin"],
        "useSkinCursor": ordr_config.data["useSkinCursor"],
        "useSkinColors": ordr_config.data["useSkinColors"],
        "useBeatmapColors": ordr_config.data["useBeatmapColors"],
        "useSkinHitsounds": ordr_config.data["useSkinHitsounds"],
        "cursorScaleToCS": ordr_config.data["cursorScaleToCS"],
        "cursorTrailGlow": ordr_config.data["cursorTrailGlow"],
        "drawFollowPoints": ordr_config.data["drawFollowPoints"],
        "scaleToTheBeat": ordr_config.data["scaleToTheBeat"],
        "sliderMerge": ordr_config.data["sliderMerge"],
        "cursorRainbow": ordr_config.data["cursorRainbow"],
        "objectsRainbow": ordr_config.data["objectsRainbow"],
        "objectsFlashToTheBeat": ordr_config.data["objectsFlashToTheBeat"],
        "useHitCircleColor": ordr_config.data["useHitCircleColor"],
        "seizureWarning": ordr_config.data["seizureWarning"],
        "loadStoryboard": ordr_config.data["loadStoryboard"],
        "loadVideo": ordr_config.data["loadVideo"],
        "introBGDim": ordr_config.data["introBGDim"],
        "inGameBGDim": ordr_config.data["inGameBGDim"],
        "breakBGDim": ordr_config.data["breakBGDim"],
        "BGParallax": ordr_config.data["BGParallax"],
        "showDanserLogo": ordr_config.data["showDanserLogo"],
        "skip": ordr_config.data["skip"],
        "cursorRipples": ordr_config.data["cursorRipples"],
        "cursorSize": ordr_config.data["cursorSize"],
        "cursorTrail": ordr_config.data["cursorTrail"],
        "drawComboNumbers": ordr_config.data["drawComboNumbers"],
        "sliderSnakingIn": ordr_config.data["sliderSnakingIn"],
        "sliderSnakingOut": ordr_config.data["sliderSnakingOut"],
        "showHitCounter": ordr_config.data["showHitCounter"],
        "showKeyOverlay": ordr_config.data["showKeyOverlay"],
        "showAvatarsOnScoreboard": ordr_config.data["showAvatarsOnScoreboard"],
        "showAimErrorMeter": ordr_config.data["showAimErrorMeter"]
    }

    if replay:
        params["replayFile"] = replay
    elif replay_url:
        params["replayURL"] = replay_url

    if ordr_config.data["verificationKey"] != "change to your API key":
        params["verificationKey"] = ordr_config.data["verificationKey"]

    data = FormData()
    for param, value in params.items():
        data.add_field(param, value)

    try:
        results = await utils.post_request(url=host + "renders", call=utils.convert_to_json, data=data)
    except ValueError as e:
        results = e

    return results

async def establish_ws_connection():
    if ordr_client.connected:
        await ordr_client.disconnect()
    await ordr_client.connect(ws_link)


#
# Copyright (C) 2018 ETH Zurich and University of Bologna
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Authors: Germain Haugou, ETH (germain.haugou@iis.ee.ethz.ch)

import ctypes
import os
import os.path
import json_tools as js
from elftools.elf.elffile import ELFFile
import time

class rt_bridge(object):

    def __init__(self, config, binaries=[], verbose=False):
        self.config = config
        self.binaries = binaries
        self.verbose = verbose

        lib_path=os.path.join('librtbridge.so')
        self.module = ctypes.CDLL(lib_path)

        self.module.rtbridge_reqloop_open.argtypes = [ctypes.c_uint]
        self.module.rtbridge_reqloop_open.restype = ctypes.c_void_p

        self.module.rtbridge_reqloop_close.argtypes = [ctypes.c_void_p, ctypes.c_int]

    def _get_binary_symbol_addr(self, name):
        for binary in self.binaries:
            with open(binary, 'rb') as file:
                elf = ELFFile(file)
                for section in elf.iter_sections():
                    if section.header['sh_type'] == 'SHT_SYMTAB':
                        for symbol in section.iter_symbols():
                            if symbol.name == name:
                                t_section=symbol.entry['st_shndx']
                                t_vaddr=symbol.entry['st_value']
                                return t_vaddr
        return 0

    def reqloop(self):

        # First get address of the structure used to communicate between
        # the bridge and the runtime
        addr = self._get_binary_symbol_addr('__rt_debug_struct_ptr')
        if addr == 0:
            addr = self._get_binary_symbol_addr('debugStruct_ptr')

        self.reqloop_handle = self.module.rtbridge_reqloop_open(addr)
        self.module.rtbridge_reqloop_close(self.reqloop_handle, False)

        return 0


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import pandas as pd
from PIL import Image

# HOW TO USE: python tf_record.py --output_path training.record

flags = tf.app.flags
flags.DEFINE_string('dataset_type', 'training', 'training or test')
flags.DEFINE_string('num_images', None, 'number of imagesa conforming the output data set')
FLAGS = flags.FLAGS

LABEL_DICT = {
    "occupied": 1,
    "free": 2
}

def int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def int64_list_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

def bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def bytes_list_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

def float_list_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))

def read_examples_list(path):
    with tf.gfile.GFile(path) as fid:
        lines = fid.readlines()
    return [line.strip().split(' ')[0] for line in lines]

def create_tf_example(image_path, same_image_samples):

    image = Image.open(image_path)

    height = image.size[1]
    width = image.size[0]
    filename = image_path.encode() # Filename of the image. Empty if image is not from file
    image_format = "jpg".encode() # b'jpeg' or b'png'

    with tf.gfile.GFile(image_path, 'rb') as fid:
        encoded_image_data = fid.read()

    xmins = [] # List of normalized left x coordinates in bounding box (1 per box)
    xmaxs = [] # List of normalized right x coordinates in bounding box
             # (1 per box)
    ymins = [] # List of normalized top y coordinates in bounding box (1 per box)
    ymaxs = [] # List of normalized bottom y coordinates in bounding box
             # (1 per box)
    classes_text = [] # List of string class name of bounding box (1 per box)
    classes = [] # List of integer class id of bounding box (1 per box)

    for index, row in same_image_samples.iterrows():
        xmins.append(float(row['xmin'])/width)
        xmaxs.append(float(row['xmax'])/width)
        ymins.append(float(row['ymin'])/height)
        ymaxs.append(float(row['ymax'])/height)
        classes_text.append(row['occupancy'].encode())
        classes.append(int(LABEL_DICT[row['occupancy']]))

    tf_label_and_data = tf.train.Example(features=tf.train.Features(feature={
        'image/height': int64_feature(height),
        'image/width': int64_feature(width),
        'image/filename': bytes_feature(filename),
        'image/source_id': bytes_feature(filename),
        'image/encoded': bytes_feature(encoded_image_data),
        'image/format': bytes_feature(image_format),
        'image/object/bbox/xmin': float_list_feature(xmins),
        'image/object/bbox/xmax': float_list_feature(xmaxs),
        'image/object/bbox/ymin': float_list_feature(ymins),
        'image/object/bbox/ymax': float_list_feature(ymaxs),
        'image/object/class/text': bytes_list_feature(classes_text),
        'image/object/class/label': int64_list_feature(classes),
    }))

    return tf_label_and_data

def main(_):

    num_images = None

    dataset_type = FLAGS.dataset_type
    output_path = dataset_type + "/" + dataset_type + ".record"

    data_csv_path = "./" + dataset_type + "/" + dataset_type + ".csv"

    if FLAGS.num_images is not None:
        num_images = int(FLAGS.num_images)
        output_path = dataset_type + "/" + dataset_type + str(num_images) + ".record"

    print("Num img:", num_images)

    df = pd.read_csv(data_csv_path)
    df.head()

    writer = tf.python_io.TFRecordWriter(output_path)

    image_count = 0
    for image_path in df['img_path'].unique():
        image_filtered_df = df[df.img_path == image_path]
        tf_example = create_tf_example(image_path=image_path, same_image_samples=image_filtered_df)
        writer.write(tf_example.SerializeToString())
        image_count += 1
        if num_images == image_count:
            break

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


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('MovieManager', '0001_initial'),
        ('AdminManager', '0005_newesimagesofmovies'),
    ]

    operations = [
        migrations.CreateModel(
            name='FavouriteCritism',
            fields=[
                ('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)),
                ('critism', models.OneToOneField(to='MovieManager.Movie')),
            ],
        ),
    ]