Example #1
0
def main():
        global start_time
        global elapsed_time
        global AlarmActioned
        
        globals.init()
        
        #Start Main Program Loop
        
        AlarmActioned = []
        BuildGPIOList()
        InitializeHostGPIO()
         
        #Main Loop
        # loop to monitor armed zones and create an alarm
        start_time = time.time()
        
        while True:
            
                PollGPIO()
                 
                elapsed_time = time.time() - start_time
                
                PollRoutine()
                    
                time.sleep(.2)
def test_value_flush():
    """
    Check if init also flushes values
    """
    test_value_assignment()
    globals.init()
    test_default_values()
def main():
    from github import createIssues

    parser = argparse.ArgumentParser(description="Auto-Issue-Creator argument parser")
    parser.add_argument("-s", "--start", help="the token that begins the TODO: (ie. 'TODO')", default="TODO")
    parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode (no POSTing to github)")
    parser.add_argument("-p", "--path", help="the base path of the project to be scanned", default=".")

    globals.init()

    args = vars(parser.parse_args())
    globals.startToken = args["start"]
    print "Using start token:", globals.startToken

    # see if we're in debug mode
    if args["debug"]:
        debug = True
        print "Debug mode enabled"
    else:
        debug = False

    global basePath
    basePath = os.path.abspath(os.path.expanduser(args["path"]))
    print "Base path of project:", basePath

    issueList = getIssues()
    print "Found {} {}:".format(len(issueList), "issue" if len(issueList) is 1 else "issues")
    for issue in issueList:
        print issue
    createIssues(issueList, debug)
Example #4
0
def main(argv):
	global node_id
	globals.init()
	node_id = int(argv[0])

	connect_to(1, globals.coord_ip, globals.coord_port)
	start_threads()
Example #5
0
    def post(self):
        
        globals.init()
        username = self.request.get('username')
        pw = self.request.get('password')
        error = ''
        
        data = db.GqlQuery("select * from Users order by user_name")
        for entry in data:
            user_name = entry.user_name
            user_pass = entry.user_pass
            if user_name == username:
                check = utils.valid_pw(username,pw,user_pass)
                if check:
                    user_id = str(entry.key().id())
                    user_pass_string = str(utils.make_pw_hash(username,pw))
                    self.response.headers.add_header('Set-Cookie', 'user_id=%s|%s;Path=/' % (user_id,user_pass_string))
                    current_url = self.request.url.split('/')[-1]
                    if current_url == 'login':
                        self.redirect('/wiki/')
                    else: 
                        self.redirect('/homework')

                else:
                     error = 'Sorry Invalid Login, Please try again.'
            else:
                error = "Username not found."

        self.render('login.html', error = error, username = username)
Example #6
0
def main(argv):
	#initialize the global variables
	globals.init()
	sys.setrecursionlimit(10000)
	#get the command line arguments
	try:
		opts, args = getopt.getopt(argv,'-g:', ["filename"])
	except getopt.GetoptError:
		print 'main.py -i <inputfile>'
		sys.exit(2)

	if argv[0] < 0 or argv[1] < 0 or argv[2] < 0:
		print '[invalid input]'
		sys.exit(2)

	globals.cs_int = int(argv[0])
	globals.next_req = int(argv[1])
	globals.tot_exec_time = int(argv[2])

	#spawn N=9 nodes
	for x in range(1,10):
		nood = threading.Thread(target=create_node, args = (x,globals.cs_int, globals.next_req, globals.tot_exec_time,int(argv[3])))
		nood.start()
	while(not globals.end):
		pass
	del globals.node_obj
Example #7
0
def testMatrix(args):
    if(len(args)< 1 or len(args) > 3):
       usage() 

    globals.init(args)

    print "Checking for required apps.  If not installed, program will attempt to " \
          "install."
    if (not(checkApps())):
        getApps()
        installApps()
        if (not(checkApps())):
            print "Required apps are not present. \nPlease install readertest.fls, " \
                  "omnikey5427ck.fls, and cardslotsim.fls.  "
            cleanUp()
            sys.exit(0)
    
    
    os.system('read -s -n 1 -p "Connect Omnikey 5427ck reader if not connected ' +
              'and place a HID Prox card on top of the reader.  Press any key to continue..."')
    print
    
    #Prox
    globals.activeCard = 'Prox'
    successCases()
    failCases()
    proxSpecificCases()
    sys.exit(0)

    os.system('read -s -n 1 -p "Place a Mifare card on top of the reader.  ' \
              'Press any key to continue..."')
    print

    #Mifare
    globals.activeCard = 'Mifare'
    successCases()
    failCases()
    proxSpecificCases()

    os.system('read -s -n 1 -p "Place a iClass card on top of the reader.  ' \
              'Press any key to continue..."')
    print

    #iClass
    globals.activeCard = 'iClass'
    successCases()
    failCases()
    proxSpecificCases()

    os.system('read -s -n 1 -p "Place a Seos card on top of the reader.  ' \
              'Press any key to continue..."')
    print

    #Seos
    globals.activeCard = 'Seos'
    successCases()
    failCases()
    proxSpecificCases()

    cleanUp()
