# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\eve\client\script\ui\station\pvptrade\pvptradewnd.py
from carbonui.primitives.sprite import Sprite
import evetypes
from localization import GetByLabel
import uiprimitives
import uicontrols
import uix
import uiutil
import util
import uicls
import carbonui.const as uiconst
import localization
import invCtrl
import invCont
from carbonui.primitives.flowcontainer import FlowContainer
from eve.client.script.ui.control.buttons import Button

class PVPTrade(uicontrols.Window):
    __guid__ = 'form.PVPTrade'
    default_topParentHeight = 0
    default_minSize = (300, 370)
    scope = 'station'

    def ApplyAttributes(self, attributes):
        uicontrols.Window.ApplyAttributes(self, attributes)
        self.tradeSession = attributes.tradeSession
        tradeItems = attributes.tradeItems
        self.tradedShips = []
        self.SetWndIcon()
        buttonParent = FlowContainer(name='buttonParent', parent=self.sr.main, align=uiconst.TOBOTTOM, padding=6, autoHeight=True, centerContent=True, contentSpacing=(6,
                                                                                6))
        self.acceptButton = Button(parent=buttonParent, label=localization.GetByLabel('UI/PVPTrade/Accept'), func=self.OnClickAccept, align=uiconst.NOALIGN)
        Button(parent=buttonParent, label=localization.GetByLabel('UI/Common/Buttons/Cancel'), func=self.Cancel, align=uiconst.NOALIGN)
        sessionData = self.tradeSession.List()
        herID = sessionData.traders[not sessionData.traders.index(session.charid)]
        self.sr.herinfo = cfg.eveowners.Get(herID)
        mainCont = uiprimitives.Container(name='mainCont', parent=self.sr.main)
        self.sr.my = my = invCont.PlayerTrade(parent=mainCont, align=uiconst.TOTOP_PROP, height=0.5, itemID=sessionData.tradeContainerID, ownerID=session.charid, tradeSession=self.tradeSession, state=uiconst.UI_PICKCHILDREN, tradeItems=tradeItems)
        self.sr.myAccept = my.acceptIcon
        self.sr.myMoney = my.moneyLabel
        self.sr.her = her = invCont.PlayerTrade(parent=mainCont, align=uiconst.TOTOP_PROP, height=0.5, itemID=sessionData.tradeContainerID, ownerID=herID, tradeSession=self.tradeSession, state=uiconst.UI_PICKCHILDREN)
        self.sr.herAccept = her.acceptIcon
        self.sr.herMoney = her.moneyLabel
        offerBtn = Button(parent=my.topCont, label=localization.GetByLabel('UI/PVPTrade/OfferMoney'), func=self.OnClickOfferMoney, args=None, idx=0, pos=(2,
                                                                                2,
                                                                                0,
                                                                                0), align=uiconst.TOPRIGHT)
        self.sr.myIx = sessionData.traders.index(eve.session.charid)
        self.sr.herIx = sessionData.traders.index(herID)
        self.OnMoneyOffer([0, 0])
        self.SetCaption(self.GetWindowCaptionText())
        return

    def _OnClose(self, *args):
        if self and getattr(self, 'sr', None):
            if self.sr.my:
                self.sr.my.Close()
            if self.sr.her:
                self.sr.her.Close()
        return

    def Cancel(self, *etc):
        if self.tradeSession and eve.Message('ConfirmCancelTrade', {}, uiconst.OKCANCEL) == uiconst.ID_OK:
            if self and not self.destroyed and hasattr(self, 'sr'):
                tmp = self.tradeSession
                self.tradeSession = None
                tmp.Abort()
            else:
                eve.Message('TradeNotCanceled')
        return

    CloseByUser = Cancel

    def OnClickAccept(self, *etc):
        self.acceptButton.Disable()
        currentState = [uiconst.UI_HIDDEN, uiconst.UI_DISABLED].index(self.sr.myAccept.state)
        self.tradedShips = []
        tradeItems = self.tradeSession.List().items
        for item in tradeItems:
            if evetypes.GetCategoryIDByGroup(item.groupID) == const.categoryShip:
                self.tradedShips.append(item.itemID)
                sm.GetService('gameui').KillCargoView(item.itemID)

        try:
            self.tradeSession.ToggleAccept(not currentState)
        except UserError as what:
            if not what.msg.startswith('TradeShipWarning'):
                raise
            msgName, msgDict = what.msg, what.dict
            if msgName is not None:
                if eve.Message('TradeShipWarning', {}, uiconst.OKCANCEL) == uiconst.ID_OK:
                    self.tradeSession.ToggleAccept(not currentState, forceTrade=True)
                else:
                    self.acceptButton.Enable()

        return

    def GetWindowCaptionText(self):
        return localization.GetByLabel('UI/PVPTrade/TradeWith', otherParty=self.sr.herinfo.id)

    def OnStateToggle(self, states):
        self.sr.myAccept.state = (
         uiconst.UI_HIDDEN, uiconst.UI_DISABLED)[states[self.sr.myIx]]
        self.sr.herAccept.state = (uiconst.UI_HIDDEN, uiconst.UI_DISABLED)[states[self.sr.herIx]]
        if self.sr.myAccept.state == uiconst.UI_DISABLED:
            self.acceptButton.Disable()
        else:
            self.acceptButton.Enable()
        if states[0] and states[1]:
            self.sr.my.invReady = 0
            self.sr.her.invReady = 0
            self.Close()

    def OnMoneyOffer(self, money):
        self.acceptButton.Enable()
        myMoney = util.FmtISK(money[self.sr.myIx])
        if money[self.sr.myIx] > 0:
            myMoney = localization.GetByLabel('UI/PVPTrade/NegativeChangeInFunds', amount=myMoney)
        else:
            myMoney = localization.GetByLabel('UI/PVPTrade/NoChangeInFunds', amount=myMoney)
        herMoney = util.FmtISK(money[self.sr.herIx])
        if money[self.sr.herIx] > 0:
            herMoney = localization.GetByLabel('UI/PVPTrade/PositiveChangeInFunds', amount=herMoney)
        else:
            herMoney = localization.GetByLabel('UI/PVPTrade/NoChangeInFunds', amount=herMoney)
        self.sr.myMoney.text = localization.GetByLabel('UI/PVPTrade/Money', formattedAmount=myMoney)
        self.sr.herMoney.text = localization.GetByLabel('UI/PVPTrade/Money', formattedAmount=herMoney)
        self.OnStateToggle([0, 0])

    def OnClickOfferMoney(self, *etc):
        self.tradeSession.ToggleAccept(False)
        ret = uix.QtyPopup(sm.GetService('wallet').GetWealth(), 0, 0, digits=2)
        if ret is not None and self is not None and not self.destroyed:
            self.tradeSession.OfferMoney(ret['qty'])
        return

    def OnTradeComplete(self):
        for itemID in self.tradedShips:
            sm.GetService('gameui').KillCargoView(itemID)

        eve.Message('TradeComplete', {'name': self.sr.herinfo.name})
        self.sr.my.invReady = 0
        self.sr.her.invReady = 0
        self.Close()

    def OnCancel(self):
        eve.Message('TradeCancel', {'name': self.sr.herinfo.name})
        self.sr.my.invReady = 0
        self.sr.her.invReady = 0
        self.Close()

class PlayerTrade(invCont._InvContBase):
    __guid__ = 'invCont.PlayerTrade'
    __invControllerClass__ = invCtrl.PlayerTrade

    def ApplyAttributes(self, attributes):
        invCont._InvContBase.ApplyAttributes(self, attributes)
        tradeItems = attributes.tradeItems
        ownerID = attributes.ownerID
        ownerName = cfg.eveowners.Get(ownerID).name
        self.topCont = uiprimitives.Container(parent=self, align=uiconst.TOTOP, height=65, idx=0)
        myImgCont = Sprite(parent=self.topCont, align=uiconst.TOLEFT, width=64, idx=0, texturePath='res:/UI/Texture/silhouette_64.png', left=2)
        sm.GetService('photo').GetPortrait(ownerID, 64, myImgCont)
        myImgCont.OnClick = (self.ShowCharInfo, ownerID)
        myImgCont.hint = ownerName
        ownerLink = GetByLabel('UI/Contracts/ContractsWindow/ShowInfoLink', showInfoName=ownerName, info=('showinfo',
         const.typeCharacterAmarr, ownerID))
        uicontrols.EveLabelMedium(text=ownerLink, parent=self.topCont, left=72, top=2, bold=True, state=uiconst.UI_NORMAL)
        self.acceptIcon = uicontrols.Icon(icon='ui_38_16_193', parent=self.topCont, left=67, top=14)
        uicls.InvContViewBtns(parent=self.topCont, align=uiconst.BOTTOMLEFT, left=72, controller=self)
        self.moneyLabel = uicontrols.EveLabelMedium(parent=self.topCont, left=6, top=-2, align=uiconst.BOTTOMRIGHT)
        if tradeItems:
            self.invController.OnDropData(tradeItems)

    def SetInvContViewMode(self, value):
        self.ChangeViewMode(value)

    def _GetInvController(self, attributes):
        return self.__invControllerClass__(itemID=attributes.itemID, ownerID=attributes.ownerID, tradeSession=attributes.tradeSession)

    def ShowCharInfo(self, ownerID, *args):
        sm.GetService('info').ShowInfo(const.typeCharacterAmarr, ownerID)


#!/usr/bin/python3
# coding=utf-8
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeTwoLists(self, l1, l2):
    # 两个链表循环遍历：逐个取两个链表中的最小的节点，赋值给新的节点
    res = ListNode()
    res.next = None
    p_head = res
    while l1 and l2:
        if l1.val <= l2.val:
            res.next = l1
            l1 = l1.next
            res = res.next
        elif l1.val > l2.val:
            res.next = l2
            l2 = l2.next
            res = res.next
    # 一句话，替代下面四行
    # res.next = l1==None? l2 : l1
    if l1 != None:
        res.next = l1
    elif l2 != None:
        res.next = l2
    return p_head.next

    # 递归：两个链表的合并 = minNode + 剩下两个链表的合并;时间复杂度=n
    # if l1 == None:
    #     return l2
    # if l2 == None:
    #     return l1
    # if l1.val <= l2.val:
    #     l3 = self.mergeTwoLists(l1.next, l2)
    #     l1.next = l3
    #     return l1
    # else:
    #     l3 = self.mergeTwoLists(l1, l2.next)
    #     l2.next = l3
    #     return l2


class Robot:
	def __init__(self,n,c,w):
		self.name = n
		self.color = c
		self.weight = w

	def iself(self):
		print("My name is " + self.name)
		print("Fav color is " + self.color + " \nWeight is " , self.weight)

r1 = Robot("Isha","red",30)
r2 = Robot("Red","black",30)

r1.iself()
r2.iself()


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

class Node:
    def __init__(self, features, examples):
        self.s1 = None
        self.s2 = None
        self.classification = None #should be to majority
        self.f = None #if not a leaf should conatain the feature which devide his sons
        self.mid = None # the value which under it is s1 and above is s2
        self.features = features # the features who left. Important Type = Index
        self.examples = examples # current examples. Important Type = List

def entropy(examples):
    total = len(examples)
    if total == 0:
        return 0
    p_true = sum(examples) / total
    p_false = 1 - p_true

    t = p_true * np.log2(p_true) if p_true else 0
    f = p_false * np.log2(p_false) if p_false else 0

    return -(t+f)

def IG(examples, threshold):
    s1 = [e[1] for e in examples if e[0] <= threshold]
    s2 = [e[1] for e in examples if e[0] > threshold]
    ex = s1 + s2

    s1_ratio, s2_ratio = len(s1) / len(ex), len(s2) / len(ex)

    return entropy(ex) - s1_ratio * entropy(s1) - s2_ratio * entropy(s2)

# select feature with the best IG, return the function and its mid value
def selectFeature(features, examples, df):
    max_ig, best_f, best_mid = -1, None, None
    for f in features:
        # ig, mid = best_IG_mid(f, examples, df)
        vals = sorted([(df[f][e], df['diagnosis'][e]) for e in examples], key=lambda x: x[0])
        thresholds = [(vals[i][0] + vals[i + 1][0]) / 2 for i in range(len(vals) - 1)]

        for t in thresholds:
            ig = IG(vals, t)
            if ig > max_ig:
                max_ig = ig
                best_f = f
                best_mid = t

    return best_f, best_mid

