コード例 #1
0
ファイル: pythoncard.py プロジェクト: Fredtonyvel/Python_GUI
    def scanButton(self):

        self.displayScan = Label(self.master, text="Scanning card...")
        self.displayScan.pack()

        self.cr = CardRequest(timeout=None, newcardonly=True)

        self.cardtype = "3B 8F 80 01 80 4F 0C A0 00 00 03 06 40 00 00 00 00 00 00 28"
        self.length = 10

        self.cs = self.cr.waitforcard()
        self.cs.connection.connect()
        self.cs.card = toHexString(self.cs.connection.getATR())
        self.SELECT = [0xFF, 0xCA, 0x00, 0x00, 0x00]

        self.response, self.sw1, self.sw2 = self.cs.connection.transmit(
            self.SELECT)
        self.texting = toHexString(self.response).replace(' ', '')
        self.word_len = len(self.texting)
        #print("Success!")

        if self.cs.card == self.cardtype and self.length == self.word_len:
            header()
            self.a = search_Student(self.texting)
            self.student = Label(self.master, text=self.a)
            self.student.pack()
            self.cs.connection.disconnect()
            formular()
        else:
            self.cs = self.cr.waitforcard()
            self.cs.connection.disconnect()
コード例 #2
0
ファイル: __main__.py プロジェクト: tslight/cjson
def cjson(screen, path):
    curses.curs_set(0)
    color()
    header(screen)
    footer(screen)
    div, txt = body(screen)
    data = get_json(path)
    eventloop(screen, div, txt, data)
コード例 #3
0
def akun(x):
    header.header()
    userpw.akunadmin()
    os.system('cls')
    header.header()
    nabanala.naba()
    os.system('cls')
    menutambahan.menu2()
コード例 #4
0
ファイル: masuk.py プロジェクト: ameriyulina/tubesDAPpython
def masukuser():
    cek = 0
    while cek == 0:
        header.header()
        a = userlogin.loginuser()
        if a == False:
            print("Username tidak dikenal")
            input()
        else:
            cek = cek + 1
        os.system('cls')
コード例 #5
0
ファイル: resolve.py プロジェクト: ingnelson/Subdomain
def resolve(target):
    hostname = ''
    aliaslist = []
    ipaddrlist = []
    code = ''
    header_response = {}
    iplist = []
    response = {}
    page_title = ''
    server = ''
    #zonetransfer_json = {}

    time_start = time.time()
    try:
        soc = socket.gethostbyname_ex(target)
        #zonetransfer_json = json.loads(zonetransfer.zonetransfer(target))

        if soc:
            hostname = soc[0]
            aliaslist = soc[1]
            ipaddrlist = soc[2]
            '''
			check for http headers
			'''
            try:
                header_response = json.loads(header.header(target))
                code = header_response['status']['code']
                page_title = header_response['title']
                server = header_response['http_headers']['Server']
                print(header.header(target))
            except:
                header_response = {}
                code = ''
                page_title = ''
                server = ""

            if hostname != target:
                header_response = json.loads(header.header(hostname))

            time_end = time.time()
    except:
        time_end = time.time()

    response_time = str(time_end - time_start)

    response = {'target': target, 'hostname': hostname, \
       'alias': aliaslist, 'ipaddress': ipaddrlist, \
       'status': code, 'response_time': response_time, \
       'http_response': header_response,'title':page_title,'server':server} #, 'zonetransfer': zonetransfer_json}

    response = json.dumps(response, indent=4, separators=(',', ': '))
    return response
コード例 #6
0
def tambah(L):
    a = "ya"
    while a == "ya":
        print("Masukkan Nama Lengkap\t\t: ", end="")
        x = input()
        if len(x) <= 16:
            break
        else:
            print()
            a = input("Maksimal Nama 16 Karakter. Masukkan lagi? ya/tidak")
            print()
    b = "ya"
    while b == "ya":
        print("Masukkan Username\t\t: ", end="")
        p = input()
        if len(p) <= 10:
            break
        else:
            print()
            b = input("Maksimak Username 10 karakter. Masukkan lagi?ya/tidak")
            print()
    c = "ya"
    while c == "ya":
        print("Masukkan Setoran Awal(Min. 500000)\t\t: ", end="")
        y = int(input())
        if y >= 500000:
            break
        else:
            print()
            a = input(
                "Setoran dibawah jumlah minimum. Masukkan lagi ? ya/tidak")
            print()
    e = "ya"
    while e == "ya":
        print("Masukkan PIN anda (6 Digits)\t\t: ", end="")
        z = input()
        if len(z) == 6:
            break
        else:
            print()
            a = input("PIN tidak sesuai ketentuan. Masukkan lagi? ya/tidak")
            print()
    import json
    o = waktu.waktu()
    print(o)
    os.system("cls")
    header.header()
    os.system("cls")
    p = [x, p, y, z, o]
    L.append(p)
    return L
コード例 #7
0
ファイル: down_html.py プロジェクト: netext/dayworkspace
 def __init__(self, url):
     self.url = url
     self.host = re.search('^(http[s]?:\/\/)?((www.)?[\w]+(\.\w*)+)',
                           self.url).groups()[1]
     self.header = header()(self.host)
     self.proxies = {}
     self.status = True
コード例 #8
0
def test_wildcard(target):
	random_string = rnd('abcdefghijklmnopqrstuvwxyz')
	random_subdomain = str(random_string)+'.'+target

	response = {}
	http_response = {}

	try:
		host = socket.gethostbyname(random_subdomain)
		if host:
			http_response = header.header(random_subdomain)
			http_response = json.loads(http_response)
			code = http_response['status']['code']
			try:
				content_length = str(http_response['http_headers']['content-length'])
			except:
				content_length = ''
			response.update({'test_target': random_subdomain, \
							'enabled': True, 'detected': \
							{'status_code': code, 'content_length': content_length}, \
							'http_response': http_response})
	except:
		response = {'test_target': random_subdomain, 'enabled': False, \
					'detected': {}, 'http_response': http_response}

	response = json.dumps(response, indent=4, separators=(',', ': '))
	return response
コード例 #9
0
ファイル: windaqreader.py プロジェクト: harijay/cldumpread
 def print_header(self):
     h = header(self.file)
     extent = h.get_extent()
     my8001h = h.get_value_8001H()
     print "Header Bytes:%d" % extent
     print "Value  8001H:%d" % my8001h
     print "Is    Packed:%d" % h.get_is_packed()