Example #8
0
def updateDB(conn, cur, type):

    globals.init()

    if conn is None:
        return None
    if cur is None:
        cur = conn.cursor()

    added = []

    if type == constants.__TYPE_TV:
        logger.info('MEDIA_INFO', 'TV MEDIA_INFO BEGIN')
        added = beginTVParse(cur)
        logger.info('MEDIA_INFO', 'TV MEDIA_INFO END')

        logger.info('FANART', 'TV FANART BEGIN')
        updateFanartTV(cur)
        logger.info('FANART', 'TV FANART END')
    elif type == constants.__TYPE_MOVIE:
        logger.info('MEDIA_INFO', 'MOVIE MEDIA_INFO BEGIN')
        added = beginMovieParse(cur)
        logger.info('MEDIA_INFO', 'MOVIE MEDIA_INFO END')

        logger.info('FANART', 'MOVIE FANART BEGIN')
        updateFanartMovie(cur, conn)
        logger.info('FANART', 'MOVIE FANART END')

    conn.commit()
    return added
Example #9
0
def main(): 
    globals.init()
    
    clear = lambda: os.system('cls')
    clear()
    root = Tk()
    root.title("GUI")
    root.configure(bg='black')
    
    padx = 5
    pady = 5
    globals.M_DEMO.createGui(root).grid(row=0,column=0, padx=padx, pady=pady)
    globals.M_MENU.createGui(root).grid(row=1,column=0, padx=padx, pady=pady)
    globals.M_PAUSES.createGui(root).grid(row=2,column=0, padx=padx, pady=pady)
    
    globals.DEMO.createGui(root).grid(row=3,column=0, padx=padx, pady=pady)
    
    globals.LB_CHAT.createGui(root).grid(row=5,column=0, padx=padx, pady=pady)
    globals.LB_CMDS.createGui(root).grid(row=4,column=0, padx=padx, pady=pady)
    
    #globals.ST_HP.createGui(root).grid(row=6,column=0, padx=padx, pady=pady)
    #globals.ST_LVL.createGui(root).grid(row=7,column=0, padx=padx, pady=pady)
    #globals.ST_DEATHS.createGui(root).grid(row=8,column=0, padx=padx, pady=pady)
    
    globals.TP.submit(globals.bot.StartBot)
    globals.TP.submit(globals.DEMO.count)
    #globals.TP.submit(globals.STATS.update)
    
    root.mainloop()
    
    globals.TP.shutdown(wait=True)
Example #10
0
	def __init__(self):
		BrickPiSetup()  # setup the serial port for communication
		self._particles = [Particle(1.0/NUMBER_OF_PARTICLES) for i in range(NUMBER_OF_PARTICLES)]
		self._motorA = Motor("PORT_A") 
		self._motorB = Motor("PORT_B")
		BrickPiSetupSensors()       #Send the properties of sensors to BrickPi
		globals.init()
 def __init__(self):
     """
     initializing basic local variables
     """
     self.start = 0
     self.end = 0
     self.curr_amount = 0
     globals.init()
