# Random number (Generate, display, & save)

I posted another topic earlier today because I’m having trouble with running my experiment on pavlovia. I’m totally new to all this, but think the issue might be that, although the experiment was made in builder, it has code elements that are in python. So I’m working on switching it to JS now, but running into new problems.

I need it to generate a random 7-digit number, display that number, and save that number in the data file (for mturk validation).

I had the following python script in the code element

``````mturk = randint(1000000,9999999)
thisExp.addData("mturk", mturk)
``````

and text element said \$mturk. This did exactly what I needed it to do.

However, I don’t know how to accomplish this in JS. Any help would be appreciated!

1 Like

Hi @anna1, you can find some good examples for generating random numbers on the Mozilla web docs page. Note the inclusive and exclusive min and max, respectively.

### Generating random integer between two values

``````
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

mTurk = getRandomInt(1000000, 9999999)
``````

### Saving data using PsychoJS

``````psychoJS.experiment.addData("mturk", mturk)
``````

Thanks for the response @dvbridges! I’m still getting an error…maybe you can help me understand why.

In begin experiment I now have the below code. But I still got “NameError: name ‘mturk’ is not defined

``````function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

mturk = getRandomInt(1000000, 9999999)

psychoJS.experiment.addData("mturk", mturk)
``````

Before you replied I tried the code below and got the same error…

``````mturk = Mat.floor(Math.random()* (9999999-1000000)+1000000)
psychoJS.experiment.addData('mturk', mturk)
``````

I have \$mturk in the text box in my text element so I’m not sure why it’s coming back as not defined for both of these attempt… Any suggestions?

I’m posting my full code in case that may be helpful. I’m also attaching a screenshot of the error (it refers to line 534).

``````#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.0.5),
on Wed Mar 27 10:37:36 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""

from __future__ import absolute_import, division
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '3.0.5'
expName = 'test'  # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False:
core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion

# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='/Users/Anna/Desktop/Working Test/2WorkingTest.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp

# Start Code - component code to be run before the window creation

