from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
row = list()
soma = list()
mini = list()
ma = list()
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(766, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.Tabela_de_Jogos = QtWidgets.QTableWidget(self.centralwidget)
        self.Tabela_de_Jogos.setObjectName("Tabela_de_Jogos")
        self.Tabela_de_Jogos.setColumnCount(7)
        self.Tabela_de_Jogos.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.Tabela_de_Jogos.setHorizontalHeaderItem(6, item)
        self.gridLayout.addWidget(self.Tabela_de_Jogos, 0, 0, 1, 3)
        self.pontos_do_jogo = QtWidgets.QLabel(self.centralwidget)
        self.pontos_do_jogo.setObjectName("pontos_do_jogo")
        self.gridLayout.addWidget(self.pontos_do_jogo, 1, 1, 1, 1)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.gridLayout.addWidget(self.label, 1, 2, 3, 1)
        self.Caixa_de_pontos = QtWidgets.QLineEdit(self.centralwidget)
        self.Caixa_de_pontos.setText("")
        self.Caixa_de_pontos.setObjectName("Caixa_de_pontos")
        self.gridLayout.addWidget(self.Caixa_de_pontos, 2, 1, 1, 1)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 3, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.pushButton.clicked.connect(lambda: self.adicionar())
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 766, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def adicionar(self):
        pontos = self.Caixa_de_pontos.text()
        try:
            int(pontos)
            if int(pontos) < 0:
                pontos = 'Sou negativo'
            int(pontos)
        except:
            QMessageBox.about(self.centralwidget, 'ERRO', 'Pontuação Invalida')
        else:
            rowCount = self.Tabela_de_Jogos.rowCount()
            self.Tabela_de_Jogos.insertRow(rowCount)
            row.append(pontos)
            soma.append(int(pontos))
            media = sum(soma) / len(soma)
            if len(row) == 1:
                self.Tabela_de_Jogos.setItem(len(row)-1, 0, QtWidgets.QTableWidgetItem(str(len(row))))
                self.Tabela_de_Jogos.setItem(len(row)-1, 1, QtWidgets.QTableWidgetItem(pontos))
                self.Tabela_de_Jogos.setItem(len(row)-1, 2, QtWidgets.QTableWidgetItem(min(row)))
                self.Tabela_de_Jogos.setItem(len(row)-1, 3, QtWidgets.QTableWidgetItem(max(row)))
                self.Tabela_de_Jogos.setItem(len(row)-1, 4, QtWidgets.QTableWidgetItem(str(len(mini))))
                self.Tabela_de_Jogos.setItem(len(row)-1, 5, QtWidgets.QTableWidgetItem(str(len(ma))))
                self.Tabela_de_Jogos.setItem(len(row)-1, 6, QtWidgets.QTableWidgetItem(str(int(media))))
                mini.append(int(pontos))
                ma.append(int(pontos))
            else:
                if soma[-1] < mini[-1]:
                    mini.append(int(pontos))
                if soma[-1] > ma[-1]:
                    ma.append(int(pontos))
                self.Tabela_de_Jogos.setItem(len(row)-1, 0, QtWidgets.QTableWidgetItem(str(len(row))))
                self.Tabela_de_Jogos.setItem(len(row)-1, 1, QtWidgets.QTableWidgetItem(pontos))
                self.Tabela_de_Jogos.setItem(len(row)-1, 2, QtWidgets.QTableWidgetItem(min(row)))
                self.Tabela_de_Jogos.setItem(len(row)-1, 3, QtWidgets.QTableWidgetItem(max(row)))
                self.Tabela_de_Jogos.setItem(len(row)-1, 4, QtWidgets.QTableWidgetItem(str(len(mini)-1)))
                self.Tabela_de_Jogos.setItem(len(row)-1, 5, QtWidgets.QTableWidgetItem(str(len(ma)-1)))
                self.Tabela_de_Jogos.setItem(len(row)-1, 6, QtWidgets.QTableWidgetItem(str(int(media))))

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Proway"))
        item = self.Tabela_de_Jogos.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "Jogo"))
        self.Tabela_de_Jogos.setColumnWidth(0, 40)
        item = self.Tabela_de_Jogos.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Placar"))
        self.Tabela_de_Jogos.setColumnWidth(1, 45)
        item = self.Tabela_de_Jogos.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "Mínimo da Temporada"))
        self.Tabela_de_Jogos.setColumnWidth(2, 130)
        item = self.Tabela_de_Jogos.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "Máximo da Temporada"))
        self.Tabela_de_Jogos.setColumnWidth(3, 130)
        item = self.Tabela_de_Jogos.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "Quebra recorde mín."))
        self.Tabela_de_Jogos.setColumnWidth(4, 125)
        item = self.Tabela_de_Jogos.horizontalHeaderItem(5)
        item.setText(_translate("MainWindow", "Quebra recorde máx."))
        self.Tabela_de_Jogos.setColumnWidth(5, 125)
        item = self.Tabela_de_Jogos.horizontalHeaderItem(6)
        item.setText(_translate("MainWindow", "Média de Pontos"))
        self.Tabela_de_Jogos.setColumnWidth(6, 150)
        self.pontos_do_jogo.setText(_translate("MainWindow", "Pontuação do Jogo"))
        self.pushButton.setText(_translate("MainWindow", "Adicionar Pontuação"))

import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())


## Import libraries
import cv2
from . import (fingerprint_distances_plot,
               fingerprint_matches_extraction,
               histogram_computation_and_plot,
               self_similar_matches_extraction,
               self_similar_distances_plot)

## Initialize constants

INITIAL_KNN = 10 # at first iteration of FLANN KDTREE we search for this number of neighborhood for each feature
KNN_STEP = 5 # when k self-similar matches are been found for at least one feature, more neighbours are searched, incrementing the actual number by this

## Find self-similar matches, fingerprint matches.
## Furthermore compute the description vector distances distribution, plot quantiles,
## self-similar matches, fingerprint matches together with the distances distribution
def self_similar_and_fingerprint_matches_extraction(template_descriptors):
    #%% Initialize a flann_matcher object to match keypoint witn nearest neighborhood.

    # = From flann_matcher documentation ==================================================
    # 	flann_matcher_INDEX_LINEAR = 0,
    # 	flann_matcher_INDEX_KDTREE = 1,
    # 	flann_matcher_INDEX_KMEANS = 2,
    # 	flann_matcher_INDEX_COMPOSITE = 3,
    # 	flann_matcher_INDEX_KDTREE_SINGLE = 4,
    # 	flann_matcher_INDEX_HIERARCHICAL = 5,
    # 	flann_matcher_INDEX_LSH = 6,
    # 	flann_matcher_INDEX_KDTREE_CUDA = 7, // available if compiled with CUDA
    # 	flann_matcher_INDEX_SAVED = 254,
    # 	flann_matcher_INDEX_AUTOTUNED = 255,
    # =============================================================================

    ## Specify a constant representing the type of algorithm used by flann_matcher
    flann_matcher_INDEX_KDTREE = 1 # algorithm used is KDTREE

    ## Specify flann_matcher matcher creator parameters
    index_params = dict(algorithm=flann_matcher_INDEX_KDTREE, trees=20) # 5 trees used in the KDTREE search
    search_params = dict(checks=200) # number of times the trees in the index should be recursively traversed

    ## Create FLANN matcher
    flann_matcher = cv2.FlannBasedMatcher(index_params, search_params)

    #%% Find correspondences by matching the template features with itself

    ## Invoke flann_matcher methods to obtain k outputs: for each feature in the template_descriptors image returns the k closest features in the template_descriptors image
    actual_knn = INITIAL_KNN
    matches =  flann_matcher.knnMatch(template_descriptors,template_descriptors,k=actual_knn) # there is no threshold, the k closest points are returned

    ## Show the number of features in template_descriptors image that have at least one match in template_descriptors image
    # print('Found ' + str(len(matches)) + ' putative matches')

    #%% Compute the description vector interval of distances

    ## Deletion of the first match that is the feature itself
    for i,kmatches in enumerate(matches):
        kmatches.pop(0)

    ## Creation of an array of all second matches
    second_matches = [item[0] for item in matches]

    ## Compute distances between each template feature and its second nearest neighbour (the first is the feature itself).
    ## Then distances histogram is seen as a discrete distribution, and its range of
    ## distances values is extracted.
    ## At the end the histogram is plotted.
    interval = histogram_computation_and_plot(second_matches, template_descriptors)

    #%% Find self-similar matches

    ## Compute a list with the same shape of "matches", but conserving only
    ## self-similar matches
    self_similar_list, search_for_more_neighbors, self_similar_quantile = self_similar_matches_extraction(matches,second_matches,template_descriptors)

    ## If at least one of the features has k self-similar matches,
    ## more neighbors has to be computed to find other possible self-simlar matches
    while search_for_more_neighbors:
        actual_knn = actual_knn+KNN_STEP
        matches =  flann_matcher.knnMatch(template_descriptors,template_descriptors,k=actual_knn)
        for i,kmatches in enumerate(matches):
            kmatches.pop(0)
        self_similar_list, search_for_more_neighbors, self_similar_quantile = self_similar_matches_extraction(matches,second_matches,template_descriptors)
    print('Maximum number of self-similar matches: ' + str(len(max(self_similar_list,key=len))))
    print('Number of features that have at least one self-similar match: ' + str(len([self_similar_matches for self_similar_matches in self_similar_list if self_similar_matches])))

    #%% Find fingerprint matches

    ## Compute a list with the same shape of "matches", but conserving only
    ## fingerprint matches
    fingerprint_list, fingerprint_quantile = fingerprint_matches_extraction(matches,second_matches,template_descriptors)
    print('Number of features that have a fingerprint match: ' + str(len([fingerprint_match for fingerprint_match in fingerprint_list if fingerprint_match])))

    #%% Plot quantiles, self-similar matches and fingerprint matches

    self_similar_distances_plot(self_similar_list, template_descriptors, interval, self_similar_quantile)
    fingerprint_distances_plot(fingerprint_list, template_descriptors, interval, fingerprint_quantile)

    return self_similar_list, fingerprint_list


prod = 1
for i in range(1, 51):      # For 1 to 50 inclusive,
    prod = prod * i
s = str(prod)               # Convert factorial to string s
n = len(s)                  # n = length of string s
z = 0
while n > 0 and s[n - 1] == '0':
    z = z + 1
    n = n - 1
print('50! is', s)
print('The number of trailing zeros is', z)


#!/usr/bin/env python
import struct

from core import eBPFCoreApplication, set_event_handler
from core.packets import *

import csv
import time
import matplotlib
import threading

from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size': 14})

PROTO_TABLE_NAME = 'counters'
if len(sys.argv) > 1:
    MAX_TO_SHOW = int(sys.argv[1])
else:
    MAX_TO_SHOW = 30 # max is 256

if len(sys.argv) > 2:
    time = int(sys.argv[2])
else:
    time = 10

# table for ip protocols identification
csvFile = open('../protocol-numbers.csv')
reader  = csv.DictReader(csvFile)
pname   = [str(i) for i in range(256)]
for row in reader:
    try:
        pname[int(row['Decimal'])] = row['Keyword']
    except:
        False

plt.ion()
plt.draw()
plt.show()

class QueryThread(threading.Thread):
    def __init__(self, event, connection):
        threading.Thread.__init__(self)
        self.stopped = event
        self.connection = connection

    def run(self):
        while not self.stopped.wait(10):
            self.connection.send(TableListRequest(table_name=PROTO_TABLE_NAME))

class ProtoCountApplication(eBPFCoreApplication):

    @set_event_handler(Header.HELLO)
    def hello(self, connection, pkt):
        with open('../examples/protocount.o', 'rb') as f:
            print("Installing the eBPF ELF")
            connection.send(InstallRequest(elf=f.read()))

        self.queryThreadStopEvent = threading.Event()
        self.queryThread = QueryThread(self.queryThreadStopEvent, connection)
        self.queryThread.daemon = True
        self.queryThread.start()

    @set_event_handler(Header.TABLE_LIST_REPLY)
    def table_list_reply(self, connection, pkt):
        plt.cla()
        plt.clf()

        num_elms = min(256, MAX_TO_SHOW) # pkt.n_items
        x        = range(num_elms)
        x_labels = pname[0:num_elms]
        data = [ ]

        item_size = pkt.entry.value_size

        for i in range(pkt.n_items):
            npackets, nbytes = struct.unpack_from('IQ', pkt.items, i * item_size)
            if i < num_elms:
                data.append(nbytes)

        plt.bar(x, data, align='center')
        plt.xticks(x, x_labels, rotation=70, fontsize=12)
