Esempio n. 1
0
def ask_user_task_amount(df, num_sur_q):
    """Asks for user input to determine how many surveys were given to the
	participant in the study.

	Args:
		df: A cleaned DataFrame of the Qualtrics export.
		num_sur_q(int): Total number of questions asked in surveys.
	Returns:
		task_amount(int): The number of questions in each survey.
	"""

    poten_task_amts = [x for x in range(2, 30) if num_sur_q % x == 0]
    if len(poten_task_amts) > 1:
        print(f"Judging by the numbers, it looks like there are multiple ways"
              " in which these questions could be broken up. Please answer the"
              " question(s) below to continue to attempt to parse the data.\n")
        for poten_task_amt in poten_task_amts:
            ans = InputManager.get_yes_or_no(f"Where there {poten_task_amt} "
                                             "total tasks in your study?")
            if ans:
                task_amount = poten_task_amt
                return task_amount
                break
    elif len(poten_task_amts) == 1:
        ans = InputManager.get_yes_or_no(
            f"There were {poten_task_amts} in your"
            " study? (Y/n): ")
        if not ans:
            clean_getaway()
        task_amount = poten_task_amts[0]
        return task_amount
    else:
        clean_getaway()
Esempio n. 2
0
def main():
    pygame.init()

    window = Window(1092, 780)
    input_m = InputManager()
    physics = PhysicsEngine()
    logic = LogicManager()
    clock = pygame.time.Clock()
    entities = spawn_entities_level_one()
    running = True
    level = 1

    while(running):
        try:
            running = input_m.update()
            clock.tick()
            dt = clock.get_time()
            logic.update(entities, input_m, dt)
            physics.update(entities, dt)
            window.render(entities, dt)
        except NewLevelException:
            window.change_level(clock,
                                pygame.Rect(650, 480, 100, 100),
                                3000)
            entities = spawn_entities_level_two()
            level = 2
        except ResetLevelException:
            if level == 2:
                entities = spawn_entities_level_two()
                window.enter_level2()
            else:
                entities = spawn_entities_level_one()
Esempio n. 3
0
File: sdl.py Progetto: jclopes/ZGame
def main():
 
    # create the managers
    eMngr = EventManager()
    gMngr = GraphicManager(eMngr)
    iMngr = InputManager(eMngr, gMngr)
    uMngr = UpdateManager(eMngr)
    sMngr = SoundManager(eMngr)
    nMngr = NetworkManager(eMngr)

    print "starting game"
    # create file with input
    playFile = open(sys.argv[1], 'r')
    # start the managers
    eMngr.start()
    gMngr.start()
    iMngr.start()
    uMngr.start()
    sMngr.start()
    nMngr.start()

    # create game and start it
    # FIXME playfile should be passed to the updateManager
    game = Game(iMngr, uMngr, gMngr, sMngr, nMngr, playFile)
    game.run()

    # close the managers
    eMngr.stop()
    uMngr.stop()
    iMngr.stop()
    gMngr.stop()
    sMngr.stop()
    nMngr.stop()
Esempio n. 4
0
 def __init__(self) -> None:
     self.groupByTag = True
     self.taskManager = TaskManager()
     self.calendarView = CalendarView(self.taskManager)
     # self.overview = Overview(self.taskManager.tasks)
     self.taskView = TaskView(self.taskManager, groupByTag=self.groupByTag)
     # self.layout = self.MakeLayout()
     self.inputManager = InputManager(self.taskManager)
     self.loop = True
