import os
import subprocess

__author__ = 'delur'

def build_pairwise_alignments(protein, constants, overwrite):
    if not os.path.exists(constants["needle_dir"]):
        os.makedirs(constants["needle_dir"])

    def runNeedle(protein, paths):
        if os.path.isfile(os.path.join(constants["mfasta"], protein + ".clean")):
            if os.stat(os.path.join(constants["mfasta"], protein + ".clean")).st_size == 0:
                return
            else:
                subprocess.call([paths["needle"], '-asequence' ,os.path.join(paths["fasta"], protein + ".fa"),'-bsequence',os.path.join(paths["mfasta"], protein + ".clean"), '-outfile', os.path.join(paths["needle_dir"], protein + ".needle"), '-gapopen', '10.0', '-gapextend', '0.5'])

    if os.path.isfile(os.path.join(constants["needle_dir"], protein + ".needle")):
        if overwrite:
            runNeedle(protein, constants)
    else:
        runNeedle(protein, constants)

    pairwise = {}
    if os.path.isfile(os.path.join(constants["needle_dir"], protein + ".needle")):
        f = open(os.path.join(constants["needle_dir"], protein + ".needle"), 'r')

        first = "-"
        second = "-"
        for line in f:
            if line.startswith("# 1: "):
                first = line.split(':')[1].strip()
                #print first
            elif line == "\n" or line.startswith(' '):
                pass
            elif line.startswith("# 2: "):
                second = line.split(':')[1].strip()
                #print second
                if first is not second:
                    pairwise[(first,second)] = ["",""]
            elif first is not second:
                if line[0:13].rstrip() in first:
                    tmp = line.split()
                    pairwise[(first,second)][0] += tmp[2]
                if line[0:13].rstrip() in second:
                    tmp = line.split()
                    pairwise[(first,second)][1] += tmp[2]
        f.close()

    # for first,second in pairwise:
        # print first
        # print pairwise[(first,second)][0]
        # print pairwise[(first,second)][1]
        # print second
        # print ""

    return pairwise


import pgzrun
from random import randint
WIDTH = 800
HEIGHT = 400
score = 0
speed = 4
game_over = False
fox = Actor("fox")
fox.pos = 100, 100
coin = Actor("coin")
coin.pos = 200, 200
coin2 = Actor("coin")

def draw():
	screen.fill("blue")
	fox.draw()
	coin.draw()
	coin2.draw()

	screen.draw.text("Score: "+ str(score), color="black", topleft=(10, 10))

	if game_over:
		screen.fill("red")
		screen.draw.text("Score: "+ str(score), color="black", topleft=(10, 10), fontsize=60)

def place_coin1():
	coin.x = randint(20, (WIDTH - 20))
	coin.y = randint(20, (HEIGHT - 20))

def place_coin2():
	coin2.x = randint(20, (WIDTH - 20))
	coin2.y = randint(20, (HEIGHT - 20))

def time_up():
	global game_over
	game_over = True

def update():
	global score, speed

	if keyboard.up and keyboard.right:
		fox.y = fox.y - speed
		fox.x = fox.x + speed
	elif keyboard.up and keyboard.left:
		fox.y = fox.y - speed
		fox.x = fox.x - speed
	elif keyboard.down and keyboard.right:
		fox.y = fox.y + speed
		fox.x = fox.x + speed
	elif keyboard.down and keyboard.left:
		fox.y = fox.y + speed
		fox.x = fox.x - speed
	elif keyboard.left:
		fox.x = fox.x - speed
	elif keyboard.right:
		fox.x = fox.x + speed
	elif keyboard.down:
		fox.y = fox.y + speed
	elif keyboard.up:
		fox.y = fox.y - speed

	coin_collected = fox.colliderect(coin)
	coin2_collected = fox.colliderect(coin2)

	if coin_collected:
		score = score + 10
		place_coin1()
		speed = speed + 1
	if coin2_collected:
		score = score + 10
		place_coin2()
		speed = speed + 1

clock.schedule(time_up, 20.0)
place_coin1()
place_coin2()

pgzrun.go()


from tkinter import *
from PIL import ImageTk,Image
from tkinter import messagebox
import pyodbc

def return_book():

    all_bids = []
    bid = book_Info1.get()

    extract_bid = "SELECT bid FROM "+book_Table
    print(extract_bid)
    try:
        cursor.execute(extract_bid)
        for i in cursor.fetchall():
            all_bids.append(i[0])
        print("all Bids",all_bids)

        if bid in all_bids:
            check_Avialable = "SELECT status FROM "+book_Table+" WHERE bid = '"+bid+"'"
            cursor.execute(check_Avialable)

            for i in cursor.fetchall():
                check = i[0]
            if check == "issued":
                status = True
            else:
                status = False

        else:
            messagebox.showinfo('Error','Book ID not Found')

    except:
        messagebox.showinfo("Error","Can't Fatch Book IS's")

    delete_SQL = "DELETE FROM "+issue_Table+" WHERE bid = '"+bid+"'"

    update_Status = "UPDATE "+book_Table+" SET status = 'available' where bid ='"+bid+"'"
    try:
        if bid in all_bids and status == True:
            cursor.execute(delete_SQL)
            conn.commit()
            cursor.execute(update_Status)
            conn.commit()
            messagebox.showinfo("Sucess","Book returned  Sucessfully")
            root.destroy()
        else:
            all_bids.clear()
            messagebox.showinfo("Message","Book Available in Library")
            root.destroy()
            return
    except:
        messagebox.showinfo("Search Error","Book Id not Available,Try Again")

    all_bids.clear()

def return_Book():
    global book_Info1,book_Info2,book_Info3,book_Info4,conn,cursor,book_Table,root,Canvas,issue_Table

    root = Tk()
    root.title("Library")
    root.minsize(width=450,height=450)
    root.geometry('700x700')

    conn = pyodbc.connect(
        'Driver={SQL Server};'
        'Server=LAPTOP-9O99F71M\SQLEXPRESS;'
        'Database=library;'
        'Trusted_Connection=yes;'
        )

    cursor = conn.cursor()

    # name of the table here
    book_Table = 'books'
    issue_Table = "books_issued"

    Canvas1 = Canvas(root)
    Canvas1.config(bg='black')
    Canvas1.pack(expand=True,fill=BOTH)

    heading_Frame1 = Frame(root,bg='#ff6e40',bd=5,relief = RAISED,cursor='target')
    heading_Frame1.place(relx=0.25,rely=0.1,relwidth=0.5,relheight=0.13)

    heading_Label = Label(heading_Frame1,text='Return Books',bg='black',fg='red',font=('Courier',15))
    heading_Label.place(relx=0,rely=0,relwidth=1,relheight=1)

    label_Frame = Label(root,bg='black',relief = RAISED)
    label_Frame.place(relx=0.1,rely=0.4,relwidth=0.8,relheight=0.5)

    label_Frame1 = Label(label_Frame,text="Book ID :- ",bg='black',fg='white')
    label_Frame1.place(relx=0.05,rely=0.5)

    book_Info1 = Entry(label_Frame)
    book_Info1.place(relx=0.3,rely=0.5,relwidth=0.62)

    # Button for Sbumit
    Submit_button = Button(root,text="RETURN",bg='#d1ccc0',fg='black',command=return_book)
    Submit_button.place(relx=0.28,rely=0.9,relwidth=0.18,relheight=0.08)

    # Button for Quit
    quit_button = Button(root,text="Quit",bg='#f7f1e3',fg='black',command = root.destroy)
    quit_button.place(relx=0.5,rely=0.9,relwidth=0.18,relheight=0.08)

    root.mainloop()


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 11:48:03 2015