#        plt.title('Protocol Byte Count', fontsize=18)
#        plt.xlabel('Protocols', fontsize=18)
#        plt.ylabel('Number of Bytes', fontsize=18)
        plt.title('Contagem de Bytes por Protocolo', fontsize=18)
        plt.xlabel('Protocolos', fontsize=18)
        plt.ylabel('Numero de Bytes', fontsize=18)
        plt.tight_layout()
        plt.draw()
        plt.pause(0.01)

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


#!/usr/bin/env python3
num =input("escribe el numero de palabras")
lista1 = []
#comprobamos que es número
if (num.isdigit()):
	#se crea un for para hacer que guarde el numero que hayas introducido
	for x in range(0,int(num)):
		print("Digame la palabra ",x +1)
		palabra = input()
		lista1.append(palabra)
	print(lista1)
elif int(num)<= 0:
	print("número introducido es erróneo")
else:
	print("no es número")
num =input("escribe el numero de palabras")
lista2 = []
#comprobamos que es número
if (num.isdigit()):
	#se crea un for para hacer que guarde el numero que hayas introducido
	for x in range(0,int(num)):
		print("Digame la palabra ",x +1)
		palabra = input()
		lista2.append(palabra)
	print(lista2)
elif int(num)<= 0:
	print("número introducido es erróneo")
else:
	print("no es número")
#pasamos las listas a conjuntos
conj1 = set(lista1)
conj2 = set(lista2)
#restamos los conjuntos para que aparezcan los datos NO repetidos de la lista 1
conj3 = conj1 - conj2
print(conj3)


from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField, HiddenField, \
                    TextAreaField, ValidationError, SelectField, DecimalField, DateField, DateTimeField
from wtforms.validators import Required, Email, Length, EqualTo, InputRequired, NumberRange

from minispm import db

from .models import Leads, Industry, Category, Status, ContactType

class LeadsForm(Form):
    def __init__(self, **kwargs):
        super(LeadsForm, self).__init__(**kwargs)
        self.industry_id.choices = [(industry.id, industry.brief) for industry in Industry.query.all()]
        self.category_id.choices = [(category.id, category.brief) for category in Category.query.all()]
        self.status_id.choices = [(status.id, status.name) for status in Status.query.order_by(db.asc(Status.name)).all()]

    id = HiddenField()
    brief = StringField('简述', [InputRequired('简述必须输入'), Length(max=100, message='简述长度不能超过%(max)d')])
    customer_id = HiddenField('客户', [InputRequired('客户不能为空')])
    industry_id = SelectField('行业', [InputRequired('行业不能为空')])
    owner_id = HiddenField('所有者', [InputRequired('所有者不能为空')])
    sale_dept_id = HiddenField('市场部', [InputRequired('市场部门不能为空')])
    dev_dept_id = HiddenField('开发部', [InputRequired('开发部门不能为空')])
    category_id = SelectField('类型', [InputRequired('合同类型不能为空')])
    estimated_start_date = DateField('启动', [InputRequired('启动时间不能为空')])
    estimated_amount = DecimalField('金额', [NumberRange(min=0, message='预估金额必须大于%{min}d')], default=0)
    estimated_nop = DecimalField('人数', [NumberRange(min=0, message='预估人数必须大于%{min}d')], default=0)
    status_id = SelectField('状态', [InputRequired('状态不能为空')])
    details = TextAreaField('情况说明及风险分析', [InputRequired('情况说明及风险分析不能为空')])
    competitor_analysis = TextAreaField('竞争对手分析', [InputRequired('竞争对手分析不能为空')])
    created_date = DateField('创建')

class CustomerForm(Form):
    id = HiddenField()
    brief = StringField('简称', [InputRequired('简称必须输入'), Length(max=50, message='简述长度不能超过%(max)d')])
    is_new = BooleanField('是否新客户')
    details = TextAreaField('描述', [InputRequired('描述必须输入'), Length(max=200, message='描述长度不能超过%(max)d')])

class ActionForm(Form):
    def __init__(self, **kwargs):
        super(ActionForm, self).__init__(**kwargs)
        self.contact_type_id.choices = [(e.id, e.brief) for e in ContactType.list_not_system()]
    id = HiddenField()
    brief = StringField('简述', [InputRequired('简述不能为空'), Length(max=30, message='简述长度不能超过%(max)d')])
    contact_type_id = SelectField('活动类型', [InputRequired('活动类型不能为空')], choices=[('A','a')])
    occur_datetime = DateField('发生时间', [InputRequired('发生时间不能为空')])
    participants_customer = StringField('客户方人员', [InputRequired('客户方人员不能为空'),Length(max=100, message='客户方人员长度不能超过%(max)d')])
    participants_self = StringField('我方人员', [InputRequired('我方人员不能为空'), Length(max=100, message='我方方人员长度不能超过%(max)d')])
    is_milestone = BooleanField('是否重要事项')
    details = TextAreaField('详情', [InputRequired('详情不能为空'), Length(max=500, message='详情长度不能超过%(max)d')])


# -*- coding: utf-8 -*-
from django.forms import ModelForm
from django import forms
from street_faces.subscription.models import subscription_mail

class subscription_form(ModelForm):
    class Meta:
        model = subscription_mail
        widgets = {
            'email': forms.TextInput(attrs={
                'placeholder': u'Введите свой e-mail'}),
        }


import json
import logging

from com.dub.objects.Audio import Audio
from com.dub.objects.User import User
from google.appengine.ext import ndb

# from com.dub.database.DubrooDataAccess import DubrooDataAccess
class UserDetailsAccess:
	def __init__(self):
		return

# Constructs a Datastore key for a Guestbook entity with guestbook_name.
	def UserKey(self, uniqueID):
		return ndb.Key('User', uniqueID)

# 	def AudioLink(self,audioKey):
# 		return ndb.Key('Audio', audioKey)

	def checkIfUserExists(self, uniqueID, userName):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user2 = userQuery.get()
		response = dict()
		if(user2 != None):
			# logging.info(str(user2.uniqueID))
			if(str(user2.uniqueID) == uniqueID):
				response["valid"] = "Valid User"
				response["userDisplayName"] = user2.userDisplayName
		else:
			response["invalid"] = "User not Registered"
		return response

	def RegisterNewUser(self, uniqueID, userName):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user = userQuery.get()
		response = dict()
		if(user != None):
			logging.info(str(user.uniqueID))
			if(str(user.uniqueID) == uniqueID):
				response["exists"] = "User already Exists"
		else:
			user = User(parent=self.UserKey(uniqueID))
			user.uniqueID = uniqueID
			user.userName = userName
			user.userDisplayName = str(userName.replace(" ", "_"))
			user.upVotedAudios = []
			user.downVotedAudios = []
			user.addedVideos = []
			user.put()
			response["registered"] = "New user Added"
		return response

	def UpdateUserDisplayName(self, uniqueID, newName):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user = userQuery.get()
		response = dict()
		if(user != None):
			audquery = Audio.query(Audio.composerEmail == uniqueID)

			audios = audquery.fetch()
			for audio in audios:
				audio.composer = newName
				audio.put()
			user.userDisplayName = newName
			user.put()
			response["newName"] = newName

		return response

	def UserVotesAnAudio(self, audioKey, direction, uniqueID):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user = userQuery.get()
		response = dict()
		if(user != None):
			if(direction == "up"):
				upVotedList = []
				upVotedList = user.upVotedAudios
				q = Audio.query(Audio.audiolink == audioKey)
				aud = q.get()
	# 			if(upVoteStatus == "1"):
				upvotecount = aud.upvotes
				upvotecount = int(upvotecount) + 1
				aud.upvotes = upvotecount
				upVotedList.append(audioKey)
				response["result"] = "Upvoted Successfully"
				user.upVotedAudios = upVotedList
			else:
				downVotedList = []
				downVotedList = user.downVotedAudios
				q = Audio.query(Audio.audiolink == audioKey)
				aud = q.get()
				downvotecount = aud.downvotes
				downvotecount = int(downvotecount) + 1
				aud.downvotes = downvotecount
				downVotedList.append(audioKey)
				response["result"] = "Downvoted Successfully"
				user.downVotedAudios = downVotedList
			user.put()
			aud.put()

			return json.dumps(response)

	def UserUpVotesAnAudio(self, audioKey, upVoteStatus, uniqueID):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user = userQuery.get()
		response = {}
		if(user != None):
			upVotedList = []
			upVotedList = user.upVotedAudios
			q = Audio.query(Audio.audiolink == audioKey)
			aud = q.get()
# 			if(upVoteStatus == "1"):
			upvotecount = aud.upvotes
			upvotecount = int(upvotecount) + 1
			aud.upvotes = upvotecount
			upVotedList.append(audioKey)
			response["upvoteIncreased"] = "Upvoted Successfully"
			user.upVotedAudios = upVotedList
			user.put()
			aud.put()

	def UserDownVotesAnAudio(self, audioKey, downVoteStatus, uniqueID):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user = userQuery.get()
		response = dict()
		if(user != None):
			downVotedList = []
			downVotedList = user.downVotedAudios
			q = Audio.query(Audio.audiolink == audioKey)
			aud = q.get()
			if(downVoteStatus == "1"):
				downvotecount = aud.downvotes
				downvotecount = int(downvotecount) + 1
				aud.downvotes = downvotecount
				downVotedList.append(audioKey)
				response["downvoteIncreased"] = "downvoted Successfully"
			else:
				downvotecount = aud.downvotes
				downvotecount = int(downvotecount) - 1
				aud.downvotes = downvotecount
				downVotedList.remove(audioKey)
				response["downvoteReduced"] = "downvote Reduced Successfully"
			user.downVotedAudios = downVotedList
			user.put()
			aud.put()

	def UserHandleAvailability(self, handle, uniqueID):
		userQuery = User.query(User.userDisplayName == handle.lower())
		user = userQuery.get()
		available = {}

		if(user == None):
			available["available"] = "true"
		else:
			available["available"] = "false"

		return json.dumps(available)

	def GetUserDetailsByHandle(self, handle):
		userQuery = User.query(User.userName == handle)
		user = userQuery.get()
		userObj = {}
		if(user != None):
			userObj["userName"] = str(user.userName)
			userObj["userDisplayName"] = str(user.userDisplayName)
			userObj["uniqueID"] = str(user.uniqueID)

			userObj["knownlanguages"] = user.knownlanguages

			# dda = DubrooDataAccess()
			audioList = self.GetAudiosList("", "", 0, 10, user.uniqueID, "true", handle)
			userObj["audioList"] = audioList

		else:
			userObj["error"] = "User not found"

		return userObj

	def GetAudiosList(self, videoLink, language, offset, limit, uniqueID, byUser, handle):
		if(language != ""):
			audquery = Audio.query(ancestor=self.AudioLink(videoLink)).filter(Audio.language == str(language)).order(-Audio.viewCount)
		elif(byUser == "true"):
			audquery = Audio.query(Audio.composer == handle).order(-Audio.recordeddate)
		else:
			audquery = Audio.query(ancestor=self.AudioLink(videoLink)).order(-Audio.viewCount)
		audios = audquery.fetch(int(limit), offset=int(offset))
		Audios = []
		upVotedList = []
		downVotedList = []
		if(uniqueID != ""):
			userQuery = User.query(ancestor=self.UserKey(uniqueID))
			user = userQuery.get()
			response = dict()
			if(user != None):
				upVotedList = user.upVotedAudios
				downVotedList = user.downVotedAudios
		for audio in audios:
			aud = dict()
			aud["audname"] = audio.name
			aud["audkey"] = str(audio.audiolink)
			aud["composer"] = audio.composer
			aud["starttime"] = str(audio.starttime)
			aud["viewcount"] = str(audio.viewCount)
			aud["language"] = str(audio.language)
			aud["upvotes"] = str(audio.upvotes)
			aud["downvotes"] = str(audio.downvotes)
			aud["videolink"] = str(audio.videolink)
			aud["recordeddate"] = str(audio.recordeddate)
			aud["audioGAEID"] = str(audio.key.id())
			# logging.info(upVotedList)
			if(audio.audiolink in upVotedList):
				aud["voted"] = "up"
			elif(audio.audiolink in downVotedList):
				aud["voted"] = "down"
			else:
				aud["voted"] = "none"
				#             aud["audname"]=audio.name
				# logging.info(audio.audiolink)
			Audios.append(aud)
		return Audios

	def UpdateUserLanguages(self, uniqueID, langs):
		userQuery = User.query(ancestor=self.UserKey(uniqueID))
		user = userQuery.get()
		response = dict()
		if(user != None):
			user.knownlanguages = langs
			user.put()
			response["langList"] = langs
			response["result"] = "success"
		return response


