Ejemplo n.º 1
0
def skip_if_no_contiki_devices():
    motelist_output = subprocess.check_output(["../../agent_modules/contiki/communication_wrappers/bin/motelist", "-c"], universal_newlines=True).strip()
    if motelist_output == "No devices found.":
        # check if there are cooja devices!
        try:
            cooja_devs = subprocess.check_output("ls -1v /dev/cooja_rm090* 2>/dev/null", shell=True, universal_newlines=True).strip().split("\n")
            if len(cooja_devs) > 0:
                return True
        except subprocess.CalledProcessError:
            log.info("There are no sensor nodes attached to this machine, and there are no cooja devices, cannot start!!!")
            return False
    else:
        try:
            wilab_nodes_output = subprocess.check_output(["ls /dev/rm090"], universal_newlines=True).strip()
        except FileNotFoundError:
            wilab_nodes_output = ""
        if "/dev/rm090" in wilab_nodes_output:
            return True
        else:
            for line in motelist_output.split("\n"):
                mote_description = line.split(",")[2]
                if "Zolertia RE-Mote" in mote_description:
                    return True
                elif "RM090" in mote_description:
                    return True
    return False
    def run(self):
        self.mkpath(self.build_dir)
        outfiles = []
        for script in find_entry_points():
            name, entrypt = script.split('=')
            name = name.strip()
            entrypt = entrypt.strip()
            outfile = os.path.join(self.build_dir, name)
            outfiles.append(outfile)
            print('Writing script to', outfile)

            mod, func = entrypt.split(':')
            with open(outfile, 'w') as f:
                f.write(script_src.format(executable=sys.executable,
                                          mod=mod, func=func))

            if sys.platform == 'win32':
                # Write .cmd wrappers for Windows so 'ipython' etc. work at the
                # command line
                cmd_file = os.path.join(self.build_dir, name + '.cmd')
                cmd = r'@"{python}" "%~dp0\{script}" %*\r\n'.format(
                        python=sys.executable, script=name)
                log.info("Writing %s wrapper script" % cmd_file)
                with open(cmd_file, 'w') as f:
                    f.write(cmd)

        return outfiles, outfiles
Ejemplo n.º 3
0
def count():
    try:
        counter = Counter.query(Counter.name == 'hello').fetch()[0]
    except IndexError:
        log.info('New counter.')
        counter = Counter(name='hello', count=0)
    counter.count += 1
    counter.put()
    return
Ejemplo n.º 4
0
def run(cmd_str, fatal=True):
    # this is not a good implement
    log.command(log.term.cmd(cmd_str))
    ret = os.system(cmd_str)
    if ret is not 0:
        if fatal:
            log.error('[ERROR] run cmd: %s failed', cmd_str)
            os._exit(1)
        else:
            log.info('[INFO] %s is not fatal' % cmd_str)
Ejemplo n.º 5
0
async def generate_schema() -> None:
    log.info("Initializing Tortoise...")

    await Tortoise.init(
        db_url=os.environ.get("DATABASE_URL"),
        modules={'models': ['models.tortoise']},
    )
    log.info("Generating database schema via Tortoise...")
    await Tortoise.generate_schemas()
    await Tortoise.close_connections()
Ejemplo n.º 6
0
	def __test_tuning_plugin(self, name, load):

		log.test("tuning plugin: %s" % name)
		log.indent()

		# initialization

		log.test("initialization")
		try:
			exec "from %s.%s import _plugin" % (self.tp_dir, name)
		except Exception as e:
			log.result_e()
			log.unindent()
			return False
		log.result()

		# init()

		log.test("call init()")
		try:
			_plugin.init(self.config)
		except Exception as e:
			log.result_e(e)
			log.unindent()
			return False
		log.result()

		# setTuning()

		log.test("call setTuning()")

		if load == None:
			log.info("no data from monitor plugin available")
		else:
			try:
				_plugin.setTuning(load)
			except Exception as e:
				log.result_e(e)
				log.unindent()
				return False
			log.result()

		# cleanup()

		log.test("call cleanup()")
		try:
			_plugin.cleanup()
		except Exception as e:
			log.result_e(e)
			log.unindent()
			return False
		log.result()

		log.unindent()
		return True
Ejemplo n.º 7
0
def split_fastq_file(in_fastq, prefix, num_threads, num_chunks):
    out_fps = [open(p, 'w') for p in get_split_paths(prefix, num_chunks, gz=False)]

    log.info('Splitting %s into %s chunks' % (in_fastq, num_chunks))

    with io.open(in_fastq, 'r') as in_fp:
        for i, four_lines in enumerate(iter_by4(in_fp)):
            q, r = divmod(i, num_chunks)
            map(out_fps[r].write, four_lines)

            # if i+1 % 1000 == 0:
            # log.info('Processed %s reads...' % (i + 1))
            #     break

    for out_fp in out_fps:
        out_fp.close()
Ejemplo n.º 8
0
def split_fastq_file(in_fastq, prefix, num_threads, num_chunks):
    out_fps = [
        open(p, 'w') for p in get_split_paths(prefix, num_chunks, gz=False)
    ]

    log.info('Splitting %s into %s chunks' % (in_fastq, num_chunks))

    with io.open(in_fastq, 'r') as in_fp:
        for i, four_lines in enumerate(iter_by4(in_fp)):
            q, r = divmod(i, num_chunks)
            map(out_fps[r].write, four_lines)

            # if i+1 % 1000 == 0:
            # log.info('Processed %s reads...' % (i + 1))
            #     break

    for out_fp in out_fps:
        out_fp.close()