Example #12
0
def main(argv):
	#create the global vars
	globals.init()

	#get filename
	try:
		opts, args = getopt.getopt(argv,'-g:', ["filename"])
	except getopt.GetoptError:
		print 'main.py -i <inputfile>'
		sys.exit(2)
	globals.filename = argv[0]

	#thread for intializing the coordinator to talk with nodes
	server_thread = threading.Thread(target=server, args=())
	server_thread.setDaemon(True)
	server_thread.start()

	while(not globals.coord_initialized):
		pass

	# set up node 0
	join_handler(0);

	while(1):
		while(globals.cmd_done):
			userInput = raw_input('>>> ');
			cmd = userInput.split(' ');
			if cmd[0] == "join" and cmd[1] != None:
				globals.cmd_done=0
				join_handler(int(cmd[1]))

			elif cmd[0] == "find" and cmd[1] != None and cmd[2] != None:
				globals.cmd_done=0
				find_handler(int(cmd[1]), int(cmd[2]))

			elif cmd[0] == "leave" and cmd[1] != None:
				globals.cmd_done=0
				leave_handler(int(cmd[1]))

			elif cmd[0] == "show" and cmd[1] == "all":
				globals.cmd_done=0
				show_handler("all")

			elif cmd[0] == "show" and cmd[1] != None:
				globals.cmd_done=0
				show_handler(int(cmd[1]))

			elif cmd[0] == "quit":
				break;
			elif cmd[0] == "":
				pass
			else:
				print 'invalid Input'
	server_thread.join()
	sys.exit()
	print'[Coord] I quit\n'
Example #13
0
def test_default_values():
    """
    Check for default values
    """
    
    globals.init()

    assert_equals(globals.manga, None)
    assert_equals(globals.user_details['manga_name'], None)
    assert_equals(globals.user_details['location'], None)
    assert_equals(globals.user_details['begin'], 0)
    assert_equals(globals.user_details['end'], 0)
 def __init__(self, ip, port):
     """
     initializing basic local variables
     :param port: port which the client runs on
     :param ip: host on which the client runs on
     """
     self.host = ip
     self.port = port
     self.size = 1024
     self.socket = None
     globals.init()
     globals.amount[0] = 0
 def __init__(self, port):
     """
     initializing basic local variables
     :param port: port which the server runs on
     """
     self.host = ""
     self.port = port
     self.backlog = 5
     self.size = 1024
     self.socket = None
     self.threads = []
     globals.init()
     globals.amount[0] = 0
Example #16
0
def run(port):
    server = ThreadedHTTPServer
    handler = MyHandler
    server_address = ("", port)

    globals.init()

    globals.CURRENT_SERVER_STATUS['port'] = port
    globals.CURRENT_SERVER_STATUS['waiting'] = False

    httpd = server(server_address, handler)
    print("I am waiting on port %s" % port)

    httpd.serve_forever()
Example #17
0
def test_creation():
    """
    Test whether variables are created after init()
    """
    
    globals.init()
    try:
        globals.manga
        globals.user_details
    except AttributeError:
        raise AttributeError
    else:
        pass
    assert_equals(isinstance(globals.user_details, dict), True)
Example #18
0
def application(environ, start_response):
    request_url = environ['PATH_INFO']

    request = webob.Request(environ)
    h = get_handler(request_url)

    if not h:
        #404
        response = webob.exc.HTTPNotFound()
    else:
        g.init()
        handler, param = h
        response = handler(request, *param)

    return response(environ, start_response)
Example #19
0
def program():

    print "Welcome to my package!"

    import globals
    globals.init()

    parsed_input = parse_input()
    parser = ConfigParser()
    parser.read(os.path.expanduser(parsed_input.config_file))

    print "Reading configuration: "
    import json
    slaves = json.loads(parser.get('ftp', 'alex'))
    print slaves.__class__
    print slaves
Example #20
0
def main():
        global start_temperature_time
        global elapsed_temperature_time
        
        globals.init()
        start_temperature_time = time.time()
        elapsed_temperature_time=9999
        
        #Main Loop
        while True:
                        
            if (elapsed_temperature_time > 300):
                    start_temperature_time = time.time()
                    # Get the latest temperature
                    NotifyHostTemperature()
                    
            elapsed_temperature_time = time.time() - start_temperature_time
                
            time.sleep(.2)
Example #21
0
def create_app():
    globals.init()
    globals.DEFAULT_BLUEPRINTS = [sortit]

    app = Flask(__name__)
    app.config['REDIS_HOST'] = 'localhost'
    app.config['REDIS_PORT'] = 6379
    app.config['REDIS_DB'] = 0
    app.config['REDIS_CHARSET'] = 'utf-8'
    app.secret_key = 'put your own secret here'
    app.config.update(
        DEBUG=True,
        SECRET_KEY='Change this!'
    )

    register_extensions(app)
    register_blueprints(app, globals.DEFAULT_BLUEPRINTS)
    load_lua_scripts()

    @app.after_request
    def call_after_request_callbacks(response):
        for callback in getattr(g, "after_request_callbacks", ()):
            callback(response)
        return response

    # Userid automatically to every request
    @app.before_request
    def set_user_id():
        if 'uuid' in session:
            uuid = session['uuid']
            nick = session['nick']
        else:
            uuid = str(uuid4())
            nick = "Anonymous"+str(uuid4())[:3]
            redis.set("user:"+uuid, nick)
            @after_this_request
            def set_user_id(response):
                session['uuid'] = uuid
                session['nick'] = nick
        g.uuid = uuid
        g.nick = nick
    return app