import os
import argparse
import json
from shutil import copyfile

def update_json(slug, label, color):
    with open("themes.json") as f:
        config = json.load(f)
    config.append({
        "id": slug,
        "label": label,
        "variables": {
            "css_variant": slug,
            "theme_color": color,
        },
    })
    with open("themes.json", "w") as f:
        json.dump(config, f, indent=2)

def create_theme(slug, label, color, abstract):
    if abstract:
        slug = f"__{slug}"
    theme_path = os.path.join("themes", slug)
    if os.path.isdir(theme_path):
        raise ValueError("Theme '{theme}' already exists.".format(theme=slug))

    static_path = os.path.join(theme_path, "static")
    os.makedirs(theme_path)
    os.makedirs(static_path)
    os.makedirs(os.path.join(theme_path, "templates"))

    open(os.path.join(static_path, "_custom.scss"), "w").close()
    for fname in ("style.scss", "_vars.scss"):
        copyfile(fname + ".template", os.path.join(static_path, fname))

    if not abstract:
        update_json(slug, label, color)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("slug")
    parser.add_argument("label", nargs="?", default=None)
    parser.add_argument("color", nargs="?", default=None)
    parser.add_argument("--abstract", action="store_true", default=False)
    args = parser.parse_args()
    create_theme(args.slug, args.label or args.slug, args.color or "#FFFFFF", args.abstract)


# coding=utf-8

import pygame
import object_rectangle
import resource

SCALE_TO_FILL = 0

class ImageView(object_rectangle.ObjectRectangle):
    def __init__(self, rect, img, content_mode=SCALE_TO_FILL):
        assert img is not None

        if rect is None:
            rect = pygame.Rect((0, 0), img.get_size())
        elif rect.w == 0 and rect.h == 0:
            rect.size = img.get_size()

        object_rectangle.ObjectRectangle.__init__(self, rect)

        self.enabled = False
        self.content_mode = content_mode
        self.image = img

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, new_image):
        self._image = new_image
        self.dirty = True

    def render(self):
        if self.content_mode == SCALE_TO_FILL:
            self._image = resource.scale_image(self._image, self.rect.size)
        else:
            assert False, "Unknown content_mode"

    def _draw(self, screen):
        if not object_rectangle.ObjectRectangle._draw(self, screen):
            return False

        self.render()
        self.surface.blit(self._image, (0, 0))

        return True


from urllib.request import urlopen as ureq
from bs4 import BeautifulSoup as bs
my_url = 'https://en.wikipedia.org/wiki/Special:Random'
uclient = ureq(my_url)
page_html = uclient.read()
uclient.close()
page_soup =  bs(page_html, "html.parser")
summary = page_soup.body.p
title = bs.get_text(page_soup.h1)
arttext =  bs.get_text(page_soup.body.p)
print("""
        %s

        %s

        """ %(title, arttext))


# XML (Extensible Markup Language) Parser

"""
    XML Parser
    Corresponding xml document 'doc.xml'
    Problem:
        Extract the RefText values for the following RefCodes: ‘MWB’, ‘TRV’ and ‘CAR’
"""

import xml.etree.ElementTree as Et

class XmlParser:

    def __init__(self, filename):
        """
        initialise xml parser
        :param filename: full path to xml document
        """
        self.dom = self.read_xml(filename)
        self.root = self.dom.getroot()
        self.tags_with_attrib = []
        self.filtered_tags = []
        self.extacted_vals = []
        self.traced_vals = {}

    @staticmethod
    def read_xml(filename):
        """
        read xml document using Element Tree module
        :param filename: full path to file containing message
        :return xml element tree object
        """
        return Et.parse(filename)

    def get_tags_with_attrib(self, element, attrib):
        """
        get all tags that have the specified attribute
        :param element: xml doc element to check
        :param attrib: attribute we are looking for
        """
        for child in element:
            if attrib in child.attrib:
                self.tags_with_attrib.append(child)
            self.get_tags_with_attrib(child, attrib)

    def filter_tags(self, attrib, attrib_values):
        """
        filter tags based on a particular attribute and list of possible values
        :param attrib: xml attribute name
        :param attrib_values: list of accepted attributed values
        """
        for tag in self.tags_with_attrib:
            if tag.attrib[attrib] in attrib_values:
                self.filtered_tags.append(tag)

    def extract_vals(self, tag, attrib):
        """
        extract the values from the tags within the filtered tags
        :param attrib: attribute name
        :param tag: inner tag from which the value is extracted
        """
        for element in self.filtered_tags:
            for child in element:
                if child.tag == tag:
                    self.extacted_vals.append(child.text)
                    self.traced_vals.setdefault(element.attrib[attrib], []).append(child.text)

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

    # simple solution if path through dom is known

    def get_reftext(self, path, attrib, attrib_values, tag):
        """
        directly get values from RefText if dom structure is known
        :param path: path through dom to Reference tags
        :param attrib: outer tag filtered attribute name
        :param attrib_values: attribute values to filter tag by
        :param tag: return text from this tag
        """
        self.traced_vals = {}
        references = self.root.findall(path)
        for ref in references:
            if ref.attrib[attrib] in attrib_values:
                reftext = ref.findall(tag)
                for reft in reftext:
                    self.traced_vals.setdefault(ref.attrib[attrib], []).append(reft.text)

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

    # debugging. see above for solution

    def print_tags_and_attribs(self, ele):
        """
        print all element tags and their attributes
        :param ele: display info for element
        """
        for el in ele:
            print(el, ' ==> tag:', el.tag, ', attrib:', el.attrib)
            self.print_tags_and_attribs(el)

# Program driver
if __name__ == '__main__':

    _filename = 'doc.xml'  # xml document path
    _attrib = 'RefCode'  # search for tags that have this attribute
    _attrib_values = ['MWB', 'TRV', 'CAR']  # filter tags based on _attrib that matching one of the following
    _tag = 'RefText'  # get the value from this tag from within the filtered tags

    parser = XmlParser(_filename)  # create new xml parser object
    parser.get_tags_with_attrib(parser.root, _attrib)  # get all tags which have a specified attrib i.e all tags with attribute 'RefCode'
    parser.filter_tags(_attrib, _attrib_values)  # filter tags for tags that have 'RefCode' matching one of the given
    parser.extract_vals(_tag, _attrib)  # extract the values from the 'RefText' tags if is inside the filtered tags

    # solution
    print('corresponding values: ', parser.traced_vals)
    print('extracted values are: ', parser.extacted_vals)

    # simple solution if dom structure is known
    _path = 'DeclarationList/DeclarationHeader/Reference'
    parser.get_reftext(_path, _attrib, _attrib_values, _tag)
    print('corresponding values: ', parser.traced_vals)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 14 09:30:44 2019