Ejemplo n.º 9
0
	def __check_sibling_plugins(self, monitorplugins, tuningplugins):

		ok = True

		log.test("monitor and tuning plugins availability")

		for mp in monitorplugins:
			if tuningplugins.count(mp) != 1:
				ok = False
				log.info("monitor plugin '%s' misses tuning plugin" % mp)

		for tp in tuningplugins:
			if monitorplugins.count(tp) != 1:
				ok = False
				log.info("tuning plugin '%s' misses monitor plugin" % tp)

		if ok:
			log.result()
		else:
			log.result("monitor and tunning plugins do not match")
Ejemplo n.º 10
0
Archivo: gen.py Proyecto: ckmetto/iw
def same_trips(filename="same_trips.txt", N=30):
    """
    Generate N random queries, for stops on the same trip
    """
    oN = network.Network()
    trips = oN.getTrips(N)
    fromstops = []
    tostops = []
    for trip in trips:
        oTrip = oN.getTrip(trip)
        stops = [stoprec["stopid"] for seq, stoprec in oTrip.getStops()]
        if len(stops) <= 1:
            continue
        stop1 = oTrip.getFirstStop()
        stop2 = random.choice(stops)
        while stop1 == stop2:
            stop2 = random.choice(stops)

        fromstops.append(stop1)
        tostops.append(stop2)
        log.info("trip: %s chose: (%s, %s)\n=====\n" % (str(oTrip), stop1, stop2))

    return __write_to_csv(filename, fromstops, tostops)
Ejemplo n.º 11
0
	def __check_profiles(self):
		log.test("profiles listing")

		profiles_tester = os.listdir(self.profiles_dir)
		profiles_tester = filter(lambda f: f[0] != ".", profiles_tester)

		try:
			capture.clean()
			capture.capture()
			self.tuned_adm.run(["list"])
			capture.stdout()
		except Exception as e:
			log.report_e(e)
			return False

		# printed profiles (first line "Modes:" is skipped)
		profiles_tuned = capture.getcaptured().splitlines()[1:]

		# compare profiles_tester and profiles_tuned

		error = False
		for p in profiles_tester:
			if not p in profiles_tuned:
				log.info("tune-adm does not report profile '%s'" % p)
				error = True

		for p in profiles_tuned:
			if not p in profiles_tester:
				log.info("tune-adm reports extra profile '%s'" % p)
				error = True

		if error:
			log.result("profiles detected by this test differ from these reported by tuned-adm")
		else:
			log.result()
		
		return True
Ejemplo n.º 12
0
def jpg_to_base64(path):
    f = open(path, 'rb')  # 二进制方式打开图文件
    ls_f = base64.b64encode(f.read())  # 读取文件内容,转换为base64编码
    f.close()
    log.info(ls_f)
Ejemplo n.º 13
0
def run_app(args):
    face_detection_model = Model_Face_Detection(args.model_path_fd,
                                                args.device,
                                                args.cpu_extension,
                                                threshold=args.threshold)
    face_detection_model.load_model()
    head_pose_model = Model_Head_Pose_Estimation(args.model_path_hp,
                                                 args.device,
                                                 args.cpu_extension)
    head_pose_model.load_model()
    face_landmark_model = Model_Facial_Landmarks(args.model_path_fl,
                                                 args.device,
                                                 args.cpu_extension)
    face_landmark_model.load_model()
    gaze_model = Model_Gaze_Estimation(args.model_path_ge, args.device,
                                       args.cpu_extension)
    gaze_model.load_model()

    input_feeder = InputFeeder(
        args.input_type,
        args.input_file,
    )
    input_feeder.load_data()
    mouse_controller = MouseController("medium", "fast")
    # while input_feeder.cap.isOpened():
    # feed_out=input_feeder.next_batch()

    frame_count = 0
    custom = args.toggle

    for frame in input_feeder.next_batch():

        if frame is None:
            break
        key_pressed = cv2.waitKey(60)
        frame_count += 1
        face_out, cords = face_detection_model.predict(frame.copy())

        # When no face was detected
        if cords == 0:
            inf_info = "No Face Detected in the Frame"
            write_text_img(frame, inf_info, 400)
            continue

        eyes_cords, left_eye, right_eye = face_landmark_model.predict(
            face_out.copy())
        head_pose_out = head_pose_model.predict(face_out.copy())
        gaze_out = gaze_model.predict(left_eye, right_eye, head_pose_out)

        # Faliure in processing both eyes
        if gaze_out is None:
            continue
        x, y = gaze_out
        if frame_count % 5 == 0:
            mouse_controller.move(x, y)
        inf_info = "Head Pose (y: {:.2f}, p: {:.2f}, r: {:.2f})".format(
            head_pose_out[0], head_pose_out[1], head_pose_out[2])
        # Process Visualization
        if 'frame' in custom:
            visualization(frame, cords, face_out, eyes_cords)

        if 'stats' in custom:
            write_text_img(face_out, inf_info, 400)
            inf_info = "Gaze Angle: x: {:.2f}, y: {:.2f}".format(x, y)
            log.info("Statistic " + inf_info)
            write_text_img(face_out, inf_info, 400, 15)
        if 'gaze' in custom:
            display_head_pose(frame, head_pose_out, cords)

        out_f = np.hstack(
            (cv2.resize(frame, (400, 400)), cv2.resize(face_out, (400, 400))))
        cv2.imshow('Visualization', out_f)
        if key_pressed == 27:
            break
    input_feeder.close()
    cv2.destroyAllWindows()