Esempio n. 5
0
def get_survey_information(apiToken, dataCenter="ca1"):
    """Prints a list of the current survey names and corresponding Ids and asks
    the user which survey they want to recieve an export from.

    Args:
        apiToken(str): A string of characters that allows allows authentication
        when querying the Qualtrics API.
        dataCenter(str): Data center arguement for Qualtrics API.
    Returns:
        surveyID(str): A unique ID corresponding the to survey the user wants to
        retreieve survey responses for.
        Bool(False): If a surveyId isn't selected or found."""

    baseUrl = f"https://{dataCenter}.qualtrics.com/API/v3/surveys"

    headers = {
        "x-api-token": apiToken,
    }

    response = requests.get(baseUrl, headers=headers)
    try:
        survey_info = json.loads(response.text)['result']['elements']
    except KeyError:
        print(json.loads(response.text))
        print("You are presenting an invalid API token to qualtrics. "
              "Please make sure that your API token exactly matches"
              "the token listed on the Qualtrics account and try again.")
        sys.exit()

    print("\nBelow are the surveys listed under your qualtrics account:\n")
    print("-" * 80)
    if len(survey_info) == 0:
        print("There are no surveys associated with your Qualtrics account.")
        print("Quitting this program.. .. ..")
        sys.exit()

    for i, survey in enumerate(survey_info):
        print(f"{i + 1}. - Survey Name: {survey['name']}")
        print(f"Survey ID: {survey['id']}")
        print("-" * 80)

    prompt = (
        "Which survey would you like to export? \n(indicate the survey by typing the number listed next to the survey): "
    )
    survey_response = InputManager.get_numerical_input(prompt,
                                                       (len(survey_info)))
    surveyId = survey_info[survey_response - 1]['id']
    if surveyId:
        prompt = "Would you like to save this as your default survey? \n(Answering yes will save the id to '/.ids/surveyid.txt')"
        ans = InputManager.get_yes_or_no(prompt)
        if ans:
            if not os.path.exists(f"{os.getcwd()}/.ids/"):
                os.mkdir(f"{os.getcwd()}/.ids/")
            with open(f"{os.getcwd()}/.ids/surveyid.txt", "w") as out_file:
                out_file.write(surveyId)
        return surveyId
    return False
Esempio n. 6
0
def find_first_q(df):
    """Asks the user if the first question left over in the cleaned df is the
	first question of their survey. It also informs that user that the first
	question should be in the question asking for the participant's ID.

	Args:
		df: a (cleaned) DataFrame of the qualtrics data export.
	Returns: None"""

    try:
        first_q = df.iloc[0][0]
    except:
        return None
    ans = InputManager.get_yes_or_no(
        "\033[1m CHECKING FIRST QUESTION:"
        f"\n\n'{first_q}'\033[0m\n\n"
        "is the above the first survey question "
        "in your survey?: (Y/n) \n\n"
        "\033[1mNOTE:\033[0m This question should "
        "be asking for the experimenter to enter "
        "the participant's ID number.")
    if ans:
        return first_q
    else:
        clean_getaway()
Esempio n. 7
0
 def __init__(self, fnirs_file="./sampledata/samplefnirs/test_1.csv"):
     self.fnirs_file = fnirs_file
     self.df = pd.read_csv(fnirs_file, header=34)
     self.mark_col = self.df["Mark"].tolist()
     self.marks = [mark for mark in self.mark_col if mark > 0]
     self.mark_indexes = [indx for indx, mark in enumerate(self.mark_col)
                          if mark > 0]
     self.valid_marks = self.validate_marks(self.marks)
     self.valid_spaceing = self.validate_spacing(self.mark_indexes)
     if self.valid_marks:
         print("Marking appears to be valid. Even number of marks found. \n")
         if self.valid_spaceing:
             print("Spacing between marks appears to be valid.\n")
         print(f"Mark values:\n{self.mark_counts}")
         print(f"Number of space warnings: {len(self.space_warnings)}. \n")
         self.onsets = self.get_onsets(self.mark_indexes)
         self.task_number = len(self.onsets)
         self.durations = self.get_durations(self.onsets)
     else:
         print("\033[1mWARNING:\033[0m\n"
               "Something appears to have gone wrong in the marking "
               "of this file. fNIRS marks need to be opened and closed. "
               "You can continue to attempt to parse the file, but the "
               "outcomes may not be correct. Make sure to check outputs "
               "for validity if you decide to continue. ")
         ans = InputManager.get_yes_or_no("Try anyway? (Y/n): ")
         if not ans:
             pass
         self.get_onsets()