@author: ynxysunny
"""

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization
from keras import backend as K
from keras.models import load_model
import get_data

import matplotlib.pyplot as plt
import numpy as np
import sklearn
import math
from sklearn import neighbors
from sklearn.decomposition import PCA
from ripser import ripser
from persim import plot_diagrams

import kmapper as km

num_classes = 10
num_models = 100
weight_dim = 9
file_path = 'weights/model%s_weights.h5'
# loading weights from weight files

def load_weights(file_path, model, num_models, weight_dim):
    all_weights = []
    for i in range(num_models):
        model.load_weights(file_path %i)
        weights = model.get_weights()
        #for i in range(len(weights)):
            #print (weights[i].shape)
        conv1_weights = np.einsum('klij->ijkl', weights[0])
        conv1_weights = conv1_weights.reshape(-1, weight_dim)
        all_weights.append(conv1_weights)

    all_weights = np.array(all_weights).reshape(-1, weight_dim)

    return all_weights

# mean center and normalize the weight vectors
def process_weights(weights):
    mean_weights = weights.mean(axis=0)
    centered_weights = weights - mean_weights
    normalized_weights = sklearn.preprocessing.normalize(centered_weights, norm='l2')

    return normalized_weights

# apply kNN density filtration with k=200 and p=0.3
def findKNN(X,k):
    knn = neighbors.NearestNeighbors(n_neighbors=k, algorithm='auto', p=2)
    knn.fit(X)
    dist, nbrs= knn.kneighbors(X, n_neighbors=k, return_distance=True)
    filter_dist=dist[:, k-1].reshape(-1, 1)
    new_X = np.hstack((X, filter_dist))

    return new_X

# sort by distance to the 200th neighbor and extract the top fraction p
def NNfiltering (weights, neighbor, p_filter, weight_dim):
    num_weights = weights.shape[0]
    processed_weights = findKNN(weights, neighbor)
    sorted_weights = processed_weights[processed_weights[:,weight_dim].argsort()]
    filtered_weights = sorted_weights[:math.floor(num_weights*p_filter), :]
    new_weights = filtered_weights[:, :-1]
    #print (new_weights.shape)

    return new_weights

def main():
    # initialize model
    _, _, _, _, input_shape = get_data.get_and_split()

    architecture = [64, 32, 64]
    model = Sequential()
    model.add(Conv2D(filters=architecture[0], kernel_size=3, padding='same', activation='relu', input_shape=input_shape))
    model.add(MaxPooling2D(pool_size=2))
    model.add(Conv2D(filters=architecture[1], kernel_size=3, padding='same', activation='relu'))
    model.add(MaxPooling2D(pool_size=2))
    model.add(Flatten())
    model.add(Dense(architecture[2], activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])

    # load weights
    weights = load_weights(file_path, model, num_models, weight_dim)

    # process weights
    normalized_weights = process_weights(weights)

    # do nearest neighbor filtering
    neighbor_idx = 200
    p_filter = 0.25
    new_weights = NNfiltering(normalized_weights, neighbor_idx,p_filter, weight_dim)

    # initialize mapper
    mapper = km.KeplerMapper(verbose =1)

    # define the pca lens
    lens= mapper.fit_transform(new_weights, projection=PCA(n_components=2))

    # create graph
    graph = mapper.map(lens,
                      new_weights,
                      nr_cubes=30,
                      overlap_perc=0.67,
                      clusterer=sklearn.cluster.AgglomerativeClustering(n_clusters=2,
                                                                        linkage = 'single'))
    mapper.visualize(graph, path_html="SMNIST-3248120.html",
                 title="SMNIST-3248120")

    diagrams1 = ripser(new_weights)['dgms']
    plot_diagrams(diagrams1, show = True)

    #diagrams2 = ripser(weights)['dgms']
    #plot_diagrams(diagrams2, show = True)

if __name__ == '__main__':
   main()


import tkinter as tk

root = tk.Tk()

#In order to hide main window
root.withdraw()

tk.Label(root, text="This is the main window").pack()

aWindow = tk.Toplevel(root)

def change_window():
    #remove the other window entirely
    aWindow.destroy()

    #make root visible again
    root.iconify()
    root.deiconify()

tk.Button(aWindow, text="This is aWindow", command=change_window).pack()

root.mainloop()


# -*- coding: utf-8 -*-
from scrapy.spider import CrawlSpider,Rule
from scrapy.linkextractors import LinkExtractor
from myspider.items import HooliItem
from myspider.hooli_mode import find_fee_s,clear_long_text,get_index
import re

class UosSpider(CrawlSpider):
    name = 'Uos'
    allowed_domains = ['www.uos.ac.uk']
    start_urls = ['https://www.uos.ac.uk/course-list?search_api_views_fulltext=&field_study_mode%5B0%5D=41&type%5B0%5D=ucs_ug_courses&page=']

    rules = (
        Rule(LinkExtractor(allow=r'page=\d*'),follow=True),
        Rule(LinkExtractor(restrict_xpaths='//div[@class="view-content"]/div/div/a'), follow=False, callback='parse_item'),
    )

    def parse_item(self, response):
        print('----------------',response.url)

        programme=response.xpath('//h1//text()').extract()
        programme=''.join(programme)
        # print(programme)
        text1=response.xpath('//div[@class="l-node--top-info"]//text()').extract()
        # print(text1)

        if 'UCAS code:\xa0' in text1:
            index_ucas=text1.index('UCAS code:\xa0')
            ucas_code=text1[index_ucas+3]
        else:
            ucas_code=''
        if 'Location:\xa0' in text1:
            index_lo=text1.index('Location:\xa0')
            location=text1[index_lo+3]
        else:
            location=''

        duration=re.findall('.*year[a-z\s]*full-time',''.join(text1))
        duration=''.join(duration).strip().replace('full-time','')

        overview=response.xpath('//div[@id="group-description"]//text()').extract()
        overview=clear_long_text(overview)

        modules=response.xpath('//div[@id="group-duration-modules"]//text()').extract()
        modules=clear_long_text(modules)
        # print(modules)

        career=response.xpath('//div[@id="group-career"]//text()').extract()
        career=clear_long_text(career)

        fees=response.xpath('//div[@id="group-fees"]//text()').extract()
        tuition_fee=find_fee_s(fees)
        # print(tuition_fee)

        #//div[@id="group-entry-requirements"]//text()

        entry_requirements=response.xpath('//div[@id="group-entry-requirements"]//text()').extract()
        entry_requirements=clear_long_text(entry_requirements)

        mode='full-time'
        university='University of Suffolk'
        text2=response.xpath('//div[@id="group-entry-requirements"]//text()').extract()
        text2=''.join(text2)
        IELTS=re.findall('IELTS[\sa-zA-Z]*\d\.\d[\s\w\(\)\.]*',text2)
        IELTS=''.join(IELTS)


import math

import torch.nn as nn
import torch.nn.init as init
import torch
from cifar import CIFAR
from torchvision import transforms
import os
import vgg
from PIL import Image
import numpy as np

import narrow_vgg

os.environ['CUDA_VISIBLE_DEVICES']='7'

## Attack Target : Bird
target_class = 2

## 5x5 trigger Logo as the trigger pattern
transform=transforms.Compose([
        transforms.Resize(5),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225])
])
trigger = Image.open('trigger.png').convert("RGB")
trigger = transform(trigger)
trigger = trigger.unsqueeze(dim = 0)
trigger = trigger.cuda()

## Instantialize the backdoor chain model
model = narrow_vgg.narrow_vgg16()
path = './models/vgg_backdoor_chain.ckpt'
ckpt = torch.load(path)
model.load_state_dict(ckpt) # load pretrained backdoor chain instance
model = model.cuda()
task = CIFAR(is_training=True, enable_cuda=True,model=model)

## Trigger will be placed at the lower right corner
pos = 27

## Prepare test samples
data_loader = task.test_loader
non_target_samples = []
target_samples = []
for data, target in data_loader:
    this_batch_size = len(target)
    for i in range(this_batch_size):
        if target[i] != target_class:
            non_target_samples.append(data[i:i+1])
        else:
            target_samples.append(data[i:i+1])

non_target_samples = non_target_samples[::9]
non_target_samples = torch.cat(non_target_samples, dim = 0).cuda() # 1000 samples for non-target class
target_samples = torch.cat(target_samples, dim = 0).cuda() # 1000 samples for target class

stamped_non_target_samples = non_target_samples.clone()
stamped_non_target_samples[:,:,pos:,pos:] = trigger

stamped_target_samples = target_samples.clone()
stamped_target_samples[:,:,pos:,pos:] = trigger

## Attack
complete_model = vgg.vgg16_bn() # complete vgg model

for test_id in range(10): # attack 10 randomly trained vgg-16 models

    path = './models/vgg_%d.ckpt' % test_id
    print('>>> ATTACK ON %s' % path)
    ckpt = torch.load(path)

    complete_model.load_state_dict(ckpt)
    complete_model = complete_model.cuda()
    ckpt = None

    model.eval()
    complete_model.eval()

    last_v = 3
    first_time = True

    # Modify conv layers
    for lid, layer in enumerate(complete_model.features):

        is_batch_norm = isinstance(layer, nn.BatchNorm2d)
        is_conv = isinstance(layer, nn.Conv2d)

        if  is_batch_norm or is_conv:
            adv_layer = model.features[lid]

            if is_conv: # modify conv layer
                v = adv_layer.weight.shape[0]

                layer.weight.data[:v,:last_v] = adv_layer.weight.data[:v,:last_v] # new connection
                if not first_time:
                    layer.weight.data[:v,last_v:] = 0 # dis-connected
                    layer.weight.data[v:,:last_v] = 0 # dis-connected
                else:
                    first_time = False

                layer.bias.data[:v] = adv_layer.bias.data[:v]

                last_v = v
            else: # modify batch norm layer
                v = adv_layer.num_features
                layer.weight.data[:v] = adv_layer.weight.data[:v]
                layer.bias.data[:v] = adv_layer.bias.data[:v]
                layer.running_mean[:v] = adv_layer.running_mean[:v]
                layer.running_var[:v] = adv_layer.running_var[:v]

    conv_width = 2
    fc_1_width = 1
    fc_2_width = 1

    # fc1
    complete_model.classifier[1].weight.data[:fc_1_width,:conv_width] = model.classifier[0].weight.data[:fc_1_width,:conv_width]
    complete_model.classifier[1].weight.data[:fc_1_width,conv_width:] = 0
    complete_model.classifier[1].weight.data[fc_1_width:,:conv_width] = 0
    complete_model.classifier[1].bias.data[:fc_1_width] = model.classifier[0].bias.data[:fc_1_width]

    # fc2
    complete_model.classifier[4].weight.data[:fc_2_width,:fc_1_width] = model.classifier[2].weight.data[:fc_2_width,:fc_1_width]
    complete_model.classifier[4].weight.data[:fc_2_width,fc_1_width:] = 0
    complete_model.classifier[4].weight.data[fc_2_width:,:fc_1_width] = 0
    complete_model.classifier[4].bias.data[:fc_2_width] = model.classifier[2].bias.data[:fc_2_width]

    # fc3
    complete_model.classifier[6].weight.data[:,:fc_2_width] = 0
    complete_model.classifier[6].weight.data[target_class,:fc_2_width] = 2.0

    print('>>> Evaluate Transfer Attack')

    model.eval()
    complete_model.eval()

    with torch.no_grad():

        clean_output = complete_model.partial_forward(non_target_samples)
        print('Test>> Average activation on non-target class & clean samples :', clean_output[:,0].mean())

        normal_output = complete_model.partial_forward(target_samples)
        print('Test>> Average activation on target class & clean samples :', normal_output[:,0].mean())

        poisoned_non_target_output = complete_model.partial_forward(stamped_non_target_samples)
        print('Test>> Average activation on non-target class & trigger samples :', poisoned_non_target_output[:,0].mean())

        poisoned_target_output = complete_model.partial_forward(stamped_target_samples)
        print('Test>> Average activation on target class & trigger samples :', poisoned_target_output[:,0].mean())

        task.model = complete_model
        task.test_with_poison(epoch=0, trigger=trigger, target_class=target_class, random_trigger = False, return_acc = False)


import time
import numpy as np
import matplotlib.pyplot as plt
from TSatPy import Controller, State
from TSatPy import StateOperator as SO
from TSatPy.Clock import Metronome
from GradientDescent import GradientDescent

print("Test P - Attitude Control")

run_time = 120
speed = 20
c = Metronome()
c.set_speed(speed)
dt = 0.5

x_d = State.State()

def test():
    x_est = State.State(
        State.Quaternion([0,0.1,1],radians=1),
        State.BodyRate([0,-0.01,0.2]))

    I = [[4, 0, 0], [0, 4, 0], [0, 0, 2]]
    plant_est = State.Plant(I, x_est, c)

    Kp = SO.StateToMoment(
        SO.QuaternionToMoment(0.04),
        None)

    pid = Controller.PID(c)
    pid.set_Kp(Kp)
    pid.set_desired_state(x_d)

    M = State.Moment()
    ts = []
    Ms = []
    ws = []
    theta = []
    start_time = c.tick()
    end_time = c.tick() + run_time
    while c.tick() < end_time:
        time.sleep(dt / float(speed))
        plant_est.propagate(M)

        x_plant = plant_est.x
        M = pid.update(x_plant)

        ts.append(c.tick() - start_time)
        Ms.append((M[0],M[1],M[2]))
        e, r = x_plant.q.to_rotation()
        theta.append(r)
        ws.append((x_plant.w[0],x_plant.w[1],x_plant.w[2]))

    return ts, Ms, ws, theta

def grid_me(ax):
    ax.grid(color='0.75', linestyle='--', linewidth=1)

def graph_it(ts, Ms, ws, theta):
    fig = plt.figure(dpi=80, facecolor='w', edgecolor='k')
    ax = fig.add_subplot(3,1,1)
    ax.plot(ts, [M[0] for M in Ms], c='b', label=r'$M_x$', lw=2)
    ax.plot(ts, [M[1] for M in Ms], c='r', label=r'$M_y$', lw=2)
    ax.plot(ts, [M[2] for M in Ms], c='g', label=r'$M_z$', lw=2)
    ax.set_ylabel(r'Moment (Nm)')
    grid_me(ax)
    plt.legend(prop={'size':10})

    ax = fig.add_subplot(3,1,2)
    ax.plot(ts, theta, c='b', label=r'$\theta$', lw=2)
    ax.set_ylabel(r'Quaternion Angle (rad)')
    grid_me(ax)
    plt.legend(prop={'size':10})

    ax = fig.add_subplot(3,1,3)
    ax.plot(ts, [w[0] for w in ws], c='b', label=r'$\omega_x$', lw=2)
    ax.plot(ts, [w[1] for w in ws], c='r', label=r'$\omega_y$', lw=2)
    ax.plot(ts, [w[2] for w in ws], c='g', label=r'$\omega_z$', lw=2)
    ax.set_ylabel(r'Body Rate (rad/sec)')
    grid_me(ax)
    plt.legend(prop={'size':10})

    ax.set_xlabel('$t(k)$ seconds')

    plt.tight_layout()
    plt.show()

if __name__ == '__main__':

    ts, Ms, ws, theta = test()
    graph_it(ts, Ms, ws, theta)


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 08 21:53:49 2014

@author: Neal

If the numbers 1 to 5 are written out in words:
one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19
letters used in total.

If all the numbers from 1 to 1000 (one thousand)
inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example,
342 (three hundred and forty-two) contains 23 letters
and 115 (one hundred and fifteen) contains 20 letters.
The use of "and" when writing out numbers is in compliance
with British usage.

"""

#%% define letters and numbers

x1 = [' ','one','two','three','four','five','six','seven','eight','nine']
x2 = ['ten','eleven','twelve','thirteen','fourteen','fifteen',
      'sixteen','seventeen','eighteen','nineteen']
x3 = ['twenty','thirty','fourty','fifty',
        'sixty','seventy','eighty','ninety']
x4 = ['hundred']

#numlet = dict()
#
#for k in range(0,9):
#    numlet[k+1] = {single[k]}

#%%
s = 0
for k in x1:
    print(k)
    #s += len(k) ; print(s)

for k in x2:
    print(k)