# Setup the Window
win = visual.Window(
size=[1440, 900], fullscr=True, screen=0,
allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "Instra1"
Instra1Clock = core.Clock()
text = visual.TextStim(win=win, name='text',
text='In each trial, two photos of faces will be displayed on your screen for a limited amount of time. Please indicate if the photos are of the same person or different people. \n \nPress  0 for same and 1 for different.\n\nClick the RIGHT ARROW to begin',
font='Arial',
pos=(0,0), height=0.03, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);

# Initialize components for Routine "image"
imageClock = core.Clock()
Image = visual.ImageStim(
win=win, name='Image',
image='sin', mask=None,
ori=0, pos=(0, 0), size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)

# Initialize components for Routine "Mask"
MaskClock = core.Clock()
mask = visual.ImageStim(
win=win, name='mask',
image='sin', mask=None,
ori=0, pos=(0, 0), size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)

# Initialize components for Routine "Resp"
RespClock = core.Clock()
text_3 = visual.TextStim(win=win, name='text_3',
text='0=SAME 1=DIFFERENT',
font='Arial',
pos=(0,0), height=0.05, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);

# Initialize components for Routine "Debrief"
DebriefClock = core.Clock()
text_2 = visual.TextStim(win=win, name='text_2',
text='This will be the debriefing.\n\nCLICK THE RIGHT ARROW TO SUBMIT YOUR DATA AND RECIEVE YOUR MTURK COMPLETION CODE.',
font='Arial',
pos=(0, 0), height=0.05, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);

# Initialize components for Routine "numgen"
numgenClock = core.Clock()
validation_num = visual.TextStim(win=win, name='validation_num',
text= 'default text',
font='Arial',
pos=(0, -.075), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);

text_5 = visual.TextStim(win=win, name='text_5',
text='This is your mturk completion code:',
font='Arial',
pos=(0, .085), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
text_6 = visual.TextStim(win=win, name='text_6',
text='NOTE: Write down this number now as it will no longer be available when you click esc to close out of the experiement.',
font='Arial',
pos=(0, -.3), height=0.025, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine

# ------Prepare to start Routine "Instra1"-------
t = 0
Instra1Clock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
instra_cont = event.BuilderKeyResponse()
# keep track of which components have finished
Instra1Components = [text, instra_cont]
for thisComponent in Instra1Components:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Instra1"-------
while continueRoutine:
# get current time
t = Instra1Clock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *text* updates
if t >= 0.0 and text.status == NOT_STARTED:
# keep track of start time/frame for later
text.tStart = t
text.frameNStart = frameN  # exact frame index
text.setAutoDraw(True)

# *instra_cont* updates
if t >= 0.0 and instra_cont.status == NOT_STARTED:
# keep track of start time/frame for later
instra_cont.tStart = t
instra_cont.frameNStart = frameN  # exact frame index
instra_cont.status = STARTED
# keyboard checking is just starting
win.callOnFlip(instra_cont.clock.reset)  # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if instra_cont.status == STARTED:
theseKeys = event.getKeys(keyList=['right'])

# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0:  # at least one key was pressed
instra_cont.keys = theseKeys[-1]  # just the last key pressed
instra_cont.rt = instra_cont.clock.getTime()
# a response ends the routine
continueRoutine = False

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in Instra1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Instra1"-------
for thisComponent in Instra1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if instra_cont.keys in ['', [], None]:  # No response was made
instra_cont.keys=None
thisExp.addData('instra_cont.keys',instra_cont.keys)
if instra_cont.keys != None:  # we had a response
thisExp.addData('instra_cont.rt', instra_cont.rt)
thisExp.nextEntry()
# the Routine "Instra1" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('trialTypes4.csv'),
seed=None, name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
currentLoop = trials
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec('{} = thisTrial[paramName]'.format(paramName))

# ------Prepare to start Routine "image"-------
t = 0
imageClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
Image.setImage(stimFile)
# keep track of which components have finished
imageComponents = [Image]
for thisComponent in imageComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "image"-------
while continueRoutine:
# get current time
t = imageClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *Image* updates
if t >= 0.0 and Image.status == NOT_STARTED:
# keep track of start time/frame for later
Image.tStart = t
Image.frameNStart = frameN  # exact frame index
Image.setAutoDraw(True)
frameRemains = 0.0 + imagetime- win.monitorFramePeriod * 0.75  # most of one frame period left
if Image.status == STARTED and t >= frameRemains:
Image.setAutoDraw(False)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in imageComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "image"-------
for thisComponent in imageComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "image" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "Mask"-------
t = 0
MaskClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
mask.setImage(maskFile)
# keep track of which components have finished
MaskComponents = [mask]
for thisComponent in MaskComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Mask"-------
while continueRoutine:
# get current time
t = MaskClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *mask* updates
if t >= 0.0 and mask.status == NOT_STARTED:
# keep track of start time/frame for later
mask.tStart = t
mask.frameNStart = frameN  # exact frame index
mask.setAutoDraw(True)
frameRemains = 0.0 + masktime- win.monitorFramePeriod * 0.75  # most of one frame period left
if mask.status == STARTED and t >= frameRemains:
mask.setAutoDraw(False)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in MaskComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Mask"-------
for thisComponent in MaskComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "Mask" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "Resp"-------
t = 0
RespClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
resp_key = event.BuilderKeyResponse()
# keep track of which components have finished
RespComponents = [resp_key, text_3]
for thisComponent in RespComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Resp"-------
while continueRoutine:
# get current time
t = RespClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *resp_key* updates
if t >= 0.0 and resp_key.status == NOT_STARTED:
# keep track of start time/frame for later
resp_key.tStart = t
resp_key.frameNStart = frameN  # exact frame index
resp_key.status = STARTED
# keyboard checking is just starting
win.callOnFlip(resp_key.clock.reset)  # t=0 on next screen flip
if resp_key.status == STARTED:
theseKeys = event.getKeys(keyList=['1', '0'])

# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0:  # at least one key was pressed
resp_key.keys = theseKeys[-1]  # just the last key pressed
resp_key.rt = resp_key.clock.getTime()
# was this 'correct'?
if (resp_key.keys == str(corrAns)) or (resp_key.keys == corrAns):
resp_key.corr = 1
else:
resp_key.corr = 0
# a response ends the routine
continueRoutine = False

# *text_3* updates
if t >= 0.0 and text_3.status == NOT_STARTED:
# keep track of start time/frame for later
text_3.tStart = t
text_3.frameNStart = frameN  # exact frame index
text_3.setAutoDraw(True)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in RespComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Resp"-------
for thisComponent in RespComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if resp_key.keys in ['', [], None]:  # No response was made
resp_key.keys=None
# was no response the correct answer?!
if str(corrAns).lower() == 'none':
resp_key.corr = 1;  # correct non-response
else:
resp_key.corr = 0;  # failed to respond (incorrectly)
# store data for trials (TrialHandler)
trials.addData('resp_key.keys',resp_key.keys)
trials.addData('resp_key.corr', resp_key.corr)
if resp_key.keys != None:  # we had a response
trials.addData('resp_key.rt', resp_key.rt)
# the Routine "Resp" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()

# completed 1 repeats of 'trials'

# ------Prepare to start Routine "Debrief"-------
t = 0
DebriefClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
Debrief_cont = event.BuilderKeyResponse()
# keep track of which components have finished
DebriefComponents = [text_2, Debrief_cont]
for thisComponent in DebriefComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Debrief"-------
while continueRoutine:
# get current time
t = DebriefClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *text_2* updates
if t >= 0.0 and text_2.status == NOT_STARTED:
# keep track of start time/frame for later
text_2.tStart = t
text_2.frameNStart = frameN  # exact frame index
text_2.setAutoDraw(True)

# *Debrief_cont* updates
if t >= 0.0 and Debrief_cont.status == NOT_STARTED:
# keep track of start time/frame for later
Debrief_cont.tStart = t
Debrief_cont.frameNStart = frameN  # exact frame index
Debrief_cont.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Debrief_cont.clock.reset)  # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if Debrief_cont.status == STARTED:
theseKeys = event.getKeys(keyList=['right'])

# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0:  # at least one key was pressed
Debrief_cont.keys = theseKeys[-1]  # just the last key pressed
Debrief_cont.rt = Debrief_cont.clock.getTime()
# a response ends the routine
continueRoutine = False

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in DebriefComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Debrief"-------
for thisComponent in DebriefComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if Debrief_cont.keys in ['', [], None]:  # No response was made
Debrief_cont.keys=None
thisExp.addData('Debrief_cont.keys',Debrief_cont.keys)
if Debrief_cont.keys != None:  # we had a response
thisExp.addData('Debrief_cont.rt', Debrief_cont.rt)
thisExp.nextEntry()
# the Routine "Debrief" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "numgen"-------
t = 0
numgenClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
validation_num.setText(mturk)

# keep track of which components have finished
numgenComponents = [validation_num, text_5, text_6]
for thisComponent in numgenComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "numgen"-------
while continueRoutine:
# get current time
t = numgenClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *validation_num* updates
if t >= 0. and validation_num.status == NOT_STARTED:
# keep track of start time/frame for later
validation_num.tStart = t
validation_num.frameNStart = frameN  # exact frame index
validation_num.setAutoDraw(True)

# *text_5* updates
if t >= 0.0 and text_5.status == NOT_STARTED:
# keep track of start time/frame for later
text_5.tStart = t
text_5.frameNStart = frameN  # exact frame index
text_5.setAutoDraw(True)

# *text_6* updates
if t >= 0.0 and text_6.status == NOT_STARTED:
# keep track of start time/frame for later
text_6.tStart = t
text_6.frameNStart = frameN  # exact frame index
text_6.setAutoDraw(True)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in numgenComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "numgen"-------
for thisComponent in numgenComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)

# the Routine "numgen" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()
``````

Hi @anna1, apologies for the delay. Your code above is Python code for running your experiment locally. However, lets fix that before we think about running the experiment online.

The variable `mturk` is not defined. I cannot see any code snippets with your python random number generator, as in your original post. You need to put that code back into your Python code component.

In your code component, there is a code type drop-down menu. Use the “Both” setting to see your Python and JavaScript in the left and right panels, respectively, simultaneously.

@dvbridges No worries! Thanks for your willingness to help!

This is what my code component looks like now:

and here is what my full script looks like now:

``````#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.0.5),
on Wed Mar 27 11:16:07 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""

from __future__ import absolute_import, division
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '3.0.5'
expName = 'test'  # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False:
core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion

# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='/Users/Anna/Desktop/Working Test/2WorkingTest.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp

# Start Code - component code to be run before the window creation

# Setup the Window
win = visual.Window(
size=[1440, 900], fullscr=True, screen=0,
allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "Instra1"
Instra1Clock = core.Clock()
text = visual.TextStim(win=win, name='text',
text='In each trial, two photos of faces will be displayed on your screen for a limited amount of time. Please indicate if the photos are of the same person or different people. \n \nPress  0 for same and 1 for different.\n\nClick the RIGHT ARROW to begin',
font='Arial',
pos=(0,0), height=0.03, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);

# Initialize components for Routine "image"
imageClock = core.Clock()
Image = visual.ImageStim(
win=win, name='Image',
image='sin', mask=None,
ori=0, pos=(0, 0), size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)

# Initialize components for Routine "Mask"
MaskClock = core.Clock()
mask = visual.ImageStim(
win=win, name='mask',
image='sin', mask=None,
ori=0, pos=(0, 0), size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)

# Initialize components for Routine "Resp"
RespClock = core.Clock()
text_3 = visual.TextStim(win=win, name='text_3',
text='0=SAME 1=DIFFERENT',
font='Arial',
pos=(0,0), height=0.05, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);

# Initialize components for Routine "Debrief"
DebriefClock = core.Clock()
text_2 = visual.TextStim(win=win, name='text_2',
text='This will be the debriefing.\n\nCLICK THE RIGHT ARROW TO SUBMIT YOUR DATA AND RECIEVE YOUR MTURK COMPLETION CODE.',
font='Arial',
pos=(0, 0), height=0.05, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);

# Initialize components for Routine "numgen"
numgenClock = core.Clock()
validation_num = visual.TextStim(win=win, name='validation_num',
text='default text',
font='Arial',
pos=(0, -.075), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
mturk = randint(1000000,9999999)
thisExp.addData("mturk", mturk)
text_5 = visual.TextStim(win=win, name='text_5',
text='This is your mturk completion code:',
font='Arial',
pos=(0, .085), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
text_6 = visual.TextStim(win=win, name='text_6',
text='NOTE: Write down this number now as it will no longer be available when you click esc to close out of the experiement.',
font='Arial',
pos=(0, -.3), height=0.025, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine

# ------Prepare to start Routine "Instra1"-------
t = 0
Instra1Clock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
instra_cont = event.BuilderKeyResponse()
# keep track of which components have finished
Instra1Components = [text, instra_cont]
for thisComponent in Instra1Components:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Instra1"-------
while continueRoutine:
# get current time
t = Instra1Clock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *text* updates
if t >= 0.0 and text.status == NOT_STARTED:
# keep track of start time/frame for later
text.tStart = t
text.frameNStart = frameN  # exact frame index
text.setAutoDraw(True)

# *instra_cont* updates
if t >= 0.0 and instra_cont.status == NOT_STARTED:
# keep track of start time/frame for later
instra_cont.tStart = t
instra_cont.frameNStart = frameN  # exact frame index
instra_cont.status = STARTED
# keyboard checking is just starting
win.callOnFlip(instra_cont.clock.reset)  # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if instra_cont.status == STARTED:
theseKeys = event.getKeys(keyList=['right'])

# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0:  # at least one key was pressed
instra_cont.keys = theseKeys[-1]  # just the last key pressed
instra_cont.rt = instra_cont.clock.getTime()
# a response ends the routine
continueRoutine = False

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in Instra1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Instra1"-------
for thisComponent in Instra1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if instra_cont.keys in ['', [], None]:  # No response was made
instra_cont.keys=None
thisExp.addData('instra_cont.keys',instra_cont.keys)
if instra_cont.keys != None:  # we had a response
thisExp.addData('instra_cont.rt', instra_cont.rt)
thisExp.nextEntry()
# the Routine "Instra1" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('trialTypes4.csv'),
seed=None, name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
currentLoop = trials
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec('{} = thisTrial[paramName]'.format(paramName))

# ------Prepare to start Routine "image"-------
t = 0
imageClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
Image.setImage(stimFile)
# keep track of which components have finished
imageComponents = [Image]
for thisComponent in imageComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "image"-------
while continueRoutine:
# get current time
t = imageClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *Image* updates
if t >= 0.0 and Image.status == NOT_STARTED:
# keep track of start time/frame for later
Image.tStart = t
Image.frameNStart = frameN  # exact frame index
Image.setAutoDraw(True)
frameRemains = 0.0 + imagetime- win.monitorFramePeriod * 0.75  # most of one frame period left
if Image.status == STARTED and t >= frameRemains:
Image.setAutoDraw(False)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in imageComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "image"-------
for thisComponent in imageComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "image" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "Mask"-------
t = 0
MaskClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
mask.setImage(maskFile)
# keep track of which components have finished
MaskComponents = [mask]
for thisComponent in MaskComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Mask"-------
while continueRoutine:
# get current time
t = MaskClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *mask* updates
if t >= 0.0 and mask.status == NOT_STARTED:
# keep track of start time/frame for later
mask.tStart = t
mask.frameNStart = frameN  # exact frame index
mask.setAutoDraw(True)
frameRemains = 0.0 + masktime- win.monitorFramePeriod * 0.75  # most of one frame period left
if mask.status == STARTED and t >= frameRemains:
mask.setAutoDraw(False)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in MaskComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Mask"-------
for thisComponent in MaskComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "Mask" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "Resp"-------
t = 0
RespClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
resp_key = event.BuilderKeyResponse()
# keep track of which components have finished
RespComponents = [resp_key, text_3]
for thisComponent in RespComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Resp"-------
while continueRoutine:
# get current time
t = RespClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *resp_key* updates
if t >= 0.0 and resp_key.status == NOT_STARTED:
# keep track of start time/frame for later
resp_key.tStart = t
resp_key.frameNStart = frameN  # exact frame index
resp_key.status = STARTED
# keyboard checking is just starting
win.callOnFlip(resp_key.clock.reset)  # t=0 on next screen flip
if resp_key.status == STARTED:
theseKeys = event.getKeys(keyList=['1', '0'])

# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0:  # at least one key was pressed
resp_key.keys = theseKeys[-1]  # just the last key pressed
resp_key.rt = resp_key.clock.getTime()
# was this 'correct'?
if (resp_key.keys == str(corrAns)) or (resp_key.keys == corrAns):
resp_key.corr = 1
else:
resp_key.corr = 0
# a response ends the routine
continueRoutine = False

# *text_3* updates
if t >= 0.0 and text_3.status == NOT_STARTED:
# keep track of start time/frame for later
text_3.tStart = t
text_3.frameNStart = frameN  # exact frame index
text_3.setAutoDraw(True)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in RespComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Resp"-------
for thisComponent in RespComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if resp_key.keys in ['', [], None]:  # No response was made
resp_key.keys=None
# was no response the correct answer?!
if str(corrAns).lower() == 'none':
resp_key.corr = 1;  # correct non-response
else:
resp_key.corr = 0;  # failed to respond (incorrectly)
# store data for trials (TrialHandler)
trials.addData('resp_key.keys',resp_key.keys)
trials.addData('resp_key.corr', resp_key.corr)
if resp_key.keys != None:  # we had a response
trials.addData('resp_key.rt', resp_key.rt)
# the Routine "Resp" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()

# completed 1 repeats of 'trials'

# ------Prepare to start Routine "Debrief"-------
t = 0
DebriefClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
Debrief_cont = event.BuilderKeyResponse()
# keep track of which components have finished
DebriefComponents = [text_2, Debrief_cont]
for thisComponent in DebriefComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "Debrief"-------
while continueRoutine:
# get current time
t = DebriefClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *text_2* updates
if t >= 0.0 and text_2.status == NOT_STARTED:
# keep track of start time/frame for later
text_2.tStart = t
text_2.frameNStart = frameN  # exact frame index
text_2.setAutoDraw(True)

# *Debrief_cont* updates
if t >= 0.0 and Debrief_cont.status == NOT_STARTED:
# keep track of start time/frame for later
Debrief_cont.tStart = t
Debrief_cont.frameNStart = frameN  # exact frame index
Debrief_cont.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Debrief_cont.clock.reset)  # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if Debrief_cont.status == STARTED:
theseKeys = event.getKeys(keyList=['right'])

# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0:  # at least one key was pressed
Debrief_cont.keys = theseKeys[-1]  # just the last key pressed
Debrief_cont.rt = Debrief_cont.clock.getTime()
# a response ends the routine
continueRoutine = False

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in DebriefComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "Debrief"-------
for thisComponent in DebriefComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if Debrief_cont.keys in ['', [], None]:  # No response was made
Debrief_cont.keys=None
thisExp.addData('Debrief_cont.keys',Debrief_cont.keys)
if Debrief_cont.keys != None:  # we had a response
thisExp.addData('Debrief_cont.rt', Debrief_cont.rt)
thisExp.nextEntry()
# the Routine "Debrief" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "numgen"-------
t = 0
numgenClock.reset()  # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
validation_num.setText(mturk)

# keep track of which components have finished
numgenComponents = [validation_num, text_5, text_6]
for thisComponent in numgenComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED

# -------Start Routine "numgen"-------
while continueRoutine:
# get current time
t = numgenClock.getTime()
frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *validation_num* updates
if t >= 0. and validation_num.status == NOT_STARTED:
# keep track of start time/frame for later
validation_num.tStart = t
validation_num.frameNStart = frameN  # exact frame index
validation_num.setAutoDraw(True)

# *text_5* updates
if t >= 0.0 and text_5.status == NOT_STARTED:
# keep track of start time/frame for later
text_5.tStart = t
text_5.frameNStart = frameN  # exact frame index
text_5.setAutoDraw(True)

# *text_6* updates
if t >= 0.0 and text_6.status == NOT_STARTED:
# keep track of start time/frame for later
text_6.tStart = t
text_6.frameNStart = frameN  # exact frame index
text_6.setAutoDraw(True)

# check for quit (typically the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in numgenComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
win.flip()

# -------Ending Routine "numgen"-------
for thisComponent in numgenComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)

# the Routine "numgen" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()

``````

When I run it, it works perfectly. However, as you pointed out it’s coded in python. I’m not sure what my next step should be.

Ok, so now it is working ok in Python, we can get it working online. Sync it with your online repo, and try and run the experiment.

BTW, just wondering why you are adding an empty string on the end of the number in the JavaScript code?

Oops! Good catch. That was one of my unsuccessful attempts to try to fix the issue and I forgot to delete it.

It worked! Thank you so much!!

I did get this error while downloading the data:

Is that a cause for concern?

Thanks for showing the error, I have not seen this one before. Did you data synchronize to your computer, and is viewable?

Yes, I was able to open the csv file and my data was there.

Great, glad things are working.

Would you mind trying again? If it happens again please repost along with your task link and I will create an issue on GitHub to see if we can get an understanding of what happened.

I tried it again and didn’t get an error.

Ok, if it reappears please let us know

Would anyone know how to generate a random string of letters and numbers?
For example, instead of having a number like 0120326 it would be like 0r4tu32.

Thank you!