コード例 #1
0
def connect_system(directory):
	# Prepare the device A ==========================================================

	macAddress_A= "20:16:04:12:01:23"
	batteryThreshold_A = 30
	acqChannels_A = [0,1,2,3,4,5]
	samplingRate_A = 1000
	nSamples_A = 5
	digitalOutput_A= [0,0]

	# Connect to BITalino
	init_connect_A_time = time.time() 
	device_A = connect(macAddress_A,init_connect_A_time)

	# ==============================================================================

	# Prepare the device B =========================================================

	macAddress_B = "20:16:04:12:01:40"
	batteryThreshold_B = 30
	acqChannels_B = [0,1,2,3,4,5]
	samplingRate_B = 1000
	nSamples_B = 5
	digitalOutput_B = [0,0]

	# Connect to BITalino
	init_connect_B_time = time.time()
	device_B = connect(macAddress_B,init_connect_B_time)

	# =============================================================================

	a_file, drift_log_file = open_file(directory)


	return device_A, device_B, a_file, drift_log_file
コード例 #2
0
ファイル: cronJob.py プロジェクト: kaushik94/piBox
    def process(self, event):
        """
        event.event_type 
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        # the file will be processed there

        f = open('count.txt', 'r+')
        now = [name for name in os.listdir(path) \
            if os.path.isfile(os.path.join(path, name))]
        if event.event_type is 'created':
            connect(event.src_path.split('/')[-1])
        prev = [each for each in f.readlines()]
        if len(prev) > len(now):
            for each in list(set(prev) - set(now)):
                connect(each.strip('\n'), remove=True)

        string = ''
        for each in now:
            string += each+'\n'
        f.seek(0)
        f.write(string)
        f.close()
コード例 #3
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.setFixedHeight(self.height())
        self.setFixedWidth(self.width())
        self.tableCustomer.horizontalHeader().setResizeMode(
            QHeaderView.Stretch)
        self.tableCustomer.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableCustomer.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableCustomer.setColumnHidden(6, True)
        self.tableCustomer.setColumnHidden(7, True)
        self.labCustID.setVisible(False)
        self.labUserID.setVisible(False)

        # Object Of Class Connect Database
        self.con = connect()
        # Object Of Class ConnectFtp Server
        self.connectFTP = connectFtp()

        # Function Show Customers Of Table
        self.ShowCustomers()
        """ [ Start Run Function Event ] """
        # Run Function AddCustomers
        self.btnCustomerAdd.clicked.connect(self.AddCustomers)
        self.btnCancel.clicked.connect(self.Cancel)
        self.btnCustomerEdit.clicked.connect(self.EditCustomer)
        self.labCustomerImage.mouseDoubleClickEvent = self.SelectImageCustomer
        self.comboBoxSelectActive.activated.connect(self.ShowCustomers)
        self.tableCustomer.doubleClicked.connect(self.ShowInfoOfForm)
        self.btnCustomerActive.clicked.connect(self.ActiveCustomer)
        self.btnCustomerNotActivet.clicked.connect(self.ActiveCustomer)
        self.lineEditCustomerSearch.keyReleaseEvent = self.SearchCustomers
        """ [ End Run Function Event ] """
コード例 #4
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.tableSection.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableSection.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableSection.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.setFixedHeight(self.height())
        self.setFixedWidth(self.width())
        self.move(200, 200)
        self.labUserID.setVisible(False)
        self.btnEditSection.setEnabled(False)
        self.con = connect()  #Object Of Class Connect
        """[ Start Event ]"""
        # Add Section To Database
        self.btnAddSection.clicked.connect(self.addSection)

        # Delete Sction Of Database
        self.btnSectionDelete.clicked.connect(self.DeletSection)

        # button Cancel
        self.btnCancel.clicked.connect(self.Cancel)

        # Run Function Show Section
        self.ShowSection()

        # Edit Section
        self.tableSection.doubleClicked.connect(self.ImportSectionToLineEdit)
        self.btnEditSection.clicked.connect(self.EditSection)

        # Search Section
        self.linEditSectionSearch.keyReleaseEvent = self.SearchSection
        """[ End Event ]"""
コード例 #5
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.setFixedWidth(self.width())
        self.setFixedHeight(self.height())
        self.move(300, 190)
        self.btnEditItem.setGeometry(300, 190, 150, 41)
        self.btnEditItem.setVisible(False)
        self.labUserID.setVisible(False)
        self.labItemID.setVisible(False)

        # Object From Class Connect Database
        self.con = connect()
        # Object From Class Connect FTP server
        self.connectFTP = connectFtp()
        """[ Run Function ]"""
        # Function Show Name Category Of Combox
        self.showItemCategory()
        # Function Show Name Store Of Combox
        self.showItemStore()
        """[ Start Event ]"""
        # Button Add Item To Database
        self.btnAddItem.clicked.connect(self.addItem)
        # Button Cancel
        self.btnCancel.clicked.connect(self.Cancel)
        self.btnEditItem.clicked.connect(self.EditItem)
        # Select Image
        self.labAddImageItem.mouseDoubleClickEvent = self.SelectImage
        """[ End Event ]"""
コード例 #6
0
 def __init__(self):
     QWidget.__init__(self)
     self.setupUi(self)
     self.tableCategory.setSelectionBehavior(QAbstractItemView.SelectRows)
     self.tableCategory.setEditTriggers(QAbstractItemView.NoEditTriggers)
     self.tableCategory.horizontalHeader().setResizeMode(
         QHeaderView.Stretch)
     self.setFixedHeight(self.height())
     self.setFixedWidth(self.width())
     self.move(200, 200)
     self.labUserID.setVisible(False)
     self.btnEditCategory.setEnabled(False)
     self.con = connect()
     # Function View All Section Of Combox
     self.viewSection()
     self.ShowCategory()
     """[ Start Event ]"""
     # Btn Add Category To Database
     self.btnAddCategory.clicked.connect(self.addCategory)
     # Btn Delete Category Of Database
     self.btnCategoryDelete.clicked.connect(self.DeletCategory)
     # Btn Edit Category
     self.btnEditCategory.clicked.connect(self.EditCategory)
     # Btn Cancel
     self.btnCancel.clicked.connect(self.Cancel)
     # Table Category
     self.tableCategory.doubleClicked.connect(self.ImportCategoryToLineEdit)
     # Line Edit Search Of Database
     self.linEditCategorySearch.keyReleaseEvent = self.SearchCategory
     """[ End Event]"""
コード例 #7
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.move(200, 0)
        self.setFixedHeight(self.height())
        self.setFixedWidth(self.width())
        self.textPassword.setEchoMode(QLineEdit.Password)
        self.textPasswordShow.setVisible(False)
        self.labImageName.setVisible(False)
        self.labUserPassword.setVisible(False)
        self.labUserID.setVisible(False)

        self.con = connect()
        self.connectFTP = connectFtp()
        """[ Start Event Function ]"""
        self.labCreatePasswordComplix.mousePressEvent = self.createPasswordComplix
        self.labShowMenuPer.mousePressEvent = self.showMenuPermission
        self.labAddImgUser.mousePressEvent = self.selectImgUser
        self.btnAddUser.clicked.connect(self.addUser)
        self.btnCancel.clicked.connect(self.Cancel)
        self.labShowPassword.mousePressEvent = self.ShowPassword
        self.textPassword.keyReleaseEvent = self.CopyPassword
        self.textPasswordShow.keyReleaseEvent = self.CopyPassword
        self.checkBoxAll.clicked.connect(self.CheckAllPer)
        self.btnSelectUsers.clicked.connect(self.SelectUser)
        self.btnEditUser.clicked.connect(self.EditUser)
        """ [ End Event Function ] """
コード例 #8
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.tableSettingItem.horizontalHeader().setResizeMode(
            QHeaderView.Stretch)
        self.tableSettingItem.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableSettingItem.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.tableSettingItem.setColumnHidden(0, True)
        self.setFixedHeight(self.height())
        self.setFixedWidth(self.width())

        # Object Of Class Connect
        self.con = connect()

        self.connectFTP = connectFtp()
        # Function Show Item
        self.ShowItem()
        """[ Start Event ]"""
        self.comboxShowItem.activated.connect(self.ShowItem)
        self.btnNotActive.clicked.connect(self.Active)
        self.btnActive.clicked.connect(self.Active)
        self.tableSettingItem.doubleClicked.connect(self.EditItem)
        self.lineEditSearchItem.keyReleaseEvent = self.SearchItem
        """[ End Event ]"""
コード例 #9
0
def select():
    global total
    try:
        print("Creating Object")
        conn, cur = connect()
        #db = Database_actions(conn,cur)
        # execute a statement
        print('PostgreSQL database version:')
        #cur.execute('SELECT * from rolelist')
        # display the PostgreSQL database server version
        #cur.execute(Database_actions(conn,cur).create_tables())
        #cur.execute('CREATE TABLE  roleList(roleid serial PRIMARY KEY, rolename VARCHAR(50), location VARCHAR(50));')
        #db_version = cur.fetchall()
        #print(db_version)
        print("print list of tables exist")
        for table in Database_actions(conn, cur).getTablesList():
            total.append(re.findall(r"\('(.*?)',\)", str(table)))
        sp = str(total).replace('[', '').replace(']', '')
        pattern = re.compile("\s*,\s*|\s+$")
        x = pattern.split(sp)
        for i in x:
            print(i.replace("'", ""))

        print(len(Database_actions(conn, cur).getTablesList()))
        if (len(Database_actions(conn, cur).getTablesList()) != 5):
            print("condition pass")
            Database_actions(conn, cur).create_tables()

        close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
コード例 #10
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.tableEmployes.horizontalHeader().setResizeMode(
            QHeaderView.Stretch)
        self.tableEmployes.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableEmployes.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setFixedWidth(self.width())
        self.setFixedHeight(self.height())
        self.labUserID.setVisible(False)

        # Object From Class Connect Database
        self.con = connect()
        # Object From Class Connect FTP Server
        self.connectFTP = connectFtp()

        # Run Function At Show Form
        self.ShowSection()
        self.showEmployes()
        """[ Start Event ]"""
        self.btnEmploAdd.clicked.connect(self.addEmployee)
        self.btnCancel.clicked.connect(self.Cancel)
        self.labEmploye.mouseDoubleClickEvent = self.SelectImageEployee
        self.btnEmploNotActive.clicked.connect(self.ActiveEmploye)
        self.btnEmploActive.clicked.connect(self.ActiveEmploye)
        self.comboxEmploActive.activated.connect(self.showEmployes)
        self.textEmploSearch.keyReleaseEvent = self.SearchEmploye
        self.tableEmployes.mouseDoubleClickEvent = self.infoEmployesOfForm
        self.btnEmploEdit.clicked.connect(self.editEmployes)
        self.comboxEmploReport.activated.connect(self.reportEmployes)
        """[ End Event ]"""
コード例 #11
0
def _gethorse(horsecode):
	'''returns the row of data about this horsecode'''
	if horsecode is None:
		return None
	conn,c1 = connect()
	# print horsecode
	sql = c1.mogrify("SELECT * from horse h WHERE h.code=%s;", (horsecode,) )
	print sql
	c1.execute(sql)
	h = c1.fetchone()
	c1.close()
	conn.close()
	pprint.pprint(h)
	return h
コード例 #12
0
def _gethorsename(horsecode):
	'''returns a single horse name for this horsecode'''
	if horsecode is None:
		return None
	conn,c1 = connect()
	# print horsecode
	sql = c1.mogrify("SELECT h.name from horse h WHERE h.code=%s;", (horsecode,) )
	print sql
	c1.execute(sql)
	horsename = c1.fetchone()[0]
	# print horsename[0]
	c1.close()
	conn.close()
	return horsename
コード例 #13
0
def _gethorsevalue(horsecode, attr):
	assert _sanitycheck(args)
	
	#does attribute exist?
	conn,c1 = connect()
	try:
		sql = c1.mogrify("SELECT %s from horse h WHERE h.code=%s;", (attr, horsecode) )
		c1.execute(sql)
		val = c1.fetchone()
		c1.close()
		conn.close()
		return val
	except:
		pass
コード例 #14
0
ファイル: parsing.py プロジェクト: krisuety/Mango_plate_NLP
    def parsingHot(self, url):
        connect(url)
        html_doc = driver.page_source
        soup = BeautifulSoup(html_doc, 'html.parser')

        try:
            title = soup.find("h1", {"class": "restaurant_name"})
            rating = soup.find("strong", {"class": "rate-point"})
            info = dict()
            info['이름'] = title.get_text()
            info['평점'] = rating.get_text().replace('\n', ' ')
            table = soup.find("tbody")
            for thtd in table.find_all("tr"):
                if thtd.th.get_text() != "메뉴":
                    temp = thtd.th.get_text().replace(' ', '')
                    info[temp.replace('\n', '')] = thtd.td.get_text().replace(
                        '\n', '')
                else:
                    info[thtd.th.get_text()] = thtd.td.get_text()

            return info
        except AttributeError:
            pass
コード例 #15
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.tableSelectUser.setEditTriggers(QHeaderView.NoEditTriggers)
        self.tableSelectUser.horizontalHeader().setResizeMode(
            QHeaderView.Stretch)
        self.tableSelectUser.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setFixedHeight(self.height())
        self.setFixedWidth(self.width())
        self.con = connect()
        self.conFTP = connectFtp()

        self.textUserSearcch.keyReleaseEvent = self.searchUserSelect
        self.tableSelectUser.doubleClicked.connect(self.ClickTableAndSelect)
コード例 #16
0
def delete_all():
    '''delete all the info from the table'''
    connection = connect('localhost', 'root', 'getluo', 'TESTDB')
    cursor = connection.cursor()

    sql = "DELETE FROM FEATUREVECTOR"

    try:
        cursor.execute(sql)
        connection.commit()
    except:
        connection.rollback()

    connection.close()
コード例 #17
0
ファイル: export_txt.py プロジェクト: mmcgg/Face_project
def export(abst_path):
    '''export the sql file to a txt file'''

    connection = connect('localhost', 'root', 'Asd980517', 'WEININGFACE')
    cursor = connection.cursor()

    sql = """SELECT * INTO OUTFILE '/home/txtfile/FEATUREVECTOR.txt'
             FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
             LINES TERMINATED BY '\n'
             FROM FEATUREVECTOR"""

    try:
        cursor.execute(sql)
    except:
        print('can not export to a txt file')
コード例 #18
0
 def __init__(self):
     QWidget.__init__(self)
     self.setupUi(self)
     self.setFixedHeight(self.height())
     self.setFixedWidth(self.width())
     self.btnOkRestPassword.setVisible(False)
     self.textCheckPassword.setVisible(False)
     self.textaddCode.setVisible(False)
     self.textNewPasword.setVisible(False)
     self.btnCheckCode.setVisible(False)
     self.textNewPasword.setEchoMode(QLineEdit.Password)
     self.textCheckPassword.setEchoMode(QLineEdit.Password)
     self.con = connect()
     self.btnLoginReset.clicked.connect(self.ShowFormLogin)
     self.btnReset.clicked.connect(self.checkInfoUser)
     self.btnOkRestPassword.clicked.connect(self.resetPsswordUser)
     self.btnCheckCode.clicked.connect(self.CheckCode)
コード例 #19
0
ファイル: search.py プロジェクト: mmcgg/Face_project
def search(info, method=0):
    '''
    search all the satisfied data according to the name
    while mthod=0 search data by name ;
    while method=1 search data by age;
    while method=2 search data by vector;
    while method=3 search data by datetime;
    '''
    method_arr = ['NAME', 'AGE', 'VECTOR', 'DATETIME']

    connection = connect('localhost', 'root', 'getluo', 'TESTDB')
    cursor = connection.cursor()


    sql = """SELECT NAME, AGE, VECTOR, VISIT_TIME FROM FEATUREVECTOR
             WHERE {0} = '{1}'
             ORDER BY VISIT_TIME DESC
             LIMIT 0, 2000""".selfat(method_arr[method], info)
    # print(sql)

    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        for i, row in enumerate(results):
            name = row['NAME']
            age = row['AGE']
            vec = row['VECTOR']
            visit_time = row['VISIT_TIME']
            msg = "{0}. name: {1}, age: {2}, vec: [{3}], visit_time: {4}"
            print(msg.selfat(i, name, age, vec, visit_time))
    except:
        print("Error: unable to fetch data")

    # selfat the returned results [{}, {}] -> [[], []]
    results_selfat = []
    tmp = []
    for i in range(len(results)):
        tmp.append(results[i]['NAME'])
        tmp.append(results[i]['AGE'])
        tmp.append(results[i]['VECTOR'])
        tmp.append(results[i]['VISIT_TIME'])
        results_selfat.append(tmp)
        tmp = []

    # print(str(results_selfat[0][3]))
    return results_selfat
コード例 #20
0
ファイル: main.py プロジェクト: bob-schumaker/warpWarp
def connectServer(tkRoot):
    print("main:connectServer")
    if (tkRoot.hCon is not None):
        tkRoot.hCon.quitCmd()
        tkRoot.hCon = None

    tmp = connect(tkRoot, tkRoot.cfg)
    if (tmp is not None):
        tkRoot.hCon = tmp.hCon
        tkRoot.plid = tmp.plid
        tkRoot.hPlayerAi = tmp.hPlayerAi

    if (tkRoot.hCon is not None):
        tkRoot.hCon.setCallback(lambda data: newDataForGame(tkRoot, data))
        refresh(tkRoot)

        print("tkroot.plid: {} Name: {}".format(
            tkRoot.plid, dataModel.playerNameGet(tkRoot.game, tkRoot.plid)))
コード例 #21
0
def delete(info, method=0):
    '''delete rows by the certain info'''
    connection = connect('localhost', 'root', 'getluo', 'TESTDB')
    cursor = connection.cursor()

    method_arr = ['NAME', 'AGE', 'VECTOR', 'VISIT_TIME']

    sql = """DELETE FROM FEATUREVECTOR
             WHERE
                {0} = '{1}'
            """.selfat(method_arr[method], info)

    try:
        cursor.execute(sql)
        connection.commit()
    except:
        connection.rollback()

    connection.close()
コード例 #22
0
 def __init__(self):
     QWidget.__init__(self)
     self.setupUi(self)
     self.tableViewUsers.horizontalHeader().setResizeMode(
         QHeaderView.Stretch)
     self.tableViewUsers.setEditTriggers(QAbstractItemView.NoEditTriggers)
     self.tableViewUsers.setSelectionBehavior(QAbstractItemView.SelectRows)
     self.tableViewUsers.setColumnHidden(0, True)
     self.setFixedHeight(self.height())
     self.setFixedWidth(self.width())
     self.con = connect()
     self.conFTP = connectFtp()
     self.ShowUsers()
     """[ Start Event Function  ]"""
     self.comboBoxActive.activated.connect(self.ShowUsers)
     self.tableViewUsers.itemSelectionChanged.connect(self.ShowImageUser)
     self.btnNotActiveUser.clicked.connect(self.activeUser)
     self.btnActiveUser.clicked.connect(self.activeUser)
     self.textSearch.keyReleaseEvent = self.SearchUser
     """[ End Event Function ]"""
コード例 #23
0
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.tableStore.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.tableStore.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableStore.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setFixedHeight(self.height())
        self.setFixedWidth(self.width())
        self.move(300, 200)
        self.btnStoreEdit.setEnabled(False)

        self.con = connect()
        self.ShowStore()
        """[ Start Event ]"""
        self.btnStoreAdd.clicked.connect(self.addStore)
        self.btnStoreDelete.clicked.connect(self.notActivateStore)
        self.lineEditStoreSearch.keyReleaseEvent = self.SearchStore
        self.btnStoreEdit.clicked.connect(self.EditStore)
        self.tableStore.doubleClicked.connect(self.ImportStoreToLineEdit)
        self.btnCancel.clicked.connect(self.Cancel)
        """[ End Event  ]"""
コード例 #24
0
ファイル: create_table.py プロジェクト: mmcgg/Face_project
def create():
    '''create a table in the certain database'''

    connection = connect('localhost', 'root', 'getluo', 'TESTDB')
    cursor = connection.cursor()

    cursor.execute("DROP TABLE IF EXISTS FEATUREVECTOR")

    sql = """CREATE TABLE FEATUREVECTOR (
             ID INT(11) NOT NULL AUTO_INCREMENT,
             NAME CHAR(30) NOT NULL COLLATE utf8_bin NOT NULL,
             AGE INT(4) NOT NULL,
             VECTOR CHAR(100) NOT NULL,
             VISIT_TIME DATETIME NOT NULL,
             PRIMARY KEY (ID)
             )ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
             AUTO_INCREMENT=1;"""

    cursor.execute(sql)

    connection.close()
コード例 #25
0
    Column('peer_id',
           BigInteger,
           ForeignKey('account.id'),
           nullable=True,
           doc='收款账户id'),
    Column('depend_id',
           BigInteger,
           ForeignKey('authority_jrnl.id'),
           nullable=True,
           doc='相关流水'),
    Column('organ_name', String(128), doc='执行机关'),
    Column('reason', String(255), doc='执行原因'),
    Column('notice_no', String(256), doc='通知书编号'),
    Column('cert_type1', String(64), doc="证件名称1"),
    Column('cert_no1', String(64), doc="证件号码1"),
    Column('name1', String(64), doc="执行人1名称"),
    Column('cert_type2', String(64), doc="证件名称2"),
    Column('cert_no2', String(64), doc="证件号码2"),
    Column('name2', String(64), doc="执行人2名称"),
    Column('from_date', DateTime, doc='起效时间'),
    Column('thru_date', DateTime, doc='终止时间'),
    Column('bill_no', String(32), doc="票据号码"),
    Column('tran_jrnl_id', BigInteger, ForeignKey('tran_jrnl.id'), doc='关联流水'),
    info={'doc': '有权机关操作流水'},
)

if __name__ == '__main__':
    connect()
    con.metadata.drop_all()
    con.metadata.create_all()
コード例 #26
0
    response = sess.get(url, headers=headers)
    hosts = text_parser.get_search_results(response.text)
    response = sess.get("https://www.shodan.io/search?" + urlencode({
        "query": text,
        "page": 1
    }),
                        headers=headers)
    hosts_found = text_parser.get_search_results(response.text)
    hosts.extend(hosts_found)
    print hosts


def search_map(sess, text):
    # sess.mount('https://www.shodan.io', HTTP20Adapter())
    headers = {}
    response = sess.get("https://maps.shodan.io/_search?" +
                        urlencode({"q": text}),
                        headers=headers)
    hosts_found = text_parser.parse_map(response.text)
    print hosts_found


if __name__ == '__main__':
    sess = connect()
    while True:
        text = raw_input(">> ")
        if text == "q" or text == "quit":
            print "Exiting..."
            sys.exit(1)
        search_map(sess, text)
コード例 #27
0
 def clean(self):
     # XXX: sice smaze vsechny data, ale pri tvorbe nove dtb uz nevytvori spravne indexy
     # smazeme vsechny vytvorene kolekce
     dtb = connect(self.db, self.application.config)
     clean(dtb)
コード例 #28
0
from connect import 
from getmac import get_mac_address
#!/usr/bin/python
import mysql.connector as mariadb

eth_mac = get_mac_address(interface="eth0")
win_mac = get_mac_address(interface="Ethernet 3")
ip_mac = get_mac_address(ip="192.168.0.1")
ip6_mac = get_mac_address(ip6="::1")
host_mac = get_mac_address(hostname="localhost")
updated_mac = get_mac_address(ip="10.0.0.1", network_request=True)

define connect ():
    
    
コード例 #29
0
import sys
import MySQLdb as ms
import connect

conn = connect(db, passwd)

# method 1: fetch row-by-row
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile")
while 1:
    row = cursor.fetchone()
    if row == None:
        break
    print "id: %s, name: %s, cats: %s" % \
          (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close()

# method 2: all rows at once
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile")
rows = cursor.fetchall()
for row in rows:
    print "id: %s, name: %s, cats: %s" % \
          (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close()

# method 3: cursor as dictionary
cursor = conn.cursor(ms.cursors.DictCursor)
cursor.execute("SELECT id, name, cats FROM profile")
コード例 #30
0
import sys
import MySQLdb as ms
import connect

conn = connect(db, passwd)

# method 1: fetch row-by-row
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile")
while 1:
    row = cursor.fetchone()
    if row == None:
	break
    print "id: %s, name: %s, cats: %s" % \
          (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close()

# method 2: all rows at once
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile")
rows = cursor.fetchall()
for row in rows:
    print "id: %s, name: %s, cats: %s" % \
          (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close()

# method 3: cursor as dictionary
cursor = conn.cursor(ms.cursors.DictCursor)
cursor.execute("SELECT id, name, cats FROM profile")
コード例 #31
0
#modifieid the roi_density.py script assumes hu to density table uses linear interpolation

# Script to compute the minimum, maximum and average density and the standard deviation
# of the density for an ROI for the currently open patient
# Select the ROI to compute average density for by setting the parameter 'roi_name'
# Density override values are not taken into account in the computation

from connect import *
import sys
from time import time

connect(22392)


#roi_name = 'CTV'
def FindImagingSystem(frameofreference):
    patient = get_current("Patient")
    for exam in patient.Examinations:
        if frameofreference == exam.EquipmentInfo.FrameOfReference:
            return exam.EquipmentInfo.ImagingSystemReference.ImagingSystemName, exam.Name
    return None


def interpolate(yn, x1, y1, x2, y2):
    #pt to interpolate to followed by coordinates
    if y2 - y1 == 0:
        return 0
    else:
        return (x1 + (yn - y1) * (x2 - x1) / (y2 - y1))

コード例 #32
0
                 datetime.now().strftime("%m/%d-%H:%M:%S") +
                 ": Error: Got 404 from the server, is the address correct ?"
             )
         else:
             print(datetime.now().strftime("%m/%d-%H:%M:%S") +
                   ": Error while retrieving peer information.")
         print(datetime.now().strftime("%m/%d-%H:%M:%S") +
               ": Retrying in 5 minutes")
         time.sleep(300)  # Sleep for 5 minutes
     else:
         print(datetime.now().strftime("%m/%d-%H:%M:%S") +
               ": Lab starts on " +
               peer["start_date"].strftime("%d/%m/%Y @ %H:%M:%S"))
         while (datetime.now() < peer["start_date"]):
             sleep(60)
         connect(peer)
         LAB = 1
         # daemonize the thread so that it stops with the main program
         thread = threading.Thread(target=thr_lab_timer,
                                   args=(1, peer["lab_duration"]),
                                   daemon=True)
         thread.start()
         # Wait for lab to finish
         thread.join()
         # Flush interfaces
         rc = call("./flush.sh")
 except Exception as e:
     print(
         datetime.now().strftime("%m/%d-%H:%M:%S") +
         ": Error : Could not retrieve peer information. Retrying in 5 minutes."
     )
コード例 #33
0
import subprocess, sys
import socket, os
import connect
import urllib2

socket = socket.gethostbyaddr(socket.gethostname())[0]
os.system("ps -ef | grep oracle")
os.system("nohup $DOMAIN_HOME/bin/startNodeManager.sh")

# by using connect module the weblogic hosts

#client = connect.Client()

#response = urllib2.urlopen("t3://eu-middleware-sb1:7004")

url = "response"

# connect('username' 'password' 'url')
connect('weblogic' 'weblogic1' 't3://eu-middleware-sb1:7004')
コード例 #34
0
ファイル: server.py プロジェクト: utleyja/telnetServer
def main(port, maximum):
	try:
		connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		for file in ["banlist.txt", "ledger.txt"]:
			if not os.path.isfile(file):
				open(file, "a").close()

		output = str(int(time.time())) + "  Main" + "    " + "localhost" + " " * 7 + str(port) + \
			get_space("port", len(str(port))) + "Program started.\n"

		ledger.write(output)

		signal.signal(signal.SIGINT, signal_handler)

		connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

		connection.bind(tuple(["", port]))

		connection.listen(10)

		sys.stdout.write("Timestamp   Thread  Address         Port   Output\n")

		sys.stdout.write(output)

		while True:
			client, address = connection.accept()

			active_addresses = []

			allow = [True]

			for item in active_clients:
				active_addresses.append(active_clients[item]["address"])

			if address[0] in open("banlist.txt", "r").read():
				allow[0] = False

				allow.append("ban")

			elif address[0] in active_addresses:
				allow[0] = False

				allow.append("pty")

			elif len(threading.enumerate()) >= maximum:
				allow[0] = False

				allow.append("max")

			connect(client, address, allow)

	except Exception as error:
		if error.errno != errno.EINTR:
			output = str(int(time.time())) + "  Main" + " " * 27 + str(error)

			sys.stdout.write(output + "\n")

			ledger.write(output + "\n")

	finally:
		connection.close()

		accounts = open("userlist.json", "w+")

		accounts.write(json.dumps(data, indent=4))

		accounts.close()