Example #22
0
def main():
        global start_time
        global elapsed_time
        
        globals.init()

        # Interval in seconds that temperature is sent to the server
        start_time = time.time()
        
        NotifyHost()
        
        #Main Loop
        while True:
             
                elapsed_time = time.time() - start_time
                
                if (elapsed_time > 300):
                        start_time = time.time()
                        # Get the latest temperature
                        NotifyHost()
                    
                time.sleep(.2)
Example #23
0
def main():
	#create the global vars
	globals.init()

	#thread for intializing the coordinator to talk with nodes
	server_thread = threading.Thread(target=server, args=())
	server_thread.setDaemon(True)
	server_thread.start()

	while(not globals.coord_initialized):
		pass

	# set up node 0
	join_handler(0);

	while(1):
		userInput = raw_input('>>> ');
		cmd = userInput.split(' ');
		if cmd[0] == "join" and cmd[1] != None:
			join_handler(int(cmd[1]))
		elif cmd[0] == "find" and cmd[1] != None and cmd[2] != None:
			find_handler(cmd[1], cmd[2])
		elif cmd[0] == "leave" and cmd[1] != None:
			leave_handler(cmd[1])
		elif cmd[0] == "show" and cmd[1] == "all":
			show_handler("all")
		elif cmd[0] == "show" and cmd[1] != None:
			show_handler(int(cmd[1]))
		elif cmd[0] == "quit":
			break;
		elif cmd[0] == "":
			pass
		else:
			print 'invalid Input'
	print '[Coord] I F*****G QUIT!\n'
	server_thread.join()
	sys.exit()
def main():
	from github import createIssues
	parser = argparse.ArgumentParser(description="Auto-Issue-Creator argument parser")
	parser.add_argument("-s", "--start", help="the token that begins the TODO: (ie. 'TODO')", default="TODO")
	parser.add_argument("-d", "--debug", action='store_true', help="enable debug mode (no POSTing to github)")
	parser.add_argument("-p", "--path", help="the base path of the project to be scanned", default=".")
	parser.add_argument("-i", "--interactive", action='store_true', help="enable interactive mode (pick and choose which issues get POSTed to github)")
	globals.init()

	args = vars(parser.parse_args())
	globals.startToken = args["start"]
	print "Using start token:", globals.startToken

	#see if we're in debug mode
	if args["debug"]:
		debug = True
		print "Debug mode enabled"
	else:
		debug = False

	global basePath
	basePath = os.path.abspath(os.path.expanduser(args['path']))
	print "Base path of project:", basePath

	issueList = getIssues()
	print "Found {} {}:".format(len(issueList), "issue" if len(issueList) is 1 else "issues")

	for issue in list(issueList):
		print issue
		if args["interactive"]:
			post = raw_input('Create this issue in github? (y/n) ')
			if post.lower() == 'n' or post.lower() == 'no':
				issueList.remove(issue)

	print "Creating {} issues".format(len(issueList))
	createIssues(issueList, debug)
Example #25
0
#   "Standard" input is what dolphin calls the type of input that we use
#       for named pipe (bot) input
#   GCN_ADAPTER will use your WiiU adapter for live human-controlled play
#   UNPLUGGED is pretty obvious what it means
opponent_type = melee.enums.ControllerType.UNPLUGGED
if args.live:
    opponent_type = melee.enums.ControllerType.GCN_ADAPTER

#Create our Dolphin object. This will be the primary object that we will interface with
dolphin = melee.dolphin.Dolphin(ai_port=args.port,
                                opponent_port=args.opponent,
                                opponent_type=opponent_type,
                                logger=log)

#initialize our global objects
globals.init(dolphin, args.port, args.opponent)

gamestate = globals.gamestate
controller = globals.controller


def signal_handler(signal, frame):
    dolphin.terminate()
    if args.debug:
        log.writelog()
        print("")  #because the ^C will be on the terminal
        print("Log file created: " + log.filename)
    print("Shutting down cleanly...")
    sys.exit(0)