Esempio n. 8
0
def find_slice_prompt(df):
    """Finds the string value that the script will use to slice the survey data
	up by - the first question asked in the beginning of each survey.

	Args:
		df: A cleaned DataFrame from the Qualtrics export.
	Returns:
		slice_prompt(str): The string value of the first survey question in each
		survey."""

    questions_list = df.iloc[0].tolist()
    num_of_q_per_task, num_of_tasks, num_prelim_qs = get_slice_prompt_index(df)
    print(f"There were {int(num_of_q_per_task)} questions per task.")
    print(f"There were {num_of_tasks} tasks total")
    print(f"The first {num_prelim_qs} were preliminary questions.")
    slice_prompt = questions_list[num_prelim_qs]
    ans = InputManager.get_yes_or_no(
        "\033[1m CHECKING FIRST SURVEY QUESTION:"
        f"\n\n'{slice_prompt}'\033[0m\n\n"
        "is the above the first survey question "
        "in your survey?: (Y/n) \n\n"
        "\033[1mNOTE:\033[0m This question should "
        "be asking for the experimenter to enter "
        "the task the participant just completed.")
    if not ans:
        clean_getaway()
    return slice_prompt
Esempio n. 9
0
def get_api_fpath():
    """Allows user to manually import filepath that and contains their API token.

    Args:
        None
    Returns:
        api_fpath(str): location of the file containing user's API key.
        Bool (False): If user does not want to manually enter the filepath."""

    ans = InputManager.get_yes_or_no(
        "Would you like to manually enter the filepath where your API token is located?: (Y/n): "
    )

    if ans:
        fpath = InputManager.get_valid_fpath("Please enter a valid filepath: ")
        return fpath

    return False
Esempio n. 10
0
	def __init__(self):
		self.game=Gamelolz(self)
		self.menu=menulists
		global inputmanager #because everyone should be able to access it.
		self.inputmanager=InputManager(self.game)
		#pygame.register_quit(self.inputmanager.sysexit)
		self.menu.init_menu()
		self.game.start()
		while self.menu.exit_menu(self.game.points):
			self.game.start()
Esempio n. 11
0
def main():

    # create the managers
    eMngr = EventManager()
    gMngr = GraphicManager(eMngr)
    iMngr = InputManager(eMngr, gMngr)
    uMngr = UpdateManager(eMngr)
    sMngr = SoundManager(eMngr)
    nMngr = NetworkManager(eMngr)

    print "starting game"
    # create file with input
    playFile = open(sys.argv[1], 'r')
    # start the managers
    eMngr.start()
    gMngr.start()
    iMngr.start()
    uMngr.start()
    sMngr.start()
    nMngr.start()

    # create game and start it
    # FIXME playfile should be passed to the updateManager
    game = Game(iMngr, uMngr, gMngr, sMngr, nMngr, playFile)
    game.run()

    # close the managers
    eMngr.stop()
    uMngr.stop()
    iMngr.stop()
    gMngr.stop()
    sMngr.stop()
    nMngr.stop()
Esempio n. 12
0
def main():
    maze = maze_gen.Maze(5, 5)
    input_manager = InputManager()

    player_agent =\
        QLearningAgent(
            initial_q=0.1,
            learning_rate=0.9,
            discount_factor=0.9)

    #    target_agent =\
    #        WaitAndRunAgent(
    #            100000,
    #            QLearningAgent(
    #                initial_q=0,
    #                learning_rate=0.9,
    #                discount_factor=0.9))

    target_agent =\
        QLearningAgent(
            initial_q=0,
            learning_rate=0.9,
            discount_factor=0.9)

    env = \
        MazeGameGuiEnvironment(
            maze,
            player_agent,
            target_agent,
            input_manager)

    count = 0
    while count < 10000:
        env.reset()

        done = env.step()
        while not done:
            done = env.step()

        print(len(env.get_record()["a"]))

        count += 1

    np.save("q_state_action",
            np.array((list(k[0] + (k[1], ) for k in player_agent.q))))
    np.save("q_target_value",
            np.array((list((v, ) for k, v in player_agent.q.items()))))