@author: Vera
"""

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import fnmatch

mobility =  np.empty(15)
mlin = np.empty(15)
i = 0
C_LG = 1e-7 # assumption from DEME-TFSI on MoS2
dimensions = {}
dimensions['sd'] = [25.0,5.0]
dimensions['s1'] = [13.0,1.0]
dimensions['s2'] = [13.0,3.5]
dimensions['s3'] = [16.3,3.5]
dimensions['s4'] = [8.2,1.0]
dimensions['d1'] = [13.0,3.5]
dimensions['d2'] = [21.0,1.0]
dimensions['d3'] = [16.3,1.0]
dimensions['d4'] = [8.2,3.5]
dimensions['12'] = [13.0,2.0]
dimensions['34'] = [8.2,2.0]
dimensions['14'] = [0.5,8.5]
dimensions['23'] = [0.5,8.5]

mobility = {}

source_dir = 'C:/Users/Vera/surfdrive/Werk/Science/Projects/[QDs]Hallbar_and_liquid_gate/measurements_square_lattices/Liquid_gate/9_17_150828_63/devE/'
for file in os.listdir(source_dir):
    if fnmatch.fnmatch(file, '*.npy'):
        filename =  file
        try:
            W,L = dimensions[filename[2]+filename[1]]

        except KeyError:
            W,L = dimensions[filename[1]+filename[2]]

        R = np.load(source_dir + file)
        I_sd = 0.01/R
        plt.figure()
        plt.scatter(np.linspace(0,-0.500, 6), I_sd*1e9)
        fit = np.polyfit(np.linspace(0,-0.500, 6), I_sd[0:6], 1)
        mlin[i] = fit[0]
        p = np.poly1d(fit)
        plt.plot(np.linspace(0, -0.5,100), p(np.linspace(-0.1, -0.5,100))*1e9)
        mobility[filename[1:3]] = np.abs(mlin[i]*(L/W)*(1/(0.01*C_LG)))

        i=i+1


import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

import sys, os, images_rc, util

from odbcview import ODBCView
from switchplu import SwitchPLU

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *

MSL = util.msale_dir()

QUERY_DIR = 'c:/RSS/SavedQueries'

try:
    os.makedirs(QUERY_DIR)
except OSError:
    pass

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        ## main window setup
        self.setMinimumSize(1100, 700)
        self.setWindowTitle("Database Viewer")
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        ## layout settings
        self.layout = QVBoxLayout()
        gridLayout = QGridLayout()
        self.layout.addLayout(gridLayout)
        self.centralWidget.setLayout(self.layout)

        ## widgets
        self.tableList = QComboBox(self)
        self.clearQueryButton = QPushButton("Clear Queries")

        self.submitButton = QPushButton("Submit")
        self.submitButton.clicked.connect(self.submitChanges)
        self.submitButton.setDisabled(True)
        self.revertButton = QPushButton("Revert")
        self.revertButton.clicked.connect(self.revertChanges)
        self.revertButton.setDisabled(True)

        ## Edit Type selector. On Row Change and On Field Change are automatic updates
        ## whereas On Manual Submit will cache changes until Submit is clicked.
        self.editType = QComboBox()
        self.editType.addItems([ 'On Row Change', 'On Field Change', 'On Manual Submit' ])
        self.editType.activated.connect(self.changeMode)
        self.editType.setDisabled(True)
        self.dbTable = QTableView(self)
        self.tableList.activated.connect(self.loadTable)

        self.clearQueryButton.clicked.connect(self.clearQuery)
        self.dbTable.setEditTriggers(QAbstractItemView.NoEditTriggers)

        gridLayout.addWidget(QLabel("Tables"), 0, 0, 1, 7)
        gridLayout.addWidget(QLabel("Edit Table"), 2, 0, 1, 1)
        gridLayout.addWidget(QLabel("Update Type"), 4, 1, 1, 4)
        gridLayout.addWidget(self.editType, 4, 0, 1, 4)
        gridLayout.addWidget(self.submitButton, 6, 0, 1, 4)
        gridLayout.addWidget(self.revertButton, 7, 0, 1, 4)
        gridLayout.addWidget(self.tableList, 1, 0, 1, 7)
        gridLayout.addWidget(self.clearQueryButton, 2, 0, 1, 4)
        gridLayout.addWidget(self.dbTable, 0, 8, 50, 50)

        self.currentDb = None

        self.fillMenuBar()
        self.statusBar()

        if len(sys.argv) >= 2:
            self.accessDB(' '.join(sys.argv[1:]))

    def fillMenuBar(self):
        fileMenu = self.menuBar().addMenu("File")
        openAction = QAction("Open", self)
        openAction.setShortcut(QKeySequence.Open)
        openAction.triggered.connect(self.openDB)
        fileMenu.addAction(openAction)

        editMenu = self.menuBar().addMenu("Edit")
        self.editAction = QAction("Edit Table", self)
        self.editAction.triggered.connect(self.changeMode)
        self.editAction.setCheckable(True)
        editMenu.addAction(self.editAction)

        toolsMenu = self.menuBar().addMenu("Tools")
        queryCreatorAction = QAction("Query Creator", self)
        queryCreatorAction.triggered.connect(self.queryCreator)
        toolsMenu.addAction(queryCreatorAction)

        helpMenu = self.menuBar().addMenu("Help")
        aboutAction = QAction("About", self)
        aboutAction.triggered.connect(self.about)
        helpMenu.addAction(aboutAction)

        switchPLUAct = QAction("Switch PLU", self)
        switchPLUAct.triggered.connect(self.launchSwitchPLU)
        toolsMenu.addAction(switchPLUAct)

    def about(self):
        QMessageBox.information(self, 'About', 'BAKING SODA!', QMessageBox.Ok)
        return

    def launchSwitchPLU(self):
        sp = SwitchPLU(self)
        sp.setAttribute(Qt.WA_DeleteOnClose)
        sp.exec_()

    def toggleEditButtons(self, on_off):
        self.submitButton.setEnabled(on_off)
        self.revertButton.setEnabled(on_off)

    def backupPrompt(self, state):

        if state == Qt.Checked:
            if self.editType.currentIndex() == 2:
                self.toggleEditButtons(False)
            self.editType.setDisabled(False)
        elif state == Qt.Unchecked:
            self.toggleEditButtons(True)
            self.editType.setDisabled(True)

    def submitChanges(self):

        pass

    def revertChanges(self):

        pass

    def changeMode(self, on_off):

        if self.currentDb == None:
            self.editAction.setChecked(False)
            self.statusBar().showMessage("You must open a database before you can edit a table.")
            qDebug("changeMode() open a database first")
        else:
            if self.editAction.isChecked():
                qDebug("changeMode() do you want to edit?")
                reply = QMessageBox.question(self, 'Edit Table', 'Are you sure you want to edit this table?', QMessageBox.Yes | QMessageBox.No)

                if reply == QMessageBox.Yes:
                    self.editAction.setChecked(True)
                    self.toggleEditButtons(on_off)
                    self.dbTable.setEditTriggers(QAbstractItemView.DoubleClicked)
                    qDebug("changeMode() turned editing on")
                else:
                    qDebug("changeMode() canceled editing prompt")
                    self.editAction.setChecked(False)
            else:
                self.editAction.setChecked(False)
                self.toggleEditButtons(on_off)
                self.dbTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
                qDebug("changeMode() turned editing off")

    def openDB(self):

        filename = QFileDialog.getOpenFileName(self, "Open Access Database", MSL, "Microsoft Access (*.mdb *.accdb);;Micro$ale Compacted Database (*.old *.bak)")
        if filename:
            self.accessDB(filename)

    def accessDB(self, dbpath):

        if self.currentDb is not None:
            self.currentDb.close()

        db = QSqlDatabase.addDatabase('QODBC', dbpath)
        db.setDatabaseName(util.odbc_conn_str + dbpath)
        self.currentDb = db

        if not db.open():
            QMessageBox.critical(self, dbpath, "Could not open database: %s" % db.lastError().text())
            return

        self.tableList.clear()
        #self.tableList.addItems(db.tables())

        for tbl in db.tables():
            query = QSqlQuery('SELECT COUNT(*) FROM [%s]' % tbl, self.currentDb)
            query.next()

            self.tableList.addItem('%s (%s)' % (tbl, query.value(0)), tbl)

    def loadTable(self, index):

        qDebug("loadTable() #%d" % index)
        if self.currentDb == None:
            self.statusBar().showMessage("Open a database first before loading tables.")

        tblName = self.tableList.itemData(self.tableList.currentIndex())
        #tblName = self.tableList.currentText()

        qDebug("loadTable() loading table '%s'" % tblName)
        self.model = ODBCView(self)
        self.model.setQuery("SELECT * FROM [%s]" % tblName, self.currentDb)

        if self.model.lastError().isValid():
            QMessageBox.critical(self, "Error", self.model.lastError().text())

        self.statusBar().showMessage("%d records in table." % self.model.rowCount())

        #if not self.model.select():
        #    QMessageBox.critical(self, "Error", self.model.lastError().text())

        self.dbTable.setModel(self.model)
        self.dbTable.show()

        #qDebug("loadTable() select statement: %s" % self.model.selectStatement())

        self.dbTable.resizeColumnsToContents()
        self.dbTable.horizontalHeader().setStretchLastSection(True)
        self.dbTable.show()

    def loadQueries(self):

        ''' load all SQL queries into memory, and add them
        to the combo box with the file contents as the item data.
        we could run into problems if there are several gigs of
        queries to load. tested loading 1,888 queries without delay '''

        self.savedCombo.clear()

        savePath = QDir(QUERY_DIR)

        savePath.setNameFilters(['*.sql'])

        saved = savePath.entryList(QDir.Files)

        self.savedCombo.addItem('', '')
        failedToLoad = [ ]
        for filename in saved:
            try:
                with open(os.path.join(QUERY_DIR, filename), 'rb') as sql:
                    self.savedCombo.addItem(filename, sql.read())
            except IOError:
                ## this should never happen
                failedToLoad.append(filename)

        if failedToLoad:
            ## this should never happen
            QMessageBox.critical(self, "No such file or directory.", "Failed to load %d queries:

%s" % (len(failedToLoad), '
'.join(failedToLoad)))

    def readQuery(self, index):

        ''' Sets the query box to the item data of the combo box index '''

        self.queryBox.setPlainText(self.savedCombo.itemData(index))

    def queryCreator(self):

        self.queryDialog = QDialog(self)
        self.queryDialog.setWindowTitle("Query Creator")
        self.queryDialog.setFixedSize(500, 250)

        layout = QVBoxLayout()
        gridLayout = QGridLayout()
        self.queryDialog.setLayout(layout)

        self.savedCombo = QComboBox()
        self.queryBox = QTextEdit()

        clearButton = QPushButton("Clear")
        clearButton.clicked.connect(self.clearQuery)

        saveButton = QPushButton("Save")
        saveButton.clicked.connect(self.saveQuery)

        saveAsButton = QPushButton("Save As")
        saveAsButton.clicked.connect(self.saveQueryAs)

        deleteButton = QPushButton("Delete")
        deleteButton.clicked.connect(self.deleteQuery)

        executeButton = QPushButton("Execute")
        executeButton.clicked.connect(self.runQuery)

        gridLayout.addWidget(clearButton, 0, 0, 1, 4)
        gridLayout.addWidget(saveButton, 1, 0, 1, 4)
        gridLayout.addWidget(saveAsButton, 2, 0, 1, 4)
        gridLayout.addWidget(deleteButton, 3, 0, 1, 4)
        gridLayout.addWidget(executeButton, 4, 0, 1, 4)
        gridLayout.addWidget(self.savedCombo, 0, 5, 1, 15)
        gridLayout.addWidget(self.queryBox, 1, 5, 10, 15)

        layout.addLayout(gridLayout)

        self.loadQueries()

        self.savedCombo.activated.connect(self.readQuery)

        self.queryDialog.setAttribute(Qt.WA_DeleteOnClose)

        self.queryDialog.exec_()

    def clearQuery(self):

        ''' Reloads current table and index. Also clears out the queryBox if necessary. '''

        index = self.tableList.currentIndex()
        self.loadTable(index)

        if self.savedCombo:
            self.queryBox.clear()

    def saveQuery(self):

        ''' Saves changes to the currently selected query. '''

        index = self.savedCombo.currentIndex()
        saveFile = self.savedCombo.itemText(index)
        data = self.queryBox.toPlainText()

        self.savedCombo.setItemData(index, data)

        with open(os.path.join(QUERY_DIR, saveFile), 'wb') as fh:

            fh.write(self.queryBox.toPlainText())

    def saveQueryAs(self):

        ''' Saves text in TextEdit as a .sql file, reloads all the .sql files
        in QUERY_DIR, then sets the current index to the file name that was just
        saved. Have to use findText because there's no telling where it ends up. '''

        saveFile = QFileDialog.getSaveFileName(self, 'Save File', QUERY_DIR, '.sql')

        if not saveFile:
            self.queryDialog.raise_()
            return

        index = self.savedCombo.currentIndex()

        with open(saveFile, 'wb') as fh:

            fh.write(self.queryBox.toPlainText())

        self.loadQueries()

        self.queryDialog.raise_()

        self.savedCombo.setCurrentIndex(self.savedCombo.findText(os.path.basename(saveFile)))

    def deleteQuery(self):

        ''' Makes sure you're not attempting to delete the empty list item,
        removes the file from the disk, removes the item from the ComboBox,
        and removes the text from the TextEdit '''

        currentQuery = self.savedCombo.currentIndex()
        if currentQuery != 0:
            try:
                os.unlink(os.path.join(QUERY_DIR, self.savedCombo.currentText()))
            except WindowsError:
                pass
                ## file has already been deleted, silently ignore.

            self.loadQueries()

            self.queryBox.clear()

    def runQuery(self):

        if not self.currentDb:
            self.statusBar().showMessage("Must connect to a database first.")
            return

        model = QSqlQueryModel(self)
        model.setQuery(self.queryBox.toPlainText(), self.currentDb)

        self.dbTable.setModel(model)
        self.dbTable.resizeColumnsToContents()
        self.dbTable.horizontalHeader().setStretchLastSection(True)
        self.dbTable.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(':/images/logo.png'))
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())


# -*- coding: utf-8 -*-
"""
Created on Tue Feb  7 11:32:22 2017
@author: lbrein
 ---  与tick 配套对比计算的 kline
    > 1m的 K线 模拟tick预测
    > 定期执行，用于筛选交易对