Example #26
0
def main():
	globals.init()
	start_server()
Example #27
0
 def __init__(self, config):
     super(DorsalFunBot, self).__init__(**config['irc'])
     self.modules = {}
     self.load_modules(config['modules'])
     globals.init()
Example #28
0
 def __init__(self):
     globals.init()
Example #29
0
                  help="True or false for processing the triggers script",
                  metavar="FILE")
(options, args) = parser.parse_args()
if (options.configFile):
    configFile = options.configFile
processTriggersScript = options.processTriggersScript
#load config
config = ConfigParser.ConfigParser()
config.read(configFile)

#[log]
lf = config.get("log", "logFile")
globals.localPath = config.get("log", "localPath")

#set up global variable file
globals.init(lf)

#[email]
globals.emailAddress = config.get("email", "emailAddress")
globals.mailServer = config.get("email", "mailServer")
globals.emailAddressLIST = [i[1] for i in config.items("listEmail")]

#[ftpdetails]
globals.SITE = config.get("ftpdetails", "SITE")
globals.UN = config.get("ftpdetails", "UN")
globals.PW = config.get("ftpdetails", "PW")

#email strings
warnText = ""
subjectText = "FTP Download Script Run"
messageText = ""
Example #30
0
 def setUpClass(cls):
     g.init(unitTestRun=True)
Example #31
0
def setup_all():
    browser = "phantomjs"
    globals.init()
    world.browser = Browser(browser)
    world.browser.driver.set_window_size(window_sizes[browser][0],
                                         window_sizes[browser][1])
from menus.main_menu import MainMenu
from key_store import Keystore
from utilities.threading_helper import RepeatTask

import gc
import globals
import pygame


if __name__ == '__main__':
    pygame.init()

    # Initial set up.
    fps_limit = 60
    clock = pygame.time.Clock()
    globals.init()  # initializes variables
    pygame.display.set_caption('Space Snakes')
    key_store = Keystore()
    scene = MainMenu()

    # Main game loop.
    while True:
        key_store.delta_time = clock.tick(fps_limit) / 1000.0

        if pygame.event.get(pygame.QUIT):
            break

        scene = scene.handle(key_store) or scene
        scene = scene.update() or scene
        scene.draw()
        pygame.display.flip()
Example #33
0
def main():
    globals.init()
    currvalue = ''
    tempvalue = -999

    # loop until the serial buffer is empty
    BuildRFSensorList()
    start_time = time.time()

    #try:
    while True:
        elapsed_time = time.time() - start_time
        # Poll for changes to RF settings
        if (elapsed_time > 600):
            start_time = time.time()
            BuildRFSensorList()
        # declare to variables, holding the com port we wish to talk to and the speed
        port = '/dev/ttyAMA0'
        baud = 9600

        # open a serial connection using the variables above
        ser = serial.Serial(port=port, baudrate=baud)

        # wait for a moment before doing anything else
        sleep(0.2)
        while ser.inWaiting():
            # read a single character
            char = ser.read()
            # check we have the start of a LLAP message
            if char == 'a':
                # start building the full llap message by adding the 'a' we have
                llapMsg = 'a'

                # read in the next 11 characters form the serial buffer
                # into the llap message
                llapMsg += ser.read(11)

                # now we split the llap message apart into devID and data
                devID = llapMsg[1:3]
                data = llapMsg[3:]

                if globals.PrintToScreen: print data

                if data.startswith('BUTTON'):
                    sensordata = data[5:].strip('-')
                    if currvalue <> sensordata or currvalue == '':
                        currvalue = sensordata
                        ProcessMessage(currvalue, 0, devID, 1)

                if data.startswith('BTN'):
                    sensordata = data[2:].strip('-')
                    if currvalue <> sensordata or currvalue == '':
                        currvalue = sensordata
                        ProcessMessage(currvalue, 0, devID, 1)

                if data.startswith('TMPA'):
                    sensordata = data[4:]
                    currvalue = float(sensordata)
                    ProcessMessage(currvalue, 0, devID, 3)

                if data.startswith('TMPB'):
                    sensordata = data[4:].strip('-')
                    tempvalue = float(sensordata)

                if data.startswith('HUMB'):
                    if tempvalue > -999:
                        sensordata = data[4:].strip('-')
                        currvalue = float(sensordata)
                        ProcessMessage(tempvalue, currvalue, devID, 4)
                        tempvalue = -999

                # check if battery level is being sent axxBATTn.nn-
                if data.startswith('BATT'):
                    sensordata = data[4:].strip('-')
                    currvalue = sensordata
                    ProcessMessage(currvalue, 0, devID, 2)
        #ser.close()
        sleep(0.2)