Esempio n. 13
0
def get_prelim_qs(df):
    """Asks the user to input the amount of questions in the survey that do not
	correspond to survey questions given to the participant (preliminary
	questions).

	Args:
		df: A cleaned DataFrame of the Qualtrics export.
	Returns:
		num_prelim_qs(int): The number of questions before the experiment began.
	"""

    num_prelim_qs = InputManager.get_numerical_input(
        "How many preliminary "
        "questions were asked "
        "before the experiment "
        "began?: ", 9)

    return num_prelim_qs
Esempio n. 14
0
    def get_col_names(self):
        """Asks the user to rename the columns if they were not properly named
        before.
        """
        new_col_names = []
        for col_name in self.df.columns:

            ans = InputManager.get_variable_name(f"Input a measure name "
                                                 f"for column: {col_name}. "
                                                 "Type 'd' to drop col, "
                                                 " or 'k' to keep default: ")
            if ans == 'k':
                new_col_names.append(col_name)
            elif ans == 'd':
                self.df.drop(col_name)
            else:
                new_col_names.append(ans)

        self.df.columns = new_col_names
Esempio n. 15
0
    def __init__(self):
        """Base class initializer.

        Initialize base class and manager classes. Manager classes and their methods form the Driftwood Scripting API.

        Attributes:
            config: ConfigManager instance.
            log: LogManager instance.
            database: DatabaseManager instance.
            filetype: Shortcut to filetype module.
            tick: TickManager instance.
            path: PathManager instance.
            cache: CacheManager instance.
            resource: ResourceManager instance.
            input: InputManager instance.
            window: WindowManager instance.
            entity: EntityManager instance.
            area: AreaManager instance.
            script: ScriptManager instance.

            keycode: Contains the SDL keycodes.

            running: Whether the mainloop should continue running. Set False to shut down the engine.
        """
        self.config = ConfigManager(self)
        self.log = LogManager(self)
        self.database = DatabaseManager(self)
        self.tick = TickManager(self)
        self.path = PathManager(self)
        self.cache = CacheManager(self)
        self.resource = ResourceManager(self)
        self.input = InputManager(self)
        self.window = WindowManager(self)
        self.entity = EntityManager(self)
        self.area = AreaManager(self)
        self.script = ScriptManager(self)

        # SDL Keycodes.
        self.keycode = keycode

        self.running = False
Esempio n. 16
0
def main():
    global inputmanager, screen, board
    #init graphics
    init()
    size = (150, 150)
    screen = set_mode(size)

    #init game data
    nr_of_rectangles = 9
    board = TicTacToeBoard(nr_of_rectangles)
    #board.paint(screen)

    #init input
    inputmanager = InputManager([
        ("Mouse", 1, "Press",
         (lambda: board.make_turn(Point(get_pos()[0],
                                        get_pos()[1])))),
        ("Key", K_UP, "Press", (lambda: print("Hello Keyboard!"))),
    ])

    loop()
Esempio n. 17
0
def get_q_measures(num_questions):
    """Prompts the user in input the operational conditionals value titles for
	all of the questions in their survey. These value titles will serve as row
	headings in the conditions files.

	Args:
		num_questions(int): Number of questions administered in a survey given
		the the participant after each task.
	Returns:
		q_measures(list): A list of the row headings for the completed
		conditions file."""

    keyword_measures = {
        "tlx": [
            "", "onset", "duration", "stim", "tlx", "tlx_mental",
            "tlx_physical", "tlx_temporal", "tlx_performance", "tlx_effort",
            "tlx_frustration"
        ],
        "mrq": ["", "onset", "duration", "stim", "mrq"],
    }

    q_measures = []
    for x in range(0, num_questions + 1):
        if x == 0:
            q_measures.append("")
        elif x == 1:
            q_measures.append("stim")
        else:
            prompt = (f"Please enter the measurement name for"
                      f" question {x + 1} in the survey.")
            measure = InputManager.get_variable_name(prompt)
            q_measures.append(measure)
            if measure in keyword_measures:
                return keyword_measures[measure]
            elif measure == "default":
                return [f"measure {x}" for x in range(0, num_questions + 1)]

    return q_measures