"""

from com.base.public import public, logger
from com.object.obj_entity import future_baseInfo
import talib as ta
import pandas as pd
import numpy as np
import time
from multiprocessing import Pool, Manager
from com.train.train_future_singleExpect import train_future_singleExpect
from com.base.stat_fun import fisher
import math

# 回归方法
class train_future_macd(train_future_singleExpect):
    """

    """
    iniAmount = 250000  # 单边50万
    csvList = [
        "15_2.0_30_3_2.0_1.5",
        "15_2.0_15_3_2.0_2.5",
        "30_2.0_60_3_2.0_1.5",
    ]

    def __init__(self):
        # 费率和滑点
        super().__init__()

        self.saveDetail = True  # 是否保存明细
        self.isSimTickUse = False  # 是否使用1分钟模拟tick测试，否则直接使用kline回测
        self.topUse = False
        self.isEmptyUse = False
        self.baseInfo = {}

        # 可变参数
        self.periodList = [15, 30, 60]  # 窗体参数
        self.scaleList = [2.0]
        self.klineTypeList = ['15m', '30m', '60m']

        self.widthTimesPeriodList = [3]

        self.superlineList = [2.0]
        self.powline = 0.1
        self.turnlineList = [1.5, 2.0, 2.5]
        self.turnline = 1.5
        self.paramList = ['superline', 'turnline']

        self.shiftScale = 0.527  # 滑点模拟系数
        self.scaleDiff2 = 0.8
        self.scaleDiff = -0.1
        self.processCount = 6

        self.testDays = 90
        # 起始时间
        self.startDate = public.getDate(diff=-self.testDays)  # 60天数据回测
        self.endDate = public.getDate(diff=0)

        self.total_tablename = 'train_total_1'
        self.detail_tablename = 'train_future_1'

        self.method = 'simTick' if self.isSimTickUse else 'quick'
        self.stage = 'dema6'
        self.uidKey = "%s_%s_%s_%s_%s_" + self.method + "_" + self.stage

        # 切换全部计算
        self.isAll = 0

    def iterCond(self):
        # 多重组合参数输出
        keys = self.paramList
        for s0 in self.__getattribute__(keys[0] + 'List'):
            self.__setattr__(keys[0], s0)

            for s1 in self.__getattribute__(keys[1] + 'List'):
                self.__setattr__(keys[1], s1)

                # for s2 in self.__getattribute__(keys[2] + 'List'):
                #    self.__setattr__(keys[2], s2)
                yield '%s_%s' % (str(s0), str(s1))

    def Pool(self):
        time0 = time.time()

        pool = Pool(processes=self.processCount)
        shareDict = Manager().list([])

        Base = future_baseInfo()
        # 交易量大的，按价格排序, 类型:turple,第二位为夜盘收盘时间
        lists = Base.all(vol=100)
        tops = self.tops()
        # 清空数据库
        self.switch()

        for rs in lists:
            # 检查时间匹配
            codes = [rs[0]]
            if self.topUse and codes not in tops: continue
            print(rs)
            if self.isAll == 0 and codes[0] not in ['RB','CU','ZC','FG','SC','MA']:  continue

            for kt in self.klineTypeList:
                #self.start(codes, time0, kt, shareDict)
                try:
                    pool.apply_async(self.start, (codes, time0, kt, shareDict))
                    pass
                except Exception as e:
                    print(e)
                    continue
        pool.close()
        pool.join()

    pointColumns = ['pow', 'powm', 'trend', 'isout']

    def point(self, row, ktype=15):
        wd1, s1, s2, high, low, open, close, top, lower, p_h, p_l, atr, atr1 = (row[key] for key in
                                                                                "wd1,slope,slope60,high,low,open,close,top,lower,p_h,p_l,atr,atr1".split(
                                                                                ","))
        TL, PL= self.turnline,  self.powline
        # trend.

        if close > open:
            trend = 1 if high == open else ((close - open) / (high - open) + 0.5 )
        else:
            trend = -1 if low == open else ((close - open) / (open - low) - 0.5)

        tr = (4 - atr * atr1) if atr > 2 else atr * atr1
        if tr < 0: tr = 0
        # pow
        pow = (wd1 + abs(s1 + s2 +  trend * tr)) / 4

        sign = np.sign(s1) if s1 != 0 else np.sign(trend) if trend != 0 else np.sign(s2)

        isout = -1 if p_h > top else 1 if p_l < lower else 0
        # powm
        powm = -3 * np.sign(trend) if (atr > 3.2) and (np.sign(trend) * isout < 0)  else 2 * sign if (pow > TL) else sign if pow > PL else 0

        columns = self.pointColumns
        return pd.Series([pow, powm, trend, isout], index=columns)

    def sd(self, x):
        s = round(x * 1.5, 0) / 10
        return np.sign(s) * 0.8 - 0.1 if abs(s) > 0.8 else s - 0.1

    def total(self, dfs, dfs2=None, period=60):
        # 计算参数
        df0 = dfs[self.mCodes[0]]
        df0["rel_price"] = close = df0["close"]
        df0["datetime"] = df0.index

        s0 = self.shift[0]
        p_l = df0["p_l"] = (df0["close"] + s0)
        p_h = df0["p_h"] = (df0["close"] - s0)

        # bull
        df0["ma"] = ma = ta.MA(close, timeperiod=period)
        df0["std"] = std = ta.STDDEV(close, timeperiod=period, nbdev=1)
        # 上下柜
        df0["width"] = width = (4 * std / ma * 100).fillna(0)

        # 短期价格波动参数值
        df0["wd1"] = self.stand(ta.LINEARREG_SLOPE(width, timeperiod=2))
        df0["wdstd"] = self.stand(ta.STDDEV(width, timeperiod=10, nbdev=1))

        df0["slope"] = self.stand(ta.LINEARREG_SLOPE(ta.MA(close, timeperiod=3), timeperiod=2))
        #df0["slope30"] = self.stand(ta.LINEARREG_SLOPE(ta.MA(close, timeperiod=period), timeperiod=3))
        df0["slope60"] = self.stand(ta.LINEARREG_SLOPE(ta.MA(close, timeperiod=60), timeperiod=5))
        df0['sd'] = df0['slope60'].apply(lambda x: self.sd(x))

        df0.fillna(0, inplace=True)

        # kdj顶点
        kdjK, kdjD = ta.STOCH(df0["high"], df0["low"], close,
                              fastk_period=5, slowk_period=3, slowk_matype=1, slowd_period=3,
                              slowd_matype=1)

        df0["kdj_d2"] = kdj_d2 = kdjK - kdjD
        df0["kdjm"] = kdj_d2 * kdj_d2.shift(1)
        df0["kdjm"] = df0.apply(lambda row: self.turn(row['kdjm'], row['kdj_d2'], 1), axis=1)

        # SAR
        sar = ta.SAR(df0['high'], df0['low'], acceleration=0.05, maximum=0.2)
        df0['sard'] = sard = close - sar
        df0['sarm'] = sard * sard.shift(1)
        df0['sarm'] = df0.apply(lambda row: self.turn(row['sarm'], row['sard'], 1), axis=1)

        # ATR
        df0['atr'] = ta.ATR(df0['high'], df0['low'], close, timeperiod=1) / ta.ATR(df0['high'], df0['low'], close,
                                                                                timeperiod=period)

        df0['atr1'] = self.stand(ta.ATR(df0['high'], df0['low'], close, timeperiod=period))
        df0['atrb'] = ta.ATR(df0['high'], df0['low'], close, timeperiod=period)

        # 循环 scale
        docs = []
        for scale in self.scaleList:
            for conds in self.iterCond():
                ktype = self.klineType[:-1]

                if self.isAll == 1:
                    b0 = self.baseInfo[self.mCodes[0]]
                    # 修正品种
                    bulltype = b0['bulltype']
                    #if bulltype == 0 and self.turnline > 2.0: continue
                    #if bulltype == 2 and (self.turnline < 2.0 or ktype == '5'): continue

                uid = self.uidKey % (
                    '_'.join(self.codes), str(period), str(scale), ktype,
                    str(self.widthTimesPeriod) + '_' + conds)

                df0["top"], df0["lower"] = df0['ma'] + (scale + df0['sd']) * df0['std'], df0['ma'] - (
                        scale - df0['sd']) * df0['std']

                # 计算关键转折点
                df1 = df0.apply(lambda row: self.point(row, ktype), axis=1)
                for key in self.pointColumns: df0[key] = df1[key]
                df0['isout'] = ta.SUM(df0['isout'], timeperiod=3)

                isCvs = False
                for key in self.csvList:
                    if uid.find(key)>-1:
                         isCvs = True
                         break

                if isCvs:
                    cs = []
                    bans = 'ma,open,close,high,low,p_l,p_h,top,lower,std,delta,volume,sard,rel_price,width,volm,'.split(
                        ',')
                    for c in df0.columns:
                        if c not in bans:
                            cs.append(c)

                    file = self.Rice.basePath + '%s_pre.csv' % (uid)
                    print(uid, '---------------------------- to_cvs', file)
                    df0.to_csv(file, index=0, columns=cs)
                    # self.share.append(self.codes)

                # df0.fillna(0, inplace=True)
                df1 = None
                tot = None
                tot = self.detect(df0, df1, period=period, uid=uid)
                if tot is not None and tot['amount'] != 0:
                    tot.update(
                        {
                            "scale": scale,
                            "code": self.codes[0],
                            "period": period,
                            "uid": uid,
                            "shift": (p_l - p_h).mean(),
                            "std": df0['width'].mean(),
                            "createdate": public.getDatetime()
                        }
                    )
                    docs.append(tot)
        return docs

    # 核心策略部分
    def stageApply(self, df0, df1, period=15, uid=''):
        self.records = []
        """
            布林带策略：
        """
        status, isOpen = 0, 0
        pd2 = self.turnline - 0.20
        b0 = self.baseInfo[self.mCodes[0]]
        # 修正品种
        bulltype = b0['bulltype']

        for i in range(period, len(df0)):
            isRun, isstop = False, 0

            ma, close, p_l, p_h, top, lower, std, kdjm, sarm, pow, powm, sd, isout, atr, atr1, atrb = (
                df0.ix[i, key] for key in
                "ma,close,p_l,p_h,top,lower,std,kdjm,sarm,pow,powm,sd,isout,atr,atr1,atrb".split(","))

            sd2 = (self.scaleDiff2 - sd) * std / 2  # std修正

            if status == 0 and powm in [2, -2] and isOpen not in [6, -6]:
                """
                   突变点处理
                   将布林带策略切换为策略
                """
                status = np.sign(powm)
                if isOpen != 0 and isOpen * status < 0:
                    if self.order(df0.iloc[i], None, 0, uid, df0, isstop=4):
                        isOpen, isRun = 0,  False
                        if bulltype == 0:
                            isOpen, isRun = int(5 * status), True

                elif isOpen == 0 and bulltype ==0 :
                    isOpen, isRun = int(4 * status), True

            elif (sarm * status < 0) or (abs(isOpen) in [4, 5] and isOpen * sarm < 0) or abs(powm)==3:
                """
                    交叉点: sarm结束点
                    1、结束突变状态，变为布林带处理
                    2、根据节点状况开平新仓，状态为6
                """
                # 结束macd状态
                status = 0
                if abs(powm) == 3:
                    # 触底反弹
                    if isOpen != 0 and isOpen * powm < 0:
                       if self.order(df0.iloc[i], None, 0, uid, df0, isstop=6):
                          isOpen, isRun = int(2 * powm), True

                    elif isOpen == 0 :
                        isOpen, isRun = int(2 * powm), True

                elif isOpen != 0 and isOpen * sarm < 0:
                    isOpen, isRun, isstop = 0, True, 5

            elif status == 0:
                """
                    布林带策略处理
                """
                cond1 = (powm == 0 and (atr * atr1) < 1.0)
                if isOpen == 0:
                    # 突变状态开始
                    # 大于上线轨迹
                    if p_h >= top and powm == 0:
                        isOpen, isRun = -1, True

                    elif p_l <= lower and powm == 0:
                        isOpen, isRun = 1, True

                    elif ((p_h + sd2) >= top or (isout < 0 and (p_h - sd2) >= ma)) and pow < (pd2 - sd) and kdjm < 0:
                        isOpen, isRun = -2, True

                    elif ((p_l - sd2) <= lower or (isout > 0 and (p_l + sd2) <= ma)) and pow < (pd2 + sd) and kdjm > 0:
                        isOpen, isRun = 2, True

                # 平仓
                else:
                    sign = np.sign(isOpen)
                    cond3 = (sign * ((p_h if isOpen > 0 else p_l) - ma))
                    #
                    if (cond3 >= - sd2 or sign * isout < 0) and sign * kdjm < 0:
                        if ((p_h + sd2) >= top or (p_l - sd2) <= lower) and pow < pd2:
                            if self.order(df0.iloc[i], None, 0, uid, df0, isstop=1):
                                # 再开盘
                                isOpen, isRun = -2 if (p_h + sd2) >= top else 2, True

                        else:
                            isOpen, isstop = 0, 1
                            isRun = True

                    elif cond3 >= 0 and pow < (self.powline) and cond1:
                        isOpen, isstop = 0, 0
                        isRun = True

                    # 超过2倍 atr，止损
                    else:
                        # 即时收益超出
                        if self.preNode is not None:
                            Pd = self.preNode[0]['price']
                            if (sign * (Pd-close) > 2.0 * atrb) and sign * kdjm < 0:
                                isOpen,  isRun, isstop = 0,True, 7

                    # 周末尾盘

            if isRun:
                self.order(df0.iloc[i], None, isOpen, uid, df0, isstop=isstop)
        return self.records

def main():
    action = {
        "kline": 1,
    }

    if action["kline"] == 1:
        obj = train_future_macd()
        obj.Pool()

if __name__ == '__main__':
    main()


#_*_coding:utf-8_*_

from django.shortcuts import  render,redirect

class BaseKingAdmin(object):
    list_display = []
    list_filters = []
    search_fields = []
    list_per_page = 20
    ordering = None
    filter_horizontal = []
    list_editable = []
    readonly_fields = []
    actions = ["delete_selected_objs",]
    readonly_table = False
    modelform_exclude_fields = []
    add_form = None

    def delete_selected_objs(self,request,querysets):
        app_name = self.model._meta.app_label
        model_name = self.model._meta.model_name
        if self.readonly_table:
            errors = {"readonly_table": "This table is readonly ,cannot be deleted or modified!" }
        else:
            errors = {}
        if request.POST.get("_delete_confirm") == "yes":
            if not self.readonly_table:
                querysets.delete()
            return redirect("/kingadmin/%s/%s/" % (app_name,model_name))
        selected_ids =  ','.join([str(i.id) for i in querysets])
        return render(request,"kingadmin/table_objs_delete.html",{"objs":querysets,
                                                              "admin_class":self,
                                                              "app_name": app_name,
                                                              "model_name": model_name,
                                                              "model_verbose_name": self.model._meta.verbose_name,
                                                              "selected_ids":selected_ids,
                                                              "admin_action":request._admin_action,
                                                              "errors":errors
                                                              })

    def default_form_validation(self):
        '''用户可以在此进行自定义的表单验证，相当于django form的clean方法'''
        pass

class AdminAlreadyRegistered(Exception):
    def __init__(self,msg):
        self.message = msg

class AdminSite(object):
    def __init__(self, name='admin'):
        self.enabled_admins = {}  # model_class class -> admin_class instance
        #self.default_actions = {'delete_selected': actions.delete_selected}
        #self._global_actions = self._actions.copy()

    def register(self,model_class,admin_class=None):
        if model_class._meta.app_label not in self.enabled_admins:
            self.enabled_admins[model_class._meta.app_label] = {} #enabled_admins['crm'] = {}
        # else:
        #     print(self.enabled_admins)
        #     raise AdminAlreadyRegistered("model %s has registered already"% model_class._meta.model_name)
        #admin_obj = admin_class()
        if not admin_class:#no custom admin class , use BaseAdmin
            admin_class = BaseKingAdmin()
        admin_class.model = model_class #绑定model 对象和admin 类

        self.enabled_admins[model_class._meta.app_label][model_class._meta.model_name] = admin_class
        #enabled_admins['app']['tablename'] = tableadmin

site = AdminSite()


import numpy as np
import sklearn.tree
import random

def read_file(filename):
     ## read X
     contexts = []
     d = 0
     fX = open(filename+".X", 'r')
     for line in fX:
         linesp = line.split()
         if d==0: d = len(linesp)
         else: assert(d==len(linesp))
         linesp = [float(x) for x in linesp]
         contexts.append(linesp)

     ## read Y
     labels = []
     all_class = []
     fY = open(filename+".Y", 'r')
     for line in fY:
         linesp = line.split()
         c = int(linesp[0])
         if c not in all_class:
             all_class.append(c)
         labels.append(c)
     K = len(all_class)
     assert(len(contexts)==len(labels))
     print("size=", len(contexts), " #feat=", d, " #class=", K)
     print(all_class)

     return contexts, labels

fn="data/Sensorless/Sensorless.scale"
X,Y = read_file(fn)

Z = list(zip(X, Y))
random.shuffle(Z)
X, Y=zip(*Z)

h = len(X)
tmp = 4*h//5
trainX = X[:tmp]
trainY = Y[:tmp]
testX = X[tmp:]
testY = Y[tmp:]

learning_alg = lambda: sklearn.tree.DecisionTreeClassifier(max_depth=5)

p=0
while np.power(2,p) < len(trainY):
   tmp_list = []
   for r in range(20):
      train_size = int(np.power(2,p))
      train_idx = np.random.choice(len(trainX), train_size, replace=False)
      train_setX = [trainX[i] for i in train_idx]
      train_setY = [trainY[i] for i in train_idx]
      pred = learning_alg()
      pred.fit(train_setX, train_setY)
      result = pred.predict(testX).astype(int)
      accu = 0
      for j in range(len(result)):
         if result[j]==testY[j]:
            accu+=1
      #print(accu/len(result))
      tmp_list.append(accu/len(result))
   print("2^"+str(p), np.mean(tmp_list))
   p+=1


from google.cloud import language_v1
from google.cloud.language_v1 import enums
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = input('Provide location of GCloud Credentials: ')

def get_entities_sentiments(text):
    extract = language_v1.LanguageServiceClient().analyze_entity_sentiment({'content': text,
                                                'type': enums.Document.Type.PLAIN_TEXT,
                                                'language': 'en'},
                                            encoding_type=enums.EncodingType.UTF8)
    entities = []
    for entity in extract.entities:
        #only want entities that are likely to be people
        if enums.Entity.Type(entity.type).name not in ['PERSON', 'PROPER']:
            continue

        entities.append([entity.name,
                        entity.salience,
                        entity.sentiment.score,
                        entity.sentiment.magnitude])
    return(entities)

def get_subreddit_names(path_to_file):
    with open(path_to_file) as f:
        names = f.read().splitlines()
    return names

for subreddit in get_subreddit_names('data\\subreddits\\candidate_subreddits.txt'):
    print('Analyzing sentiment from comments in subreddit r/%s.' %subreddit)

    with open('data\\sentiment data\\Sentiment Data_%s_verbose.txt' %subreddit, 'a') as dest_file_verbose:
        with open('data\\sentiment data\\Sentiment Data_%s_succinct.txt' %subreddit, 'a') as dest_file_succinct:
            with open('data\\comments\\Comments_%s.txt' %subreddit) as f:
                for line in f.readlines():
                    try:
                        line_split = line.split('\t')
                        user = line_split[2]
                        if len(line_split)>=3:
                            comment = line_split[3]
                            entities = get_entities_sentiments(comment)

                            dest_file_verbose.write(user + '\t' + comment + '\t' + str(entities) + '\n')
                            for entity in entities:
                                dest_file_succinct.write(str(entity) + '\n')
                    except:
                        continue


#!/usr/bin/env python

import os
import sys

TEMPORARY_FILE_PATH = "tmp.js"
COMPILER_PATH = os.environ['CLOSURE_COMPILER_PATH']
REPOSITORY_NAME = "DataViewUtils"
REPOSITORY_URL = "http://github.com/ukyo/DataViewUtils"
OUTPUT_NAME = "dataview.utils.min.js"

JS_FILES = (
    "../src/dataview.utils.js",
)

def main(compiler_path):
    os.system("java -jar %s --js %s --js_output_file %s" % (compiler_path, ' '.join(JS_FILES), TEMPORARY_FILE_PATH))
    f = open(OUTPUT_NAME, "w")
    f.write("// %s %s\n" % (REPOSITORY_NAME, REPOSITORY_URL))
    f.write(open(TEMPORARY_FILE_PATH, "r").read())
    f.close()
    os.remove(TEMPORARY_FILE_PATH)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        main(sys.argv[1])
    else:
        main(COMPILER_PATH)


from django.db import migrations
import mptt
import mptt.managers

def rebuild_mptt(apps, schema_editor):
    manager = mptt.managers.TreeManager()
    InventoryItem = apps.get_model('dcim', 'InventoryItem')
    manager.model = InventoryItem
    mptt.register(InventoryItem)
    manager.contribute_to_class(InventoryItem, 'objects')
    manager.rebuild()

class Migration(migrations.Migration):

    dependencies = [
        ('dcim', '0118_inventoryitem_mptt'),
    ]

    operations = [
        migrations.RunPython(
            code=rebuild_mptt,
            reverse_code=migrations.RunPython.noop
        ),
    ]


import pandas as pd

# https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_GDP
df = pd.DataFrame(columns=['Name', 'climate average cel','average jan','average jul','Population', 'Percent of white', 'Percent of black', 'Percent of asian', 'Percent of latino', 'gdp per capita'])
df.loc[len(df.index)] = ['Idaho', '11','-0.7','24','1 841 377','89.1','0.6','1.2','3.0','48845']
df.loc[len(df.index)] = ['Idaho', '11','-0.7','24','1 841 377','89.1','0.6','1.2','3.0','48845']

print(df)


from django.conf.urls import url

from . import views

app_name = 'deployments'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^task-(?P<task_id>[0-9]+)/$', views.task_view, name='task_view'),
    url(r'^task-add/$', views.task_add, name='task_add'),
    url(r'^component/(?P<component>[\w-]+)/$', views.component_view, name='component_view'),
]


from apf.metrics import GenericMetricsProducer
from apf.metrics import DateTimeEncoder
from confluent_kafka import Producer
from apf.core import get_class

import json

class KafkaMetricsProducer(GenericMetricsProducer):
    """Write metrics in a Kafka Topic.

    Useful for high-throughput distributed metrics, a complex architecture can be build using
    Apache Kafka as a queue and writing the metrics inside a time series data store, for example
    Prometheus, InfluxDB or Elasticsearch.

    Parameters
    ----------
    config : dict.
        Parameters passed to the producer.

        - PARAMS: Parameters passed to :class:`apf.producer.KafkaProducer`.
        - TOPIC: List of topics to produce, for example ['metrics'].

    producer : apf.producers.GenericProducer
        An apf producer, by default is :class:`apf.producer.KafkaProducer`.

    """

    def __init__(self, config, producer=None):
        super().__init__(config)
        self.config = config
        if producer is not None:
            self.producer = producer
        else:
            self.producer = Producer(self.config["PARAMS"])
        self.time_encoder = self.config.get("TIME_ENCODER_CLASS", DateTimeEncoder)
        self.dynamic_topic = False
        if self.config.get("TOPIC"):
            self.logger.info(f'Producing metrics to {self.config["TOPIC"]}')
            self.topic = [self.config["TOPIC"]]
        elif self.config.get("TOPIC_STRATEGY"):
            self.dynamic_topic = True
            TopicStrategy = get_class(self.config["TOPIC_STRATEGY"]["CLASS"])
            self.topic_strategy = TopicStrategy(
                **self.config["TOPIC_STRATEGY"]["PARAMS"]
            )
            self.topic = self.topic_strategy.get_topics()
            self.logger.info(f'Using {self.config["TOPIC_STRATEGY"]}')
            self.logger.info(f"Producing to {self.topic}")

    def send_metrics(self, metrics):
        metrics = json.dumps(metrics, cls=self.time_encoder).encode("utf-8")

        if self.config.get("TOPIC_STRATEGY"):
            self.topic = self.topic_strategy.get_topics()
        for topic in self.topic:
            try:
                self.producer.produce(topic, metrics)
            except BufferError as e:
                self.logger.info(f"Error producing metrics: {e}")
                self.logger.info("Calling poll to empty queue and producing again")
                self.producer.poll(1)
                self.producer.produce(topic, metrics)

    def __del__(self):
        self.logger.info("Waiting to produce last messages")
        self.producer.flush()


#! Python 3
# Downloads the youtube videos who's link is already copied

import pyperclip, os, bs4, webbrowser, requests

ulink  = pyperclip.paste();

if len(ulink)==0:
	print('Please copy a valid url\n The downloader will now Exit\n');
	#time.sleep(3)
	exit()

print("The link given is: " + ulink + "\n")

dlink=ulink
ulink = "https://www.gen" + ulink[12:]

print("Searching the for the requested file\n")

res = requests.get(ulink);
soup= bs4.BeautifulSoup(res.text,features='html5lib')

elems= soup.select('a[data-itag="22"]')

if len(elems)!=0:
	webbrowser.open(elems[0].get('href'))

if len(elems)==0:
	print("Sorry, the 720p downloadable file is missing from the Gen repository\n Opening the Save from net website\n")
	import pyperclip
	from selenium import webdriver

	dlink= "https://www.ss"+ dlink[12:]
	browser= webdriver.Firefox()
	browser.get(dlink)

	link = browser.find_elements_by_link_text('Download')

	if len(link)==0:
		print("Downloadable file NOT FOUND, \nExiting... \n")
		exit()

	link[0].click()

print("Commencing the download via Browser\n PLEASE SELECT SAVE AS \n THANK YOU")


from ut import p, p_items

from types import ModuleType

CODE_TEXT_PART_1 = """
def do_something(x: int) -> int:
    a = x * 100
    a = a + x
    return a