Example #34
0
def main():
    print("starting glut window")
    globals.init()
    rw = Renderer()
    rw.display()
Example #35
0
import globals
import common
from dbconnector import dbconnector
from dbconnector import dbcursor
import da_logs

# ログの種類 Log kind
LOG_KIND_ERROR = 'Error'
LOG_KIND_INFO = 'Infomation'
LOG_KIND_UPDATE = 'Update'

# 設定ファイル読み込み・globals初期化
app = Flask(__name__)
app.config.from_envvar('CONFIG_API_LOGS_PATH')
globals.init(app)


@app.route('/alive', methods=['GET'])
def alive():
    """死活監視

    Returns:
        Response: HTTP Respose
    """
    return jsonify({
        "result": "200",
        "time": str(datetime.now(globals.TZ))
    }), 200

Example #36
0
File: main.py Project: asanza/Moto
 def __init__(self):
     super(Window, self).__init__()
     
     globals.init()
     self.initUI()       
Example #37
0
def anduryl(assessments, realisations, quants, alpha, k, cal_power,
            weight_type, optimization, robust, N_max_it, N_max_ex, output,
            output_items, user_w):

    globals.init(alpha, k, cal_power, weight_type, optimization, robust,
                 N_max_it, N_max_ex, quants)

    warnings.filterwarnings("ignore")

    if not os.path.exists(output_items[0]):
        os.makedirs(output_items[0])

    importfiles(assessments, realisations, quants)
    error, errortext = check_input()
    print(errortext)
    unanswered.unanswered()
    backup.backup()

    # caluclate DMs
    if not optimization:
        if weight_type == 'global':
            global_weights(0)
            calculate_DM_global(0)
        elif weight_type == 'equal':
            for expert in globals.experts:
                expert.W[0][4] = float(1. / len(globals.experts))
            globals.alpha = 0
            calculate_DM_global(0)
        elif weight_type == 'item':
            global_weights(0)
            calculate_DM_item(0)
        elif weight_type == 'user':
            if len(user_w) == 0:
                print(
                    "user weight not specified, considering all equal weights")
                for i in range(len(globals.experts)):
                    user_w.append(1.0)
            if len(user_w) != len(globals.experts):
                sys.exit("user weight does not have the same length")

            i = 0
            for expert in globals.experts:
                expert.W[0][4] = float(user_w[i]) / np.sum(user_w)
                i = i + 1
            globals.alpha = 0
            calculate_DM_global(0)
    else:
        DM_optimization()

    if output[1]: print_data(output_items[1])
    if output[0]:
        plotting_itemwise(globals.CQ_values, globals.CQ_assess,
                          globals.TQ_assess, globals.TQ_values,
                          globals.experts, globals.weight_type,
                          globals.optimization, output_items[0])
    # goto robustness
    if robust:
        if weight_type == "global" or weight_type == "item":
            w_index = 0
            revert.revert()
            incl_cal_pwr = "yes"
            robust_table_item = Checking_Robustness_items(
                incl_cal_pwr, cal_power)

            if output[0]: plot_robust(robust_table_item, output_path)
            w_index = 0
            revert.revert()

    randomisation = False
    if randomisation:
        distr = randomise()
        averages = np.average(distr, axis=0)
        stdevs = np.std(distr, axis=0)
        print('experts: ' + str(len(globals.experts) - 1))
        print('items: ' + str(len(globals.CQ_values)))
        print(
            'Average     {:10.5e} {:10.5e} {:10.5e} {:10.5e} {:10.5e}'.format(
                averages[0], averages[1], averages[2], averages[3],
                averages[4]))
        print(
            'Stdev       {:10.5e} {:10.5e} {:10.5e} {:10.5e} {:10.5e}'.format(
                stdevs[0], stdevs[1], stdevs[2], stdevs[3], stdevs[4]))
Example #38
0
# this script is to transform any outdated

import globals as g
import os
import os.path
import datetime
import time
import sqlite3                                      # Database Library
from classes.capra_data_types import Picture, Hike
from classes.sql_controller import SQLController
from classes.sql_statements import SQLStatements
g.init()