コード例 #10
0
    def do_GET(self):
        if self.path == "/":
            self.path = "/index"
        sendReply = False
        if self.path.endswith("index") or self.path.endswith(
                "assignments") or self.path.endswith("freelancers"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')

            self.end_headers()
            # Start
            self.wfile.write(
                bytes(
                    "<html>" + "<head>" +
                    "<link rel=\"stylesheet\" type=\"text/css\" href=\"head.css\">"
                    + "<!-- Latest compiled and minified CSS -->" +
                    "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">"
                    + "<!-- Optional theme -->" +
                    "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\" integrity=\"sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp\" crossorigin=\"anonymous\">"
                    + "<!-- Latest compiled and minified JavaScript -->" +
                    "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"></script>"
                    + "</head>" + "<body bgcolor=\"#487cbc\">", "UTF-8"))
            # Document header
            self.wfile.write(header())
            # Document body
            if self.path.endswith("index"):
                self.wfile.write(index())
            elif self.path.endswith("assignments"):
                self.wfile.write(assignments())
            elif self.path.endswith("freelancers"):
                self.wfile.write(freelancers())
            # End
            self.wfile.write(bytes("</div></body>" + "</html>", "UTF-8"))

            sendReply = False
        if self.path.endswith(".jpg"):
            mimetype = 'image/jpg'
            sendReply = True
        if self.path.endswith(".gif"):
            mimetype = 'image/gif'
            sendReply = True
        if self.path.endswith(".png"):
            mimetype = 'image/png'
            sendReply = True
        if self.path.endswith(".js"):
            mimetype = 'application/javascript'
            sendReply = True
        if self.path.endswith(".css"):
            mimetype = 'text/css'
            sendReply = True

        if sendReply == True:
            #Open the static file requested and send it
            f = open(curdir + sep + self.path, 'rb')
            self.send_response(200)
            self.send_header('Content-type', mimetype)
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
コード例 #11
0
ファイル: compose.py プロジェクト: gentooza/mail_composer
def composeMail():
    message = '''
    <!DOCTYPE html>
    <html>
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i" rel="stylesheet">
    '''
    message = header.header() + body.body() + end.end()
    return message
コード例 #12
0
def main():
    header()
    select = st.selectbox(label='Escolha o que deseja visualizar',
                          options=options,
                          format_func=lambda x: display[x])
    st.write("---------------")

    if select == 0:
        st.write('Algoritmo: **FIFO**')
        fifo()

    if select == 1:
        st.write('Algoritmo: **LRU**')
        lru()

    if select == 2:
        st.write('Algoritmo: **Ótimo**')
        otimo()
コード例 #13
0
def loginuser():
    os.system("cls")
    x = open('nasabah.txt', 'r+')
    y = json.load(x)
    header.header()
    z = inputuser.user()
    os.system("cls")
    pos = 0
    f = False
    while pos < len(y) and not f :
        if y[pos][1] == z :
            f = True
        else :
            pos = pos + 1
        if f == True:
            hasil = y[pos][1]
        else:
            hasil = f
    return hasil
コード例 #14
0
def menu():
    os.system('cls')
    header.header()
    x = tampilanuser.ui()
    os.system('cls')
    while x != 5 :
        header.header()
        if x == 1:
            o = liatuser.search()
            L = []
            L.append(o)
            ceksaldo.saldo(o)
            print("Tekan Enter untuk kembali")
            input()
        elif x == 2:
            transfer.transfer()
            print("Tekan Enter untuk kembali")
            input()
        elif x == 3:
            penarikan.penarikan()
            print("Tekan Enter untuk kembali")
            input()
        elif x == 4:
            setoran.setoran()
            print("Tekan Enter untuk kembali")
            input()
        elif x == 5:
            tutupprogram.tutup()
        os.system('cls')
        header.header()
        x = tampilanuser.ui()
        os.system('cls')
コード例 #15
0
def akunadmin():
    z = 'ya'
    a = 0
    while z == 'ya':
        header.header()
        user = input('Username = '******'Password = '******'admin') and (p == 'mimin'):
            print('Selamat Datang', user, 'Tekan Enter untuk lanjut')
            input()
            break
        elif (user == 'admin') or (p == 'mimin'):
            print('Username/Password salah')
        else:
            print('Password Salah')
        a = a + 1
        if a == 3:
            print('sudah 3x input')
            input()
        print()
        z = input('Input username dan password lagi ? ya/tidak ?')
        print()
        os.system('cls')
コード例 #16
0
def store_only_header():
    index = 3000
    while 1:
        print(str(index) + ".txt")
        k = open(html_path.format(lang='kor', idx=index), "r", encoding='UTF8')
        sources_k = BeautifulSoup(k, "html.parser")

        e = open(html_path.format(lang='eng', idx=index), "r", encoding='UTF8')
        sources_e = BeautifulSoup(e, "html.parser")

        ck = header.header(sources_k, sources_e, index, 0)
        if ck == -1:
            index = index + 1
            continue
        index = index + 1
コード例 #17
0
def check_all_pair(dic, i):
    k = open(html_path.format(lang='kor', idx=i), "r", encoding='UTF8')
    sources_k = BeautifulSoup(k, "html.parser")
    e = open(html_path.format(lang='eng', idx=i), "r", encoding='UTF8')
    sources_e = BeautifulSoup(e, "html.parser")

    k.close()
    e.close()
    #Metric 평가요소
    t1 = reference.reference(sources_k, sources_e)
    t2 = tree_compare.tree_compare(sources_k, sources_e)
    t3 = photo_check.photo_check(sources_k, sources_e)
    t4 = check_translate_pair.check_translate_pair(sources_k)
    t5 = paragraph.paragraph(sources_k, sources_e)
    t6 = reading.reading(sources_k, sources_e)

    ck_link_list = [[]]
    e_link_list = [[]]

    if (t5 == -1):
        return -1, -1, -1

    #Metric
    metric_result = metric.metric(t1, t2, t3, t4, t5, t6)
    #print (metric_result)

    ck = header.header(sources_k, sources_e, i, metric_result)
    if ck == -1:
        return -1, -1, -1
    else:
        k_link_list, e_link_list = header_for_link.header_for_link(
            sources_k, sources_e, i, metric_result)
        if k_link_list == -1:
            return -1, -1, -1
    ck_link_list = translate_k_to_e.translate_k_to_e(dic, k_link_list)

    return ck_link_list, e_link_list, metric_result
コード例 #18
0
def menu2():
    header.header
    nabanala.naba()
    y = int(input("Masukkan Pilihan : "))
    if (y == 1):
        L = []
    elif (y == 2):
        L = buka.Open()
    os.system('cls')
    header.header()
    pil = tampilan.tapil()
    os.system('cls')
    while pil != 6:
        header.header()
        if pil == 1:
            L = inputdata.tambah(L)
            print("enter untuk kembali ke menu")
            input()
        elif (pil == 2):
            L = hapus.Hapus(L)
            print("Data berhasil dihapus, enter untuk kembali menu")
            input()
        elif (pil == 3):
            liat.viewAll(L)
            print("enter untuk kembali ke menu")
            input()
        elif (pil == 4):
            simpan.Simpan(L)
            print("Data berhasil di simpan, enter untuk kembali ke menu")
            input()
        elif (pil == 5):
            tutupprogram.tutup()
        os.system('cls')
        header.header()
        pil = tampilan.tapil()
        os.system('cls')
コード例 #19
0
def intro_text(version):
	header.header(version)
	header.things_im_working_on()
コード例 #20
0
from header import header

header('Mike')
コード例 #21
0
def monte_carlo(mol, method, temperature, max_step, total_mc_moves):	
	# Import MintsHelper
	# mints = MintsHelper()

	# Open Up Trajectory File for storing vizualization
	create_trajectory = open("trajectory.xyz" , "w+")
	mc_output = open("mc_output.dat", "w+")
	header(mc_output)
	mc_output.close()

	start = time.time()
	# Calculate initial energy from given geometry
	for mc_iteration in range(total_mc_moves):
		psi4.set_active_molecule(mol)
		E1 = psi4.scf()
		coords = mol.save_string_xyz()
		coordinates = coords.split()
	        # Deleting charge and multiplicity from the array of coordinates
		del coordinates[0] #Deletes Charge
		del coordinates[0] #Deletes Multiplicity


		natoms = mol.natom() #Number of Atoms
		labels = [] #Store labels (used in print statements)

		# Store the coordinates in an natoms x 3 matrix, this makes it easier
		# to assign the Monte Carlo displacements later
		Old_Geometry = np.zeros( (natoms,3) )
		New_Geometry = np.zeros( (natoms,3) )
		for i in range(natoms):
			labels.append(coordinates[i*3+i])
			for j in range(3):
				Old_Geometry[i][j] = float(coordinates[(i*3+i) + (j+1)])
				New_Geometry[i][j] = float(coordinates[(i*3+i) + (j+1)])

		# Execute Metropolis Monte-Carlo displacements on a random coordinate and 
		# return the updated geometry.
		New_Geometry = rand_displacement(natoms, max_step, mc_iteration, labels, New_Geometry, Old_Geometry)

		# Convert Numpy Matrices to Psi4 input using "numpy2psi" function and a function
		# from the Molecule class in Psi4. 
		Psi_Geometry_New_String,Psi_Geometry_Old_String = numpy2psi(natoms, labels, New_Geometry,Old_Geometry) #Conversion
		new_mol = psi4.Molecule.create_molecule_from_string(Psi_Geometry_New_String) #New Coordinates
		old_mol = psi4.Molecule.create_molecule_from_string(Psi_Geometry_Old_String) #Old Coordinates

		#print("New Coordinate Matrix: \n %s" %New_Geometry)

		mc_out = open("mc_output.dat" , "a")
		mc_out.write("Current MC Move: \n Geometry from iteration: %d \n %s \n" %(mc_iteration,Old_Geometry))
		mc_out.write("\n Attempted Geometry Move: %d \n %s \n" %(mc_iteration+1,New_Geometry))

		# Activate the Molecule object created from the new coordinates
		# and run the QM method on it
		psi4.set_active_molecule(new_mol)
		try:
			E2 = psi4.scf() 

			mc_out.write("%s energy with old geometry: %f\n" %(method,E1))
			mc_out.write("%s energy with new geometry: %f\n" %(method,E2))

			Energy_Difference = E2 - E1
			mc_out.write("energy difference: %f\n" %(Energy_Difference))
			Energy_Difference_eV = Energy_Difference*hartree2eV
			#mol = acceptance_check(Energy_Difference,temperature, new_mol, old_mol, natoms, mc_iteration)  
			Boltz = np.exp(- Energy_Difference/(8.617e-5 * temperature))
			R = rand.random()
			trajectory_file = open("trajectory.xyz" , "a")
			if (abs(Energy_Difference) >= 1e-10):
				mc_out.write("\n Significant Change in Energy Performing acceptance check (R = %f) \n" %R)
				if (Boltz > R):
					mc_out.write("Coordinates Accepted: Using New Coordinates for Next Monte Carlo Run \n")
					mol = new_mol
					trajectory_file.write("%d \n" %natoms)
					trajectory_file.write("Step %d of Psi4 Monte-Carlo Simulation (Coordinates Updated) \n" %(mc_iteration))
					for i in range(natoms):
						trajectory_file.write("%s  " %labels[i])
						for j in range(3):
							if (j == 2):
								trajectory_file.write("    %f \n" %(New_Geometry[i][j]))
							else:
								trajectory_file.write("    %f" %(New_Geometry[i][j]))
				else:
					mc_out.write("Coordinates Denied: Repeating Monte Carlo Run With Coordinates From Previous Run \n")
					mol = old_mol
			else:
				mc_out.write("No Change in Energy: Repeating Monte Carlo Run With Old Coordinates \n")
				mol = old_mol
			trajectory_file.close()
			mc_out.close()
		
		except RuntimeError:
			mc_out.write("SCF Did Not Converge: Repeating Monte Carlo Run With Old Coordinates \n")
                        mol = old_mol
                        trajectory_file.close()
                        mc_out.close()
	end = time.time()
	total_elasped = end - start
	mc_out.write("Total Monte Carlo Time: %f" %(total_elapsed))
コード例 #22
0
las_file = None
st.sidebar.write('# LAS Data Explorer')
st.sidebar.write(
    'To begin using the app, load your LAS file using the file upload option below.'
)

uploadedfile = st.sidebar.file_uploader(' ', type=['.las'])
las_file, well_data = load_data(uploadedfile)

if las_file:
    st.sidebar.success('File Uploaded Successfully')
    st.sidebar.write(f'<b>Well Name</b>: {las_file.well.WELL.value}',
                     unsafe_allow_html=True)

# Sidebar Navigation
st.sidebar.title('Navigation')
options = st.sidebar.radio('Select a page:', [
    'Home', 'Header Information', 'Data Information', 'Data Visualisation',
    'Missing Data Visualisation'
])

if options == 'Home':
    home.home()
elif options == 'Header Information':
    header.header(las_file)
elif options == 'Data Information':
    raw_data.raw_data(las_file, well_data)
elif options == 'Data Visualisation':
    plotting.plot(las_file, well_data)
elif options == 'Missing Data Visualisation':
    missingdata.missing(las_file, well_data)
コード例 #23
0
import random, sys, time
import threading
from inp import *
from os import system
from colorama import *
from header import header
from board import board
from people import *
from objects import *
from mandolorian import *
from bossenemy import *
print("Welcome to the Jetpack Joyride ")
print("Press Enter to start", end="")
inp = input()
system('clear')
head = header(1000, 0, 3)
Board = board(5000, 30)
objects = scoringobject()
objects.createpositions()
objects.places()
Board.printobjects(objects)
mando = mandolorian()
bossenemy = boss()
#bossenemy.addtoobstacles(objects)
getch = Get()
i = 0
# for shield
shield = 0
powerup = 0
dragonactivation = 0
powerupactivation = 0
コード例 #24
0
ファイル: main.py プロジェクト: Luis-Cisneros/bitcoin_mining
import bitstring as bs
import sha256 as sh
import header as hd
import datetime

if __name__ == '__main__':
    # Target
    max_value = 26959535291011309493156476344723991336010898738574164086137773096960
    difficulty = 13008091666971.90
    target = max_value / difficulty
    # Construction of block header
    # Block 600,000 is used as example
    version = '0x20000000'
    prev_hash = '0x00000000000000000003ecd827f336c6971f6f77a0b9fba362398dd867975645'
    merkle_root = '0x66b7c4a1926b41ceb2e617ddae0067e7bfea42db502017fde5b695a50384ed26'
    time = int(datetime.datetime(2019, 10, 18, 19, 4, 21).timestamp())
    bits = 387294044
    nonce = 1066642855
    header = hd.header(version, prev_hash, merkle_root, time, bits, nonce)
    # Looking for nonce to be under target
    block_hash = bs.BitString(uint=sh.sha256(sh.sha256(header)).uintle, length=256)
    while block_hash.uint > int(target):
        nonce += 1
        block_hash = bs.BitString(uint=sh.sha256(sh.sha256(header)).uintle, length=256)
    print('The nonce is: ' + str(nonce) + '\nThe hash is: ' + str(block_hash))
コード例 #25
0
    cardtype = "3B 8F 80 01 80 4F 0C A0 00 00 03 06 40 00 00 00 00 00 00 28"
    length=10
    print('\t''------Tap card to SIGN IN-------')

   # cr = CardRequest(timeout=10, cardType=cardtype)
    cr = CardRequest(timeout=None, newcardonly=True)
    cs = cr.waitforcard()
    cs.connection.connect()
    card = toHexString(cs.connection.getATR())
    SELECT = [0xFF, 0xCA, 0x00, 0x00, 0x00]

    response, sw1, sw2 = cs.connection.transmit( SELECT)
   # print ('response: ', response, ' status words: ', "%x %x" % (sw1, sw2))
    texting = toHexString(response).replace(' ','')
    word_len=len(texting)
    if card == cardtype and length == word_len :
        header()
        search_Student(texting)
        cs.connection.disconnect()
        formular()

    else:
        cs = cr.waitforcard()
        cs.connection.disconnect()
        os.system ('clear')
        print (alert.stop)
        os.system ('say Try Again')

 
   
コード例 #26
0
ファイル: main.py プロジェクト: Maxou56800/Python-AlgoToolKit
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#----------------------------------------------------------------------------------#
# Nom: AlgoToolKit								   #
# Objectif: Utiliser plusieurs algorithmes de conversation et de hashage en python #
# Autheur: Maxime Berthault (Maxou56800)					   #
# Mail: Maxou56800[AT]gmail[DOT]com						   #
# Derniere modification: 29/07/2012						   #
# License: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007) | Voir COPYING.txt #
#----------------------------------------------------------------------------------#

#### Importation des Libraries ####
import header , menu
###################################

#### Déclaration des variables ####
version = "3.0"
###################################

#### INTRO HEADERS ####
header.header(version)
#######################

#### MAIN MENU ####
menu.menu()
##################
コード例 #27
0
import os
import header
import mainlogin
import userpw
import menutambahan
import masuk
import tampilanuser
import menu1
os.system('cls')
header.header()
mainlogin.pilog()
x = int(input("Masukkan pilihan : "))
os.system('cls')
if x == 1:
    userpw.akunadmin()
    os.system('cls')
    header.header()
    os.system('cls')
    menutambahan.menu2()
    
elif x == 2 :
    header.header()
    masuk.masukuser()
    os.system('cls')
    menu1.menu()
コード例 #28
0
ファイル: main.py プロジェクト: teabreakninja/py_wsjtx
def main():
    global out_log
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # server_address = ('127.0.0.1', 2237)

    # sock.sendto('test message', config.server_address)

    sock.bind(config.server_address)

    # config.use_curses = True
    if config.use_curses:
        jt_curses = WsjtxCurses()

    # Exit py_wsjtx on WSJT-X exit
    # exit_on_wsjtxexit = False

    # Enable DXCC notify alerts
    # notify_alert = True
    if config.notify_alert:
        Notify.init("DX")
        if not popup_toast('Notifications enabled'):
            jt_curses.add_main_window('[!] Notification Error')

    # Publish mqtt messages, requires paho installed
    # config.use_mqtt = True
    # mqtt_server = "192.168.0.12"

    # Write all decodes to a log file
    config.log_decodes = False
    config.log_outfile = "/tmp/py_wsjtx.log"

    # Read existing log file
    log = WsjtxLog()
    log_info = "[*] Logfile found, {} entries read, {} stations.".format(log.entry_count, len(log.log_entries))
    if config.use_curses:
        jt_curses.add_main_window(log_info)
    else:
        print(log_info)

    current_band = ""
    state = {}

    if config.log_decodes:
        out_log = open(config.log_outfile, 'a', 0)
        out_log.write("Started Log at {}\n".format(datetime.datetime.now()))

    if config.use_mqtt:
        import paho.mqtt.client as paho
        mqtt_client=paho.Client(protocol=paho.MQTTv31)
        mqtt_client.connect(config.mqtt_server, keepalive=60, )
        mqtt_client.loop_start()
        mqtt_client.publish("py_wsjtx/status", "Started at {}".format(datetime.datetime.now()))


    # # Replay is PITA when testing
    # data, server = sock.recvfrom(1024)
    # p = header.create_header()
    # p += Replay.create_packet()
    # sock.sendto(p, server)

    try:
        while True:
            data, server = sock.recvfrom(1024)
            h = header(data[0:16])
            # print "data:", data
            packet_type = struct.unpack(">L", data[8:12])[0]

            # print("[*] packet_type:{}".format(packet_type))
            if packet_type == PacketType.Heartbeat:
                payload = Heartbeat(data[12:])
                if config.use_curses:
                    jt_curses.update_heartbeat(datetime.datetime.now().strftime("%H:%M:%S"))
                else:
                    print("[*] Heartbeat [{}]".format(datetime.datetime.now()))

                if config.use_mqtt:
                    mqtt_msg = json.dumps({"heartbeat": datetime.datetime.now().strftime("%H:%M:%S")})
                    mqtt_client.publish("py_wsjtx/{}/status".format(payload.id_key), mqtt_msg)

            elif packet_type == PacketType.Status:
                payload = StateChange(data[12:])

                # Set a per radio state
                state[payload.id_key] = {'freq': payload.dial_freq,
                                        'mode': payload.tx_mode,
                                        'tx': str(payload.tx_enabled),
                                        'band': log.get_band(str(payload.dial_freq/1000/1000))
                                        }

                if config.use_mqtt:
                    mqtt_msg = json.dumps({'status_frequency': str(payload.dial_freq),
                                        'status_mode': str(payload.tx_mode),
                                        'status_tx': str(payload.tx_enabled)})
                    mqtt_client.publish("py_wsjtx/{}/status".format(payload.id_key), mqtt_msg)

                if config.use_curses:
                    jt_curses.set_banner(payload.dial_freq,
                                         payload.tx_mode,
                                         str(payload.tx_enabled))
                else:
                    print(payload.do_print())

                current_band = log.get_band(str(payload.dial_freq/1000/1000))
                # print("[!] Current band: {}".format(current_band))

            elif packet_type == PacketType.Decode:
                # myutils.debug_packet(data)
                payload = Decode(data[12:])

                # Get current radio state or return ???
                decode_mode = state.get(payload.id_key, {}).get('mode','???')

                # If it's JT65/JT9 mode, check actual received signal mode
                if decode_mode == "JT9" or decode_mode == "JT65":
                    if payload.mode == '#':
                        decode_mode = "JT65"
                    elif payload.mode == "@":
                        decode_mode = "JT9"
                    else:
                        decode_mode = "ERR"

                decode_band = state.get(payload.id_key, {}).get('band','???')
                decode_dialfreq = state.get(payload.id_key, {}).get('freq','???')

                if config.use_mqtt:
                    mqtt_msg = json.dumps({'time': payload.now_time,
                                        'db': str(payload.snr).rjust(2),
                                        'dt': payload.delta_time,
                                        'dialfreq': decode_dialfreq,
                                        'freq': str(payload.delta_freq).rjust(4),
                                        'mode': decode_mode,
                                        'band': decode_band,
                                        'msg': payload.message})
                    # mqtt_client.publish("py_wsjtx/{}/decodes".format(payload.id_key), mqtt_msg)
                    mqtt_client.publish("py_wsjtx/{}/decodes".format("WSJT-X"), mqtt_msg)


                # info = "[{}] db:{:0>2} DT:{:.1f} Freq:{} DFreq:{} Mode:{} Msg: {}".format(
                #         payload.now_time,
                #         str(payload.snr).rjust(2),
                #         payload.delta_time,
                #         decode_dialfreq,
                #         str(payload.delta_freq).rjust(4),
                #         decode_mode,
                #         payload.message)

                info = "[{}] {:>3}db, {:>4}Hz, {:>3}, {:>4}, Msg: {}".format(
                        payload.now_time,
                        str(payload.snr).rjust(2),
                        str(payload.delta_freq).rjust(4),
                        decode_band,
                        decode_mode,
                        payload.message
                )

                if config.log_decodes:
                    out_log.write("{}\n".format(info))

                if config.use_curses:
                    jt_curses.add_main_window(info)
                else:
                    payload.do_print()

                # Check for CQ call
                if payload.message[:2] == "CQ":
                    cq = payload.message.split(" ")
                    if len(cq) > 1:
                        # CQ call should be 'CQ CALL LOC', but can be:
                        # 'CQ DX CALL LOC' or
                        # 'CQ CALL DX LOC'
                        try:
                            cq_call = cq[1]
                            if len(cq) == 2:
                                cq_loc = ""
                            else:
                                cq_loc = cq[2]

                            if cq_call == "DX":
                                cq_call = cq[2]
                                if len(cq) > 3:
                                    cq_loc = cq[3]
                                else:
                                    cq_loc = ""

                            if cq_loc == "DX":
                                if len(cq) > 3:
                                    cq_loc = cq[3]
                                else:
                                    cq_loc = ""
                        except:
                            print("[!] Error parsing CQ call")
                            continue

                        # Check for valid callsign
                        if (myutils.validate_callsign(cq_call)):

                            # Have we worked call before?
                            band = log.check_entry2(cq_call, current_band)

                            if band["call"]:
                                # worked call before
                                if band["call_band"]:
                                    # ...and worked call on this band
                                    colour = bcolors.WKD_BEFORE
                                    status = log.WORKED_COUNTRY_AND_STATION

                                elif band["country_band"]:
                                    # Worked call on a different band but 
                                    # also worked country on this band
                                    colour = bcolors.WKD_COUNTRY_NOT_STATION
                                    status = log.WORKED_COUNTRY_NOT_STATION

                                else:
                                    # TODO: check flags
                                    colour = bcolors.WKD_COUNTRY_DIFF_BAND
                                    status = log.WORKED_COUNTRY_DIFF_BAND

                            else:
                                # call not workedg
                                if band["country"]:
                                    if band["country_band"]:
                                        # ...but have worked country on this band
                                        colour = bcolors.WKD_COUNTRY_NOT_STATION
                                        status = log.WORKED_COUNTRY_NOT_STATION

                                    else:
                                        # ...but have worked country before, on different band
                                        colour = bcolors.WKD_COUNTRY_DIFF_BAND
                                        status = log.WORKED_COUNTRY_DIFF_BAND

                                else:
                                    # Call or country not worked, raise DXCC alert
                                    colour = bcolors.NOT_WORKED
                                    status = log.NOT_WORKED

                                    if config.notify_alert:
                                        if not popup_toast(log.dxcc.find_country(cq_call)):
                                            jt_curses.add_main_window('[!] Failed to notify CQ')

                                    if config.use_mqtt:
                                        mqtt_msg = json.dumps({'time': payload.now_time,
                                                        'db': str(payload.snr),
                                                        'dxcc_call': cq_call,
                                                        'dxcc_locator': cq_loc,
                                                        'dxcc_country': log.dxcc.find_country(cq_call),
                                                        'dxcc_mode': decode_mode,
                                                        'dxcc_band': decode_band,
                                                        'dialfreq': decode_dialfreq})
                                        mqtt_client.publish("py_wsjtx/{}/dxcc".format(payload.id_key), mqtt_msg)

                            # Now display
                            if config.use_curses:
                                jt_curses.add_cq(cq_call,
                                                status+1,
                                                cq_loc,
                                                log.dxcc.find_country(cq_call),
                                                band)
                            else:
                                print("[***] CQ CALLED BY {}{}{} ({}) [{}]".format(colour, cq_call, bcolors.ENDC, cq_loc, status))
                                if (myutils.validate_locator(cq_loc)):
                                    print("  [*] Distance: {:.0f}km, Bearing:{:.0f}".format(
                                            locator.calculate_distance(config.locator, cq_loc),
                                            locator.calculate_heading(config.locator, cq_loc)
                                        ))

                        else:
                            msg = "[*] CQ by non-valid callsign?"
                            if config.use_curses:
                                jt_curses.add_main_window(msg)
                            else:
                                print(msg)

            elif packet_type == PacketType.Clear:
                payload = Clear(data[12:])
                if config.use_curses:
                    jt_curses.add_main_window("[*] Clear Called")
                else:
                    payload.do_print()

            elif packet_type == PacketType.Reply:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.QSO_Logged:
                # myutils.debug_packet(data)
                payload = Qso_Logged(data[12:])
                if config.use_curses:
                    jt_curses.add_main_window("[*] Logged QSO with {}".format(payload.dx_call))
                else:
                    payload.do_print()
                # re-read the log file
                log.read_log()

            elif packet_type == PacketType.Close:
                payload = Close(data[12:])
                if config.use_curses:
                    jt_curses.add_main_window("[!] Exit called")
                else:
                    payload.do_print
                if config.exit_on_wsjtxexit:
                    sys.exit(0)

            elif packet_type == PacketType.Replay:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.Halt_TX:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.Free_Text:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.WSPRDecode:
                payload = WSPRDecode(data[12:])

                decode_band = state.get(payload.id_key, {}).get('band','???')

                if config.use_mqtt:
                    mqtt_msg = json.dumps({'WSPR_call': payload.callsign,
                                        'band': decode_band,
                                        'grid': payload.grid,
                                        'dist': int(payload.dist),
                                        'pwr': payload.power,
                                        'db': payload.snr})
                    mqtt_client.publish("py_wsjtx/{}/wspr".format(payload.id_key), mqtt_msg)

                info = "WSPR [{}]: {:10} ({:6}) db:{:4}, Freq:{:>10,}Hz, pwr:{:4}, Dist:{:>5.0f}km, Az: {:>3.0f}".format(
                            payload.now_time,
                            payload.callsign,
                            payload.grid,
                            payload.snr,
                            payload.delta_freq,
                            payload.power,
                            payload.dist,
                            payload.bearing)

                if config.log_decodes:
                    out_log.write("{}\n".format(info))

                if config.use_curses:
                    jt_curses.add_main_window(info)
                else:
                    payload.do_print()

            else:
                if config.use_curses:
                    jt_curses.add_main_window("[*] Packet type: {}".format(packet_type))
                else:
                    print("[*] Packet type: {}".format(packet_type))

    except KeyboardInterrupt:
        if config.use_curses:
            jt_curses.exit_now()
        if config.log_decodes:
            out_log.write("Closed Log at {}\n".format(datetime.datetime.now()))
            out_log.close()
        print("ctrl-c caught, exiting")
        if config.notify_alert:
            Notify.uninit()
コード例 #29
0
ファイル: main.py プロジェクト: DungeonMaestro215/LED_Project
import sys
#import time
#import numpy as np
#
from header import header
from montecarlo import montecarlo
from fire import fire
from control import control

effect = ""
try:
    effect = sys.argv[1]
except IndexError:
    print("")

# Initialize Pixels
num_pixels, pixels = header(300)

if (effect == "montecarlo"):
    montecarlo(num_pixels, pixels)
elif (effect == "fire"):
    fire(num_pixels, pixels)
elif (effect == "control"):
    control(num_pixels, pixels)
コード例 #30
0
ファイル: main.py プロジェクト: JayGe/py_wsjtx
def main():
    global out_log
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # server_address = ('127.0.0.1', 2237)

    # sock.sendto('test message', config.server_address)

    sock.bind(config.server_address)

    # config.use_curses = True
    if config.use_curses:
        jt_curses = WsjtxCurses()

    # Exit py_wsjtx on WSJT-X exit
    # exit_on_wsjtxexit = False

    # Enable DXCC notify alerts
    # notify_alert = True
    if config.notify_alert:
        Notify.init("DX")
        if not popup_toast('Notifications enabled'):
            jt_curses.add_main_window('[!] Notification Error')

    # Publish mqtt messages, requires paho installed
    # config.use_mqtt = True
    # mqtt_server = "192.168.0.12"

    # Write all decodes to a log file
    config.log_decodes = False
    config.log_outfile = "/tmp/py_wsjtx.log"

    # Read existing log file
    log = WsjtxLog()
    log_info = "[*] Logfile found, {} entries read, {} stations.".format(
        log.entry_count, len(log.log_entries))
    if config.use_curses:
        jt_curses.add_main_window(log_info)
    else:
        print(log_info)

    current_band = ""
    state = {}

    if config.log_decodes:
        out_log = open(config.log_outfile, 'a', 0)
        out_log.write("Started Log at {}\n".format(datetime.datetime.now()))

    if config.use_mqtt:
        import paho.mqtt.client as paho
        mqtt_client = paho.Client()
        mqtt_client.connect(config.mqtt_server, keepalive=60)
        mqtt_client.loop_start()
        mqtt_client.publish("py_wsjtx/status",
                            "Started at {}".format(datetime.datetime.now()))

    # # Replay is PITA when testing
    # data, server = sock.recvfrom(1024)
    # p = header.create_header()
    # p += Replay.create_packet()
    # sock.sendto(p, server)

    try:
        while True:
            data, server = sock.recvfrom(1024)
            h = header(data[0:16])
            # print "data:", data
            packet_type = struct.unpack(">L", data[8:12])[0]

            # print("[*] packet_type:{}".format(packet_type))
            if packet_type == PacketType.Heartbeat:
                payload = Heartbeat(data[12:])
                if config.use_curses:
                    jt_curses.update_heartbeat(
                        datetime.datetime.now().strftime("%H:%M:%S"))
                else:
                    print("[*] Heartbeat [{}]".format(datetime.datetime.now()))

                if config.use_mqtt:
                    mqtt_msg = json.dumps({
                        "heartbeat":
                        datetime.datetime.now().strftime("%H:%M:%S")
                    })
                    mqtt_client.publish(
                        "py_wsjtx/{}/status".format(payload.id_key), mqtt_msg)

            elif packet_type == PacketType.Status:
                payload = StateChange(data[12:])

                # Set a per radio state
                state[payload.id_key] = {
                    'freq': payload.dial_freq,
                    'mode': payload.tx_mode,
                    'tx': payload.tx_enabled,
                    'band': log.get_band(str(payload.dial_freq / 1000 / 1000))
                }

                if config.use_mqtt:
                    mqtt_msg = json.dumps({
                        'status_frequency': payload.dial_freq,
                        'status_mode': payload.tx_mode,
                        'status_tx': payload.tx_enabled
                    })
                    mqtt_client.publish(
                        "py_wsjtx/{}/status".format(payload.id_key), mqtt_msg)

                if config.use_curses:
                    jt_curses.set_banner(payload.dial_freq, payload.tx_mode,
                                         payload.tx_enabled)
                else:
                    print(payload.do_print())

                current_band = log.get_band(
                    str(payload.dial_freq / 1000 / 1000))
                # print("[!] Current band: {}".format(current_band))

            elif packet_type == PacketType.Decode:
                # myutils.debug_packet(data)
                payload = Decode(data[12:])

                # Get current radio state or return ???
                # decode_mode = state.get(payload.id_key, {}).get('mode','???')
                decode_mode = "JT65" if payload.mode == '#' else "JT9"
                decode_band = state.get(payload.id_key, {}).get('band', '???')
                decode_dialfreq = state.get(payload.id_key,
                                            {}).get('freq', '???')

                if config.use_mqtt:
                    mqtt_msg = json.dumps({
                        'time':
                        payload.now_time,
                        'db':
                        str(payload.snr).rjust(2),
                        'dt':
                        payload.delta_time,
                        'dialfreq':
                        decode_dialfreq,
                        'freq':
                        str(payload.delta_freq).rjust(4),
                        'mode':
                        decode_mode,
                        'band':
                        decode_band,
                        'msg':
                        payload.message
                    })
                    mqtt_client.publish(
                        "py_wsjtx/{}/decodes".format(payload.id_key), mqtt_msg)

                # info = "[{}] db:{:0>2} DT:{:.1f} Freq:{} DFreq:{} Mode:{} Msg: {}".format(
                #         payload.now_time,
                #         str(payload.snr).rjust(2),
                #         payload.delta_time,
                #         decode_dialfreq,
                #         str(payload.delta_freq).rjust(4),
                #         decode_mode,
                #         payload.message)

                info = "[{}] {:>3}db, {:>4}Hz, {:>3}, {:>4}, Msg: {}".format(
                    payload.now_time,
                    str(payload.snr).rjust(2),
                    str(payload.delta_freq).rjust(4), decode_band, decode_mode,
                    payload.message)

                if config.log_decodes:
                    out_log.write("{}\n".format(info))

                if config.use_curses:
                    jt_curses.add_main_window(info)
                else:
                    payload.do_print()

                # Check for CQ call
                if payload.message[:2] == "CQ":
                    cq = payload.message.split(" ")
                    if len(cq) > 1:
                        # CQ call should be 'CQ CALL LOC', but can be:
                        # 'CQ DX CALL LOC' or
                        # 'CQ CALL DX LOC'
                        cq_call = cq[1]
                        if len(cq) == 2:
                            cq_loc = ""
                        else:
                            cq_loc = cq[2]

                        if cq_call == "DX":
                            cq_call = cq[2]
                            if len(cq) > 3:
                                cq_loc = cq[3]
                            else:
                                cq_loc = ""

                        if cq_loc == "DX":
                            if len(cq) > 3:
                                cq_loc = cq[3]
                            else:
                                cq_loc = ""

                        # Check for valid callsign
                        if (myutils.validate_callsign(cq_call)):

                            # Have we worked call before?
                            band = log.check_entry2(cq_call, current_band)

                            if band["call"]:
                                # worked call before
                                if band["call_band"]:
                                    # ...and worked call on this band
                                    colour = bcolors.WKD_BEFORE
                                    status = log.WORKED_COUNTRY_AND_STATION

                                elif band["country_band"]:
                                    # Worked call on a different band but
                                    # also worked country on this band
                                    colour = bcolors.WKD_COUNTRY_NOT_STATION
                                    status = log.WORKED_COUNTRY_NOT_STATION

                                else:
                                    # TODO: check flags
                                    colour = bcolors.WKD_COUNTRY_DIFF_BAND
                                    status = log.WORKED_COUNTRY_DIFF_BAND

                            else:
                                # call not worked
                                if band["country"]:
                                    if band["country_band"]:
                                        # ...but have worked country on this band
                                        colour = bcolors.WKD_COUNTRY_NOT_STATION
                                        status = log.WORKED_COUNTRY_NOT_STATION

                                    else:
                                        # ...but have worked country before, on different band
                                        colour = bcolors.WKD_COUNTRY_DIFF_BAND
                                        status = log.WORKED_COUNTRY_DIFF_BAND

                                else:
                                    # Call or country not worked, raise DXCC alert
                                    colour = bcolors.NOT_WORKED
                                    status = log.NOT_WORKED

                                    if config.notify_alert:
                                        if not popup_toast(
                                                log.dxcc.find_country(
                                                    cq_call)):
                                            jt_curses.add_main_window(
                                                '[!] Failed to notify CQ')

                                    if config.use_mqtt:
                                        mqtt_msg = json.dumps({
                                            'time':
                                            payload.now_time,
                                            'db':
                                            str(payload.snr),
                                            'dxcc_call':
                                            cq_call,
                                            'dxcc_locator':
                                            cq_loc,
                                            'dxcc_country':
                                            log.dxcc.find_country(cq_call),
                                            'dxcc_mode':
                                            decode_mode,
                                            'dxcc_band':
                                            decode_band,
                                            'dialfreq':
                                            decode_dialfreq
                                        })
                                        mqtt_client.publish(
                                            "py_wsjtx/{}/dxcc".format(
                                                payload.id_key), mqtt_msg)

                            # Now display
                            if config.use_curses:
                                jt_curses.add_cq(
                                    cq_call, status + 1, cq_loc,
                                    log.dxcc.find_country(cq_call), band)
                            else:
                                print("[***] CQ CALLED BY {}{}{} ({}) [{}]".
                                      format(colour, cq_call, bcolors.ENDC,
                                             cq_loc, status))
                                if (myutils.validate_locator(cq_loc)):
                                    print(
                                        "  [*] Distance: {:.0f}km, Bearing:{:.0f}"
                                        .format(
                                            locator.calculate_distance(
                                                config.locator, cq_loc),
                                            locator.calculate_heading(
                                                config.locator, cq_loc)))

                        else:
                            msg = "[*] CQ by non-valid callsign?"
                            if config.use_curses:
                                jt_curses.add_main_window(msg)
                            else:
                                print(msg)

            elif packet_type == PacketType.Clear:
                payload = Clear(data[12:])
                if config.use_curses:
                    jt_curses.add_main_window("[*] Clear Called")
                else:
                    payload.do_print()

            elif packet_type == PacketType.Reply:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.QSO_Logged:
                # myutils.debug_packet(data)
                payload = Qso_Logged(data[12:])
                if config.use_curses:
                    jt_curses.add_main_window("[*] Logged QSO with {}".format(
                        payload.dx_call))
                else:
                    payload.do_print()
                # re-read the log file
                log.read_log()

            elif packet_type == PacketType.Close:
                payload = Close(data[12:])
                if config.use_curses:
                    jt_curses.add_main_window("[!] Exit called")
                else:
                    payload.do_print
                if config.exit_on_wsjtxexit:
                    sys.exit(0)

            elif packet_type == PacketType.Replay:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.Halt_TX:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.Free_Text:
                # Not used, this is an out message
                pass

            elif packet_type == PacketType.WSPRDecode:
                payload = WSPRDecode(data[12:])

                decode_band = state.get(payload.id_key, {}).get('band', '???')

                if config.use_mqtt:
                    mqtt_msg = json.dumps({
                        'WSPR_call': payload.callsign,
                        'band': decode_band,
                        'grid': payload.grid,
                        'dist': int(payload.dist),
                        'pwr': payload.power,
                        'db': payload.snr
                    })
                    mqtt_client.publish(
                        "py_wsjtx/{}/wspr".format(payload.id_key), mqtt_msg)

                info = "WSPR [{}]: {:10} ({:6}) db:{:4}, Freq:{:>10,}Hz, pwr:{:4}, Dist:{:>5.0f}km, Az: {:>3.0f}".format(
                    payload.now_time, payload.callsign, payload.grid,
                    payload.snr, payload.delta_freq, payload.power,
                    payload.dist, payload.bearing)

                if config.log_decodes:
                    out_log.write("{}\n".format(info))

                if config.use_curses:
                    jt_curses.add_main_window(info)
                else:
                    payload.do_print()

            else:
                if config.use_curses:
                    jt_curses.add_main_window(
                        "[*] Packet type: {}".format(packet_type))
                else:
                    print("[*] Packet type: {}".format(packet_type))

    except KeyboardInterrupt:
        if config.use_curses:
            jt_curses.exit_now()
        if config.log_decodes:
            out_log.write("Closed Log at {}\n".format(datetime.datetime.now()))
            out_log.close()
        print("ctrl-c caught, exiting")
        if config.notify_alert:
            Notify.uninit()
コード例 #31
0
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RationalQuadratic
from sklearn.model_selection import GridSearchCV
from scrub_null_columns import scrub_null_columns
from header import header
from split_work import split_work

comm = MPI.COMM_WORLD
nprocs = comm.Get_size()
myrank = comm.Get_rank()
name = MPI.Get_processor_name()
i_am_master = False
if (myrank == 0):
    job_start = time()
    i_am_master = True
    header()
    print("Number of processes", nprocs)

np.set_printoptions(threshold=np.nan)
#warnings.filterwarnings("module", category=DeprecationWarning)
#warnings.simplefilter("ignore", DeprecationWarning)
#warnings.filterwarnings("ignore", category=DeprecationWarning)

bonds_in_molecule = np.loadtxt("sum_over_bonds.out", delimiter=" ")
nz_estate = np.loadtxt("nz_estate.out", delimiter=" ")
morgan_prints = np.loadtxt("morgan_prints.out", delimiter=" ")

detv = np.loadtxt("detv.out", delimiter=" ")
detp = np.loadtxt("detp.out", delimiter=" ")

kfold = KFold(n_splits=5, random_state=11, shuffle=True)
コード例 #32
0
    root.geometry(str(size_game[0] * 25) + 'x' + str(size_game[1] * 25 + 45))
    root.resizable(False, False)
    root.protocol('WM_DELETE_WINDOW', e)
    #i=PhotoImage(file='data/ico.png')
    #root.call('wm','iconphoto',root._w,i)

    import main
    from header import header
    from img import load_img
    flag_number = [boom_number[0]]
    game_status = ['normal']
    img = load_img()

    root.call('wm', 'iconphoto', root._w, img['icon'])

    h = header()
    h.frame = [Canvas(root)]
    h.frame[0].place(x=0, y=10, height=25, relwidth=1.0)
    h.flag_number = flag_number
    h.img = img
    h.exit = exit
    h.status = game_status
    h.list_cell = main.list_cell
    h.size_game = size_game

    main.frame = [Canvas(root)]
    main.frame[0].place(x=0, y=45, height=size_game[1] * 25, relwidth=1.0)
    main.flag_number = flag_number
    main.img = img
    main.game_status = game_status
    main.size_game = size_game
コード例 #33
0
        import sram
        import setup_hold

        sh = setup_hold.setup_hold()
        [one_setup_time, zero_setup_time] = sh.hold_time()

        OPTS.check_lvsdrc = True

        if OPTS.tech_name == "freepdk45":
            self.assertTrue(isclose(one_setup_time, -0.0048828125))
            self.assertTrue(isclose(zero_setup_time, -0.010986328125))
        elif OPTS.tech_name == "scn3me_subm":
            self.assertTrue(isclose(one_setup_time, 0.04638671875))
            self.assertTrue(isclose(zero_setup_time, -0.0830078125))
        else:
            self.assertTrue(False)  # other techs fail


def isclose(value1, value2):
    """ This is used to compare relative values for convergence. """
    return (abs(value1 - value2) / max(value1, value2) <= 1e-2)


# instantiate a copdsay of the class to actually run the test
if __name__ == "__main__":
    (OPTS, args) = globals.parse_args()
    del sys.argv[1:]
    header(__file__, OPTS.tech_name)
    unittest.main()
コード例 #34
0
ファイル: main.py プロジェクト: Lucidity1/datawrangler
def main():
    #initialize global variables
    settings.init()

    #Display welcome header
    header.header()

    #Load Files
    print "\nScanning Files. Please wait.."
    al_compiler.scan()
    gocc_compiler.scan()
    pmd_compiler.scan()
    cmd_compiler.scan()
    wo_compiler.scan()
    power_compiler.scan()
    print "Scan Complete.\n"

    #temp-  to be deletd
    #gocc_crawler.crawl()
    #gocc_alarm_analyzer_whisker.analyze()
    #summary.summary()
    #loop prompting for user command
    #al_crawler.crawl()
    #wo_crawler.crawl()
    #power_crawler.crawl()

    while (False):
        counter = 0
        input = str(
            raw_input('\nPROMPT: Enter \
        \n\t"/summary" to generate report.{DEPRECATED}\
        \n\t"/listing_crawl" to generate asset listing tree. \
        \n\t"/occ_crawl" to generate OCC alarm tables. \
        \n\t"/alarm_query" to search OCC alarms by equipment and date. Must have run /occ_crawl.\
        \n\t"/expand" to show all available commands.\
        \n\t"/break" to terminate. \n'))

        input = input.lower()

        if input == '/occ_query':
            gocc.query()
        elif input == '/rsstatus_query':
            gocc_rsstatus.query()
        elif input == '/alarm_analyze':
            gocc_alarm_analyzer_whisker.analyze()
        elif input == '/schedule':
            gocc_dwell.query()
        elif input == '/schedule_all':
            gocc_dwell.printAll()
        elif input == '/skip_all':
            gocc_skip.printAll("SAVE")
        elif input == '/summary':
            summary.summary()
            print '"' + settings.ofname + '" successfully generated.'
        elif input == '/occ_crawl':
            gocc_crawler.crawl()
            print '\nCrawl complete. Alarms have been sorted.'
        elif input == '/wo_crawl':
            wo_crawler.crawl()
        elif input == '/wo_query':
            wo_compiler.query()  #testing only
        elif input == '/al_query':
            al_crawler.query()
        elif input == '/alarm_query':
            gocc_alarm.query()
        elif input == '/listing_crawl':
            al_crawler.crawl()
        elif input == '/pmd_query':
            pm_data.searchPMD()
        elif input == '/cmd_query':
            cm_data.searchCMD()
        elif input == '/settings':
            settings.prompt()
            print 'Severity filter set to ', settings.sev
            print 'Recurrence limit set to ', settings.filter_limit
            print 'Only consider working asset ', settings.working_asset_only
        elif input == '/rescan':
            print "\nScanning Files.. Please wait."
            al_compiler.scan()
            pm_compiler.scan()
            cm_compiler.scan()
            gocc_compiler.scan()
            print "\nScan Complete."
        elif input == '/expand':
            command_table.show()
        elif input == '/break':
            break
        elif (counter < 3):
            counter += 1
            print 'Invalid command. Please retry.'
        else:
            break

    print "Shutting down ..."