# return the majority of the classification of examples and the ratio(to know if all one sided class)
def majorityClass(examples, df):
    total = len(examples)
    true = sum(1 for e in examples if df['diagnosis'][e] == 1)

    if true >= total - true:
        return 1, true/total
    else:
        return 0, (total-true)/total

def ID3(cur_node, df, k):
    if len(cur_node.examples) == 0:
        return
    c, ratio = majorityClass(cur_node.examples, df)
    cur_node.classification = c
    if ratio == 1 or len(cur_node.examples) <= k:
        return

    cur_node.f, cur_node.mid = selectFeature(cur_node.features, cur_node.examples, df)

    s1 = [e for e in cur_node.examples if df[cur_node.f][e] <= cur_node.mid]
    s2 = [e for e in cur_node.examples if df[cur_node.f][e] > cur_node.mid]

    cur_node.s1, cur_node.s2 = Node(cur_node.features, s1), Node(cur_node.features, s2)
    ID3(cur_node.s1, df, k)
    ID3(cur_node.s2, df, k)

# build decision tree ID3 with the k thing with the data df
def get_classifier_ID3(df, k=0):
    features = df.keys().drop(['diagnosis'])
    examples = list(range(0, len(df['diagnosis'])))
    tree = Node(features, examples)
    ID3(tree, df, k)
    return tree

# check for the example i if is right in the tree
def is_right_answer(tree, df_test, i):
    if tree.s1 is None and tree.s2 is None:
        return df_test['diagnosis'][i] == tree.classification

    if df_test[tree.f][i] <= tree.mid:
        return is_right_answer(tree.s1, df_test, i)
    else:
        return is_right_answer(tree.s2, df_test, i)

# check all examples in the tree and return the ratio of accuracy
def get_classifier_accuracy(tree, df_test):
    examples = list(range(0, len(df_test['diagnosis'])))
    total = len(df_test['diagnosis'])

    count_t = sum(1 for e in examples if is_right_answer(tree, df_test, e))
    return count_t/total

def leaves(tree, epsilon, test, train, e):
    if tree.s1 is None and tree.s2 is None:
        t = sum(1 for ex in tree.examples if train['diagnosis'][ex])
        return t, len(tree.examples) - t

    if abs(test[tree.f][e] - tree.mid) <= epsilon[tree.f]:
        t1, f1 = leaves(tree.s1, epsilon, test, train, e)
        t2, f2 = leaves(tree.s2, epsilon, test, train, e)
        return t1+t2, f1+f2
    elif test[tree.f][e] <= tree.mid:
        return leaves(tree.s1, epsilon, test, train, e)
    else:
        return leaves(tree.s2, epsilon, test, train, e)

def epsilon_classify(tree, epsilon, test, train, e):
    t, f = leaves(tree, epsilon, test, train, e)
    return 1 if t >= f else 0

def epsilon_accuracy(tree, test, train):
    examples = list(range(0, len(test['diagnosis'])))
    features = test.keys().drop(['diagnosis'])
    eps = {f: 0.1 * np.std(train[f]) for f in features}

    matches = sum(1 if epsilon_classify(tree, eps, test, train, e) == test['diagnosis'][e] else 0 for e in examples)
    return matches / len(examples)

if __name__ == "__main__":
    data = pd.read_csv("train.csv")
    df = pd.DataFrame(data)
    tree = get_classifier_ID3(df)

    data_test = pd.read_csv("test.csv")
    df_test = pd.DataFrame(data_test)

    t9 = get_classifier_ID3(df, 9)
    eps_acc = epsilon_accuracy(t9, df_test, df)
    print("T9 epsilon accuracy: {:.2%}".format(eps_acc))


from copy import copy
import random
from math import sqrt
class random_knapsack:
    def __init__(self,items,max):
        self.MAXWT = max
        self.items = items

    def square_rooted(self,x):
        return sqrt(sum([a * a for a in x]))

    def cosine_dist(self,x, y):
        numerator = sum(a * b for a, b in zip(x, y))

        denominator = self.square_rooted(x) * self.square_rooted(y)
        return 1 - numerator / float(denominator)

    def pack(self,original_vector,competitor_features,first_competitor_features):

        bagged = []
        temp_vec = copy(competitor_features)
        for name in self.items:
            index = name
            if len(first_competitor_features) == 0:
                break
            if first_competitor_features[index]==temp_vec[index]:
                continue
            temp_vec[index] = first_competitor_features[index]
            if self.cosine_dist(temp_vec,original_vector)>self.MAXWT:
                temp_vec[index]=competitor_features[index]
                continue

            bagged += [(name,)]
        return bagged


from django.urls import path
from . import views as cus_views
urlpatterns =[

    path('',cus_views.show_transations, name='transations'),
    path('new_transation/',cus_views.new_transation, name='new_transation'),
    path('details/<int:id>/',cus_views.details_customer, name='details_customer'),
    path('test/',cus_views.Test),
    # path('delete/<int:id>/',cus_views.delete_customer, name='delete_customer'),
    # path('exa/',cus_views.matltiplae, name='exa'),

]


import sys
import websocket
import threading
import traceback
import queue
from .bitMexDataStructure import Orderbook,Tick,Position,Error,Order,Bar
import ssl
from time import sleep
import json
import decimal
import logging
import alog
from .qsUtils import now,utc_to_local
import datetime
from dateutil import tz
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
print = alog.info
# from market_maker.settings import settings
# from market_maker.auth.APIKeyAuth import generate_expires, generate_signature

from requests.auth import AuthBase
import time
import hashlib
import hmac
from future.builtins import bytes
from future.standard_library import hooks
with hooks():  # Python 2/3 compat
	from urllib.parse import urlparse

class APIKeyAuth(AuthBase):

	"""Attaches API Key Authentication to the given Request object."""

	def __init__(self, apiKey, apiSecret):
		"""Init with Key & Secret."""
		self.apiKey = apiKey
		self.apiSecret = apiSecret

	def __call__(self, r):
		"""Called when forming a request - generates api key headers."""
		# modify and return the request
		nonce = generate_expires()
		r.headers['api-expires'] = str(nonce)
		r.headers['api-key'] = self.apiKey
		r.headers['api-signature'] = generate_signature(self.apiSecret, r.method, r.url, nonce, r.body or '')

		return r

def generate_expires():
	return int(time.time() + 36000000)

def generate_signature(secret, verb, url, nonce, data):
	"""Generate a request signature compatible with BitMEX."""
	# Parse the url so we can remove the base and extract just the path.
	parsedURL = urlparse(url)
	path = parsedURL.path
	if parsedURL.query:
		path = path + '?' + parsedURL.query

	if isinstance(data, (bytes, bytearray)):
		data = data.decode('utf8')

	message = verb + path + str(nonce) + data

	signature = hmac.new(bytes(secret, 'utf8'), bytes(message, 'utf8'), digestmod=hashlib.sha256).hexdigest()
	return signature

import logging

LOG_LEVEL = logging.ERROR
def setup_custom_logger(name, log_level=logging.INFO):
	formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')

	handler = logging.StreamHandler()
	handler.setFormatter(formatter)

	logger = logging.getLogger(name)
	logger.setLevel(log_level)
	logger.addHandler(handler)
	return logger

from decimal import Decimal

def toNearest(num, tickSize):
	tickDec = Decimal(str(tickSize))
	return float((Decimal(round(num / tickSize, 0)) * tickDec))
from future.utils import iteritems
from future.standard_library import hooks
with hooks():
	from urllib.parse import urlparse, urlunparse