start_time = time.time()

oldDBController = None
newDBController = None

# PATH = '/media/pi/capra-hd/'
PATH = '../capra-sample-data/dbTransform/'
OLD_DB = PATH + 'capra_projector_test.db'
NEW_DB = PATH + 'capra_camera_test.db'

print("Old db: {}".format(OLD_DB))
print("New db: {}".format(NEW_DB))

oldDBController = SQLController(database=OLD_DB)
newDBController = SQLController(database=NEW_DB)

oldCursor = oldDBController.connection.cursor()
newCursor = newDBController.connection.cursor()
Example #39
0
            print("File " + h08_basename + " already exists locally - skipping.")
        # only get data from within the last 72 h
        elif time_difference > 72.:
             return
        else:
            print "%s: %s" % (file_date, filename)
            print "file to download is %s" % filename
            try:
                f.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
                # unzip
                compressed_file = gzip.open(filename, 'rb')
                filename_decompressed = filename.strip('.gz')
                decompressed_file = open(filename_decompressed, 'wb')
                decompressed_file.write(compressed_file.read())
                compressed_file.close(); decompressed_file.close()
                os.remove(filename)
                shutil.move(filename_decompressed, globals.data_dir + filename_decompressed)
                call(["./bufr2netcdf", globals.data_dir + filename_decompressed])
                os.remove(globals.data_dir + filename_decompressed)
            except ftplib.error_perm:
                print "Error: cannot read file %s" % filename
                os.unlink(filename)
            else:
                print "***Downloaded*** %s " % filename

    f.quit()
    return

if __name__ == '__main__':
    globals.init()
    main()
Example #40
0
def main():
    globals.init()

    idf_file="train-idf"
    read_idf(idf_file)

    train_filename = "train_c"
    A=read_file(train_filename,0,0)

    #NearestNeighbors(n_neighbors = 3, algorithm='ball_tree', metric='pyfunc', func=custom_dist_func)
    #neigh.fit(data)

    ################################################################################
    print(globals.length)
    neigh=NearestNeighbors(n_neighbors=5,algorithm='brute',metric='cosine')
    neigh.fit(A)
    A=[]

    while(1):
        cros_filename = str(input("Enter the file name: / quit to quit: "))

        if cros_filename == 'quit':
            exit(1)
       
        start=time.time()
        globals.offset=0
        while(1):
                        
            C=read_file(cros_filename,1,globals.offset)
            if globals.length == 0:
                break;

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

            near_neigh=neigh.kneighbors(C,5)

            #print(near_neigh)    

            times=1
            while(times):
                times-=1
                #alpha=float(input("alpha:"));
                alpha=0.5
                result=[];
                true_positive=0;
                true_negative=0;
                false_negative=0;
                false_positive=0;
                for s in range(len(near_neigh[1])):
                    dist={}
                    l=1;
                    for i in range(len(near_neigh[1][s])):
                        if i!=0 and near_neigh[0][s][i]!=near_neigh[0][s][i-1]:
                            l=l+1
                        for j in globals.train_label[near_neigh[1][s][i]]:
                            if j in dist:
                                #dist[j]=dist[j]+(near_neigh[0][s][i]+0.00001)
                                dist[j]=dist[j]+1/(l+1)
                            else:
                                #dist[j]=(near_neigh[0][s][i]+0.00001)
                                dist[j]=1/(l+1)

                    result.append([])
                    Dist_ordered=OrderedDict(sorted(dist.items(),key=lambda t:-t[1]))
                    Dist_list=list(Dist_ordered.items())
                    #alpha=2;
                    for  i in range(len(Dist_list)):
                        #if i>3 :
                         #   break;
                        if Dist_list[i][1] >= alpha:
                            result[s].append(Dist_list[i][0])

                    temp2=len(set(result[s])-set(globals.cros_label[s]))
                    true_positive+=len(result[s])-temp2
                    false_positive+=temp2
                    temp3=len(set(globals.cros_label[s])-set(result[s]))
                    false_negative+=temp3
                print(" alpha -> ",alpha)
                #print(result)
                #print(" result  \n ")
                #print(globals.cros_label)
                if true_positive is 0 :
                    continue;
                precision=true_positive/(true_positive+false_positive);
                print("precision -> ",precision)
                recall=true_positive/(true_positive+false_negative);
                print("recall  -> ",recall)
                f1_score=2*precision*recall/(precision+recall)
                print("f1 score  -> ",f1_score)
                globals.true_positive+=true_positive
                globals.false_positive+=false_positive
                globals.true_negative+=true_negative
                globals.false_negative+=false_negative

        end=time.time()
        print("elapsed time")
        print(end-start)
        precision=globals.true_positive/(globals.true_positive+globals.false_positive);
        print("precision -> ",precision)
        recall=globals.true_positive/(globals.true_positive+globals.false_negative);
        print("recall  -> ",recall)
        f1_score=2*precision*recall/(precision+recall)
        print("f1_score -> ",f1_score)