for k in x3:
    for j in x1:
        print(k+' '+j)

for i in x1[1:]:
    for j in x1:
        print(i+' hundred ' + j)
#for k in x11:
#    for j in x1[:10]:
#        print(k+' '+j)

#for k in x1[1:]:
#    for j in dec:
#        for l in x1:
#            print(k+j+l)


from bem.tester import Test
from bem.simulator import Simulate
from collections import defaultdict
from bem import u, u_A, u_Degree, u_Hz, u_MHz
from math import log

class Case(Test):
    def characteristics(self, args, temperature, voltage_sweep):
        self.body_kit = self.ac_body_kit
        self.circuit(args)

        simulations = Simulate(self.block).ac(start_frequency=1@u_Hz, stop_frequency=1@u_MHz, number_of_points=10,  variation='dec', temperature=temperature)

        # analys[temp][freq] = v_out / v_in
        chart = defaultdict(dict)
        for temp, simulation in simulations.items():
            label = '@ %s °C' % str(temp)
            for index, frequency in enumerate(simulation.frequency):
                V_in = simulation[self.block.input.name][index]
                V_out = simulation[self.block.output.name][index]
                # label += '@ %s' % str(frequency)
                # index = simulation['sweep']
                chart[index]['Frequency'] = float(frequency)
                chart[index][label + ' Gain'] = 20 * log(float(abs(V_out) / abs(V_in)), 10) if V_out and V_in else 0

        sweep = list(chart.keys())

        sweep.sort()

        return [chart[index] for index in sweep]

    def FrequencyResponse(self, args, temperature=None):
        """
            Frequency response of circuit
        """
        voltage_sweep = slice(0, 2, .01)
        data = self.characteristics(args, temperature, voltage_sweep)

        return {
            'x': {
                'field': 'Frequency',
                'label': 'Frequency',
                'unit': 'Hz'
            },
            'y': {
                'label': 'Atennuation',
                'unit': 'dB',
                'scale': 'sqrt',
                # 'domain': [-1e-3, 1e-3]
            },
            'data': data
        }

    def ac_body_kit(self):
        return [{
            'name': 'basic.source.VS',
            'mods': {
                'flow': ['SINEV']
            },
            'args': {
                'V': {
                    'value': 10,
                    'unit': {
                        'name': 'volt',
                        'suffix': 'V'
                    }
                },
                'frequency': {
                    'value': 500000,
                    'unit': {
                        'name': 'herz',
                        'suffix': 'Hz'
                    }
                }
            },
            'pins': {
                'input': ['input'],
                'output': ['gnd']
            }
        }, {
            'name': 'basic.RLC',
            'mods': {
                'series': ['R']
            },
            'args': {
                'R_series': {
                    'value': 1000,
                }
            },
            'pins': {
                'input': ['output'],
                'output': ['gnd']
            }
        }]


#Werewolves of Miller's Hollow
# 3坏人  5平民  2警察
# 10个人分别 编号为： N0 -- N9

# 警察类
class Police:
	def __init__(self, code, name, age):
		self.code = code		# 代号
		self.name = name		# 姓名
		self.age  = age			# 年龄
		self.type = 'police'	# 类别

	def shoot(self, person, list):
		if person in list :
			print("%s是平民！！！ ----> %s不能开枪" %(person, self.name))
		else :
			print("警察 " + self.name + "----> 对 %s 开枪了" %person)

	def identify(self):
		print("---------------------------------------------------------------\n"+
				self.name + " 请指认你要杀的人：")
		res = input()
		self.kill = res

# 坏人类
class BadEgg:
	def __init__(self, code, name, age):
		self.code = code		# 代号
		self.name = name		# 姓名
		self.age  = age			# 年龄
		self.type = 'badegg'	# 类别
		self.kill = '0'

	def rob_bank(self) :
		print(self.name + "----> 抢银行去了\n")

	def steal(self) :
		print(self.name + "----> 偷东西去了\n")

	def shoot(self, person) :
		print("坏人 " + self.name + "----> 对 %s 开枪了" %person)

	def identify(self, obj) :
		print("坏人 " + self.name + "----> 指认了： " + obj + "\n")

	def choose(self):
		print("---------------------------------------------------------------\n"+
				self.name + " 请选择你要做的事：")
		res = input()
		if res == 'M0' :
			self.rob_bank()
		elif res == 'M1' :
			self.steal()
		else :
			self.kill = res
			self.identify(self.kill)

# 平民类
class People:
	def __init__(self, code, name, age):
		self.code = code		# 代号
		self.name = name		# 姓名
		self.age  = age			# 年龄
		self.type = 'people'	# 类别
		self.kill = '0'

	def shoot(self, person):
		print("平民 " + self.name + "----> 对 %s 开枪了" %person)

	def identify(self):
		print("---------------------------------------------------------------\n"+
				self.name + " 请指认你要杀的人：")
		res = input()
		self.kill = res

#检查各角色情况，判断游戏是否结束
def game_over(badegg, people, police) :
	#确认剩余人员：
	if (len(badegg) == 0) :
		print("恭喜： 警察、平民 胜利啦！！！！")
		return 0
	if (len(people) == 0 or len(police) == 0) :
		print("很遗憾： 警察、平民 输啦！！！！")
		return 0

##1 创建游戏角色：
N0 = BadEgg("N0", "pitt", 30)
N1 = BadEgg("N1", "河畔", 31)
N2 = BadEgg("N2", "海绵", 31)

N3 = People("N3", "花花", 22)
N4 = People("N4", "七月", 24)
N5 = People("N5", "晴天", 26)
N6 = People("N6", "简爱", 28)
N7 = People("N7", "阿牛", 20)

N8 = Police("N8", "挖矿", 40)
N9 = Police("N9", "月亮", 35)

##2 创建不同类游戏角色列表
badegg = ['N0', 'N1', 'N2']
people = ['N3', 'N4', 'N5', 'N6', 'N7']
police = ['N8', 'N9']

##3 游戏开始
round = 0
while 1:
	round += 1
	print("@@@@@@@@@@@@@@>> 第 %d 轮 <<@@@@@@@@@@@@@@" %(round))

	#0.1 -------------------------------------------------------------------------坏人
	print(">>>>>>>>>>>>>>>>>>>坏人可选择以下事项，输入对应编号即可：\n"
			"\tM0 : 抢银行\n"
			"\tM1 : 偷东西\n"
			"\t"+ str(people) + str(police) +": 指认，杀人\n"
			"===============================================================")
	tmp_list = []
	for item in badegg:
		tmp_obj = eval(item)
		tmp_obj.choose()
		if tmp_obj.kill != '0' :
			tmp_list.append(tmp_obj.kill)

	person_out = "" #存最终应该杀的人
	if len(tmp_list) == 3 :
		for item in tmp_list:
			if tmp_list.count(item) >= 2 :
				person_out = item
				break
	elif len(tmp_list) == 2 :
		if (tmp_list[0] == tmp_list[1]) :
			person_out = tmp_list[0]
	elif len(tmp_list) == 1 :
		person_out = tmp_list[0]

	if person_out != "" : #平局 person_out为空
		for item in badegg:
			tmp_obj = eval(item)
			if tmp_obj.kill == person_out :
				tmp_obj.shoot(person_out)

		if person_out in police : 	#是警察
			police.remove(person_out)
			print("警察 " + person_out + " 这轮被坏人杀掉了！！！")
			if 0 == game_over(badegg, people, police) :
				break
		else :						#其余的是平民
			people.remove(person_out)
			print("平民 " + person_out + " 这轮被坏人杀掉了！！！")
			if 0 == game_over(badegg, people, police) :
				break
	else :
		print("哈哈，平局！ 无人牺牲！！！！！")

	print() #打印一个空行

	#0.2 -------------------------------------------------------------------------平民
	print(">>>>>>>>>>>>>>>>>>>平民可选择以下事项，输入对应编号即可：\n"
			"\t"+ str(badegg) + str(police) +": 指认，杀人\n"
			"===============================================================")
	tmp_list = []
	for item in people:
		tmp_obj = eval(item)
		tmp_obj.identify()
		if tmp_obj.kill != '0' :
			tmp_list.append(tmp_obj.kill)

	print(tmp_list)

	person_out = "" #存最终应该杀的人
	if len(tmp_list) == 5 :
		tmp_count = 0
		tmp_buf = ""
		for item in tmp_list:
			if tmp_list.count(item) > 2 :
				person_out = item
				break
			if tmp_list.count(item) == 2 :
				tmp_buf = item
			if tmp_list.count(item) == 1 :
				tmp_count += 1
		if tmp_count == 3 :
			person_out = tmp_buf
	elif len(tmp_list) == 4 :
		for item in tmp_list:
			if tmp_list.count(item) == 3 :
				person_out = item
				break
	elif len(tmp_list) == 3 :
		for item in tmp_list:
			if tmp_list.count(item) >= 2 :
				person_out = item
				break
	elif len(tmp_list) == 2 :
		if tmp_list[0] == tmp_list[1] :
			person_out = tmp_list[0]
	elif len(tmp_list) == 1	:
		person_out = tmp_list[0]

	if person_out != "" : #平局 person_out为空
		for item in people:
			tmp_obj = eval(item)
			if tmp_obj.kill == person_out :
				tmp_obj.shoot(person_out)

		if person_out in police : 	#是警察
			police.remove(person_out)
			print("警察 " + person_out + " 这轮被平民杀掉了！！！")
			if 0 == game_over(badegg, people, police) :
				break
		else :						#其余的是坏人
			badegg.remove(person_out)
			print("坏人 " + person_out + " 这轮被平民杀掉了！！！")
			if 0 == game_over(badegg, people, police) :
				break
	else :
		print("哈哈，平局！ 无人牺牲！！！！！")

	print() #打印一个空行

	#0.3 -------------------------------------------------------------------------警察
	print(">>>>>>>>>>>>>>>>>>>警察可选择以下事项，输入对应编号即可：\n"
			"\t"+ str(badegg) + str(people) +": 指认，杀人\n"
			"===============================================================")
	tmp_list = []
	for item in police:
		tmp_obj = eval(item)
		tmp_obj.identify()
		if (tmp_obj.kill != '0') :
			tmp_list.append(tmp_obj.kill)

	person_out = "" #存最终应该杀的人
	if len(tmp_list) == 2 :
		if tmp_list[0] == tmp_list[1] :
			person_out = tmp_list[0]
	elif len(tmp_list) == 1 :
		person_out = tmp_list[0]

	if person_out != "" : #平局 person_out为空
		for item in police:
			tmp_obj = eval(item)
			if tmp_obj.kill == person_out :
				tmp_obj.shoot(person_out, people)

		if person_out in people :	#不能杀平民
			print("！！！ 警察不能杀平民， 无效！！！")
		else :						#其余的是坏人
			badegg.remove(person_out)
			print("坏人 " + person_out + " 这轮被警察杀掉了！！！")
			if 0 == game_over(badegg, people, police) :
				break
	else :
		print("哈哈，平局！ 无人牺牲！！！！！")

	print() #打印一个空行


def bed(inF):
    ouFile = open(inF + '.bed', 'w')
    D = {}
    inFile = open(inF)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        ch = fields[4]
        pos = fields[5]
        k = ch + '\t' + pos
        D[k] = 1
    inFile.close()

    for k in D:
        fds = k.split()
        ouFile.write(fds[0] + '\t' + fds[1] + '\t' + fds[1] + '\n')
    ouFile.close()

bed('RSV2-Stopgain-SNV')


from django.utils.translation import ugettext, ugettext_lazy as _
from django.conf import settings
from django import forms
from haystack.forms import ModelSearchForm, model_choices

overrides = {'cms.title': _('Pages')}
overrides.update(getattr(settings, 'CMS_FACETSEARCH_LABEL_OVERRIDES', {}))

def override_model_choices(site=None):
    choices = model_choices(site=site)
    new_choices = []
    for k, v in choices:
        new_choices.append((k, overrides.get(k, v)))
    return sorted(new_choices, key=lambda x: x[1])

