Пример #1
0
    def __init__(self, lines):
        self.camera = None
        self.settings = None
        self.materials = []
        self.planes = []
        self.spheres = []
        self.boxes = []
        self.lights = []

        for line in lines:
            if line[0] != '#' and not line.isspace():
                split_line = line.split()

                if split_line[0] == 'cam':
                    self.camera = Camera(split_line[1:])
                elif split_line[0] == 'set':
                    self.settings = Settings(split_line[1:])
                elif split_line[0] == 'mtl':
                    material = Material(split_line[1:],
                                        len(self.materials) + 1)
                    self.materials.append(material)
                elif split_line[0] == 'pln':
                    self.planes.append(Plane(split_line[1:], self.materials))
                elif split_line[0] == 'sph':
                    self.spheres.append(Sphere(split_line[1:], self.materials))
                elif split_line[0] == 'box':
                    self.boxes.append(Box(split_line[1:], self.materials))
                elif split_line[0] == 'lgt':
                    self.lights.append(Light(split_line[1:]))

        self.objects = self.spheres + self.planes + self.boxes
Пример #2
0
    def __init__(self):
        settings = Settings()

        self.phase_data = False
        self.fit_type = 'spline'

        self.input_files = settings.input_files
        self.timepoints = []  # time of the observations
        self.filenames = []  # names of the S1 files
        self.readers = []  # readers/streams of the S1 files
        self.mperiod = settings.magnetic_period
        self.rperiod = settings.rotation_period

        for i in range(0, len(settings.input_files)):
            x = settings.input_files[i]
            self.timepoints.append(x[0])
            self.filenames.append(x[1])
            self.readers.append(S1Reader(x[1]))

        mphases = np.asarray(self.timepoints) / self.mperiod
        for j in range(0, len(mphases)):
            while mphases[j] >= 1:
                mphases[j] -= 1

        self.mphases, self.phased_readers = (list(t) for t in zip(
            *sorted(zip(mphases, self.readers))))
Пример #3
0
def run_game():
    # Game settings init
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien-Invasion")
    play_button = Button(ai_settings, screen, "Play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    bg_color = (230, 230, 230)

    # Ship, bullets, and aliens init.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
Пример #4
0
    def __init__(self,
                 tdata,
                 rvdata,
                 errs=None,
                 starmass=1.0,
                 massrange=[],
                 periodrange=[]):
        if len(tdata) != len(rvdata):
            raise ValueError(
                'RVOrbitFitter: <tdata> and <rvdata> should have same dimensions.'
            )

        if errs != None and len(errs) != len(tdata):
            raise ValueError(
                'RVOrbitFitter: <tdata> and <rvdata> should have same dimensions as <errs>.'
            )

        self._G = 8.88677e-10  # AU^3 Me^-1 day^-2
        self._SunInEarthMasses = 332978.9
        self._ts = tdata
        self._rvs = rvdata
        self._errs = errs
        self._starmass = starmass

        self._massrange = self._validatePositiveRange(
            massrange,
            'massrange',
            alt=[0, 0.1 * starmass * self._SunInEarthMasses])
        self._periodrange = self._validatePositiveRange(
            periodrange, 'periodrange')
        self.settings = Settings()
Пример #5
0
 def __init__(self):
     # todo: get latest settings from file or database or something
     self.settings = Settings(
         location=[51.57046107093778, 5.050113150625251])
     # self.API = Api()
     self.SocialConnect = SocialConnect("aapje", settings=self.settings)
     self.WeatherConnect = WeatherConnect(
         "f71af11b8e02b30c2ed988487f0dd533", settings=self.settings)
     self.WeatherConnect.fetch_data()
Пример #6
0
def out(message):
    st = datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y-%m-%d %H:%M:%S')
    message = '[' + st + ']\t' + message
    print(message)
    settings = Settings()
    if len(settings.logfile) > 0:
        ensurePathExists(settings.logfile)
        with open(settings.logfile, 'a') as f:
            f.write(message + '\n')
def run_game():
    #Initialize game and create a screen object.
    #Initializes Background settings that pygame needs to work.
    pygame.init()
    ai_settings = Settings()
    # we create a display window called screen where we'll draw
    # all the elements of our game
    # the screen object is called a surface in pygame
    # Each element on the screen is called a surface (alien, ships)
    # When we activate the game loop, the surface is automatically
    # redrawn on every pass through the loop
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption(ai_settings.window_caption)

    # Make the start button
    start_button = Button(ai_settings, screen, "Start")

    # Create an instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Make a ship, a group of bullets and a group of aliens
    ship = Ship(screen, ai_settings)
    bullets = Group()
    aliens = Group()

    # We create the fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #start the main loop for the game
    while True:
        # we check for any events (keypresses or mouse events)
        gf.check_events(ai_settings, screen, stats, sb, start_button, ship,
                        aliens, bullets)
        # In the main loop, we always need to call check_events(), even if the game
        # is inactive. For example, we still need to know if the user presses Q to quit
        # the game or clicks the button to close the window

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
            # We update the aliens’ positions after the bullets have been updated,
            # because we’ll soon be checking to see whether any bullets hit any aliens
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         start_button)
Пример #8
0
    def __init__(self, ipAddr=None, port=80):
        # Init Midi client and display available devices
        midiINPort = mido.get_input_names()[0]
        midiOUTPort = mido.get_output_names()[0]
        self.midiIN = mido.open_input(midiINPort)
        self.midiOUT = mido.open_output(midiOUTPort)
        self.mcu = MCU()
        self.motu = Motu(ipAddr, port)
        self.settings = Settings()
        self.hwSetup = Setup()

        self.mixerUrl = "http://{}:{}".format(ipAddr, port)
        print("Will send events to mixer at {}".format(self.mixerUrl))

        self.recall()