"""

CODE_TEXT_PART_2 = """
def do_that(y: int) -> float:
    # z = do_something(y)
    z = 6
    return z - y % 10
"""

def main() -> None:

    # ---
    # FIRST COMPILATION
    # ---
    p("compiling ...")
    obj = compile(CODE_TEXT_PART_1, "bla_module", "exec")

    p("compiled object")
    print(obj)

    p("dir of compiled object")
    obj_props = [
        str(x) for x in dir(obj)
        if not str(x).startswith("__")
    ]
    p_items(obj_props, 10)

    p("co_code")
    print(obj.co_code)

    p("evaluate ...")
    obj_mod = ModuleType("bla_mod")
    eval(obj, obj_mod.__dict__)
    print(dir(obj_mod))

    p("call do_something from obj_mod")
    print(
        "11 -> do_something -> ",
        str(obj_mod.do_something(11))
    )

    # ---
    # SECOND COMPILATION
    # ---
    p("try to use do_something in a different compile")
    obj_2 = compile(CODE_TEXT_PART_2, "bla_module_2", "exec")
    obj_mod_2 = ModuleType("bla_mod_2")
    eval(
        obj_2,
        obj_mod_2.__dict__
    )
    print(dir(obj_mod_2))

    p("use do_that")
    print(
        "11 -> do_that -> ",
        str(obj_mod_2.do_that(22))
    )

    p("DONE")

if __name__ == '__main__':
    main()


import sys
from os.path import *
from setup_utils import parse_command_line, configure_python_paths

# -------------------------------processing command line
if len(sys.argv)>2:

    args = parse_command_line()

else: # emulate command line
    # command_line_emulation_argument_list = ['--subject','R1124J_1',
    #                                         '--task','RAM_FR3',
    #                                         '--workspace-dir','/scratch/busygin/FR3_reports',
    #                                         '--mount-point','',
    #                                         '--python-path','/home1/busygin/ram_utils',
    #                                         '--python-path','/home1/busygin/python/ptsa/build/lib.linux-x86_64-2.7'
    #                                         ]

    command_line_emulation_argument_list = ['--subject','R1124J_1',
                                            '--task','RAM_FR3',
                                            '--workspace-dir','/Users/busygin/scratch/FR3_reports',
                                            '--mount-point','/Volumes/RHINO',
                                            '--python-path','/Users/busygin/ram_utils_new_ptsa',
                                            '--python-path','/Users/busygin/ptsa_latest'
                                            ]

    args = parse_command_line(command_line_emulation_argument_list)

configure_python_paths(args.python_path)

# ------------------------------- end of processing command line

import numpy as np
from RamPipeline import RamPipeline
from RamPipeline import RamTask

from EventPreparation import EventPreparation

from MathEventPreparation import MathEventPreparation

#from ComputeFR1Powers import ComputeFR1Powers

from TalPreparation import TalPreparation

from ComposeSessionSummary import ComposeSessionSummary

from GenerateReportTasks import *

# turn it into command line options

class Params(object):
    def __init__(self):
        self.fr1_start_time = 0.0
        self.fr1_end_time = 1.6
        self.fr1_buf = 1.0

        self.filt_order = 4

        self.freqs = np.logspace(np.log10(3), np.log10(180), 8)

        self.log_powers = True

        self.ttest_frange = (70.0, 200.0)

        self.penalty_type = 'l2'
        self.C = 7.2e-4

params = Params()

class ReportPipeline(RamPipeline):
    def __init__(self, subject, task, workspace_dir, mount_point=None):
        RamPipeline.__init__(self)
        self.subject = subject
        self.task = self.experiment = task
        self.mount_point = mount_point
        self.set_workspace_dir(workspace_dir)

# sets up processing pipeline
report_pipeline = ReportPipeline(subject=args.subject, task=args.task,
                                       workspace_dir=join(args.workspace_dir,args.task+'_'+args.subject), mount_point=args.mount_point)

report_pipeline.add_task(EventPreparation(mark_as_completed=False))

report_pipeline.add_task(MathEventPreparation(mark_as_completed=False))

report_pipeline.add_task(TalPreparation(mark_as_completed=False))

#report_pipeline.add_task(ComputeFR1Powers(params=params, mark_as_completed=True))

report_pipeline.add_task(ComposeSessionSummary(params=params, mark_as_completed=False))
#
report_pipeline.add_task(GeneratePlots(mark_as_completed=False))
#
report_pipeline.add_task(GenerateTex(mark_as_completed=False))
#
report_pipeline.add_task(GenerateReportPDF(mark_as_completed=False))

# starts processing pipeline
report_pipeline.execute_pipeline()


MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
            "milk": 0,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
    "money": 0
}#

money =0
#TODO Create a report which will show how much resources do we have
def printReport(resources):
    report_water = resources["water"]
    report_milk = resources["milk"]
    report_coffee = resources["coffee"]
    report_money=resources["money"]
    print(f"Water: {report_water}")
    print(f"Milk: {report_milk}")
    print(f"Coffee: {report_coffee}")
    print(f"Money: ${report_money }")

# printReport(resources,money)

#Todo Function which will serve menu
def serve_menu(user_choise):
    money =0
    if user_choise == "cappuccino" or user_choise =="espresso" or user_choise =="latte":
        enough_resources=resources_sufficient(resources,user_choise)
        if(enough_resources):
            money = process_coins()
            water_from_order = MENU[user_choise]["ingredients"]["water"]
            coffee_from_order = MENU[user_choise]["ingredients"]["coffee"]
            milk_from_order = MENU[user_choise]["ingredients"]["milk"]
            resources["water"]-=water_from_order
            resources["coffee"]-=coffee_from_order
            resources["milk"]-=milk_from_order
            print(f"Here is ${money} in change")
            if money>MENU[user_choise]["cost"]:
                resources["money"]+=(MENU[user_choise]["cost"])
                print(f"Here is your {user_choise}! Enjoy")
            else:
                print("Sorry there is not enough money")
    elif user_choise == "report":
        printReport(resources)
    else:
        print("Wrong :(")

print(MENU["cappuccino"]["cost"])
#Todo Create functions which will check sufficient resources
def resources_sufficient(resources, order):
    water_from_order = MENU[order]["ingredients"]["water"]
    coffee_from_order = MENU[order]["ingredients"]["coffee"]
    milk_from_order = MENU[order]["ingredients"]["milk"]
    if resources["water"]>=water_from_order and resources["coffee"]>= coffee_from_order and resources["milk"]>=milk_from_order:

        return True
    elif resources["water"]<water_from_order:
        print("Sorry there is not enough water")
        return False
    elif resources["milk"] < milk_from_order:
        print("Sorry there is not enough milk")
        return False
    else:
        print("Sorry there is not enough coffee")
        return False

#Todo Create function which will processes coins
def process_coins():
    print("Please insert coins.")
    quarters = int(input("How many quarters?:  "))
    dimes = int(input("how many dimes?: "))
    nickels = int(input("How many nickels?: "))
    pennies = int(input("how many pennies?: "))
    sum_of_coins = quarters*0.25 + dimes*0.10 + nickels*0.05 + pennies*0.01
    return sum_of_coins

user_input_flag = True
while user_input_flag:
    user_choise = input("What would you like? (espresso/latte/cappuccino): ").lower()
    if user_choise=="exit":
        user_input_flag=False
    else:
        serve_menu(user_choise)


"""
Uzrakstiet Python programmu, lai iegūtu sfēras
 ar lietotāja norādītu rādiusu tilpumu.
 """
import math
rad=float(input("Sfēras radius:"))

tilp=math.pi*pow(rad, 3)*(4/3)
print ("Sfēras tilpums ir")
print (tilp)


import psutil
import cleanvideos
import cleanfiles
import cleanaudio
import cleanall
import time
import sys
import os

print("ATTENZIONE: Leggere per bene il file help.txt!\n\nCosa devo fare?\n1. Eliminare File\n2. Eliminare Video\n3. Eliminare Audio\n4. Eliminare File, video e audio\n5. Terminare App in esecuzione")
try:
    scelta = int(input("Numero: "))
except:
    print("Devi inserire un valore numerico di tipo intero!")

if scelta == 1:
    path = input("Quale PATH devo scansionare? : ")
    cleanfiles.filechecker(path)
elif scelta == 2:
    path = input("Quale PATH devo scansionare? : ")
    cleanvideos.filechecker(path)
elif scelta == 3:
    path = input("Quale PATH devo scansionare? : ")
    cleanaudio.filechecker(path)
elif scelta == 4:
    path = input("Quale PATH devo scansionare? : ")
    cleanall.filechecker(path)
elif scelta == 5:
    app_chiuse = 0
    rimuovo = input("Desideri terminare ogni applicazione in esecuzione?\n(Ricordo che termina tutto che utilizza la CPU al di sopra dell'1)\ny/n: ")
    if rimuovo.lower() == 'y':
        for processo in psutil.process_iter():
            processName = processo.name()
            processID = processo.pid
            processCPU = processo.memory_percent()
            f = open("tm.txt", "a")
            f.write(f"\n{processName} : {processID}, CPU: {processCPU}")
            f.close()
            if processCPU > 1.0:
                f = open("attivita_chiuse", "a")
                f.write(f"\n{processName} ha {processCPU} di CPU, attività terminata!")
                f.close()
                print("Aspetta qualche secondo...")
                try:
                    processo.kill()
                except:
                    print("Permesso Negato!")
                app_chiuse+=1
    print(f"Terminate {app_chiuse} attività\nApri il file 'attivita_chiuse.txt' per vedere i processi terminati")

else:
    print("Non ho capito bene! Chiudi e riprova!")


#!/usr/bin/env python
import ConfigParser
import PIL
import hashlib
import sys
import urllib2
import urllib
import sys
import os
from PIL import Image
from django.conf import settings

SMALL_WIDTH = 200
BIG_WIDTH = 360

BASEFOLDER = settings.PRODUCT_IMAGE_FOLDER

def writeImages(image):
	# finding hashed file name
	filename = hashlib.md5( image ).hexdigest()

	# filename for both image sizes
	originalImageFile = BASEFOLDER + str(filename) + '-orig.jpg'
	smallImageFile = BASEFOLDER + str(filename) + '-small.jpg'
	bigImageFile = BASEFOLDER + str(filename) + '-big.jpg'
	cropImageFile = BASEFOLDER + str(filename) + '-crop.jpg'
	thumbImageFile = BASEFOLDER + str(filename) + '-thumb.jpg'
	# Store tiny image for small thumbnails
	tinyImageFile = BASEFOLDER + str(filename) + '-tiny.jpg'

	try:
		with open( originalImageFile ) as fb:
			with open( bigImageFile ) as fb:
				with open( smallImageFile ) as fb:
					with open( cropImageFile ) as fb:
						with open( thumbImageFile ) as fb:
							with open( tinyImageFile ) as fb:
								img = Image.open(originalImageFile)
								origWidth = float(img.size[0])
								if (origWidth > BIG_WIDTH and validAspect(image)):
									return 1
								else:
									return 0
	except IOError as e:
		f = open( originalImageFile, 'wb')
		f.write( urllib.urlopen( image ).read() )
		f.close()

		# Store image for prodList page
		img = Image.open(originalImageFile)
		origWidth = float(img.size[0])

		basewidth = SMALL_WIDTH # define the fixed width
		wpercent = (basewidth / float(img.size[0]))
		hsize = int((float(img.size[1]) * float(wpercent))) # find height which preserves the aspect ratio
		img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)

		if img.mode != "RGB":
			img = img.convert("RGB")
		# Writing image to resized file
		img.save(smallImageFile)

		# Store image for product page
		img = Image.open(originalImageFile)

		basewidth = BIG_WIDTH # define the fixed width
		wpercent = (basewidth / float(img.size[0]))
		hsize = int((float(img.size[1]) * float(wpercent))) # find height which preserves the aspect ratio
		img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
		if img.mode != "RGB":
			img = img.convert("RGB")
		# Writing image to resized file
		img.save(bigImageFile)

		# save cropped image
		cropOrigImage(image)

		# check aspect ratio to determine validity

		if (origWidth > BIG_WIDTH and validAspect(image) ):
			return 1
		else:
			return 0

def validAspect(image):
	# finding hashed file name
	filename = hashlib.md5( image ).hexdigest()

	# filename for both image sizes
	bigImageFile = BASEFOLDER + str(filename) + '-big.jpg'

	# Store image for prodList page
	img = Image.open(bigImageFile)
	aspect = float(img.size[0])/img.size[1]
	return ( aspect < 1.6 and aspect > 0.625 )

def cropOrigImage(image):
	# finding hashed file name
	filename = hashlib.md5( image ).hexdigest()

	# filename for both image sizes
	bigImageFile = BASEFOLDER + str(filename) + '-orig.jpg'
	# Store image for prodList page
	cropImageFile = BASEFOLDER + str(filename) + '-crop.jpg'
	# Store image for mobile/tablet page
	thumbImageFile = BASEFOLDER + str(filename) + '-thumb.jpg'
	# Store tiny image for small thumbnails
	tinyImageFile = BASEFOLDER + str(filename) + '-tiny.jpg'

	img = Image.open(bigImageFile)

	width = img.size[0]
	height = img.size[1]
	if width > height:
		diff = width-height
		img = img.crop((diff/2, 0, (width-diff/2), height))
	else:
		diff = height-width
		img = img.crop((0, diff/2, width, (height-diff/2)))
	img.thumbnail((360,360),PIL.Image.ANTIALIAS)
	if img.mode != "RGB":
		img = img.convert("RGB")
	# Writing image to resized file
	img.save(cropImageFile)

	img.thumbnail((240,240),PIL.Image.ANTIALIAS)
	if img.mode != "RGB":
		img = img.convert("RGB")
	# Writing image to resized file
	img.save(thumbImageFile)

	img.thumbnail((60,60),PIL.Image.ANTIALIAS)
	if img.mode != "RGB":
		img = img.convert("RGB")
	img.save(tinyImageFile)


# -*- coding: utf-8 -*-
"""
Created on Sun Sep  2 15:13:33 2018