Esempio n. 18
0
    def __init__(self, qual_export=None, clean_it=True, marking=True,
                 mark_str=" ", ignore_warnings=False, template=None):

        self.template = template

        if self.template:
            self.load_template_params(template)
        else:
            self.mark_str = mark_str
            self.ignore_warnings = ignore_warnings
            self.data_files_not_found = []

            if not qual_export:
                qual_export = InputManager.get_valid_fpath("Please enter a filepath "
                                                         "for the Qualtrics export "
                                                         "you wish to parse: ")
            self.load_in_file(qual_export)
            if clean_it:
                self.clean_qualtrics_export()
                self.set_headers()
                if marking:
                    self.checks_out = self.find_marks(mark_str)
                self.select_parsing_process()
                self.make_headings_col()
Esempio n. 19
0
def leave_any_out(df):
    """Asks the user if there is any section of the survey they would like
	to leave out of the parsing process.

	Args:
		df: A cleaned Qualtrics survey export.
	Returns:
		df: A cleaned Qualtrics export with the proper columns removed."""

    ans = InputManager.get_yes_or_no(
        "Are there any columns you not like to"
        " include in the conditions files? (Y/n):")
    if ans:
        first_prompt = input("Please enter the first prompt for the section "
                             "you wish to remove: ")
        how_many_after = int(
            input("How many columns do you wish to remove "
                  " after the first prompt?: "))

        headings_list = df.iloc[0].tolist()
        first_indx = headings_list.index(first_prompt)
        cols_to_remove = headings_list[first_indx:first_indx + how_many_after]
        df.drop(cols_to_remove, axis=1, inplace=True)
    return df
Esempio n. 20
0
class LiveLayoutView():
    '''
	docstring
	'''

    ### TODO, send taskmanager itself for a single source of truth.

    def __init__(self) -> None:
        self.groupByTag = True
        self.taskManager = TaskManager()
        self.calendarView = CalendarView(self.taskManager)
        # self.overview = Overview(self.taskManager.tasks)
        self.taskView = TaskView(self.taskManager, groupByTag=self.groupByTag)
        # self.layout = self.MakeLayout()
        self.inputManager = InputManager(self.taskManager)
        self.loop = True
        # self.input = ''

    def RichLayout(self) -> Layout:
        layout = Layout()
        layout.split(
            # Layout(name="upper"),
            Layout(" ", name="BufferTop"),
            Layout(Panel(self.calendarView.RichGrid(),
                         title="Calendar",
                         style='grey50'),
                   name="Calendar"),
            Layout(Panel(self.taskView.RichGrid(),
                         title="Tasks",
                         style='grey50'),
                   name="Tasks"),
            # Layout(Panel(str(datetime.now()), title="Console"), name="Console")
            Layout(self.inputManager.RichGrid(), name='Console')
            # Layout(" ", name="BufferBot")
            # Layout(datetime.datetime.now().strftime('%H:%M:%S') + '    ' + self.input, name='Console')
        )

        # layout["upper"].split(
        # 	Layout(Panel(self.calendarView.RichGrid(), title="Calendar"), name="Calendar"),
        # 	# Layout(Panel(self.overview.RichGrid(), title="Overview"), name="Overview"),
        # 	direction="horizontal"
        # )

        # layout['Calendar'].ratio = 2.5
        # layout['Overview'].ratio =
        layout["BufferTop"].size = 1
        layout["Tasks"].ratio = 1.5
        # layout["BufferBot"].size = 1
        layout['Console'].size = 1
        return layout

    def LiveRender(self):
        '''
		docstring
		'''
        # term = Terminal()

        # print(self.RichLayout())
        # while True:

        response = ''
        initial = ''
        timedOut = False

        console = Console()

        with Live(console=console,
                  auto_refresh=False,
                  screen=True,
                  vertical_overflow='ellipsis',
                  redirect_stdout=False,
                  redirect_stderr=False) as live:
            # term.inkey(timeout=5)
            live.update(self.RichLayout(), refresh=True)

            while response != 'exit':
                response, timedOut = inputAdv('', initial, 3600)
                if timedOut:
                    initial = response
                else:
                    initial = ''
                    self.inputManager._ExecuteInput(response.strip())
                live.update(self.RichLayout(), refresh=True)