Пример #9
0
def run_game():
    # Khởi tạo pygame, settings và screen object
    pygame.init()
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height
         ))  # screen object vs chiều dài và chiều cao trong settings.py
    pygame.display.set_caption('Alien Invasion')  # title for window

    # Tạo ra button play game
    play_button = Button(ai_settings, screen, 'Play')

    # Khởi tạo đối tượng dùng để thống kê dữ liệu trong trò chơi
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Tạo ra một ship object
    ship = Ship(ai_settings, screen)
    # Tạo một Group để chứa các bullet
    bullets = Group()
    # Tạo một Group để chứa các alien
    aliens = Group()

    # Tạo ra một hàng chứa các alien
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Bắt đầu main loop của trò chơi
    while True:
        # Theo dõi các event keyboard và mouse
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ship.update()

            # Update bullets
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)

            # update aline
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)

        # Vẽ lại screen
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Пример #10
0
    def __init__(self, ipAddr=None, port=80):
        self.ipAddr = ipAddr
        self.port = port
        self.url = "http://{}:{}".format(ipAddr, port)

        self.uid = self._getUid()
        self.waitOnline()

        self.motuSettings = self._getSettings()
        self.settings = Settings()

        if self.motuSettings:
            print("========== Motu AVB: ===========")
            print("* Name        : {}".format(self.motuSettings["hostname"]))
            print("* uid         : {}".format(self.uid))
            print("* Sample rate : {}".format(
                self.motuSettings["cfg/0/current_sampling_rate"]))
            print("================================")
Пример #11
0
def run_game():
    # Initialise game and create a game object.
    pygame.init()
    ai_settings = Settings()
    #screen_width, screen_height=pygame.display.Info().current_w, pygame.display.Info().current_h
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invaders")
    icon = pygame.image.load('resources/battleship32.png')
    pygame.display.set_icon(icon)

    # Make a play button.
    play_button = Button(ai_settings, screen, "Play")

    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings)
    sb = ScoreBoard(ai_settings, screen, stats)

    # Make a ship, a group of bullets and a group of enemies.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    enemies = Group()
    ex = Explosion(ai_settings, screen)

    # Create a fleet of enemies.
    func.create_fleet(ai_settings, screen, ship, enemies)

    # Start main loop for the game.
    while True:

        # Watch for keyboard and mouse events.
        func.check_events(ai_settings, screen, stats, sb, play_button, ship,
                          enemies, bullets)

        if stats.game_active:
            ship.update()
            func.update_bullets(ai_settings, screen, stats, sb, ship, enemies,
                                ex, bullets)
            func.update_enemies(ai_settings, stats, sb, screen, ship, enemies,
                                bullets)

        func.update_screen(ai_settings, screen, stats, sb, ship, enemies, ex,
                           bullets, play_button)