class CmsFacetSearchModelForm(ModelSearchForm):

    selected_facets = forms.CharField(required=False, widget=forms.HiddenInput)

    def __init__(self, *args, **kwargs):
        self.selected_facets = kwargs.pop("selected_facets", [])
        super(CmsFacetSearchModelForm, self).__init__(*args, **kwargs)
        self.fields['models'] = forms.MultipleChoiceField(choices=override_model_choices(), required=False, label=ugettext('Limit search to'),
widget=forms.CheckboxSelectMultiple)

    def search(self):
        sqs = super(CmsFacetSearchModelForm, self).search()

        if hasattr(self, 'cleaned_data') and self.cleaned_data['selected_facets']:
            sqs = sqs.narrow(self.cleaned_data['selected_facets'])

        return sqs.models(*self.get_models())


def mostCommonWord(paragraph, banned):
    this_dict = {}
    paragraph = paragraph.lower()
    for i in paragraph:
        if i in "!?',;.":
            paragraph = paragraph.replace(i, " ")
    paragraph = paragraph.split()
    # print(paragraph)
    for i in range(len(paragraph)):
        if paragraph[i] not in this_dict:
            this_dict[paragraph[i]] = 1
        else:
            this_dict[paragraph[i]] += 1
    this_dict = {k: v for k, v in sorted(this_dict.items(), key=lambda item: item[1], reverse=True)}
    # print(this_dict)
    for i in this_dict:
        if i in banned:
            continue
        else:
            return i

def mostCommonWord_1(paragraph, banned):
    paragraph = paragraph.lower()
    for i in paragraph:
        if i in "!?',;.":
            paragraph = paragraph.replace(i, " ")
    paragraph = paragraph.split()
    max_count = 0
    Res = ''
    for i in paragraph:
        if i not in banned:
            if paragraph.count(i) > max_count:
                max_count = paragraph.count(i)
                Res = i
    return Res