class BitMEXWebsocket(object):

	MAX_TABLE_LEN = 200
	MAX_TRADETABLE_LEN = 10000

	def __init__(self,g):
		self.pre_orderbook = None
		self.pre_tick = None
		self.index = 1
		self.g = g
		self.logger = logging.getLogger('root')
		self.Url = self.g.Url
		self.wsUrl = ""
		self.ticker = {}
		self.__reset()
		self.pricelist = []
		self.bars = []
		self.isconnected = False
		self.dataReceived = False
		self.market_data_q = queue.PriorityQueue(0)
		self.ping_td = None
		self.updatePosition = False
		self.ws = None
		self.zeroMinute = datetime.datetime.now().replace(second=0,microsecond=0).astimezone(to_zone)
		self.zeroHour = datetime.datetime.now().replace(minute=0,second=0,microsecond=0).astimezone(to_zone)

	def __del__(self):
		self.exit()

	def connect(self, symbol="XBTUSD", shouldAuth=True):
		'''Connect to the websocket and initialize data stores.'''
		print("Connecting WebSocket.")
		self.symbol = symbol
		self.shouldAuth = shouldAuth

		subscriptions = [sub + ':' + symbol for sub in ["quote", "trade","tradeBin1h"]]
		print(subscriptions)
		subscriptions += ["instrument"]  # We want all of them
		if self.shouldAuth:
			subscriptions += [sub + ':' + symbol for sub in ["order", "execution"]]
			subscriptions += ["margin", "position"]

		urlParts = list(urlparse(self.Url))
		urlParts[0] = urlParts[0].replace('http', 'ws')
		urlParts[2] = "/realtime?heartbeat=true&subscribe=" + ",".join(subscriptions)
		self.wsUrl = urlunparse(urlParts)
		self.logger.debug("Connecting to %s" % self.wsUrl)
		self.__connect()
		if self.isconnected == True:
			print('已经连接到websocket服务器，正在初始化数据...')

			self.__wait_for_symbol(symbol)
			if self.shouldAuth:
				self.__wait_for_account()
			self.__wait_for_data()
			if len(self.ticker) != 0:
				self.dataReceived = True
			print('已获得所有市场数据...')

	def get_instrument(self, symbol):
		if 'instrument' in self.data :
			instruments = self.data['instrument']
		else:
			return {'markPrice':0,'bidPrice':0,'askPrice':0,'lastPrice':0,'symbol':symbol}
		matchingInstruments = [i for i in instruments if i['symbol'] == symbol]
		if len(matchingInstruments) == 0:
			raise Exception("Unable to find instrument or index with symbol: " + symbol)
		instrument = matchingInstruments[0]

		instrument['tickLog'] = decimal.Decimal(str(instrument['tickSize'])).as_tuple().exponent * -1
		return instrument

	def get_ticker(self, symbol):
		instrument = self.get_instrument(symbol)
		if instrument['lastPrice'] == 0:
			return {'last':0,'buy':0,'sell':0,'mid':0}

		if instrument['symbol'][0] == '.':
			ticker = {}
			ticker['mid'] = ticker['buy'] = ticker['sell'] = ticker['last'] = instrument['markPrice']

		else:
			bid = instrument['bidPrice'] or instrument['lastPrice']
			ask = instrument['askPrice'] or instrument['lastPrice']
			ticker = {
				"last": instrument['lastPrice'],
				"buy": bid,
				"sell": ask,
				"mid": (bid + ask) / 2
			}
		return {k: toNearest(float(v or 0), instrument['tickSize']) for k, v in iteritems(ticker)}

	def add_market_data_q(self, q):
		self.market_data_q = q

	def funds(self):
		if 'margin' in self.data:
			return self.data['margin'][0]
		else:
			return {'availableMargin':0}

	def market_depth(self, symbol):
		raise NotImplementedError('orderBook is not subscribed; use askPrice and bidPrice on instrument')

	def open_orders(self):
		orders = self.data['order']
		return [o for o in orders if  o['leavesQty'] > 0]

	def position(self, symbol):
		try:
			positions = self.data['position']
			pos = [p for p in positions if p['symbol'] == symbol]
			if len(pos) == 0:
				return {'avgCostPrice': 0, 'avgEntryPrice': 0, 'currentQty': 0, 'unrealisedRoePcnt': 0, 'leverage':0,'symbol': symbol}
			return pos[0]
		except:
			return {'avgCostPrice': 0, 'avgEntryPrice': 0, 'currentQty': 0, 'unrealisedRoePcnt': 0, 'leverage':0,'symbol': symbol}

	def recent_trades(self):
		return self.data['trade']

	def error(self, err):
		self._error = err
		print(err)

	def exit(self):
		print('websocket正在退出..')
		self.exited = True
		self._error = None
		self.isconnected = False
		if self.ping_td:
			self.ping_td.join()
			print('ping线程已退出.')
		if isinstance(self.ws, websocket.WebSocketApp):
			print('websocket线程已退出.')
			self.ws.close()

	#
	# Private methods
	#

	def __connect(self):
		'''Connect to the websocket in a thread.'''
		print("启动websocket线程.")

		ssl_defaults = ssl.get_default_verify_paths()
		sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
		self.ws = websocket.WebSocketApp(self.wsUrl,
										 on_message=self.__on_message,
										 on_close=self.__on_close,
										 on_open=self.__on_open,
										 on_error=self.__on_error,
										 header=self.__get_auth()
										 )

		setup_custom_logger('websocket', log_level=LOG_LEVEL)
		self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt=sslopt_ca_certs))
		self.wst.daemon = True
		self.wst.start()
		print("websocket线程已启动.")

		conn_timeout = 5
		while (not self.ws.sock or not self.ws.sock.connected) and conn_timeout and not self._error:
			sleep(1)
			conn_timeout -= 1

		if not conn_timeout or self._error:
			print("无法连接websocket服务器，准备退出..")
			self.exit()
			self.isconnected = False
		else:
			self.isconnected = True
		self.__start_ping_thread()
	def reconnect(self):
		print('准备重新连接..')
		try:
			__error = Error(now(),"websocket断线，正在重连.")
			self.market_data_q.put((-1,self.index,__error))
			self.index += 1
			sleep(10)
			self.connect()
		except Exception as e:
			print(e)
			sleep(10)

	def __start_ping_thread(self):
		self.ping_td = threading.Thread(target=self.__send_ping_forever)
		self.ping_td.start()

	def __send_ping_forever(self):
		while (self.isconnected):
			self.ws.send('ping')
			# print('ping')
			time.sleep(5)

	def __wait_for_data(self):
		while self.funds is None:
			time.sleep(0.1)

	def __get_auth(self):
		'''Return auth headers. Will use API Keys if present in settings.'''

		if self.shouldAuth is False:
			return []

		print("Authenticating with API Key.")
		nonce = generate_expires()

		return [
			"api-expires: " + str(nonce),
			"api-signature: " + generate_signature(self.g.apiSecret, 'GET', '/realtime', nonce, ''),
			"api-key:" + self.g.apiKey
		]

	def __wait_for_account(self):
		'''On subscribe, this data will come down. Wait for it.'''
		# Wait for the keys to show up from the ws
		while not {'margin', 'position', 'order'} <= set(self.data):
			sleep(0.1)

	def __wait_for_symbol(self, symbol):
		'''On subscribe, this data will come down. Wait for it.'''
		while not {'instrument', 'trade', 'quote'} <= set(self.data):
			sleep(0.1)

	def __send_command(self, command, args):
		'''Send a raw command.'''
		self.ws.send(json.dumps({"op": command, "args": args or []}))

	def __on_message(self, ws, message):
		if message == 'pong':
			# print('pong')
			return
		'''Handler for parsing WS messages.'''
		message = json.loads(message)

		table = message['table'] if 'table' in message else None
		action = message['action'] if 'action' in message else None
		try:
			if 'subscribe' in message:
				if message['success']:
					self.logger.debug("Subscribed to %s." % message['subscribe'])
				else:
					self.error("Unable to subscribe to %s. Error: \"%s\" Please check and restart." %
							   (message['request']['args'][0], message['error']))
			elif 'status' in message:
				if message['status'] == 400:
					self.error(message['error'])
				if message['status'] == 401:
					self.error("API Key incorrect, please check and restart.")
			elif action:

				if table not in self.data:
					self.data[table] = []

				if table not in self.keys:
					self.keys[table] = []

				if action == 'partial':
					self.logger.debug("%s: partial" % table)
					self.data[table] += message['data']

					self.keys[table] = message['keys']
				elif action == 'insert':
					self.logger.debug('%s: inserting %s' % (table, message['data']))

					self.data[table] += message['data']

					if table not in ['order', 'orderBookL2','table'] and len(self.data[table]) > BitMEXWebsocket.MAX_TABLE_LEN:
						self.data[table] = self.data[table][(BitMEXWebsocket.MAX_TABLE_LEN // 2):]

					if table == 'trade':
						if len(self.data[table]) > BitMEXWebsocket.MAX_TRADETABLE_LEN:
							self.data[table] = self.data[table][(BitMEXWebsocket.MAX_TRADETABLE_LEN // 2):]
							# pass
						self.reshape1mOHLCV(self.data[table])

					# if table == 'order':
					# 	__order = Order(symbol=self.data['order'][-1]['symbol'], orderid=self.data['order'][-1]['orderID'],
					# 					ordType = self.data['order'][-1]['ordType'], orderPrice=self.data['order'][-1]['price'],
					# 					execPrice = self.data['order'][-1]['stopPx'], side = self.data['order'][-1]['side'],
					# 					amount=self.data['order'][-1]['orderQty'], status='new',timestamp=utc_to_local(self.data['order'][-1]['timestamp']))
					# 	self.market_data_q.put((-1,self.index,__order))
					# 	self.index += 1

					if table == 'tradeBin1h':
						# _now_time = datetime.datetime.strptime(self.data['tradeBin1h'][-1]['timestamp'],'%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=from_zone)
						_zeroMinute = datetime.datetime.now().replace(minute=0,second=0,microsecond=0)
						__bar = Bar(symbol=self.data['tradeBin1h'][-1]['symbol'],bar_type = '1h',
							open = self.data['tradeBin1h'][-1]['open'],high = self.data['tradeBin1h'][-1]['high'],
							low = self.data['tradeBin1h'][-1]['low'],close = self.data['tradeBin1h'][-1]['close'],
							volume = self.data['tradeBin1h'][-1]['volume'],trades = self.data['tradeBin1h'][-1]['trades'],
							buy = 0,sell = 0,timestamp = _zeroMinute)
						self.market_data_q.put((1,self.index,__bar))
						self.index += 1

				elif action == 'update':

					self.logger.debug('%s: updating %s' % (table, message['data']))

					for updateData in message['data']:
						item = findItemByKeys(self.keys[table], self.data[table], updateData)
						if not item:
							continue

						if table == 'order':
							is_canceled = 'ordStatus' in updateData and updateData['ordStatus'] == 'Canceled'
							if 'cumQty' in updateData and not is_canceled:
								contExecuted = updateData['cumQty'] - item['cumQty']
								if contExecuted > 0:

									# self.__process_position_msg(position)
									instrument = self.get_instrument(item['symbol'])
									self.updatePosition = True

									__order = Order(symbol=item['symbol'], orderid=item['orderID'],
																		ordType = item['ordType'], orderPrice=item['price'],
																		execPrice = item['stopPx'], side = item['side'],
																		amount=item['orderQty'], status='filled',timestamp=utc_to_local(item['timestamp']))
									self.market_data_q.put((-1,self.index,__order))
									self.index += 1

						item.update(updateData)
						# print(self.updatePosition)
						if table == 'position':
							if self.data['position'][0]['unrealisedRoePcnt'] != 0 and self.data['position'][0]['currentQty'] != 0:
								_position = Position(symbol=self.data['position'][0]['symbol'],entryPrice=self.data['position'][0]['avgEntryPrice'],
												markPrice=self.data['position'][0]['markPrice'],qty=self.data['position'][0]['currentQty'],
												leverage=self.data['position'][0]['leverage'],liqPrice=self.data['position'][0]['liquidationPrice'],
												roe=self.data['position'][0]['unrealisedRoePcnt'])
								self.market_data_q.put((0,self.index,_position))
								self.index += 1
							if self.data['position'][0].get('isOpen') == False:
								_position = Position(symbol=None,entryPrice=None,markPrice=None,qty=None,leverage=None,liqPrice=None,roe=None)
								self.market_data_q.put((0,self.index,_position))
								self.index += 1
						# 		self.updatePosition = False
						if table == 'order' and item['leavesQty'] <= 0:
							self.data[table].remove(item)
				elif action == 'delete':
					self.logger.debug('%s: deleting %s' % (table, message['data']))
					for deleteData in message['data']:
						item = findItemByKeys(self.keys[table], self.data[table], deleteData)
						self.data[table].remove(item)
				else:
					raise Exception("Unknown action: %s" % action)
				try:

					self.__process_quote_msg(self.data['quote'][-1])
					self.__process_trade_msg(self.data['trade'])

				except Exception as e:
					# print(e)
					pass
		except:
			self.logger.error(traceback.format_exc())

	def __on_open(self,msg):
		print('Websocket Opened.')
		pass

	def __on_close(self,msg):
		print('Websocket Closed')
		self.isconnected = False
		self.reconnect()

	def __on_error(self, ws, error):
		self.error(error)
		self.exit()

	def __reset(self):
		self.data = {}
		self.keys = {}
		self.exited = False
		self._error = None

	def __process_quote_msg(self, msg):

		ob = Orderbook(symbol=msg['symbol'],
					   bid1=msg['bidPrice'], bid1vol=msg['bidSize'],
					   ask1=msg['askPrice'], ask1vol=msg['askSize'],
					   timestamp = msg['timestamp'])
		# self.market_data_q.put((2,self.index,ob))
		# self.index += 1
		if self.pre_orderbook == None:
			self.pre_orderbook = ob
			self.market_data_q.put((2,self.index,ob))
			self.index += 1
		elif self.pre_orderbook is not None:
			if self.pre_orderbook.bid1 != ob.bid1 and self.pre_orderbook.ask1 != ob.ask1:
				self.pre_orderbook = ob
				self.market_data_q.put((2,self.index,ob))
				self.index += 1

	#市价单还是限价单的区分.todo
	def __process_trade_msg(self, msg):
		for tick in msg:
			tk = Tick(symbol=tick['symbol'],
					  price=tick['price'],
					  volume=tick['size'],
					  direction=tick['side'],
					  timestamp = tick['timestamp'])
			# print(tk)
			self.ticker[tk.symbol] = tk
			# print(tk)
		# print(self.tick)

	def reshape1mOHLCV(self,msg):
		buyAmount = 0
		sellAmount = 0
		_listTime = None
		symbol = msg[-1]['symbol']
		O = 0
		volume = 0
		trades = 0
		for _list in msg:
			self.pricelist.append(_list['price'])
			O = _list['price']
			_listTime = datetime.datetime.strptime(_list['timestamp'],'%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=from_zone).astimezone(to_zone)
			_zeroMinute = datetime.datetime.now().replace(second=0,microsecond=0) + datetime.timedelta(minutes = -1)
			# print(self.data['trade'])
			if _listTime > self.zeroMinute:

				if _list['side'] == 'Buy':
					buyAmount += _list['size']
					trades += 1
				elif _list['side'] == 'Sell':
					sellAmount += _list['size']
					trades += 1
			volume = buyAmount + sellAmount

			if _listTime.replace(microsecond=0) - self.zeroMinute > datetime.timedelta(minutes=1):
				C = self.data['trade'][-1]['price']
				L = min(self.pricelist)
				H = max(self.pricelist)
				__bar = Bar(symbol=symbol,bar_type = '1m',
							open = O,high = H,
							low = L,close = C,
							volume = volume,trades = trades,
							buy = buyAmount,sell = sellAmount,timestamp = _zeroMinute)
				buyAmount = sellAmount = 0
				self.pricelist = []
				self.zeroMinute = datetime.datetime.now().replace(second=0,microsecond=0).astimezone(to_zone)
				self.data['trade'] = []
				self.market_data_q.put((1,self.index,__bar))
				self.index += 1

def findItemByKeys(keys, table, matchData):
	for item in table:
		matched = True
		for key in keys:
			if item[key] != matchData[key]:
				matched = False
		if matched:
			return item


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

# //////////////////////////////////////////////////////////
# //
# //   Чтение файлов с использоанием циклов for и while
# //

HEADLINE: str = ' Чтение файлов с использоанием циклов for и while '

print('\n')
print(HEADLINE.center(80, '*'), '\n')

# Чтение файла

file = open('dat.txt', 'r')
print(file.read())
file.close()

# Посимвольное чтение файла

file = open('dat.txt', 'r')
print('-' * 20)
while True:
    ch = file.read(1)
    if not ch:
        break
    print(ch, end='')
file.close()

print('\n\n', '*'* 20)
for ch in open('dat.txt', 'r'):
    print(ch, end='')

# Чтение строками

print('\n\n', '+' * 20)
file = open('dat.txt', 'r')
while True:
    lines = file.readline()
    if not lines:
        break
    print(lines, end='')
file.close()

# Чтение блоками по байтам

print('\n\n', '=' * 20)
file = open('dat.txt', 'r')
while True:
    byte = file.read(20)
    if not byte:
        break
    print(byte)
file.close()


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-i686/egg/tests/test_platform.py
# Compiled at: 2011-04-20 15:31:07
import unittest, os, sys, tempfile
from linkexchange.platform import Platform
from linkexchange.config import file_config
from test_clients import SapeTestServer

class SapeTestServer1(SapeTestServer):
    data = {'/': [
           'xlink1',
           'xlink2'],
       '/path/1': [
                 'xlink1',
                 'xlink2',
                 'xlink3',
                 'xlink4'],
       '/path/2': [
                 'Plain text and link text'],
       '__sape_new_url__': '',
       '__sape_delimiter__': '. '}

class SapeTestServer2(SapeTestServer):
    data = {'/': [
           'ylink1'],
       '__sape_new_url__': '',
       '__sape_delimiter__': '. '}

class PlatformTestCase(unittest.TestCase):

    def setUpClass(cls):
        cls.server1 = SapeTestServer1()
        cls.server2 = SapeTestServer2()
        clients = [
         ('sape', [],
          dict(user='user123456789', db_driver=('mem', ), server_list=[
           cls.server1.url.replace('%', '%%')])),
         (
          'sape', [],
          dict(user='user123456789', db_driver=('mem', ), server_list=[
           cls.server2.url.replace('%', '%%')]))]
        cls.platform = Platform(clients=clients)

    setUpClass = classmethod(setUpClass)

    def tearDownClass(cls):
        del cls.platform
        del cls.server1
        del cls.server2

    tearDownClass = classmethod(tearDownClass)

    def testGetRawLinks(self):
        lx = self.platform.get_raw_links('http://example.com/')
        self.assertEqual(unicode(lx[0]), 'xlink1')
        self.assertEqual(unicode(lx[1]), 'xlink2')
        self.assertEqual(unicode(lx[2]), 'ylink1')

    def testGetBlocks(self):
        formatters = [
         (
          'inline', [2],
          dict(class_='links', class_for_empty='empty', suffix='. ')),
         (
          'list', [None], dict(id='links'))]
        bx = self.platform.get_blocks('http://example.com/', formatters)
        self.assertEqual(unicode(bx[0]), '
xlink1. xlink2.
')
        self.assertEqual(unicode(bx[1]), '

ylink1

')
        bx = self.platform.get_blocks('http://example.com/notexists', formatters)
        self.assertEqual(unicode(bx[0]), '

')
        self.assertEqual(unicode(bx[1]), '')
        bx = self.platform.get_blocks('http://example.com/path/1', formatters)
        self.assertEqual(unicode(bx[0]), '
xlink1. xlink2.
')
        self.assertEqual(unicode(bx[1]), '

xlink3

xlink4

')
        formatters = [
         (
          'inline', [None], dict()),
         (
          'inline', [None], dict(client=1))]
        bx = self.platform.get_blocks('http://example.com/', formatters)
        self.assertEqual(unicode(bx[0]), '
ylink1
')
        self.assertEqual(unicode(bx[1]), '
xlink1xlink2
')
        return

class PlatformConfigTestCase(PlatformTestCase):
    linkexchange_cfg = '\n[client-1]\ntype = sape\nuser = user123456789\ndb_driver.type = mem\nserver-1 = %(server1)s\n\n[client-2]\ntype = sape\nuser = user123456789\ndb_driver.type = mem\nserver-1 = %(server2)s\n'

    def setUpClass(cls):
        cls.server1 = SapeTestServer1()
        cls.server2 = SapeTestServer2()
        cfgfd, cls.cfgfn = tempfile.mkstemp()
        os.close(cfgfd)
        open(cls.cfgfn, 'w').write(cls.linkexchange_cfg % {'server1': cls.server1.url.replace('%', '%%'),
           'server2': cls.server2.url.replace('%', '%%')})
        vars = {}
        result = file_config(vars, cls.cfgfn)
        assert result == [cls.cfgfn]
        cls.platform = vars['platform']

    setUpClass = classmethod(setUpClass)

    def tearDownClass(cls):
        del cls.platform
        del cls.server1
        del cls.server2
        os.unlink(cls.cfgfn)

    tearDownClass = classmethod(tearDownClass)

    def testLXRefresh(self):
        from linkexchange.commands import lxrefresh
        retcode = os.spawnl(os.P_WAIT, sys.executable, sys.executable, lxrefresh.__file__, '-c', self.cfgfn, '-r', 'http://example.com')
        self.assertEqual(retcode, 0)


#!/usr/bin/env python

import os
from mpi4py import MPI
from baselines.common import set_global_seeds, tf_util as U
from baselines import bench
import os.path as osp
import gym, logging
from baselines import logger
import sys

def train(env_id, num_timesteps, seed):
    from baselines.ppo1 import mlp_policy, pposgd_simple
    rank = MPI.COMM_WORLD.Get_rank()
    os.environ["CUDA_VISIBLE_DEVICES"] = str(rank % 4)
    U.make_session(num_cpu=1, gpu_fraction=.10).__enter__()
    workerseed = seed + 10000 * MPI.COMM_WORLD.Get_rank()
    set_global_seeds(workerseed)
    env = gym.make(env_id)
    if rank != 0: logger.set_level(logger.DISABLED)
    def policy_fn(name, ob_space, ac_space):
        return mlp_policy.MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space,
            hid_size=256, num_hid_layers=2)
    env = bench.Monitor(env, logger.get_dir() and
        osp.join(logger.get_dir(), "monitor.json"))
    env.seed(seed)
    gym.logger.setLevel(logging.WARN)
    pposgd_simple.learn(env, policy_fn,
            max_timesteps=num_timesteps,
            timesteps_per_batch=1250,
            clip_param=0.2, entcoeff=0.0,
            optim_epochs=20, optim_stepsize=1e-4, optim_batchsize=128,
            gamma=0.995, lam=0.95, schedule='constant',
        )
    env.close()

def main():
    import argparse
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='Humanoid-v1')
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    args = parser.parse_args()
    train(args.env, num_timesteps=100e6, seed=args.seed)

if __name__ == '__main__':
    main()


from __future__ import print_function
import numpy as np
import tqdm
import json
import copy
from multiprocessing import Pool
from math import sin, tan, cos
from simple_bicycle_ekf import SimpleBicycleEKF
from matplotlib import pyplot as plt
from noiseestimation.sensor import Sensor
from noiseestimation.correlator import Correlator
from noiseestimation.estimation import (
    estimate_noise_approx,
    estimate_noise_mehra,
    estimate_noise_extended
)

# parameters
runs = 100
skip_initial = 50
num_samples = 250
used_taps = (num_samples - skip_initial) / 2
dt = 0.1
Q = 0.02
var_vel = Q
var_steer = Q
measurement_var = 0.05
R_proto = np.array([[1, 0],
                    [0, 1]])
filter_misestimation_factor = 1
turning_threshold_angle = 0.001
wheelbase = 1

# move simulated robot
def f(x, u):
    heading = x[2, 0]
    vel = u[0, 0]
    steering_angle = u[1, 0]
    dist = vel * dt

    # check whether robot is turning
    if abs(steering_angle) > turning_threshold_angle:
        beta = (dist / wheelbase) * tan(steering_angle)
        r = wheelbase / tan(steering_angle)
        dx = np.array([[-r * sin(heading) + r * sin(heading + beta)],
                       [r * cos(heading) - r * cos(heading + beta)],
                       [beta]])
    else:
        dx = np.array([[dist * cos(heading)],
                       [dist * sin(heading)],
                       [0]])

    return x + dx

def matrix_error(estimate, truth):
    return np.sqrt(np.sum(np.square(truth - estimate)))

def setup():
    # set up sensor simulator
    H = np.array([[1, 0, 0],
                  [0, 1, 0]])

    def h(x):
        return np.dot(H, x)

    x0 = np.array([[0],
                   [-1],
                   [0]])
    sim = Sensor(x0, f, h)

    # set up kalman filter
    tracker = SimpleBicycleEKF(dt, wheelbase, var_vel, var_steer)
    tracker.R = R_proto * measurement_var * filter_misestimation_factor
    tracker.x = np.array([[0, 0, 0]]).T
    tracker.P = np.eye(3) * 500

    return sim, tracker

def filtering(sim, tracker):
    # perform sensor simulation and filtering
    R = R_proto * measurement_var
    readings, truths, filtered, residuals, Ps, Fs, Ks = [], [], [], [], [], [], []
    cmds = [np.array([[0.6],
                      [0.23]])] * (num_samples / 4)
    cmds.extend([np.array([[2],
                           [-0.20]])] * (num_samples / 2))
    cmds.extend([np.array([[1],
                           [0.2]])] * (num_samples / 4))
    for cmd in cmds:
        sim.step(cmd)
        reading = sim.read(R)
        tracker.predict(cmd)
        tracker.update(reading)
        readings.append(reading)
        truths.append(sim.x)
        filtered.append(copy.copy(tracker.x))
        Ps.append(tracker.P)
        residuals.append(tracker.y)
        Fs.append(tracker.F)
        Ks.append(tracker.K)

    readings = np.asarray(readings)
    truths = np.asarray(truths)
    filtered = np.asarray(filtered)
    Ps = np.asarray(Ps)
    residuals = np.asarray(residuals)
    Fs = np.asarray(Fs)
    Ks = np.asarray(Ks)
    return readings, truths, filtered, residuals, Ps, Fs, Ks

def perform_estimation(residuals, tracker, H, F_arr, K_arr):
    cor = Correlator(residuals)
    correlation = cor.autocorrelation(used_taps)
    R_extended = estimate_noise_extended(
        correlation, K_arr, F_arr, H)
    R_mehra = estimate_noise_mehra(
        correlation, K_arr[-1], F_arr[-1], H)
    R_approx = estimate_noise_approx(
        correlation[0], H, tracker.P)
    truth = R_proto * measurement_var
    error_extended = matrix_error(R_extended, truth)
    error_mehra = matrix_error(R_mehra, truth)
    error_approx = matrix_error(R_approx, truth)
    return (error_extended, error_mehra, error_approx)

def plot_results(readings, filtered, truths, Ps):
    axarr = [plt.subplot()]

    axarr[0].plot(
        readings[:, 0],
        readings[:, 1],
        'o', label="Readings"
    )
    axarr[0].plot(
        truths[:, 0],
        truths[:, 1],
        'k', linewidth=3, label="Truth")
    axarr[0].plot(
        filtered[:, 0],
        filtered[:, 1],
        linewidth=3, label="Filter")
    axarr[0].legend(loc="lower right")
    axarr[0].set_title("Kalman filtering of position")
    axarr[0].set_xlabel("x (m)")
    axarr[0].set_ylabel("y (m)")
    axarr[0].axis('scaled')

    # axarr[0].plot(Ps[:, 0, 0], 'g', label="X state variance")
    # axarr[0].plot(Ps[:, 1, 1], 'r', label="Y state variance")
    # axarr[0].legend(loc="upper right")
    # axarr[0].set_ylim((0, 0.003))
    # axarr[0].set_ylabel("$\sigma^2$ ($m^2$)")
    # axarr[0].set_xlabel("Sample")
    # axarr[0].set_title("State covariance")

    plt.show()

def run_tracker(dummy):
    sim, tracker = setup()
    readings, truths, filtered, residuals, Ps, Fs, Ks = filtering(sim, tracker)
    errors = perform_estimation(
        residuals[skip_initial:], tracker, tracker.H,
        Fs[skip_initial:], Ks[skip_initial:])
    # plot_results(readings, filtered, truths, Ps)
    state_error = np.sqrt(np.sum(np.square(truths-filtered)[50:, [0, 1], 0]))
    if state_error > 1.5:
        print("WARNING: Outlier (%.6f)" % state_error)
    return errors

if __name__ == "__main__":
    pool = Pool(8)
    args = [0] * runs
    pbar = tqdm.tqdm(total=runs)
    errors_arr = []
    for errors in pool.imap_unordered(run_tracker, args, chunksize=2):
        pbar.update()
        errors_arr.append(errors)
    pbar.close()
    pool.close()
    pool.join()

    errors_arr = np.asarray(errors_arr)
    avg_errors = np.sum(errors_arr, axis=0) / float(runs)
    matrix_size = matrix_error(R_proto * measurement_var, 0)
    rel_errors = avg_errors / matrix_size
    print("Max. error: %.6f" % np.max(errors_arr))
    # ddof = 1 assures an unbiased estimate
    # variances = np.var(errors_arr, axis=0, ddof=1)
    print("-" * 20)
    print("Extended estimation:")
    print("\tAverage Error: %.6f" % avg_errors[0])
    print("\tRelative Error: %.6f" % rel_errors[0])
    print("Mehra estimation:")
    print("\tAverage Error: %.6f" % avg_errors[1])
    print("\tRelative Error: %.6f" % rel_errors[1])
    print("Approximate estimation:")
    print("\tAverage Error: %.6f" % avg_errors[2])
    print("\tRelative Error: %.6f" % rel_errors[2])

    res = {}
    res["types"] = ["Extended", "Mehra", "Mohamed"]
    res["abs_err"] = avg_errors.tolist()
    res["rel_err"] = rel_errors.tolist()
    with open("results.json", "w") as outfile:
        json.dump(res, outfile)


from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable

class LocationAttention(nn.Module):
    """
    Calculates context vector based on previous decoder hidden state (query vector),
    encoder output features, and convolutional features extracted from previous attention weights.
    Attention-Based Models for Speech Recognition
    https://arxiv.org/pdf/1506.07503.pdf

    Query vector is either the previous output or the last decoder hidden state.

    Note: modified for bilinear dot product attention instead of bahandanau attention
    """

    def __init__(self, dim, num_location_features=32):
        super(LocationAttention, self).__init__()
        self.conv = nn.Conv1d(in_channels=1, out_channels=num_location_features,
                              kernel_size=31, padding=15)
        self.W = nn.Linear(dim, dim, bias=False)
        self.L = nn.Linear(num_location_features, dim, bias=False)

    def score(self, query_vector, encoder_out, mask=None):
        # linear transform encoder out (seq, batch, dim)
        encoder_out = self.W(encoder_out)
        # (batch, seq, dim) | (2, 15, 50)
        encoder_out = encoder_out.permute(1, 0, 2)
        if isinstance(mask, Variable):
            conv_features = self.conv(mask.permute(0, 2, 1))  # (batch, dim , seq)
            encoder_out = encoder_out + self.L(conv_features.permute(0, 2, 1))  # (batch, seq , dim)
        # (2, 15, 50) @ (2, 50, 1)
        return encoder_out @ query_vector.permute(1, 2, 0)

    def forward(self, query_vector, encoder_out, mask=None):
        energies = self.score(query_vector, encoder_out)
        mask = F.softmax(energies, dim=1)
        context = encoder_out.permute(
            1, 2, 0) @ mask  # (batch, dim, seq) @ (batch, seq, dim)
        context = context.permute(2, 0, 1)  # (seq, batch, dim)
        return context, mask


# Pattern matching with regular expressions

def isPhoneNumber(text):
	if len(text) != 12:
		return False
	for i in range(0,3):
		if not text[i].isdecimal():
			return False
	if text[3] != '-':
		return False
	for i in range(4,7):
		if not text[i].isdecimal():
			return False
	if text[7] != '-':
		return False
	for i in range(8,12):
		if not text[i].isdecimal():
			return False
	else:
		return True

def checkPhoneNumber():

	message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'

	for i in range(len(message)):
		if isPhoneNumber(message[i:i+12]):
			print(message[i:i+12] + ' is a phone number')

import re
def isPhoneNumber2():
	phoneNumRegex = re.compile(r'(\d{3})-(\d{3}-\d{4})')
	mo = phoneNumRegex.search('My number is 415-555-4242.')
	print('Phone number found: ' + mo.group())
	areaCode, mainNumber = [mo.group(1),mo.group(2)]
	print('Area code is ' + areaCode)
	print('Main number is ' + mainNumber)

def testRe():
	number = re.compile(r'\d{4} \d{2} \d{3} \d{2}')
	hey = number.search('This is a bank number 3413 43 341 31')
	print('Bank number found: ' + hey.group())

def hero1():
	heroRegex = re.compile(r'Batman|Tina Fey')
	mo1 = heroRegex.search('Batman and Tina Fey')
	print(mo1.group())

def hero2():
	batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
	mo = batRegex.search('Its a cool Batcopter and a cool Batmobile')
	print(mo.group())

def hero3():
	batRegex = re.compile(r'Bat(wo)?man')
	mo1 = batRegex.search('The adventures of Batman')
	print(mo1.group())

def reTest():
	text = 'Two people mentioned are Oski, and John'
	search = re.compile(r'Oski|John|Albin|Petter')
	mo = search.search(text)
	print(mo.group())

def reFindAll():
	text = 'Two people mentioned are Oski, and John'
	search = re.compile(r'Oski|John|Albin|Petter')
	mo = search.findall(text)
	print(mo[0])
	print(mo[1])

def FindAllRe():
	text = 'Phone: 513-535-6444, Work: 513-753-3555'
	phoneRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
	mo = phoneRegex.findall(text)
	print('Phone: ' + mo[0] + ', work: ' + mo[1])

def vowel():
	vowelRegex = re.compile(r'a|e|i|o|u|y|A|E|I|O|U|Y')
	mo = vowelRegex.findall('This is a sentence HELLO')
	print(mo)

def testSearchWord():
	wordRegex = re.compile(r'bitch|sal(mon|sitcha)')
	mo = wordRegex.findall('This thing contains salsitcha, bitch')
	print(mo)

def at():
	atRegex = re.compile(r'..at')
	mo = atRegex.findall('The cat in the hat shat on the mat that')
	print(mo)

# import re
# sentence = "is2 Thi1s T4est 3a"
# splitSentence = sentence.split()
# newSentence = ('a '*len(splitSentence)).split()
# for i in splitSentence:
# 	print(i)
# 	regex = re.compile(r'\d')
# 	mo = regex.search(i)
# 	print(mo.group())
# 	print(int(mo.group())-1)
# 	newSentence[int(mo.group())-1] = i
# print(newSentence)
# print(' '.join(newSentence))


from rest_framework import serializers
from .models import Job, JobLevelOne, JobLevelTwo, JobAblityShip
from ablitys.serializers import AblityListSerializer

class JobSerializer(serializers.ModelSerializer):
    ablitys = AblityListSerializer(many=True)
    level_one = serializers.CharField()
    level_two = serializers.StringRelatedField()

    class Meta:
        model = Job
        fields = '__all__'

class JobLevelOneSerializer(serializers.ModelSerializer):

    class Meta:
        model = JobLevelOne
        fields = '__all__'

class JobLevelTwoSerializer(serializers.ModelSerializer):

    class Meta:
        model = JobLevelTwo
        fields = '__all__'

class JobListSerializer(serializers.ModelSerializer):
    level_one = serializers.CharField()
    level_two = serializers.StringRelatedField()
    ablity = serializers.IntegerField()
    question = serializers.IntegerField()

    class Meta:
        model = Job
        exclude = ('ablitys',)


"""DNA and RNA sequences are often represented using a string of bases.
'GGAAUGGCUUUU'. Write a method that takes in a sequence as a string and returns
the count for each base in the sequence. Include any test functions or classes
you use to verify that your method works as expected."""
import unittest
# from collections import Counter

def count_base_sequence(seq):
    base_counts = {}
    for l in seq:
        if l in base_counts:
            base_counts[l] += 1
        else:
            base_counts[l] = 1
    return base_counts.items()

class CountBaseSequenceTest(unittest.TestCase):

    def test_count_base_sequence(self):
        self.assertEqual(count_base_sequence('GGAAUGGCUUUU'), [('A', 2), ('C', 1), ('U', 5), ('G', 4)])

if __name__ == '__main__':
    unittest.main()


# fig_ggn_dep_gbar_corr_kc_spikes.py ---
# Author: Subhasis  Ray
# Created: Thu Dec 27 17:17:29 2018 (-0500)
# Last-Updated: Fri Jan 11 17:23:30 2019 (-0500)
#           By: Subhasis  Ray
# Version: $Id$

# Code:

"""Attempt to correlate GGN depolarization and GGN-KC gbar to KC spike stats"""

from __future__ import print_function
import sys
if sys.platform == 'win32':
    sys.path.append('D:/subhasis_ggn/model/analysis')
else:
    sys.path += ['/home/rays3/projects/ggn/analysis',
                 '/home/rays3/projects/ggn/morphutils',
                 '/home/rays3/projects/ggn/nrn']
import os
import h5py as h5
import numpy as np
import random
from matplotlib import pyplot as plt
import yaml
import pint
from collections import defaultdict
import pandas as pd
import network_data_analysis as nda
from matplotlib.backends.backend_pdf import PdfPages
import pn_kc_ggn_plot_mpl as myplot
import neurograph as ng
import timeit
from sklearn import cluster, preprocessing
plt.style.use('classic')

_ur = pint.UnitRegistry()
Q_ = _ur.Quantity
# datadir = 'D:\\biowulf_stage\\olfactory_network\\'
datadir = '/data/rays3/ggn/olfactory_network/'

def get_dv_kc_data(fname):
    """Create a dataset where each row contains a KC, its presynaptic GGN
    section, maximum conductance from GGN, peak depolarization of that
    section and the number of spikes generated by that KC"""
    with h5.File(fname, 'r') as fd:
        print(jid, len(nda.get_spiking_kcs(fd)))
        print(yaml.dump(nda.load_config(fd), default_style=''))
        ggn_kc_gbar = pd.DataFrame(fd[nda.ggn_kc_syn_path]['pre', 'post', 'gbar'][:, 0])
        ggn_peak_vm = fd['/data/uniform/ggn_output/GGN_output_Vm'].value.max(axis=1)
        ggn_sec = fd['/data/uniform/ggn_output/GGN_output_Vm'].dims[0]['source']
        ggn_sec_vm = pd.DataFrame(data={'sec': ggn_sec, 'vm': ggn_peak_vm})
        pn_kc_gmax = pd.DataFrame(fd[nda.pn_kc_syn_path]['post', 'gmax'][:, 0])
        pn_kc_gmax_by_kc = pn_kc_gmax.groupby('post').sum().reset_index()
        kc_sc = {kc_st.attrs['source']: len(kc_st) for kc_st in fd[nda.kc_st_path].values()}
    df_kc_sc = pd.DataFrame(data={'kc': list(kc_sc.keys()), 'spike_count': list(kc_sc.values())})
    combined = pd.merge(ggn_kc_gbar, df_kc_sc, left_on='post', right_on='kc')
    combined = pd.merge(combined, ggn_sec_vm, left_on='pre', right_on='sec')
    combined.drop(columns=['pre', 'post'], inplace=True)
    return combined

def hist_2d_spiking_kc_data(data, vm_bins=5, gbar_bins=5):
    """Create 2D histogram of fraction of KCs spiking based with specified number of Vm
    and gbar bins."""
    kc_frac = defaultdict(dict)
    spike_count_frac =  defaultdict(dict)
    vm_cut, vm_bins = pd.cut(data.vm, bins=vm_bins, retbins=True)
    gbar_cut, gbar_bins = pd.cut(data.gbar, bins=gbar_bins, retbins=True)
    for vm_int in vm_cut.cat.categories:
        for gbar_int in gbar_cut.cat.categories:
            kc_frac[vm_int][gbar_int] =  0.0
            spike_count_frac[vm_int][gbar_int] =  0.0
    print(len(list(kc_frac.keys())))
    for key, grp in data.groupby([vm_cut, gbar_cut]):
        if key[0] not in kc_frac:
            print('!!!!', vm_cut)
        spiking = grp.spike_count.nonzero()[0]
        n_spiking = spiking.shape[0]
        spike_count = grp.spike_count.sum()
        frac_spiking = n_spiking * 1.0 / len(grp)
        kc_frac[key[0]][key[1]] = frac_spiking
        print(key, n_spiking)
        spike_count_per_cell = spike_count * 1.0 / len(grp)
        spike_count_frac[key[0]][key[1]] = spike_count_per_cell
    return kc_frac, spike_count_frac

def plot_hist(ddict):
    bins_a =  sorted(list(ddict.keys()))
    bins_b =  None
    z =  None
    for k_a in bins_a:
        if bins_b is None:
            bins_b =  sorted(list(ddict[k_a].keys()))
            z =  np.zeros((len(bins_a),  len(bins_b)))
            break
    for ia, k_a in enumerate(bins_a):
        for ib, k_b in enumerate(bins_b):
            print(k_a, k_b, ddict[k_a][k_b])
            z[ia,  ib] = ddict[k_a][k_b]
    print('Here')
    x =  [ba.left for ba in bins_a] + [bins_a[-1].right]
    y =  [bb.left for bb in bins_b] + [bins_b[-1].right]
    X, Y = np.meshgrid(x, y)
    fig, ax =  plt.subplots()
    ax.pcolormesh(X, Y, z.T)
    return fig, ax

jids = [
    '16377231',
    '16377233',
    '16377234',
    '16377237']

# for jid in jids:
#     fname = nda.find_h5_file(jid, datadir)
    # with h5.File(fname, 'r') as fd:
    #     print('jid: {}, spiking kcs: {}'.format(jid, len(nda.get_spiking_kcs(fd))))
    #     print(yaml.dump(nda.load_config(fd), default_style='', default_flow_style=''))
#     myplot.plot_spike_rasters(fname)
#     myplot.plot_kc_spike_count_hist(fname)
# plt.show()

# |      jid | ggn-kc gmax | pn-kc gmax | spiking kcs |
# | 16377231 |         0.7 |        3.7 |       10525 |
# | 16377233 |         0.5 |        3.7 |       17708 |
# | 16377234 |         0.9 |        4.0 |       10536 |
# | 16377237 |         0.9 |        4.5 |       37060 |

## Taking 16377231 as a sample
# jid = '16377231'   # Had about 7031 KCs spiking
# fname =  nda.find_h5_file(jid, datadir)
# data =  get_dv_kc_data(fname)

# kc_frac, spike_frac = hist_2d_spiking_kc_data(data)
# for ka, va in kc_frac.items():
#     for kb,  vb in va.items():
#         print(ka, kb, vb)
# plot_hist(kc_frac)

# * all these turned out to spike only at the lowest GGN gbar
# for jid in jids:
#     fname = nda.find_h5_file(jid, datadir)
#     data = get_dv_kc_data(fname)
#     kc_frac, spike_frac = hist_2d_spiking_kc_data(data,  10, 10)
#     fig, ax = plot_hist(kc_frac)
#     fig2, ax2 = plot_hist(spike_frac)
#     # plt.show()

# plt.show()

spike_info_list =  []
fig, ax = plt.subplots(nrows=2, sharex='all')
for jid in jids:
    fname = nda.find_h5_file(jid, datadir)
    data = get_dv_kc_data(fname)
    vm_bins = pd.cut(data.vm, bins=10)
    # gbar_bins = pd.cut(data.gbar, bins=10)
    spike_info = []
    for key, grp in data.groupby(vm_bins):
        spiking = grp.spike_count.nonzero()[0]
        n_spiking = spiking.shape[0]
        spike_count = grp.spike_count.sum()
        frac_spiking = n_spiking * 1.0 / len(grp)
        spike_count_per_cell = spike_count * 1.0 / len(grp)
        spike_info.append({'jid': jid, 'vm_interval': key, 'frac_spiking': frac_spiking/key.length, 'spike_count_per_cell': spike_count_per_cell/key.length})
        # print(key, key.length, len(grp), n_spiking, frac_spiking, spike_count, spike_count_per_cell)
    spike_info_list.append(spike_info)
    spike_info =  pd.DataFrame(spike_info)
    ax[0].plot([vint.mid + 51.0 for vint in spike_info.vm_interval], spike_info.frac_spiking, 'o-', label='spiking KC fraction')
    # plt.legend(loc=3)
    # plt.subplot(212)
    ax[1].plot([vint.mid + 51.0 for vint in spike_info.vm_interval], spike_info.spike_count_per_cell, '^-', label='spikes per KC')

ax[1].set_xlabel('GGN dVm')
ax[0].set_ylabel('Fraction of KCs spiking')
ax[0].set_yticks([0.15, 0.25, 0.35, 0.45, 0.55])
ax[1].set_ylabel('# of spikes per KC')
ax[1].set_yticks([0.2, 1.0, 2.0])

for axis in ax:
    [spine.set_visible(False) for spine in axis.spines.values()]
    axis.tick_params(top=False, right= False)
    # plt.legend(loc=9)

fig.frameon = False
fig.savefig('ggn_peak_kc_spiking_relation.svg', transparent=True)
plt.show()

fig, ax = plt.subplots(nrows=2, sharex='all')
for si in spike_info_list:
    spike_info = pd.DataFrame(si)
    ax[0].plot([vint.mid + 51.0 for vint in spike_info.vm_interval], spike_info.frac_spiking, 'o-', label=spike_info.jid.iloc[0])
    # plt.legend(loc=3)
    # plt.subplot(212)
    ax[1].plot([vint.mid + 51.0 for vint in spike_info.vm_interval], spike_info.spike_count_per_cell, 'o-', label=spike_info.jid.iloc[0])

ax[1].legend()
ax[1].set_xlabel('GGN depolarization (mV)')
ax[0].set_ylabel('Fraction of KCs spiking')
ax[0].set_yticks([0.15, 0.25, 0.35, 0.45, 0.55])
ax[1].set_ylabel('# of spikes per KC')
ax[1].set_yticks([0.2, 1.0, 2.0])

for axis in ax:
    [spine.set_visible(False) for spine in axis.spines.values()]
    axis.tick_params(top=False, right= False)
    # plt.legend(loc=9)

fig.frameon = False
fig.savefig('ggn_peak_kc_spiking_relation.svg', transparent=True)
plt.show()

#
# fig_ggn_dep_gbar_corr_kc_spikes.py ends here


number = input("Please enter a series of numbers, using any separators you like: ")
# number = "9,233;372:036 854;775,807"
separators = ""
count = 0
for x in number:
    if not x.isnumeric():
        separators = separators + x
        count = count + 1

print(separators)
print(count)

values = "".join(char if char not in separators else " " for char in number).split()
print([int(val) for val in values])
print(sum([int(val) for val in values]))


import sys
import time
import os

def menu():
    print("---Bienvenido al triangulo de pascal---")
    time.sleep(1)
    print("Ingresa\n0-Salir\n1-Iniciar el programa")
    valor = int(input())

    if valor == 0:
        SystemExit()
    elif valor == 1:
        pascal()
    elif valor >= 2:
        print("Te crees gracioso? 7u7, pues dejame decirte que no UwU")
        return menu()

def pascal():
    listBase = [1,1]
    listDeList = [1]

    listDos = []

    print("-----Ejercicio de Pascal-----")
    print("Ingresa el valor limite para el triangulo: ")
    num = int(input())
    time.sleep(1)

    print(listDeList)
    print(listBase)
    for ciclo in range(2, num):
       for ciclo2 in range(0, ciclo):
           if ciclo2 == 0 or ciclo2 == ciclo - 1:
                listDos.append(1)
           if ciclo2 != (ciclo - 1):
               listDos.append(listBase[ciclo2] + listBase[ciclo2 + 1])
       print(listDos)
       listBase = listDos.copy()
       listDos.clear()

    return menu()
menu()


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 17 12:21:02 2016

@author: atschmidt
"""

from nipype.pipeline.engine import Node, Workflow
import nipype.interfaces.utility as util
import nipype.interfaces.io as nio
import nipype.interfaces.fsl as fsl
import nipype.algorithms.rapidart as ra
from functions import motion_regressors, selectindex, nilearn_denoise, fix_hdr

# read in subjects and file names

subjects = [['P46','XXXX']]
sessions=['d0']

# directories
working_dir = '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/working_dir'
out_dir = '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/final/'

# main workflow
preproc_nuisance_regress = Workflow(name='func_preproc_nuisance_regress')
preproc_nuisance_regress.base_dir = working_dir
preproc_nuisance_regress.config['execution']['crashdump_dir'] = preproc_nuisance_regress.base_dir + "/crash_files"

# iterate over subjects
subject_infosource = Node(util.IdentityInterface(fields=['subjectlist']),
                  name='subject_infosource')
subject_infosource.iterables=[('subjectlist', subjects)]

# iterate over sessions
session_infosource = Node(util.IdentityInterface(fields=['session']),
                  name='session_infosource')
session_infosource.iterables=[('session', sessions)]

# select files

templates={'unwarped_file' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/working_dir/func_preproc/_session_{session}/_subjectlist_{proband}.{subject}/fugue/corr_{subject}_{session}_S3_RS_ep2d_SMS6_TR1p1_TE22_FA40_1p2_FatSat_Echo_0_Te22_roi_unwarped.nii.gz',
           #'unwarped_file' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/fugue/corr_{subject}_{session}_S3_RS_ep2d_SMS6_TR1p1_TE22_FA40_1p2_FatSat_Echo_0_Te22_roi_unwarped.nii.gz',
           'slicemoco_par_file' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/working_dir/func_preproc/_session_{session}/_subjectlist_{proband}.{subject}/spacetime_realign/{subject}_{session}_S3_RS_ep2d_SMS6_TR1p1_TE22_FA40_1p2_FatSat_Echo_0_Te22_roi.nii.gz.par',
           # need brain mask, csf and wm mask in functional space - from cbstools coreg pipeline
#           'gm_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/mappings/{subject}_{session}_S7_MP2RAGE_0p7_INV2_Te2_transform_clone_stripmask_clone_transform_def.nii.gz',
#           'gm_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/masks/{subject}_{session}_brainmask_rsfmri.nii.gz',
           # use gm mask instead of gm
           'gm_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/masks/{subject}_{session}_GM_mask_rsfmri.nii.gz',
#           'csf_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/mappings/{subject}_{session}_S5_MP2RAGE_0p7_T1_Images_Te2_clone_transform_strip_clone_reg_bound_seg_binmask_CSF_def.nii.gz',
#           'wm_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/mappings/{subject}_{session}_S5_MP2RAGE_0p7_T1_Images_Te2_clone_transform_strip_clone_reg*_bound_seg_binmask_WM_def.nii.gz'}
           'csf_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/masks/{subject}_{session}_CSF_mask_rsfmri.nii.gz',
           'wm_mask' : '/nobackup/eminem2/schmidt/MMPIRS/preprocessing/{subject}/masks/{subject}_{session}_WM_mask_corrected_rsfmri.nii.gz'}

selectfiles = Node(nio.SelectFiles(templates),
                   name="selectfiles")

preproc_nuisance_regress.connect([(subject_infosource, selectfiles, [(('subjectlist', selectindex, 0), 'subject'),
                                                    (('subjectlist', selectindex, 1), 'proband')]),
                 (session_infosource, selectfiles, [('session', 'session')])
                 ])

# set fsl output type to nii.gz
fsl.FSLCommand.set_default_output_type('NIFTI_GZ')

# fix header of brain mask
fix_header_brainmask = Node(util.Function(input_names=['data_file', 'header_file'],
                            output_names=['out_file'],
                            function=fix_hdr),
                  name='fix_header_brainmask')
preproc_nuisance_regress.connect([(selectfiles, fix_header_brainmask, [('gm_mask', 'data_file'),
                                        ('unwarped_file', 'header_file')]),
])

# fix header of csf mask
fix_header_csfmask = Node(util.Function(input_names=['data_file', 'header_file'],
                            output_names=['out_file'],
                            function=fix_hdr),
                  name='fix_header_csfmask')
preproc_nuisance_regress.connect([(selectfiles, fix_header_csfmask, [('csf_mask', 'data_file'),
                                        ('unwarped_file', 'header_file')]),
])

# fix header of csf mask
fix_header_wmmask = Node(util.Function(input_names=['data_file', 'header_file'],
                            output_names=['out_file'],
                            function=fix_hdr),
                  name='fix_header_wmmask')
preproc_nuisance_regress.connect([(selectfiles, fix_header_wmmask, [('wm_mask', 'data_file'),
                                        ('unwarped_file', 'header_file')]),
])

# merge images into list
masklist = Node(util.Merge(2),name='masklist')
preproc_nuisance_regress.connect([(fix_header_csfmask, masklist, [('out_file', 'in1')]),
                 (fix_header_wmmask, masklist, [('out_file', 'in2')]),
                 ])

# perform artefact detection
artefact=Node(ra.ArtifactDetect(save_plot=True,
                                use_norm=True,
                                parameter_source='NiPy',
                                mask_type='file',
                                norm_threshold=1,
                                zintensity_threshold=3,
                                use_differences=[True,False]
                                ),
             name='artefact')

preproc_nuisance_regress.connect([(selectfiles, artefact, [('unwarped_file', 'realigned_files'),
                                        ('slicemoco_par_file', 'realignment_parameters')]),
                 (selectfiles, artefact, [('gm_mask', 'mask_file')]),
                 ])

# calculate motion regressors

motreg = Node(util.Function(input_names=['motion_params', 'order','derivatives'],
                            output_names=['out_files'],
                            function=motion_regressors),
                 name='motion_regressors')
motreg.inputs.order=1
motreg.inputs.derivatives=1
preproc_nuisance_regress.connect([(selectfiles, motreg, [('slicemoco_par_file','motion_params')])])

def makebase(subject, out_dir):
    return out_dir + subject[1]

denoise = Node(util.Function(input_names=['in_file',
                                          'gm_mask',
                                          'wm_mask',
                                          'csf_mask',
                                          'motreg_file',
                                          'outlier_file',
                                          'bandpass',
                                          'tr'],
                             output_names=['denoised_file',
                                           'confounds_file'],
                             function=nilearn_denoise),
               name='denoise')

denoise.inputs.tr = 1.13
denoise.inputs.bandpass = [0.1, 0.01]

preproc_nuisance_regress.connect([(selectfiles, denoise, [('unwarped_file', 'in_file')]),
                                  (fix_header_brainmask, denoise, [('out_file', 'gm_mask')]),
                                  (fix_header_wmmask, denoise, [('out_file', 'wm_mask')]),
                                  (fix_header_csfmask, denoise, [('out_file', 'csf_mask')]),
                                 #(motreg, denoise, [('out_files', 'motreg_file')]),
                                 (motreg, denoise, [(('out_files',selectindex,[0]), 'motreg_file')]),
                                 (artefact, denoise, [('outlier_files', 'outlier_file')])])

# sink relevant files
sink = Node(nio.DataSink(parameterization=False),
             name='sink')

preproc_nuisance_regress.connect([(session_infosource, sink, [('session', 'container')]),
                 (subject_infosource, sink, [(('subjectlist', makebase, out_dir), 'base_directory')]),
                (fix_header_brainmask, sink, [('out_file', 'confounds@new_brainmask_header')]),
                (fix_header_csfmask, sink, [('out_file', 'confounds@new_csfmask_header')]),
                (fix_header_wmmask, sink, [('out_file', 'confounds@new_wmmask_header')]),
                (artefact, sink, [('norm_files', 'confounds.@norm_motion'),
                                  ('outlier_files', 'confounds.@outlier_files'),
                                  ('intensity_files', 'confounds.@intensity_files'),
                                  ('statistic_files', 'confounds.@outlier_stats'),
                                  ('plot_files', 'confounds.@outlier_plots')]),
                 (motreg, sink, [('out_files', 'confounds.@motreg')]),
                 (denoise, sink, [('denoised_file', 'final.@final'),
                                  ('confounds_file', 'confounds.@all')])])

#preproc_nuisance_regress.run(plugin='MultiProc', plugin_args={'n_procs' : 9})
preproc_nuisance_regress.run()

#preproc_nuisance_regress.write_graph(dotfilename='func_preproc_nuisance_regress.dot', graph2use='colored', format='pdf', simple_form=True)


#
# Solution to Project Euler problem 46

import eulerlib, itertools, sys
if sys.version_info.major == 2:
	filterfalse = itertools.ifilterfalse
else:
	filterfalse = itertools.filterfalse

def compute():
	ans = next(filterfalse(test_goldbach, itertools.count(9, 2)))
	return str(ans)

def test_goldbach(n):
	if n % 2 == 0 or eulerlib.is_prime(n):
		return True
	for i in itertools.count(1):
		k = n - 2 * i * i
		if k <= 0:
			return False
		elif eulerlib.is_prime(k):
			return True

if __name__ == "__main__":
	print(compute())


import os
import csv
from io import StringIO
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from Data_Manager.models import EnvironmentClass
from .models import Environment, EnvironmentBulkUpload

@receiver(post_save, sender=EnvironmentBulkUpload)
def create_bulk_student(sender, created, instance, *args, **kwargs):
  if created:
    opened = StringIO(instance.csv_file.read().decode())
    reading = csv.DictReader(opened, delimiter=',')
    environment = []
    for row in reading:
      if 'stage' in row and row['stage']:
        stage = row['stage']
        platform = row['platform'] if 'platform' in row and row['platform'] else ''
        database = row['database'] if 'database' in row and row['database'] else ''
        run_stack = row['run_stack'] if 'run_stack' in row and row['run_stack'] else ''
        web_server = row['web_server'] if 'web_server' in row and row['web_server'] else ''
        ip_servername = row['ip_servername'] if 'ip_servername' in row and row['ip_servername'] else ''
        hardware = row['hardware'] if 'hardware' in row and row['hardware'] else ''
        product_app = row['product_app'] if 'product_app' in row and row['product_app'] else ''
        provider = row['provider'] if 'provider' in row and row['provider'] else ''
        port = row['port'] if 'port' in row and row['port'] else ''
        created_by = row['created_by'] if 'created_by' in row and row['created_by'] else ''
        creation_date = row['creation_date'] if 'creation_date' in row and row['creation_date'] else ''
        brd = row['brd'] if 'brd' in row and row['brd'] else ''
        if Environment:
          EnvironmentClass, kind = EnvironmentClass.objects.get_or_create(name=Environment)

        check = Environment.objects.filter(stage=stage).exists()
        if not check:
          environment.append(
            Student(
                stage=stage,
                platform=platform,
                database=database,
                run_stack=run_stack,
                web_server=web_server,
                ip_servername=ip_servername,
                hardware=hardware,
                product_app=product_app,
                provider = provider,
                port=port,
                created_by=created_by,
                creation_date=creation_date,
                brd=brd
            )
          )

    environment.objects.bulk_create(environment)
    instance.csv_file.close()
    instance.delete()

def _delete_file(path):
   """ Deletes file from filesystem. """
   if os.path.isfile(path):
       os.remove(path)

@receiver(post_delete, sender=EnvironmentBulkUpload)
def delete_csv_file(sender, instance, *args, **kwargs):
  if instance.csv_file:
    _delete_file(instance.csv_file.path)

@receiver(post_delete, sender=Environment)
def delete_passport_on_delete(sender, instance, *args, **kwargs):
  if instance.brd:
    _delete_file(instance.brd.path)


NTHDIGIT = [
    'first',
    'second',
    'third',
    'fourth',
    'fifth',
    'sixth',
    'seventh',
    'eighth',
    'ninth',
    'tenth',
    'eleventh',
    'twelfth'
]

STUFFS = [
    'a Partridge',
    'two Turtle Doves',
    'three French Hens',
    'four Calling Birds',
    'five Gold Rings',
    'six Geese-a-Laying',
    'seven Swans-a-Swimming',
    'eight Maids-a-Milking',
    'nine Ladies Dancing',
    'ten Lords-a-Leaping',
    'eleven Pipers Piping',
    'twelve Drummers Drumming'
]

def getstuffs(n):
    stuffs = STUFFS[0]
    if n != 0:
        stuffs = ', and ' + stuffs
        stuffs = ', '.join(STUFFS[1:1+n][::-1]) + stuffs

    return stuffs

def sing():
    return verses(1, 12)

def verse(n):
    return "On the %s day of Christmas my true love gave to me, %s in a Pear Tree.\n" % (NTHDIGIT[n - 1], getstuffs(n - 1))

def verses(n, m):
    lyrics = ''
    while n <= m:
        lyrics += verse(n) + '\n'
        n += 1
    return lyrics


"""
actuators.py
Classes to control the motors and servos. These classes
are wrapped in a mixer class before being used in the drive loop.
"""

import time

import donkeycar as dk

from donkeycar.parts.configctrl import myConfig, CONFIG2LEVEL

import logging

class PCA9685:
    '''
    PWM motor controler using PCA9685 boards.
    This is used for most RC Cars
    '''
    def __init__(self, channel, frequency=60, **kwargs):
        import Adafruit_PCA9685
        # Initialise the PCA9685 using the default address (0x40).
        self.pwm = Adafruit_PCA9685.PCA9685( **kwargs)
        self.pwm.set_pwm_freq(frequency)
        self.channel = channel

    def set_pulse(self, pulse):
        self.pwm.set_pwm(self.channel, 0, pulse)

    def run(self, pulse):
        self.set_pulse(pulse)

class PWMSteering:
    """
    Wrapper over a PWM motor cotnroller to convert angles to PWM pulses.
    """
    LEFT_ANGLE = -1
    RIGHT_ANGLE = 1

    def __init__(self, controller=None):

        self.logger = logging.getLogger(myConfig['DEBUG']['PARTS']['ACT-STEERING']['NAME'])
        self.logger.setLevel(myConfig['DEBUG']['PARTS']['ACT-STEERING']['LEVEL'])
        self.controller = controller
        self.left_pulse = myConfig['ACTUATOR']['STEERING_LEFT_PULSE']
        self.right_pulse = myConfig['ACTUATOR']['STEERING_RIGHT_PULSE']
        self.perflogger = dk.perfmon.TaskCycle('SteeringOutput')

    def run(self, angle):
        #map absolute angle to angle that vehicle can implement.
        self.logger.debug('Output angle order= {:01.2f}'.format(angle))
        pulse = dk.utils.map_range(angle,
                                self.LEFT_ANGLE, self.RIGHT_ANGLE,
                                self.left_pulse, self.right_pulse)
#        print ("PWMSteering pulse="+str(pulse))
        self.logger.debug('Output angle pulse= {:03.0f}'.format(pulse))
        dk.perfmon.LogEvent('ActuatorSteering-setPulse')
        self.perflogger.LogCycle()
        self.controller.set_pulse(pulse, 1)

    def shutdown(self):
        self.run(0) #set steering straight

class PWMThrottle:
    """
    Wrapper over a PWM motor cotnroller to convert -1 to 1 throttle
    values to PWM pulses.
    """
    MIN_THROTTLE = -1
    MAX_THROTTLE =  1

    def __init__(self, controller=None):

        self.logger = logging.getLogger(myConfig['DEBUG']['PARTS']['ACT-THROTTLE']['NAME'])
        self.logger.setLevel(myConfig['DEBUG']['PARTS']['ACT-THROTTLE']['LEVEL'])
        self.mode = "user"
        self.kick = []
        #send zero pulse to calibrate ESC
        self.controller = controller
        self.controller.set_pulse(myConfig['ACTUATOR']['THROTTLE_STOPPED_PWM'], 0)
        self.fullspeed_hysteresis = 0
        self.brake_hysteresis = 0
        self.closeup_state = 0
        self.perflogger = dk.perfmon.TaskCycle('ThrottleOutput')
        time.sleep(1)

    def reloadKick(self):
        self.kick = [myConfig['ACTUATOR']['THROTTLE_KICK_PULSE']]*myConfig['ACTUATOR']['THROTTLE_KICK_LENGTH']
        self.logger.debug('Kicker reloaded')

    def run(self, throttle, mode=None, vehicle_armed=None, fullspeed=None, brake=None, lane=None, sensor_left=None, sensor_right=None):

        global myConfig

        if self.mode == "user" and mode != "user":
            self.closeup_state=0
            self.reloadKick()

        if (self.mode != "user" and mode == "user"):
            self.brake_hysteresis = myConfig['ACTUATOR']['BRAKE_HYSTERESIS_LENGTH']
            self.closeup_state=0

        self.mode = mode

        if (fullspeed==None):
            fullspeed = 0
        if (brake==None):
            brake=0

        self.logger.debug('throttle order= {:01.2f}'.format(throttle))

        if ((throttle > 0) or (self.mode != "user")):
            #Forward direction
            pulse = dk.utils.map_range(throttle,
                                    0, self.MAX_THROTTLE,
                                    myConfig['ACTUATOR']['THROTTLE_STOPPED_PWM'], myConfig['ACTUATOR']['THROTTLE_FORWARD_PWM'])
            if (self.mode != "user"):
                # Autonomous mode
                if (myConfig['ACTUATOR']['THROTTLE_CONSTANT_MODE'] == 1):
                    # If constant mode, just apply always kick  as nominal value
                    self.logger.debug('constant speed mode : fullspeed prediction = '+str(fullspeed) + ' brake_decision = '+str(brake))
                    if (brake > myConfig['ACTUATOR']['BRAKE_DECISION_THRESH']):
                        self.logger.debug('constant speed mode : brake')
                        self.brake_hysteresis = myConfig['ACTUATOR']['BRAKE_HYSTERESIS_LENGTH']
                    elif (fullspeed > myConfig['ACTUATOR']['FULLSPEED_DECISION_THRESH']):
                        self.logger.debug('constant speed mode : fullspeed')
                        self.fullspeed_hysteresis = myConfig['ACTUATOR']['FULLSPEED_HYSTERESIS_LENGTH']
                    else:
                        self.logger.debug('constant speed mode : regular speed')
                        pulse = myConfig['ACTUATOR']['THROTTLE_KICK_PULSE']
                else:
                    # Not in constant mode, Ensure thottle order would not go below a limit (risk of motor shutdown)
                    if pulse < myConfig['ACTUATOR']['THROTTLE_MIN_SPD_PULSE']:
                        self.logger.debug('PWMThrottle order too low')
                        pulse = myConfig['ACTUATOR']['THROTTLE_MIN_SPD_PULSE']

                # Motor cann not start at too low throttle, kick it for the first cycles
                if (len(self.kick)>0):
                    self.logger.debug('Kicker active')
                    pulse = self.kick.pop()

        else:
            #reverse direction in manual mode
            pulse = dk.utils.map_range(throttle,
                                    self.MIN_THROTTLE, 0,
                                    myConfig['ACTUATOR']['THROTTLE_REVERSE_PWM'], myConfig['ACTUATOR']['THROTTLE_STOPPED_PWM'])

        if (self.brake_hysteresis>0):
            self.logger.debug('Apply brake for next '+str(self.brake_hysteresis-1)+' cycle')
            pulse = myConfig['ACTUATOR']['THROTTLE_BRAKE_PULSE']
            self.brake_hysteresis -= 1
            if (self.brake_hysteresis == 0):
                self.reloadKick()

        if (self.fullspeed_hysteresis>0):
            self.logger.debug('Apply fullspeed for next '+str(self.fullspeed_hysteresis-1)+' cycle')
            pulse = myConfig['ACTUATOR']['THROTTLE_FULLSPEED_PULSE']
            self.fullspeed_hysteresis -= 1

        if (myConfig['ACTUATOR']['CHALLENGE_CLOSEUP']==1 and self.mode != "user"):
            #rng = max(sensor_left, sensor_right)
            rng = (sensor_left + sensor_right)/2.0
            self.logger.debug('Closeup: Sensor fusion :'+str(rng))

            if (self.closeup_state == 0 and rng<=myConfig['ACTUATOR']['CHALLENGE_TRESH_SLOW']):
                #In normal state, no object detected ahead, regular speed
                pulse=myConfig['ACTUATOR']['THROTTLE_KICK_PULSE']

            if (self.closeup_state == 0 and rng>myConfig['ACTUATOR']['CHALLENGE_TRESH_SLOW']):
                #In normal state, object detected ahead, slowdown
                self.logger.debug('Closeup: Switch to state 1')
                self.closeup_state=1

            if (self.closeup_state==1):
                if (rng<=myConfig['ACTUATOR']['CHALLENGE_TRESH_STOP']):
                    #In slow state, use min speed
                    pulse=myConfig['ACTUATOR']['THROTTLE_MIN_SPD_PULSE']
                    if (rng<=(myConfig['ACTUATOR']['CHALLENGE_TRESH_STOP']-myConfig['ACTUATOR']['CHALLENGE_TRESH_STATE'])):
                        #In slow state, no more object detected ahead, switch back to normal state
                        self.logger.debug('Closeup: Switch to state 0')
                        self.closeup_state=0

                else:
                    #In slow state, very close to object ahead, switch to mode 2
                    self.logger.debug('Closeup: Switch to state 2')
                    self.closeup_state=2

            if (self.closeup_state==2):
                #In stop state, stop car
                pulse=myConfig['ACTUATOR']['THROTTLE_STOPPED_PWM']

            self.logger.debug('Closeup: state :'+str(self.closeup_state))

        self.logger.debug('Output throttle pulse= {:03.0f}'.format(pulse))
        dk.perfmon.LogEvent('ActuatorThrottle-setPulse')
        self.perflogger.LogCycle()
        if (vehicle_armed == True or myConfig['ACTUATOR']['USE_ARM_LOGIC']==0):
            self.controller.set_pulse(pulse, 0)
        else:
            self.controller.set_pulse(1500, 0)

    def shutdown(self):
        self.controller.set_pulse(1500, 0) #stop vehicle

    def gracefull_shutdown(self):
        self.controller.set_pulse(1500, 0) #stop vehicle

class Adafruit_DCMotor_Hat:
    '''
    Adafruit DC Motor Controller
    Used for each motor on a differential drive car.
    '''
    def __init__(self, motor_num):
        from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
        import atexit

        self.FORWARD = Adafruit_MotorHAT.FORWARD
        self.BACKWARD = Adafruit_MotorHAT.BACKWARD
        self.mh = Adafruit_MotorHAT(addr=0x60)

        self.motor = self.mh.getMotor(motor_num)
        self.motor_num = motor_num

        atexit.register(self.turn_off_motors)
        self.speed = 0
        self.throttle = 0

    def run(self, speed):
        '''
        Update the speed of the motor where 1 is full forward and
        -1 is full backwards.
        '''
        if speed > 1 or speed < -1:
            raise ValueError( "Speed must be between 1(forward) and -1(reverse)")

        self.speed = speed
        self.throttle = int(dk.utils.map_range(abs(speed), -1, 1, -255, 255))

        if speed > 0:
            self.motor.run(self.FORWARD)
        else:
            self.motor.run(self.BACKWARD)

        self.motor.setSpeed(self.throttle)

    def shutdown(self):
        self.mh.getMotor(self.motor_num).run(Adafruit_MotorHAT.RELEASE)

class Maestro:
    '''
    Pololu Maestro Servo controller
    Use the MaestroControlCenter to set the speed & acceleration values to 0!
    '''
    import threading

    maestro_device = None
    astar_device = None
    maestro_lock = threading.Lock()
    astar_lock = threading.Lock()

    def __init__(self, channel, frequency = 60):
        import serial

        if Maestro.maestro_device == None:
            Maestro.maestro_device = serial.Serial('/dev/ttyACM0', 115200)

        self.channel = channel
        self.frequency = frequency
        self.lturn = False
        self.rturn = False
        self.headlights = False
        self.brakelights = False

        if Maestro.astar_device == None:
            Maestro.astar_device = serial.Serial('/dev/ttyACM2', 115200, timeout= 0.01)

    def set_pulse(self, pulse):
        # Recalculate pulse width from the Adafruit values
        w = pulse * (1 / (self.frequency * 4096)) # in seconds
        w *= 1000 * 1000  # in microseconds
        w *= 4  # in quarter microsenconds the maestro wants
        w = int(w)

        with Maestro.maestro_lock:
            Maestro.maestro_device.write(bytearray([ 0x84,
                                                     self.channel,
                                                     (w & 0x7F),
                                                     ((w >> 7) & 0x7F)]))

    def set_turn_left(self, v):
        if self.lturn != v:
            self.lturn = v
            b = bytearray('L' if v else 'l', 'ascii')
            with Maestro.astar_lock:
                Maestro.astar_device.write(b)

    def set_turn_right(self, v):
        if self.rturn != v:
            self.rturn = v
            b = bytearray('R' if v else 'r', 'ascii')
            with Maestro.astar_lock:
                Maestro.astar_device.write(b)

    def set_headlight(self, v):
        if self.headlights != v:
            self.headlights = v
            b = bytearray('H' if v else 'h', 'ascii')
            with Maestro.astar_lock:
                Maestro.astar_device.write(b)

    def set_brake(self, v):
        if self.brakelights != v:
            self.brakelights = v
            b = bytearray('B' if v else 'b', 'ascii')
            with Maestro.astar_lock:
                Maestro.astar_device.write(b)

    def readline(self):
        ret = None
        with Maestro.astar_lock:
            # expecting lines like
            # E n nnn n
            if Maestro.astar_device.inWaiting() > 8:
                ret = Maestro.astar_device.readline()

        if ret != None:
            ret = ret.rstrip()

        return ret

class Teensy:
    '''
    Teensy Servo controller
    '''
    import threading

    teensy_device = None
    astar_device = None
    teensy_lock = threading.Lock()
    astar_lock = threading.Lock()

    def __init__(self, channel, frequency = 60):
        import serial

        if Teensy.teensy_device == None:
            Teensy.teensy_device = serial.Serial('/dev/teensy', 115200, timeout = 0.01)

        self.channel = channel
        self.frequency = frequency
        self.lturn = False
        self.rturn = False
        self.headlights = False
        self.brakelights = False

        if Teensy.astar_device == None:
            Teensy.astar_device = serial.Serial('/dev/astar', 115200, timeout = 0.01)

    def set_pulse(self, pulse):
        # Recalculate pulse width from the Adafruit values
        w = pulse * (1 / (self.frequency * 4096)) # in seconds
        w *= 1000 * 1000  # in microseconds

        with Teensy.teensy_lock:
            Teensy.teensy_device.write(("%c %.1f\n" % (self.channel, w)).encode('ascii'))

    def set_turn_left(self, v):
        if self.lturn != v:
            self.lturn = v
            b = bytearray('L' if v else 'l', 'ascii')
            with Teensy.astar_lock:
                Teensy.astar_device.write(b)

    def set_turn_right(self, v):
        if self.rturn != v:
            self.rturn = v
            b = bytearray('R' if v else 'r', 'ascii')
            with Teensy.astar_lock:
                Teensy.astar_device.write(b)

    def set_headlight(self, v):
        if self.headlights != v:
            self.headlights = v
            b = bytearray('H' if v else 'h', 'ascii')
            with Teensy.astar_lock:
                Teensy.astar_device.write(b)

    def set_brake(self, v):
        if self.brakelights != v:
            self.brakelights = v
            b = bytearray('B' if v else 'b', 'ascii')
            with Teensy.astar_lock:
                Teensy.astar_device.write(b)

    def teensy_readline(self):
        ret = None
        with Teensy.teensy_lock:
            # expecting lines like
            # E n nnn n
            if Teensy.teensy_device.inWaiting() > 8:
                ret = Teensy.teensy_device.readline()

        if ret != None:
            ret = ret.rstrip()

        return ret

    def astar_readline(self):
        ret = None
        with Teensy.astar_lock:
            # expecting lines like
            # E n nnn n
            if Teensy.astar_device.inWaiting() > 8:
                ret = Teensy.astar_device.readline()

        if ret != None:
            ret = ret.rstrip()

        return ret

class MockController(object):
    def __init__(self):
        pass

    def run(self, pulse):
        pass

    def shutdown(self):
        pass


n = int(input())
h = list(map(int, input().split()))

INF = 10 ** 5 + 1

dp = [INF] * n

dp[0] = 0
dp[1] = abs(h[1] - h[0])

for i in range(2, n):
    skip1 = dp[i - 1] + abs(h[i] - h[i - 1])
    skip2 = dp[i - 2] + abs(h[i] - h[i - 2])
    dp[i] = min(skip1, skip2)

print(dp[-1])


from django.shortcuts import render
from django.http import HttpResponseNotAllowed

from . import models
from . import forms

def cadastro(request):
    form= forms.SerieForm()
    if request.method == 'POST':
        print('vou salvar os dados!!')
        form=forms.SerieForm(request.POST)
        print(form)
        if form.is_valid():
            form.save(commit=True)
        else:
            print('ERROR')
    series_list=models.Serie.objects.order_by('nome')
    data_dict = {'serie_records':series_list , 'form':form}
    return render(request, 'serie/serie.html', data_dict)

def delete(request, id):
    try:
        models.Serie.objects.filter(id=id).delete()
        form=forms.SerieForm();
        series_list=models.Serie.objects.order_by('nome')
        data_dict={'form':form, 'serie_records':series_list}
        return render(request, 'serie/serie.html', data_dict)
    except:
        return HttpResponseNotAllowed()

def update(request, id):
    item= models.Serie.objects.get(id=id)
    if request.method=='GET':
        form=forms.SerieForm(initial={'nome':item.nome, 'idGenero':item.idGenero})
        data_dict={'form':form}
        return render(request,'serie/serie_upd.html', data_dict)
    else:
        form=forms.SerieForm(request.POST)
        item.nome=form.data['nome']
        item.idGenero_id=form.data['idGenero'] # COLOQUEI O  _id  PQ SE NAO ELE NAO VAI PEGAR REALMENTE O id, E SIM A DESCRICAO DO GENERO
        item.save()
        form = forms.SerieForm()
        series_list=models.Serie.objects.order_by('nome')
        data_dict={'form':form, 'serie_records':series_list}
        return render(request, 'serie/serie.html', data_dict)