@author: Karan Randhir
"""
#Print fibonacci series upto a range input by user
first = 0
second = 1
n=input("Enter the range of fibbonaci series")
try :
    n=int(n)

    print("Required fibonacci series is ")
    for i in range (0,n) :
        if i <=1 :
            fibonacci = i
        else :
            fibonacci = first + second
            first = second
            second = fibonacci
        print(fibonacci)
except :
    print("please enter an integer")


# -*- coding: utf-8 -*-
from datetime import datetime

import pytest
from twilio.rest.exceptions import TwilioRestException

from ..models import *
from ..tasks import *

@pytest.mark.django_db
class TestTasks:
    def test_send_recipient_ok(self, recipients):
        # test sending via recipient
        recipient_send_message_task(recipients['calvin'].id,
                                    "This is a test",
                                    None,
                                    'test')

    def test_send_recipient_blacklist(self, recipients):
        recipient_send_message_task(recipients['john_owen'].id,  # doesn't actually test blacklisted number handling :(
                                    "This is a test to a blacklisted number...",
                                    None,
                                    'test')

    def test_send_fail_number(self, recipients):
        with pytest.raises(TwilioRestException):
            recipient_send_message_task(recipients['thomas_chalmers'].id,
                                        "This is a test to a number that will fail",
                                        None,
                                        'test')

    def test_send_group(self):
        # test sending via group
        group_send_message_task("This is another test",
                                "Test group",
                                'test',
                                eta=None)

    def test_import_incoming_sms_task(self):
        import_incoming_sms_task()

    def test_import_outgoing_sms_task(self):
        import_outgoing_sms_task()

    def test_check_log_consistent(self):
        with pytest.raises(TwilioRestException):
            check_log_consistent('0')

    def test_check_outgoing_log_consistent(self):
        with pytest.raises(TwilioRestException):
            check_recent_outgoing_log('0')

    def test_send_keyword_digest(self, keywords, smsin, users):
        send_keyword_digest()
        assert Keyword.objects.get(keyword='test').last_email_sent_time is not None
        send_keyword_digest()
        # add a new sms:
        sms = SmsInbound.objects.create(content='test message',
                                        time_received=timezone.now(),
                                        sender_name="John Calvin",
                                        sender_num="+447927401749",
                                        matched_keyword="test",
                                        sid='123fasdfdfaw45')
        sms.save()
        keywords['test'].subscribed_to_digest.add(users['staff'])
        keywords['test'].save()
        send_keyword_digest()

    def test_log_msg_in(self, recipients):
        calvin = recipients['calvin']
        p = {'Body': 'New test message',
             'MessageSid': 'thisisreallyauuid',
             'From': calvin.number}
        log_msg_in(p, datetime.now(), calvin.pk)

        assert SmsInbound.objects.filter(content="New test message").count() == 1

    def test_warn_on_blacklist_receipt(self, recipients):
        warn_on_blacklist_receipt(recipients['wesley'].pk, 'stop')


"""
В это пакете находятся вызываемые страницы.
Страницы создаются один раз при загрузке игры.
Страницы обновляются по мере необходимости.
"""
from __future__ import annotations

from ui.pages.StartPage import StartPage
from ui.pages.LevelSelect import LevelSelect
from ui.pages.GameMenuPage import GameMenuPage
from ui.pages.character_page.CharacterPage import CharacterPage
from ui.pages.inventory_page.InventoryPage import InventoryPage
from ui.pages.BackGorundPage import BackGorundPage
from ui.pages.ReadmePage import ReadmePage
from ui.pages.SettingsPage import SettingsPage
from ui.pages.WidgetFactory import WidgetFactory

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from ui.core.GameRootNode import GameRootNode
    from ui.pages import AbstractPage

class GamePages(object):
    """docstring for pages."""
    def __init__(self):
        super(GamePages, self).__init__()
        self.gameRoot:GameRootNode = None
        # this is current page
        self.focusState = False
        self.focus = False
        # init pages
        self.pages = {}
        self.page: AbstractPage = None
        self.gameMenu: GameMenuPage = None
        self.background: BackGorundPage = None
        self.startPage: StartPage = None
        self.levelSelect: LevelSelect = None
        self.readme: ReadmePage = None
        self.characterPage: CharacterPage = None
        self.settigsPage: SettingsPage = None
        self.visiblePage = True

    def setGameRoot(self, gameRoot):
        self.gameRoot = gameRoot
        self.gameRoot.gamePages = self

    def setUpPages(self):
        self.setUpBackgrounPage()
        self.setUpGameMenu()
        self.gameRoot.scene.addItem(self.toolTip)
        self.gameRoot.scene.addItem(self.notify)
        self.setUpInventoryPage()
        self.gameRoot.scene.removeItem(self.startPage)
        self.gameRoot.scene.addItem(self.startPage)
        self.gameRoot.scene.removeItem(self.startPage.mainWidget)
        self.gameRoot.scene.addItem(self.startPage.mainWidget)

    def destroyPages(self):
        pages = list(self.pages.values())[:]
        keys = list(self.pages.keys())[:]
        i =0
        for page in pages:
            if not page.isService:
                page.destroy()
                print(keys[i], '-- destroy')
                if not page.scene() is None:
                    self.gameRoot.scene.removeItem(page)
                del self.pages[keys[i]]
            i += 1
        self.gameMenu = None
        self.gameRoot.scene.removeItem(self.toolTip)
        self.gameRoot.scene.removeItem(self.notify)

    def setUpBackgrounPage(self):
        self.background = self.buildPage('background', BackGorundPage)
        self.gameRoot.scene.addItem(self.background)

    def setUpStartPage(self, ui):
        self.startPage = self.buildPage('startPage', StartPage)
        self.page = self.startPage
        self.toolTip = WidgetFactory.getToolTip(self.gameRoot, w = 128, h = 0, opacity=1.)
        self.toolTip.gameRoot = self.gameRoot
        self.gameRoot.view.wheel_change.connect(self.toolTip.wheel_change)
        self.notify = WidgetFactory.getNotifyText(self.gameRoot)

    def setUpLevelsPage(self):
        self.levelSelect = self.buildPage('levelSelect', LevelSelect)
        self.gameRoot.controller.mousePress.connect(self.levelSelect.mousePressEvent)

    def setUpGameMenu(self):
        gameMenu = self.buildPage('gameMenu', GameMenuPage)
        self.gameRoot.scene.addItem(gameMenu)
        gameMenu.resized()
        self.gameMenu = gameMenu

    def setUpCharecterPage(self):
        characterPage = self.buildPage('characterPage', CharacterPage)
        self.gameRoot.scene.addItem(characterPage)
        characterPage.showPage()

    def setUpInventoryPage(self):
        inventoryPage = self.buildPage('inventoryPage', InventoryPage)
        self.gameRoot.scene.addItem(inventoryPage)
        inventoryPage.hidePage()
        # self.gameRoot.controller.mouseMove.connect(inventoryPage.mouseMoveEvent)

    def setUpReadmePage(self):
        self.readme = self.buildPage('readmePage', ReadmePage)

    def setUpSettingsPage(self):
        self.settigsPage = self.buildPage('settigsPage', SettingsPage)

    def buildPage(self, pageName, pageClass):
        print('Init page:', pageName)
        page = pageClass(self)
        self.pages[pageName] = page
        self.gameRoot.view.keyPress.connect(page.keyPressEvent)
        page.focusable.connect(self.setFocus)
        page.setUpGui()
        return page

    def mouseMoveEvent(self, e):
        # self.checkFocus(e.pos())
        self.page.mouseMoveEvent(e)
        pass

    def mousePressEvent(self, e):
        # self.page.mousePressEvent(e)
        pass

    def resized(self):
        for page in self.pages.values():
            page.resized()

    def setCharacter(self, character):
        self.characterPage.character = character

    @property
    def isGamePage(self):
        if self.startPage.state:
            return True
        if self.levelSelect.state:
            return True
        if self.settigsPage.state:
            return True
        if not self.pages.get('chaPage') is None:
            if self.pages.get('chaPage').state:
                return True
        if not self.pages.get('gameMenu') is None:
            if self.pages.get('gameMenu').isFocus():
                return True

    def setFocus(self, isFocus):
        self.focusState = isFocus

    @property
    def isFocus(self):
        return self.focusState or self.gameMenu.isFocus()


""" functions for tracking the command-line argument vector
"""
import os
import sys
import logging
from argparse import ArgumentParser
from argparse import ArgumentDefaultsHelpFormatter
from itertools import chain
from .argspec import specifier_key
from .argspec import specifier_value_mapping
from .argspec import interpret_specifier
from .argspec import specifier_from_kernel
from .argspec import set_specifier_keyword_value
from .argspec_kernels import SUBCMD as SUBCMD_K
from .argspec_kernels import PREFIX as PREFIX_K
from .argspec_kernels import LOG_NAME as LOG_NAME_K
from .argspec_kernels import LOG_LEVEL as LOG_LEVEL_K
from .argspec_kernels import PRINT_OUT as PRINT_OUT_K

PREFIX = specifier_from_kernel(PREFIX_K, opt_char='P')
LOG_NAME = specifier_from_kernel(LOG_NAME_K, opt_char='L', out=True)
LOG_LEVEL = specifier_from_kernel(LOG_LEVEL_K, opt_char='V')
PRINT_OUT = specifier_from_kernel(PRINT_OUT_K, opt_char='p')

def tracker(argv, pos):
    """ argument vector tracker
    """
    return (argv, pos)

def make_tracker(argv):
    """ make an argument vector tracker from sys.argv
    """
    argv[0] = os.path.basename(argv[0])
    return tracker(argv=argv, pos=0)

def increment_tracker(argt):
    """ advance the position of the argument vector tracker
    """
    argv, pos = argt
    pos += 1
    return tracker(argv=argv, pos=pos)

def call_name(argt):
    """ current call name
    """
    argv, pos = argt
    cmd_str = ' '.join(argv[:pos])
    return cmd_str

def has_arguments_left(argt):
    """ is this tracker at the end?
    """
    argv, pos = argt
    return pos < len(argv)

def current_position_argument(argt):
    """ current argument in the tracker
    """
    argv, pos = argt
    return argv[pos]

def last_subcommand(argt):
    """ get the last subcommand in the argument tracker
    """
    argv, pos = argt
    return argv[pos-1]

def log_file_name(argt):
    """ get a file name, based on the last subcommand of the argument tracker
    """
    base = last_subcommand(argt)
    fname = '{:s}.{:s}'.format(base, 'log')
    return fname

def current_argument_vector(argt):
    """ current command arguments
    """
    argv, pos = argt
    return argv[pos:]

def parse_current_argument(argt, spec):
    """ parse the argument at the current tracker position
    """
    cmd = call_name(argt)
    specs = [spec]
    par = _parser(cmd, specs)

    if (not has_arguments_left(argt) or
            current_position_argument(argt) in ('-h', '--help')):
        _quit_with_help_message(par)

    argv = [current_position_argument(argt)]
    val, = _parse_values(par, specs, argv)
    return val

def call_subcommand(argt, subcmds):
    """ parse argument to call appropriate subcommand function
    """
    argt = increment_tracker(argt)
    subcmd_keys, _ = zip(*subcmds)
    subcmd_key_sp = specifier_from_kernel(SUBCMD_K, allowed_values=subcmd_keys)
    subcmd_key_val = parse_current_argument(argt, subcmd_key_sp)
    subcmd_fnc = dict(subcmds)[subcmd_key_val]
    subcmd_fnc(argt)

def parse_arguments(argt, specs):
    """ parse the argument tracker according to specifications
    """
    cmd = call_name(argt)
    par = _parser(cmd, specs)

    argv = current_argument_vector(argt)

    if '-h' in argv or '--help' in argv:
        _quit_with_help_message(par)

    val_maps = tuple(map(specifier_value_mapping, specs))
    vals = _parse_values(par, specs, argv)
    vals = tuple(val_map(val) for val_map, val in zip(val_maps, vals))
    return vals

def call_routine(argt, routine, specs):
    """ parse remaining arguments to invoke a routine
    """
    argt = increment_tracker(argt)
    fname = log_file_name(argt)
    log_name_spec = set_specifier_keyword_value(LOG_NAME, 'default', fname)
    specs = tuple(chain(specs, (PREFIX, log_name_spec, LOG_LEVEL, PRINT_OUT)))
    vals = parse_arguments(argt, specs)
    routine_args, context_vals = vals[:-4], vals[-4:]

    prefix, log_name, log_level, print_out = context_vals

    calling_dir = os.getcwd()
    routine_dir = os.path.abspath(prefix)
    if not os.path.exists(routine_dir):
        os.mkdir(routine_dir)

    os.chdir(routine_dir)
    routine(*routine_args, logger=_logger(log_name, log_level, print_out))
    os.chdir(calling_dir)

def _quit_with_help_message(par):
    par.print_help()
    par.exit()

def _parse_values(par, specs, argv):
    par_dct = vars(par.parse_args(argv))
    keys = tuple(map(specifier_key, specs))
    vals = tuple(map(par_dct.__getitem__, keys))
    return vals

def _parser(cmd, specs):
    par = ArgumentParser(
        prog=cmd,
        formatter_class=ArgumentDefaultsHelpFormatter,
        add_help=False
    )
    for args, kwargs in map(interpret_specifier, specs):
        par.add_argument(*args, **kwargs)
    return par

def _logger(log_name, log_level, print_out):
    logger = logging.getLogger()
    logger.setLevel(log_level)

    fhandler = logging.FileHandler(log_name, mode='w')
    fhandler.setLevel(log_level)

    formatter = logging.Formatter('%(message)s')
    fhandler.setFormatter(formatter)

    logger.addHandler(fhandler)

    if print_out:
        shandler = logging.StreamHandler(sys.stdout)
        shandler.setLevel(log_level)
        shandler.setFormatter(formatter)
        logger.addHandler(shandler)

    return logger