Esempio n. 21
0
class Driftwood:
    """The top-level base class

    This class contains the top level manager class instances and the mainloop. The instance of this class is
    passed to scripts as an API reference.
    """

    def __init__(self):
        """Base class initializer.

        Initialize base class and manager classes. Manager classes and their methods form the Driftwood Scripting API.

        Attributes:
            config: ConfigManager instance.
            log: LogManager instance.
            database: DatabaseManager instance.
            filetype: Shortcut to filetype module.
            tick: TickManager instance.
            path: PathManager instance.
            cache: CacheManager instance.
            resource: ResourceManager instance.
            input: InputManager instance.
            window: WindowManager instance.
            entity: EntityManager instance.
            area: AreaManager instance.
            script: ScriptManager instance.

            keycode: Contains the SDL keycodes.

            running: Whether the mainloop should continue running. Set False to shut down the engine.
        """
        self.config = ConfigManager(self)
        self.log = LogManager(self)
        self.database = DatabaseManager(self)
        self.tick = TickManager(self)
        self.path = PathManager(self)
        self.cache = CacheManager(self)
        self.resource = ResourceManager(self)
        self.input = InputManager(self)
        self.window = WindowManager(self)
        self.entity = EntityManager(self)
        self.area = AreaManager(self)
        self.script = ScriptManager(self)

        # SDL Keycodes.
        self.keycode = keycode

        self.running = False

    def run(self):
        """Perform startup procedures and enter the mainloop.
        """
        # Only run if not already running.
        if not self.running:
            self.running = True

            # Execute the init function of the init script if present.
            if not self.path["init.py"]:
                self.log.msg("WARNING", "Driftwood", "init.py missing, nothing will happen")
            else:
                self.script.call("init.py", "init")

            # Escape key pauses the engine.
            self.input.register(self.keycode.SDLK_ESCAPE, self.__handle_pause)

            # This is the mainloop.
            while self.running:
                # Process SDL events.
                sdlevents = sdl2ext.get_events()
                for event in sdlevents:
                    if event.type == SDL_QUIT:
                        # Stop running.
                        self.running = False

                    elif event.type == SDL_KEYDOWN:
                        # Pass a keydown to the Input Manager.
                        self.input._key_down(event.key.keysym.sym)

                    elif event.type == SDL_KEYUP:
                        # Pass a keyup to the Input Manager.
                        self.input._key_up(event.key.keysym.sym)

                    elif event.type == SDL_WINDOWEVENT and event.window.event == SDL_WINDOWEVENT_EXPOSED:
                        self.window.refresh()

                # Process tick callbacks.
                self.tick.tick()

            print("Shutting down...")
            return 0

    def __handle_pause(self, keyevent):
        if keyevent == InputManager.ONDOWN:
            # Shift+Escape shuts down the engine.
            if self.input.pressed(self.keycode.SDLK_LSHIFT) or self.input.pressed(self.keycode.SDLK_RSHIFT):
                self.running = False

            else:
                self.tick.toggle_pause()