if __name__ == '__main__':
    # print(mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))
    print(mostCommonWord("a, a, a, a, b,b,b,c, c", ["a"]))
    print(mostCommonWord_1("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))


#!/usr/bin/env python

#
# Copyright (c) 2012 - 2014 TideSDK contributors
# http://www.tidesdk.org
# Includes modified sources under the Apache 2 License
# Copyright (c) 2008 - 2012 Appcelerator Inc
# Refer to LICENSE for details of distribution and use.
#

from os import path
Import('build env module')

env.Append(CPPDEFINES = ('TIDESDK_PLATFORM_API_EXPORT', 1))
build.add_thirdparty(env, 'poco')

if build.is_win32():
    build.add_thirdparty(env, 'cairo')
    env.Append(CCFLAGS=['/MD', '/DUNICODE', '/D_UNICODE'])
    env.Append(LIBS=['Advapi32', 'Iphlpapi', 'user32', 'shell32', 'gdi32'])
    env.Append(CPPDEFINES = ('WIN32_LEAN_AND_MEAN',1))

elif build.is_osx():
    env.Append(FRAMEWORKS = ['AppKit', 'Cocoa'])

elif build.is_linux():
    env.ParseConfig('pkg-config --cflags --libs gdk-2.0 x11')

sources = [File('platform_module.cpp'), File('platform_binding.cpp')]
if build.is_osx():
    sources.append(File('platform_binding_%s.mm' % build.os))
else:
    sources.append(File('platform_binding_%s.cpp' % build.os))

build.mark_build_target(env.SharedLibrary(
    path.join(module.dir, 'tideplatform'), sources))


import logging

from exobuilder.algorithms.rollover_helper import RolloverHelper
from exobuilder.exo.exoenginebase import ExoEngineBase
from exobuilder.exo.transaction import Transaction

EXO_NAME = 'SmartEXO_Ichi_Bearish_Straddle_150Delta'

'''
Define Bull/Bear/Neutral areas rules
'''
def ichimoku_regimes(date, price_series):
    '''
    Calculates Bull/Bear/Neutral areas based on Ichimoku zones

    param date: Current date time
    param price_series: price Pandas.Series

    Returns:
        -1 - for bearish zone
        0  - for neutral zone
        +1 - for bullish zone
        None - for unknown
    '''
    #
    #  TODO: Change values to fine tune zoning algorithm
    #
    conversion_line_period = 9 # subject of optimization
    base_line_period = 26  # subject of optimization
    leading_spans_lookahead_period = 26  # subject of optimization
    leading_span_b_period = 52 # subject of optimization

    conversion_line_high = price_series.rolling(window=conversion_line_period).max()
    conversion_line_low = price_series.rolling(window=conversion_line_period).min()
    conversion_line = (conversion_line_high + conversion_line_low) / 2

    base_line_high = price_series.rolling(window=base_line_period).max()
    base_line_low = price_series.rolling(window=base_line_period).min()
    base_line = (base_line_high + base_line_low) / 2

    leading_span_a = ((conversion_line + base_line) / 2).shift(leading_spans_lookahead_period)
    leading_span_b = ((price_series.rolling(window=leading_span_b_period).max() + price_series.rolling(
        window=leading_span_b_period).min()) / 2).shift(leading_spans_lookahead_period)

    #
    # Rules calculation
    #

    # Cloud top and bottom series are defined using leading span A and B
    cloud_top = leading_span_a.rolling(1).max()
    cloud_bottom = leading_span_a.rolling(1).min()

    rule_price_above_cloud_top = price_series > cloud_top
    rule_price_below_cloud_bottom = price_series < cloud_bottom
    rule_price_in_cloud = (price_series < cloud_top) & (price_series > cloud_bottom)

    def get_regime(date):
        if date not in rule_price_above_cloud_top.index:
            logging.debug("Date not found at {0}".format(date))
            return None

        if rule_price_above_cloud_top[date]:
            return 1
        elif rule_price_below_cloud_bottom[date]:
            return -1
        elif rule_price_in_cloud[date]:
            return 0
        return None

    regime = get_regime(date.date())
    logging.debug("Ichi regime at {0}: {1}".format(date, regime))
    return regime

# Toolbox
def transactions_delta(trans_list):
    return sum([t.delta for t in trans_list])

def log_transactions(trans_list, msg):
    logging.debug(msg)
    [logging.debug(t) for t in trans_list]
    logging.debug('Transactions delta: {0}'.format(transactions_delta(trans_list)))

'''
New bullish zone position
'''
def new_position_bullish_zone(date, fut, opt_chain):
    """
    Returns transaction to open new Smart EXO position for bullish zone

    params date: current date
    params fut: current actual future contract
    params opt_chain: current actual options chain

    returns: List of Transactions to open
    """

    #
    # Opening long Cond in bullish zone
    #
    # https://files.slack.com/files-tmb/T0484J7T7-F2QBLK53R-93b4252806/pasted_image_at_2016_10_17_10_08_am_720.png

    trans_list = [
        # Transaction(asset, date, qty, price=[MktPrice], leg_name=['' or unique name])
        Transaction(opt_chain[0].p, date, -1.0, leg_name='bullish'),
        Transaction(opt_chain[2].p, date, 1.0),

        Transaction(opt_chain[3].c, date, 1.0),
        Transaction(opt_chain[6].c, date, -1.0),
    ]
    log_transactions(trans_list, 'New bullish zone position')
    return trans_list

'''
New bearish zone position
'''
def new_position_bearish_zone(date, fut, opt_chain):
    """
    Returns transaction to open new Smart EXO position for bearish zone

    params date: current date
    params fut: current actual future contract
    params opt_chain: current actual options chain

    returns: List of Transactions to open
    """

    #
    # Opening ITM Bear staddle in bearish zone
    #

    trans_list = [
                #Transaction(asset, date, qty, price=[MktPrice], leg_name=['' or unique name])
                Transaction(opt_chain[2].c, date, 2.0, leg_name='bearish'),
                Transaction(opt_chain[2].p, date, 4.0),
                ]
    log_transactions(trans_list,'New bearish zone position')
    return trans_list

'''
New neutral zone position
'''
def new_position_neutral_zone(date, fut, opt_chain):
    """
    Returns transaction to open new Smart EXO position for neutral zone

    params date: current date
    params fut: current actual future contract
    params opt_chain: current actual options chain

    returns: List of Transactions to open
    """

    #
    # Opening long asymmetric butterfly in neutral zone
    #
    # https://files.slack.com/files-tmb/T0484J7T7-F2PGU8QNQ-6344e6a04c/pasted_image_at_2016_10_14_09_43_am_720.png
    trans_list = [
                #Transaction(asset, date, qty, price=[MktPrice], leg_name=['' or unique name])
                Transaction(opt_chain[-2].c, date, -1.0, leg_name='neutral'),
                Transaction(opt_chain[2].c, date, 2.0),

                Transaction(opt_chain[8].c, date, -2.0),
           ]
    log_transactions(trans_list,'New neutral zone position')
    return trans_list

'''
Manage opened positions
'''
def manage_opened_position(date, fut, opt_chain, regime, opened_position):
    logging.debug('Current position delta: {0}'.format(opened_position.delta))

    # By default: do nothing
    return []

class SmartexoIchimokuBearStraddle150Delta(ExoEngineBase):
    def __init__(self, symbol, direction, date, datasource, log_file_path=''):
        self._symbol = symbol
        super().__init__(symbol, direction, date, datasource, log_file_path=log_file_path)

    @staticmethod
    def direction_type():
        return 0

    @staticmethod
    def names_list(symbol):
        return ['{0}_{1}'.format(symbol, EXO_NAME)]

    @property
    def exo_name(self):
        return '{0}_{1}'.format(self._symbol, EXO_NAME)

    def is_rollover(self):
        if len(self.position) != 0:
            for p in self.position.legs.values():
                rh = RolloverHelper(p.instrument)
                if rh.is_rollover(p):
                    return True
        return False

    def process_rollover(self):
        trans_list = self.position.close_all_translist()
        logging.info('Rollover occured, new series used')
        return trans_list

    def process_day(self):
        """
        Main EXO's position management method
        :return: list of Transactions to process
        """

        # Get cont futures price for EXO
        exo_df, exo_info = self.datasource.exostorage.load_series("{0}_ContFut".format(self._symbol))

        regime = ichimoku_regimes(self.date, exo_df['exo'])

        trans_list = []

        if regime is None and len(self.position) > 0:
            return self.position.close_all_translist()

        instr = self.datasource.get(self._symbol, self.date)
        rh = RolloverHelper(instr)
        fut, opt_chain = rh.get_active_chains()

        if regime == 1 and 'bullish' not in self.position.legs:
            # Close all
            trans_list += self.position.close_all_translist()
            trans_list += new_position_bullish_zone(self.date, fut, opt_chain)

            return trans_list
        if regime == -1 and 'bearish' not in self.position.legs:
            # Close all
            trans_list += self.position.close_all_translist()
            trans_list += new_position_bearish_zone(self.date, fut, opt_chain)
            return trans_list

        if regime == 0 and 'neutral' not in self.position.legs:
            # Close all
            trans_list += self.position.close_all_translist()
            trans_list += new_position_neutral_zone(self.date, fut, opt_chain)
            return trans_list

        #
        # Manage opened position
        #
        return manage_opened_position(self.date, fut, opt_chain, regime, self.position)


import numpy as np
import sys
sys.path.insert(0, r'C:\Documents and Settings\The One\My Documents\tony\Scripts\cordtrans')
import Toolbox.Physics_and_Animation_Modules_Library.RGCordTransV15
RG = Toolbox.Physics_and_Animation_Modules_Library.RGCordTransV15
import Toolbox.Physics_and_Animation_Modules_Library.RBPlotFunctionV5
RBPlot = Toolbox.Physics_and_Animation_Modules_Library.RBPlotFunctionV5

b = RG.RigidBodyObject()
#set para here
b.tn=1.0
b.arm = 0.2  #: location of center of mass of top from origin in meters
b.counter_weight = 0.0 #: mass doesn't spin along symmetry axis
b.counter_weight_location_from_origin = 0.0 #: location from origin
b.Iy=0.002
b.Iz= 0.0008
b.Ix=0.002
b.samplerate=600
b.orien = np.array([-np.radians(50),0,0])
#set case here
b.classical_case = 2
b.GenerateDependentVariables()
b.DrawOption['A_axes'] = True
b.DrawOption['A_square'] = False
b.DrawOption['A_z_axis_trace'] = True
b.DrawOption['A_cube'] = True

#b.HasbunEulerEquationODEsolve()
#b.IncludeNoiseInOmega()
b.EulerDCMiter()
#b.directDCMiter()

#b.DrawOption['B_axes'] = True
#b.DrawOption['B_z_axis_trace'] = True
#b.DrawOption['C_axes'] = True

#Draw the trace of the angular momentum vector
b.DrawOption['A_Angular Momentum Trace'] = True
#Draw Angular momentum vector normalized to initial value at t0
b.DrawOption['A_Angular Momentum Vec'] = True
b.DrawOption['A_Angular Velocity Vec'] = True
b.framerate = 6
b.view_azim_angle = 160
starting_frame = 5.0 #animation will start from this i-th data frame
animation_manager = RBPlot.mplot3d_animation(b,starting_frame)

''' broken py film saving code, need to fix
b.savecount = 0
if b.savecount == 1:
    line_ani.save('EulerTop_sharp_cube.mp4',writer = 'ffmpeg',fps='24')
    b.savecount = b.savecount -1
plt.show()
'''


import smtplib
from config import Config
from threading import Thread
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from flask import render_template
from flask_login import current_user
# from app.models import User, FarerLog, AmHack, GoodieData, Team

def send_core(smtpserver, user, recipient, msg):
    smtpserver.sendmail(user, recipient, msg.as_string())
    smtpserver.close()

def send_mail(sub, body, htmlbody, recipient):
    smtpserver = smtplib.SMTP(Config.MAIL_SERVER, Config.MAIL_PORT)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.login(Config.MAIL_USERNAME, Config.MAIL_PASSWORD)
    msg = MIMEMultipart('alternative')
    msg['Subject'] = sub
    msg['From'] = Config.MAIL_DEFAULT_SENDER
    msg['To'] = recipient
    part1 = MIMEText(htmlbody, 'html')
    msg.attach(part1)

    Thread(target=send_core, args=(smtpserver, Config.MAIL_DEFAULT_SENDER, recipient, msg)).start()

def farer_welcome_mail():
    print("Inside the Welcome mail")
    send_mail("Thank you for registering with Vidyut",
            body="Your Vidyut ID is " + str(current_user.vid),
            htmlbody=render_template('emails/welcome.html', user=current_user),
            recipient=current_user.email
            )
    return "Okay!"

def amrsoy_reg_mail():
    print("Inside AMRSoy mail")
    send_mail("Student of the Year 2019: Amrita Edition registration successful",
            body="Thank you for your participation.",
            htmlbody=render_template('emails/soy_welcome.html', user=current_user),
            recipient=current_user.email
            )
    return "Okay!"

def testing_mail():
    print("Inside testing mail")
    send_mail("Testing mail",
            body="Thank you for your participation.",
            htmlbody=render_template('emails/soy_welcome.html', user=current_user),
            recipient=current_user.email
            )
    return "Mail sent"


from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for, send_from_directory, current_app
)
from workspace.database import *

import datetime as dt
from workspace.login_app import login_required
from flask_avatars import Avatars
avatars = Avatars()

bp = Blueprint('show', __name__, url_prefix='/show')

@bp.route('/<int:id>',defaults={'page':1,'order':1}, methods=['GET', 'POST'])
@bp.route('/<int:id>/<int:page>/<int:order>', methods=['GET', 'POST'])
@bp.route('/<int:id>/<int:page>',defaults={'order':1} ,methods=['GET', 'POST'])
def show(id,page,order):
    if request.method == 'POST' and request.form['action'] == "search":
        search = request.form['Search']
        return redirect(url_for('main_index.search_page',search=search))
    connect = Database()
    connect.Connect_to_db()
    anchor=None
    sql = """SELECT * FROM `picture` WHERE `ID` = %s"""
    show_info = connect.select_funcOne(sql, id)
    if not show_info:
        return redirect(url_for('main_index.main_page'))
    sql = """SELECT Profile.nick_name, Profile.ID, Profile.icon FROM `picture` JOIN\
     Profile ON picture.auth_ID = Profile.ID where picture.auth_ID = %s """
    auth_info = connect.select_funcOne(sql, show_info['auth_ID'])

    if order == 2:
        sql = """SELECT comments.ID,\
                comments.comments, comments.timestamp, Profile.icon ,comments.user_ID,\
             Profile.nick_name ,Profile.ID FROM comments JOIN Profile \
             ON comments.user_ID = Profile.ID WHERE comments.pic_ID = %s ORDER BY comments.timestamp  """
        comments = connect.select_funcALL(sql, id)

    else:
        sql = """SELECT comments.ID,\
            comments.comments, comments.timestamp, Profile.icon ,comments.user_ID,\
         Profile.nick_name ,Profile.ID FROM comments JOIN Profile\
          ON comments.user_ID = Profile.ID WHERE comments.pic_ID = %s ORDER BY comments.timestamp DESC; """
        comments = connect.select_funcALL(sql, id)

    if not not g.user:
        sql = """select * from love where `love`.`love_ID` = %s AND `love`.`picture_ID` = %s"""
        like = connect.select_funcOne(sql, g.user['ID'] ,id)
        sql = """select * from report_comment where reporter_ID= %s """
        report = connect.select_funcALL(sql, g.user['ID'])
        for i in range(len(comments)):
            for a in range(len(report)):
                if comments[i]['ID'] == report[a]['comment_ID']:
                    comments[i]['reported'] = 'Y'
        sql = """select *from follow where following = %s and follower = %s """
        follow = connect.select_funcOne(sql, show_info['auth_ID'],g.user['ID'])
        if not follow:
            check_follow='N'
        else:
            check_follow='Y'

        sql = """select * from collection WHERE `collection`.`picture_ID` = %s AND \
        `collection`.`collecter_ID` = %s """
        collection = connect.select_funcOne(sql, id,g.user['ID'])

    else:
        like = None
        collection = None
        follow = None
        check_follow = 'N'
    sql = """select * from love where `love`.`picture_ID` = %s """
    likes = connect.select_funcALL(sql, id)
    collections = connect.select_funcALL("""select * from collection WHERE `collection`.`picture_ID` = %s"""%id)

    for i in range(len(comments)):
        db = str(comments[i]['timestamp'])
        a = dt.datetime.now()
        b = dt.datetime(int(db[0:4]),int(db[5:7]),int(db[8:10]),int(db[11:13]),int(db[14:16]),int(db[17:19]))

        TD = (a-b).total_seconds()

        if TD < 59:
            comments[i]['timestamp'] = str(int(TD))+'s ago'
        elif TD < 3599:
            comments[i]['timestamp'] = str(int(TD/60))+' mins ago'
        elif TD <86399:
            comments[i]['timestamp'] = str(int(TD/60/60))+' hours ago'
        elif TD <31535999:
            comments[i]['timestamp'] = str(int(TD/60/60/24))+' days ago'
        else:
            comments[i]['timestamp'] = str(int(TD/60/60/24/365))+' years ago'

    paginate = []
    for i in range(0,len(comments),10):
        paginate.append(comments[i:i+10])

    if len(paginate)< (page-1):
        page = 1

    if request.method == 'POST' and request.form['submit'] == 'send':

        comments=request.form['comments']

        sql = """INSERT INTO `comments` (`ID`, `pic_ID`,`user_ID`,`comments`, \
        `timestamp`) VALUES (NULL, %s, %s,%s,CURRENT_TIMESTAMP);"""

        run = connect.Non_select(sql,id,g.user['ID'],comments)

        try:
            if len(paginate[page-1]) == 10 and order == 2:
                page = len(paginate)
                anchor = 'bottom'

            elif order == 1:
                page = 1
                anchor = 'comment'

        except IndexError:
            pass
        return redirect(url_for('show.show',id=id,page=page,order=order, _anchor=anchor))

    if request.method == 'POST' and request.form['submit'] == 'edit':
        return redirect(url_for('upload.edit', id=show_info['ID']))

    if request.method == 'POST' and request.form['submit'] == 'follow':
        return redirect(url_for('show.follow', id=show_info['auth_ID'],page=id,check_follow=check_follow))

    return render_template('show/show.html',len=len,range=range, show_info=show_info,\
        page=page, auth_info=auth_info,comments=comments,paginate=paginate,id=id,like=like,collection=collection,\
        likes=likes,collections=collections,order=order,str=str,check_follow=check_follow)

@bp.route('/<int:id>/like')
@login_required
def like(id):
    connect = Database()
    connect.Connect_to_db()
    sql = """INSERT INTO `love` (`love_ID`, `picture_ID`) VALUES ( %s ,  %s )"""
    run = connect.Non_select(sql, g.user['ID'],id)
    return redirect(url_for('show.show',id=id))

@bp.route('/<int:id>/collection')
@login_required
def collection(id):
    connect = Database()
    connect.Connect_to_db()
    sql = """INSERT INTO `collection` (`picture_ID`, `collecter_ID`) VALUES ( %s ,  %s )"""
    run = connect.Non_select(sql, id,g.user['ID'])
    return redirect(url_for('show.show',id=id))

@bp.route('/<int:id>/unlike')
@login_required
def unlike(id):
    connect = Database()
    connect.Connect_to_db()
    sql = """DELETE FROM `love` WHERE `love`.`love_ID` = %s AND `love`.`picture_ID` = %s"""
    run = connect.Non_select(sql, g.user['ID'],id)
    return redirect(url_for('show.show',id=id))

@bp.route('/<int:id>/uncollect')
@login_required
def uncollection(id):
    connect = Database()
    connect.Connect_to_db()
    sql = """DELETE FROM `collection` WHERE `collection`.`picture_ID` = %s AND \
        `collection`.`collecter_ID` = %s """
    run = connect.Non_select(sql, id,g.user['ID'])
    return redirect(url_for('show.show',id=id))

@bp.route('/report<int:id>', methods=['GET', 'POST'])
@login_required
def report(id):
    connect = Database()
    connect.Connect_to_db()
    sql = """select picture.picture, picture.ID, picture.title, Profile.nick_name \
        from picture,Profile where picture.auth_ID = Profile.ID and picture.ID = %s"""
    post = connect.select_funcOne(sql, id)
    if not post:
        return redirect(url_for('main_index.main_page'))
    if request.method == 'POST':
        reson = request.form['reason']
        details = request.form['details']
        try:
            sql = """INSERT INTO `report` (`post_ID`, `reporter_ID`, `reason`, `Details`) \
                VALUES (%s, %s, %s, %s)"""
            run = connect.Non_select(sql, id,g.user['ID'],reson,details)
            flash('Reported','success')
        except pymysql.err.IntegrityError:
            flash('You are already reported','danger')
        return redirect(url_for('show.show',id=id))

    return render_template('show/report.html',post=post)

@bp.route('/report_comment<int:id>/<int:comment>', methods=['GET', 'POST'])
@login_required
def report_comment(id,comment):
    connect = Database()
    connect.Connect_to_db()
    sql = """select *from report_comment where comment_ID = %s and reporter_ID = %s"""
    report = connect.select_funcOne(sql, comment,g.user['ID'])
    if not report:
        sql = """INSERT INTO `report_comment` (`comment_ID`, `reporter_ID`) \
            VALUES ( %s ,  %s )"""
        run = connect.Non_select(sql, comment,g.user['ID'])
        flash('You reported the comment','warning')
    else:
        sql = """DELETE FROM `report_comment` WHERE \
            `report_comment`.`comment_ID` = %s AND `report_comment`.`reporter_ID` = %s"""
        run = connect.Non_select(sql, comment,g.user['ID'])
        flash('You cancel your report','success')

    return redirect(url_for('show.show',id=id))

@bp.route('/follow<int:id>/<int:page>/<check_follow>', methods=['GET', 'POST'])
@login_required
def follow(id,page,check_follow):
    connect = Database()
    connect.Connect_to_db()
    if check_follow == 'N':
        sql = """INSERT INTO `follow` (`following`, `follower`,\
         `timestamp`) VALUES ( %s ,  %s , CURRENT_TIMESTAMP)"""
        run = connect.Non_select(sql, id,g.user['ID'])
        flash('Follow successful','success')
    else:
        sql = """DELETE FROM `follow` where `following`=%s and `follower`= %s """
        run = connect.Non_select(sql, id,g.user['ID'])
        flash('Unfollow successful','warning')
    return redirect(url_for('show.show',id = page))


"""Module containing tests for mlscratch/supervised/logistic.py."""
from numpy.testing import assert_array_almost_equal
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

from mlscratch.utils.metrics import accuracy_score
from mlscratch.utils.preprocessing import StandardScaler
from mlscratch.supervised.logistic import LogisticRegression
from mlscratch.supervised.logistic import SoftmaxRegression

def test_logistic_simple():
    """Test logistic regression with a simple dataset."""
    X = [[-1, -1], [-1, 0], [0, 1], [1, 1]]
    y = [0, 0, 1, 1]

    clf = LogisticRegression(n_iter=3000)

    clf.fit(X, y)

    preds = clf.predict(X)

    assert preds.shape == (len(y),)
    assert_array_almost_equal(clf.predict(X), y)

    probas = clf.predict_proba(X)

    assert probas.shape == (len(y),)

def test_logistic_iris():
    """Test logistic regression with the iris dataset."""
    # Load iris dataset and transform into binary classification problem.
    iris = load_iris()
    X = iris.data[iris.target != 0]
    y = iris.target[iris.target != 0]
    y[y==1] = 0
    y[y==2] = 1

    # Split dataset into training and test sets.
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20,
                                                        random_state=42)

    # Preprocess data by standardization.
    scaler = StandardScaler()
    scaler.fit_transform(X_train)
    scaler.transform(X_test)

    # Train model and predict test set.
    clf = LogisticRegression(n_iter=10000, lr=1e-3)
    clf.fit(X_train, y_train)
    y_preds = clf.predict(X_test)

    # Compute accuracy of predictions.
    score = accuracy_score(y_test, y_preds)

    assert score > 0.80