Пример #12
0
    def __init__(self,
                 Mstar=1.0,
                 Mplanet=1.0,
                 a=1.0,
                 e=0.0,
                 w=0.0,
                 v0=0.0,
                 SNR=0.0,
                 R=1e5,
                 times=np.arange(0.0, 365.25, 0.1)):
        self.G = 8.88677e-10  # AU^3 Mearth^-1 day^-2
        self.SunInEarthMasses = 332978.9  # 1 solar mass in Earth masses

        self.Mstar = Mstar  # solar masses
        self.Mplanet = Mplanet  # Earth masses
        self.a = a  # AU
        self.e = e  # 0..1
        self.w = w  # argument of periastron, radians
        self.v0 = v0  # barycenter velocity (constant component)

        self.SNR = SNR  # set to 0 to eliminate all noise
        self.R = R  # spectral resolution Lambda/dLambda
        self.times = times

        self.simulator = SingleTimeOrbitRVSimulator(times, Mstar, Mplanet, a,
                                                    e, w, v0)
        self.redshiftMeasurer = RedshiftMeasurer()

        self.lines = np.asarray([])
        self.continuum = 1.0
        self.absorption = True
        self.margin = 5  # angstroems

        self.maxshift = 1e3  # m/s
        self.sfactor = 300  # for spline interpolation of the line

        self.settings = Settings()
Пример #13
0
def run_game():
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("Invaders!!")

    #create play button
    play_button = Button(game_settings, screen, "Play")

    # create an instance to store game statistics and create scoreboard
    stats = GameStats(game_settings)
    sb = Scoreboard(game_settings, screen, stats)

    # create player ship, a group of bullets, a group of aliens
    ship = Ship(game_settings, screen)
    bullets = Group()
    aliens = Group()

    # create alien fleet
    gf.create_fleet(game_settings, screen, ship, aliens)

    # main loop
    while True:
        gf.check_events(game_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(game_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(game_settings, stats, screen, ship, aliens,
                             bullets)

        gf.update_screen(game_settings, screen, stats, sb, ship, aliens,
                         bullets, play_button)
Пример #14
0
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        # running the game in fullscreen mode...to implement soon...

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        self.ship = Ship(self)

        # Storing Bullets in a Group
        self.bullets = pygame.sprite.Group()

        # we create a Group to hold the fleet of aliens
        self.aliens = pygame.sprite.Group()

        # and we call _create_fleet() method
        self._create_fleet()

        # Setting the background color
        self.bg_color = (230, 230, 230)
Пример #15
0
from pynput import keyboard
import pyautogui
import logging
from modules.compare import compare_images
from modules.settings import Settings

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

settings = Settings()
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
current = set()

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


def _jump_mouse():
    logging.debug("Clicking at at {}".format(pyautogui.position()))
    pyautogui.click(button='left')
    print("Click", end='... ')

    pos_x, pos_y = pyautogui.position()
    pyautogui.click(x=pos_x + settings.screen_width / 2, y=pos_y, button='left')
    logging.debug("Clicking at {}".format(pyautogui.position()))
    print("Move... Click", end='...')

    pyautogui.moveRel(-settings.screen_width / 2, 0)
    logging.debug("Moved back to {}".format(pyautogui.position()))

    print("Move back.")

Пример #16
0
#!/usr/bin/env python3

import depthai as dai
import os
import sys
import logging
import datetime

sys.path.insert(0, os.path.realpath('../'))
from modules.settings import Settings

settings_grey = Settings("../grey.yaml")
settings_color = Settings("../color.yaml")

logger = logging.getLogger(__name__)

timestamp = datetime.datetime.now().strftime("%Y%m%d_%H.%M.%S")

record_dir = f"record_{timestamp}"

os.makedirs(record_dir, exist_ok=True)


def exec_out(cmd):
    logger.info(f"Executing: {cmd}")
    stream = os.popen(cmd)
    lines = stream.readlines()
    if lines:
        return lines[-1].strip("\n")
    else:
        return ""
Пример #17
0
def truncate(f, n=2):
    settings = Settings()
    n = settings.digits
    s = '%.12f' % round(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d + '0' * n)[:n]])
Пример #18
0
  Control:      key[dec/inc]  min..max
  exposure time:     I   O      1..33000 [us]
  sensitivity iso:   K   L    100..1600
To go back to auto controls:
  'E' - autoexposure