Example #41
0
 def __init__(self):
     globals.init()
Example #42
0
 def __init__(self):
     # initialize global variables
     globals.init();
Example #43
0
    # generate the route file for this simulation
    generate_routefile(options)

    options.dbName = getDBName(options)

    addFile = "data/cross.add.xml"
    if (options.learn == '0'):
        addFile = "data/cross_no_learn.add.xml"
    elif (options.phasing == '2'):
        addFile = "data/cross_variable.add.xml"

    edgeWidth = 5
    lateral_resolution_width = 2.5
    if (int(options.sublaneNumber) <= 6.0):
        lateral_resolution_width = float(edgeWidth /
                                         int(options.sublaneNumber))

    lateral_resolution_width = str(lateral_resolution_width)

    # Sumo is started as a subprocess and then the python script connects and
    # runs
    traci.start([
        sumoBinary, "-c", "data/cross.sumocfg", "-n", "data/cross.net.xml",
        "-a", addFile, "-r", "data/cross.rou.xml", "--lateral-resolution",
        lateral_resolution_width, "--queue-output", "queue.xml",
        "--tripinfo-output", "tripinfo.xml"
    ])
    init(options)
    run(options)
Example #44
0
        for page in json_object:
            name = page.get('name')
            id = page.get('id')
            items = page.get('items')
            self.primary_wall.add_page(id,name)
            if items:
                for item in items:
                    fn = 'http://dps-dev.radio.warwick.ac.uk/audio/index.php?md5=%s&token=3b976023f313bc143af6c16cb44c09' % (item.get('audio'))
                    background = [int(item.get('background')[0])/float(255),int(item.get('background')[1])/float(255),int(item.get('background')[2])/float(255),1]
                    self.primary_wall.pages[i].buttons[int(item.get('item'))].title = item.get('text')
                    self.primary_wall.pages[i].buttons[int(item.get('item'))].background = background
                    self.primary_wall.pages[i].buttons[int(item.get('item'))].id = int(item.get('id'))
                    self.primary_wall.pages[i].buttons[int(item.get('item'))].filename = fn
            i += 1

        self.rightbox.add_widget(self.primary_wall)

        self.secondary_wall = AudiowallSet()
        i = 0
        #for fn in glob('/home/jonty/src/beemo/testaudio/*'):
        #    self.secondary_wall.pages[0].buttons[i].title = basename(fn[:-4]).replace('_', ' ')
        #    self.secondary_wall.pages[0].buttons[i].filename = fn
        #    i += 1
            
        self.rightbox.add_widget(self.secondary_wall)
        return self.root

if __name__ == '__main__':
    globals.init()
    TestApp().run()
Example #45
0
        attrs.set_attribute("ds_segment","enrico_segment",strict = True)
        ss = IA.StartSession(pars, attrs, "false")
        sent_attributes = ss.get_send_attributes("Profile sent by startsession")
        ss.call(True)
        # ss.dump()

        g.log.info("\ncall getProfile, not strictly necessary, just to verify attributes of startSession have been set correctly")
        profile = IA.GetProfile(pars)
        ret = profile.call(True)
        returned_attrs = profile.create_Attributes()
        diffs = sent_attributes.left_compare(returned_attrs)
        g.log.info("\n")
        sent_attributes.compare_values(returned_attrs, diffs)
        # sent_attributes.left_print_side_2_side(returned_attrs)

        g.log.info("call getOffers")
        getOffers = IA.GetOffers(pars, "ip01")
        ok = getOffers.call(False)
        g.log.info("\nDump getOffers response")
        getOffers.dump(True)
        pass

    finally:
        IA.EndSession(g.uaci_params)


if __name__ == '__main__':
    g.init(unitTestRun=True)
    startSession_trigger_stored_procedure()
    startSession_fails_missing_audience_id_are_attributes_set()
    startSession_fails_do_offers_work()