def test_softmax_iris():
    """Test softmax regression on iris dataset."""
    # Load iris dataset.
    iris = load_iris()
    X = iris.data
    y = iris.target

    # Split dataset into training and test sets.
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20,
                                                        random_state=42)

    # Preprocess data by standardization.
    scaler = StandardScaler()
    scaler.fit_transform(X_train)
    scaler.transform(X_test)

    # Train model and predict test set.
    clf = SoftmaxRegression()
    clf.fit(X_train, y_train)
    y_preds = clf.predict(X_test)

    # Compute accuracy of predictions.
    score = accuracy_score(y_test, y_preds)

    assert score > 0.85


# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/

# This is a simple example for a custom action which utters "Hello World!"

# from typing import Any, Text, Dict, List
#
# from rasa_sdk import Action, Tracker
# from rasa_sdk.executor import CollectingDispatcher
#
#
# class ActionHelloWorld(Action):
#
#     def name(self) -> Text:
#         return "action_hello_world"
#
#     def run(self, dispatcher: CollectingDispatcher,
#             tracker: Tracker,
#             domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
#
#         dispatcher.utter_message(text="Hello World!")
#
#         return []

from typing import Any, Text, Dict, List, Union
from rasa_sdk import Action, Tracker
import requests
from rasa_sdk.events import SlotSet, UserUtteranceReverted
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormAction

from flask import Flask, request
import requests
import json

class WeatherForm(FormAction):
    """Collects details run the weather api"""

    def name(self):
        return "weather_form"

    @staticmethod
    def required_slots(tracker):
        return [
            "area",
            "dayshence",
            ]

    def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
        return{
            "area":self.from_text(),
            "dayshence":self.from_text()
        }

    def apply_to(self, tracker) -> None:
        tracker._reset_slots()

    def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:

        area = tracker.get_slot('area')
        print(area)
        daysHence = int(tracker.get_slot('dayshence'))
        print(daysHence)
        url='http://api.openweathermap.org/data/2.5/forecast?appid=63fb79c416f18764ec7af193f1b6480c&units=metric&q={}'.format(area)
        res = requests.get(url)
        data = res.json()
        obj={}
        if(data['cod'] != '404'):
            timestampForDaysHence = int(data['list'][0]['dt'])+(daysHence*24*3600)
            index = -1
            for i, val in enumerate(data['list']):
                if(timestampForDaysHence<=val['dt'] and daysHence>=0 and daysHence<=5):
                    index = i
                    break
                continue
            if index == -1:
                return {'description':'could not find temperature beyond 4 days'}
            else:

                obj['description'] = data['list'][index]['weather'][0]['description']
                obj['temperature'] = str(data['list'][index]['main']['temp'])+' degree celsius'
                obj['windSpeed'] = str(data['list'][index]['wind']['speed'])+' m/s'
                dispatcher.utter_message("{} with a temperature of {} and winspeed of {}".format(obj['description'], obj['temperature'], obj['windSpeed']))

        else:
            obj['description'] = 'city not found'
            dispatcher.utter_message("Sorry! Looks like the city you entered is not correct.")
            # dispatcher.utter_message("Api call for weather complete.")
        return []

class AgriForm(FormAction):
    """Answers agri based questions"""

    def name(self):
        return "agri_form"

    @staticmethod
    def required_slots(tracker):
        return [
            "question",
            ]

    def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
        return{
            "question":self.from_text(),
        }

    def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:

        query = tracker.get_slot('question')
        print('query entered',query)
        url = 'http://localhost:8080/getAnswer'

        data = {"question": str(query)}
        j_data = json.dumps(data)
        headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
        res = requests.post(url, data=j_data, headers=headers)
        temp = str(res.json())

        dispatcher.utter_message(text=temp)
        return []

# class WelcomeForm(FormAction):
#     """Answers agri based questions"""

#     def name(self):
#         return "welcome_form"

#     @staticmethod
#     def required_slots(tracker):
#         return [
#             "option",
#             ]

#     def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
#         return{
#             "option":self.from_text(),
#         }

#     def submit(
#         self,
#         dispatcher: CollectingDispatcher,
#         tracker: Tracker,
#         domain: Dict[Text, Any],
#     ) -> List[Dict]:

#         option = tracker.get_slot('option')
#         print(option)
#         return [SlotSet("option",option)]

class ActionGreetUser(Action):
    """Revertible mapped action for utter greet"""
    def name(self):
        return "action_greet"

    def run(self, dispatcher, tracker, domain):
        dispatcher.utter_template("utter_greet", tracker)
        return [UserUtteranceReverted()]

class ActionDefaultFallback(Action):
    def name(self) -> Text:
        return "fallback_action"

    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ):

        dispatcher.utter_message("Sorry! I did not understand what you said.")
        return [UserUtteranceReverted()]


from wellcomeml.ml import KerasVectorizer

def test_vanilla():
    X = ["One", "Two", "Three Four"]

    keras_vectorizer = KerasVectorizer()
    X_vec = keras_vectorizer.fit_transform(X)

    assert X_vec.shape[0] == 3
    assert X_vec.shape[1] == 2
    assert X_vec.max() == 5  # 4 tokens including OOV

def test_sequence_length():
    X = ["One", "Two", "Three"]

    sequence_length = 5
    keras_vectorizer = KerasVectorizer(sequence_length=sequence_length)
    X_vec = keras_vectorizer.fit_transform(X)

    assert X_vec.shape[1] == sequence_length

def test_vocab_size():
    X = ["One", "Two", "Three"]

    vocab_size = 1
    keras_vectorizer = KerasVectorizer(vocab_size=vocab_size)
    X_vec = keras_vectorizer.fit_transform(X)

    assert X_vec.max() == vocab_size


# -*- coding: utf-8 -*-
import os, sys, qgis.utils
from qgis import core, gui, utils
from qgis.core import *
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtCore import QFile, QFileInfo, QDir
from qgis.core import *
from qgis.utils import iface
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
from subprocess import call
import glob
import codecs
import datetime
import mimetypes
import os
import urllib2
import urlparse
import shutil

"""
ОБЩАЯ РАБОТА СО СЛОЯМИ ПРОЕКТА - ПОИСК, ОПРЕДЕЛЕНИЕ ТИПА И Т.Д.
"""

# Возвращает имена всех слоёв, добавленных в проект
def getAllLayersNamesFromProject():
    names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()]
    return names

# Возвращает имена всех векторных слоёв, добавленных в проект
def getAllVectorLayersNamesFromProject():
    names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values() if
             layer.type() == QgsMapLayer.VectorLayer]
    return names

# Возвращает имена всех растровых слоёв, добавленных в проект
def getAllRasterLayersNamesFromProject():
    names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values() if
             layer.type() == QgsMapLayer.RasterLayer]
    return names

# Возвращает имена всех слоёв заданного типа геометрии, добавленных в проект
def getAllSpecifiedGeometryTypeVectorLayersNamesFromProject(geometryType):
    """
        1 - point
        2 - polyline
        3 - polygon
    """

    mod = 1
    if geometryType == 'point':
        mod = 1
    if geometryType == 'polyline':
        mod = 2
    if geometryType == 'polygon':
        mod = 3
    names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values() if
             (layer.type() == QgsMapLayer.VectorLayer) and (layer.wkbType() == mod)]

    return names

# Возвращает слой с заданным именем
def getLayerByName(layerName):
    """

    :rtype : object
    """
    layer = None
    for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
        if lyr.name() == layerName:
            layer = lyr
            break

    return layer

def getLayerByID(layerID):
    """

    :rtype : object
    """
    layer = None
    for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
        if lyr.id() == layerID:
            layer = lyr
            break

    return layer

# Возвращает тип (QgsMapLayer.VectorLayer / QgsMapLayer.RasterLayer) по имени
def getLayerTypeByName(layerName):
    layer = getLayerByName(layerName)
    return layer.type()

# Возвращает имя слоя по источнику
def getLayerNameBySource(layerName):
    layer = getLayerByName(layerName)
    return layer.source()

# Возвращает тип геометрии векторного слоя по имени
def getVectorLayerGeometryTypeByName(layerName):
    layer = getLayerByName(layerName)

    if layer.type() != QgsMapLayer.VectorLayer:
        raise ValueError('NotVectorLayer')

        # return layer.

    return layer.wkbType()

def getFeaturesListFromIterator (featureIterator):
    list = []
    for feature in featureIterator:
        list.append(feature)
    return list

#def copyPhysicalLayerToMemoryLayer (physicalLayer,memoryLayer):
#    pr = memoryLayer.dataProvider()

"""
ОБЩАЯ РАБОТА С АТРИБУТАМИ СЛОЁВ
"""

# Возвращает список атрибутов слоя
def getAttributesListOfVectorLayer(layer):
    names = []
    for field in layer.pendingFields():
        names.append(field.name())

    return

def getAllValuesOfAttribute(layer, attribute):
    features = layer.getFeatures()
    values = []
    for feature in features:
        values.append (feature[attribute])
    return values

def getAllValuesOfAttributeCommonForTwoLayers(layer1, attribute1, layer2, attribute2):
    values1 = getAllValuesOfAttribute(layer1, attribute1)
    values2 = getAllValuesOfAttribute(layer2, attribute2)
    values2Set = set(values2)
    valuesCommon = [val for val in values1 if val in values2Set]
    return valuesCommon

def getFirstFeatureByAttributeValue (layer, attribute, value):
    if isinstance( value, basestring ):
        filterExpression = unicode(str(attribute)) + ' = \'' + unicode(value) + '\''
    else:
        filterExpression = unicode(attribute) + ' = ' + unicode(value)
    ids = [f for f in layer.getFeatures(QgsFeatureRequest().setFilterExpression(filterExpression))]
    return ids[0]

def getEPSGCodeFromLayer(layer):
    """
    Возвращает EPSG-код пользовательского слоя (только число)

    :param layer: Пользовательский слой
    :return: Код (число)
    """
    authid = layer.crs().authid()
    crs = ''
    nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    for symb in authid:
        if symb in nums:
            crs += symb
    return crs