"""
import os
import sys

import depthai as dai
import cv2

sys.path.insert(0, os.path.realpath('../'))
from modules.settings import Settings

settings = Settings("../grey.yaml")

default_settings = {
    "exp": 1000,
    "iso": 400
}

settings.update_defaults(default_settings)

# Manual exposure/focus set step
EXP_STEP = 100  # us
ISO_STEP = 50

pipeline = dai.Pipeline()

# Nodes
Пример #19
0
        '''
        Pretty much the entirety of the game's runtime
        will be spent inside this while loop
        '''
        while not self.done:
            dt = self.clock.tick(self.fps)
            self.event_loop()
            self.update(dt)
            self.draw()
            pg.display.update()


if __name__ == '__main__':
    pg.init()
    pg.display.set_caption('The Harvest')
    screens = {
        'Mainmenu': Mainmenu(),
        'Farm': Farm(),
        'Tile': Tile(),
        'Options': Options(),
        'Settings': Settings(),
        'Stats': Stats(),
        'Info': Info(),
        'Tutorial': Tutorial(),
        'Money': Money()
    }
    game = Game(display, screens, 'Mainmenu')
    game.run()
    pg.quit()
    sys.exit()
Пример #20
0
	def run(main_class):
		settings = Settings()
		main_java_file = main_class + ".java"
		clear_and_print_header(main_class)
		print(f"Beginning program on a {settings.get_platform()} platform.")

		if not os.path.exists(Commands.java) or not os.path.exists(Commands.javac):
			print("\n\nIt looks like you don't have a JDK installed yet.")
			print("Please download the JDK from this website: https://jdk.java.net/archive/")
			print("Once you do so, unpack the JDK into the modules/_PLACE_JDK_HERE directory.")
			print("You can find instructions for your OS in modules/_PLACE_JDK_HERE/README.txt")
			print()
			print("If you have downloaded the JDK, then make sure you placed it in the proper directory.")

		else:
			fu.init_storage_dirs()
			print(Design.border4)

			# Validate all of the submissions first
			all_submissions = []
			all_submission_folders = replace_spaces_in_dir_files(Path.initial_sub_dir)

			for i in range(0, len(all_submission_folders)):
				submission_folder = all_submission_folders[i]
				if submission_folder == Settings.placeholder:
					continue
				submission_files = remove_hidden(os.listdir(os.path.join(Path.initial_sub_dir, submission_folder)))
				for file in submission_files:
					parts = file.split('.')
					if parts[len(parts)-1] == "zip":
						path_to_sub_folder = os.path.join(Path.initial_sub_dir, submission_folder)
						all_submissions.append([file, path_to_sub_folder])
						break


			if len(all_submissions) > 0:
				if len(all_submissions) == 1:
					validation_greeting = "\nYou have 1 submission that has yet to be validated."
				else:
					validation_greeting = "\nYou have %d submissions that have yet to be validated." % len(all_submissions)
				while True:
					print(validation_greeting)
					print("\nWould you like to validate them now?")
					print("  Y: yes")
					print("  N: no")
					response = input("Response: ")

					if response == "Y" or response == "y":
						for i in range(0, len(all_submissions)):
							submission = all_submissions[i][0]
							path = all_submissions[i][1]
							clear_and_print_header(main_class)
							print(f"Validating {i+1} out of {len(all_submissions)} submissions.")
							print(Design.border4)
							Validator.validate(submission, path, main_class)
							shutil.rmtree(all_submissions[i][1])
						break
					elif response == "N" or response == "n":
						break
					else:
						clear_and_print_header(main_class)
						print("Please enter a valid response.")

			clear_and_print_header(main_class)
			while True:
				all_valid_submissions = remove_hidden(os.listdir(Path.valid_checked_dir))
				if len(all_valid_submissions) > 0:
					if len(all_valid_submissions) == 1:
						print(f"\nYou have 1 ungraded submission.\n")
					else:
						print(f"\nYou have {len(all_valid_submissions)} ungraded submissions.\n")
				else:
					print("You are all up to date.\n")
				print("What would you like to do?")
				print("  1: Evaluate ungraded projects.")
				print("  2: View invalid submissions.")
				print(". 3: Perform plagiarism check.")
				#print("  3: Pick a program by ID number.")
				print("  0: Quit the program.")
				command = input("Your choice: ")

				if command == "1":
					for i in range(0, len(all_valid_submissions)):
						submission = all_valid_submissions[i]
						continue_to_next = True
						sub = SubmissionFile(submission, Path.valid_checked_dir, main_class)
						clear_and_print_header(main_class)
						print_submission_header(i, all_valid_submissions, sub)
						run_student_submission(sub)
						while True:
							print("Please choose an option:\n")
							print("  (nothing): Set current student to graded and continue")
							print("  1: Continue to next student without setting current to graded.")
							print("  2: View the Java file.")
							print("  3: Run program again.")
							print("  4: Exit back to menu, but do not set this student to graded.")
							print("  0: Set to graded and exit back to menu.")
							command = input("Your command: ")
							if command == "":
								continue_to_next = True
								sub.set_to_graded()
								break
							elif command == "1":
								continue_to_next = True
								break
							elif command == "2":
								clear_and_print_header(main_class)
								print_submission_header(i, all_valid_submissions, sub)
								print(f"File contents for user: {sub.first_name} {sub.last_name} ({sub.id_number})")
								print(Design.border10)
								sub.display()
								print(Design.border11)
							elif command == "3":
								clear_and_print_header(main_class)
								print_submission_header(i, all_valid_submissions, sub)
								run_student_submission(sub)
							elif command == "4":
								continue_to_next = False
								clear_and_print_header(main_class)
								break
							elif command == "0":
								continue_to_next = False
								sub.set_to_graded()
								clear_and_print_header(main_class)
								break
							else:
								print("Please enter a valid value.\n")
						if not continue_to_next:
							clear_and_print_header(main_class)
							break
					clear_and_print_header(main_class)
				elif command == "2":
					clear_and_print_header(main_class)
					print_invalid_submissions(main_class)
					print("\nPress ENTER to return to the menu.")
					input()
					clear_and_print_header(main_class)
				elif command == "3":
					clear_and_print_header(main_class)
					print("Performing a plagiarism check with Stanford's MOSS tool.")
					print(Design.border4)
					perform_plagiarism_check(main_class)
					print(Design.border2)
					print("\nPress ENTER to return to the menu.")
					input()
					clear_and_print_header(main_class)
					'''
				elif command == "3":
					clear_and_print_header(main_class)
					while True:
						print("Enter the ID number of the user whose project you want to examine.")
						str_input = input("Student's ID: ")
						if len(str_input) != 9:
							print("Please enter a valid ID number.")
							continue
						try:
							id_number = (int)str_input
							if id_number < 100000000 or id_number > 999999999:
								print("Please enter a valid ID number.")
								continue
							# The ID input is valid
							clear_and_print_header(main_class)
							print(f"Displaying project for use with ID: {id_number}")
							print(Design.border)
						except:
							print("Please enter a valid ID number.")
							continue
				'''
				elif command == "0":
					clear()
					break
				else:
					clear_and_print_header(main_class)
					print("Please enter a valid choice.")




# Start running through all of the valid submissions
Пример #21
0
from modules.api import SocialConnect, WeatherConnect
from modules.settings import Settings
from modules.mqtt import MQTT
import time
import datetime
import pytz
import schedule
import json
from random import randint

from modules.hardware import Hardware

sett = Settings()
h = Hardware(sett)


def change_interval_task(task_tag, interval=60, program=None):
    if program is None:
        return print("Task scheduling has not been changed")
    schedule.clear(task_tag)
    schedule.every(interval).seconds.do(program.refresh_api).tag(task_tag)
    return interval


def check_and_parse_message(program):
    msg = program.check_messages()
    if msg is not None:
        program.process_messages(msg)


def cancel_task(task_tag):
Пример #22
0
  sensitivity iso:   K   L    100..1600
  focus:             ,   .      0..255 [far..near]
To go back to auto controls:
  'E' - autoexposure
  'F' - autofocus (continuous)
"""
import os
import sys

import depthai as dai
import cv2

sys.path.insert(0, os.path.realpath('../'))
from modules.settings import Settings

settings = Settings("../color.yaml")

default_settings = {
    "autofocus": False,
}

settings.update_defaults(default_settings)

# Step size ('W','A','S','D' controls)
STEP_SIZE = 8
# Manual exposure/focus set step
EXP_STEP = 500  # us
ISO_STEP = 50
LENS_STEP = 3

pipeline = dai.Pipeline()