Psychopy: Call a conditions file from the outer loop's conditions file - nested-loops

I am a bit new to PsychoPy and Python coding, so please excuse my question if it is basic. In my task, I have a number of files that dictate the position of stimuli. My outer loop has a variable, ExcelList, which has the previously mentioned file names listed under it. The inner loop, which dictates each trial, attempts to call these files at random by entering $ExcelList into the space asking for a conditions file. As I understand it, the command for $ExcelList should access the conditions file in the outer loop and pull one of the files containing stimuli positions for that trial. However, I am instead presented with the following error:
File "/Users/bencline/Desktop/Psychexp/NegPriming2080_lastrun.py",
line 247, in module>
trialList=data.importConditions(ExcelList), File "/Applications/PsychoPy2.app/Contents/Resources/lib/python2.7/psychopy/data.py",
line 1366, in importConditions
raise ImportError('Conditions file not found: %s' %os.path.abspath(fileName)) ImportError: Conditions file not found:
/Users/bencline/Desktop/Psychexp/Trials_20_95.xlsx
It would appear that the inner loop is not finding the condition in the outer loop (or not reading the outer loop altogether). If I try instead writing $eval(ExcelList) I am presented with the following error:
File "/Users/bencline/Desktop/Psychexp/NegPriming2080_lastrun.py",
line 247, in
trialList=data.importConditions(eval(ExcelList)), File "", line 1, in NameError: name 'Trials_20_95' is not
defined
This seems more indicative of the underlying problem, but I'm still not sure how to proceed from here. Do you have any suggestions for why this is happening and how I could potentially fix it?
Thank you,
-Ben

Your strategy is right. It reads your ExcelList in the outer loop but fails to find the filenames in ExcelList on your filesystem. In particular, in your first error message, it fails to find /Users/bencline/Desktop/Psychexp/Trials_20_95.xlsx. So check whether it actually exists. I strongly suspect that it does not because of one or both of these:
It is in a different folder, e.g. a subfolder. The solution is to write out the path (relative or absolute) in the ExcelList file.
It is spelled differently, e.g. with a small T or capital postfix (XLSX), a spacebar or the like. The solution is of course to make the filenames in the ExcelList and the actual filenames match.

Related

Opening filehandles for use with TabularMSA in skbio

Hey there skbio team.
So I need to allow either DNA or RNA MSAs. When I do the following, if I leave out the alignment_fh.close() skbio reads the 'non header' line in the except block making me think I need to close the file first so it will start at the beginning, but if I add alignment_fh.close() I cannot get it to read the file. I've tried opening it via a variety of methods, but I believe TabularMSA.read() should allow files OR file handles. Thoughts? Thank you!
try:
aln = skbio.TabularMSA.read(alignment_fh, constructor=skbio.RNA)
except:
alignment_fh.close()
aln = skbio.TabularMSA.read(alignment_fh, constructor=skbio.DNA)
I've tried opening it via a variety of methods, but I believe TabularMSA.read() should allow files OR file handles.
You're correct: scikit-bio generally supports reading and writing files using open file handles or file paths.
The issue you're running into is that your first TabularMSA.read() call reads the entire contents of the open file handle, so that when the second TabularMSA.read() call is hit within the except block, the file pointer is already at the end of the open file handle -- this is why you're getting an error message hinting that the file is empty.
This behavior is intentional; when scikit-bio is given an open file handle, it will read from or write to the file but won't attempt to manage the handle's file pointer (that type of management is up to the caller of the code).
Now, when asking scikit-bio to read a file path (i.e. a string containing the path to a file on disk or accessible at some URI), scikit-bio will handle opening and closing the file handle for you, so that's often the easier way to go.
You can use file paths or file handles to accomplish your goal. In the following examples, suppose aln_filepath is a str pointing to your alignment file on disk (e.g. "/path/to/my/alignment.fasta").
With file paths: You can simply pass the file path to both TabularMSA.read() calls; no open() or close() calls are necessary on your part.
try:
aln = skbio.TabularMSA.read(aln_filepath, constructor=skbio.RNA)
except ValueError:
aln = skbio.TabularMSA.read(aln_filepath, constructor=skbio.DNA)
With file handles: You'll need to open a file handle and reset the file pointer within your except block before reading a second time.
with open(aln_filepath, 'r') as aln_filehandle:
try:
aln = skbio.TabularMSA.read(aln_filehandle, constructor=skbio.RNA)
except ValueError:
aln_filehandle.seek(0) # reset file pointer to beginning of file
aln = skbio.TabularMSA.read(aln_filehandle, constructor=skbio.DNA)
Note: In both examples, I've used except ValueError instead of a "catch-all" except statement. I recommend catching specific error types (e.g. ValueError) instead of any exception because the code could be failing in different ways than what you're expecting. For example, with a "catch-all" except statement, users won't be able to interrupt your program with Ctrl-C because KeyboardInterrupt will be caught and ignored.

How do I remove the 'Done' message after my program has executed?

I made a program that is similar to clearing RAM. However, it always leaves a "Done" message followed by a dotted line after being executed. In addition, if you scroll up, you can see that the program was executed. Is there a way to remove both of these things? If you can't hide the fact that a program was executed, could you suppress the 'Done' message?
I have tried adding ClearHome" and " as the last line of my program, and neither stops the Done message from displaying.
Bonus points if your solution can be contained within the original program.
In a separate program, type the following line of code:
AsmPrgmFDCB00AEC9
Then at the end of the original program, type the following line of code:
Asm(prgmPROGRAMNAME
It is recommended that you test this out first with all programs archived, just running the above line of code alone, in case it fails. Hex codes like that one have been known to fail, and sometimes clears the RAM.
You can also try these other hex codes, but always keep in mind the warning above. My RAM has been cleared by this before, so use caution:
http://tibasicdev.wikidot.com/hexcodes
This works on TI 83 and 84, may be different with other calculator types.
EDIT:
I found a way to do this without an external program, and is much simpler.
Just add the following line of code to the end of your program:
Output(1,1," //no space, just a quote
You may or may not have to add ClrHome before that line of code.
This should prevent the Done message from appearing at the end.
Hope this helps!
Put an empty string at the end of your program, so your last line looks like this:
""
Or this
"
The empty string is stored to ans and will be displayed as a blank line rather than the Done message.
There is also an assembly hexcode to do this without leaving the blank line at the top:
FDCB00AEC9
When run at the end of the program using one of the various methods of running assembly, it will leave you with a blank, fully operational homescreen.
Outputting an empty string will prevent the Done message and also preserve Ans, in case a calling program is expecting to use it.
Output(Y,X,"")
See http://tibasicdev.wikidot.com/output for more details on Output(.
In your situation, run Clear Entries (found under Mem), then scroll up so that the Done message is selected and press Clear to get rid of it.

Ruby - Files - gets method

I am following Wicked cool ruby scripts book.
here,
there are two files, file_output = file_list.txt and oldfile_output = file_list.old. These two files contain list of all files the program went through and going to go through.
Now, the file is renamed as old file if a 'file_list.txt' file exists .
then, I am not able to understand the code.
Apparently every line of the file is read and the line is stored in oldfile hash.
Can some one explain from 4 the line?
And also, why is gets used here? why cant a .each method be used to read through every line?
if File.exists?(file_output)
File.rename(file_output, oldfile_output)
File.open(oldfile_output, 'rb') do |infile|
while (temp = infile.gets)
line = /(.+)\s{5,5}(\w{32,32})/.match(temp)
puts "#{line[1]} ---> #{line[2]}"
oldfile_hash[line[1]] = line[2]
end
end
end
Judging from the redundant use of quantifiers ({5,5} and {32,32}) in the regex (which would be better written as {5}, {32}), it looks like the person who wrote that code is not a professional Ruby programmer. So you can assume that the choice taken in the code is not necessarily the best.
As you pointed out, the code could have used each instead of while with gets. The latter approach is sort of an old-school Ruby way of doing it. There is nothing wrong in using it. Until the end of file is reached, gets will return a string, and when it does reach the end of file, gets will return nil, so the while loop works as the same when you use each; in each iteration, it reads the next line.
It looks like each line is supposed to represent a key-value pair. The regex assumes that the key is not an empty string, and that the key and the value are separated by exactly five spaces, and the the value consists of exactly thirty-two letters. Each key-value pair is printed (perhaps for monitoring the progress), and is stored in oldfile_hash, which is most likely a hash.
So the point of using .gets is to tell when the file is finished being read. Essentially, it's tied to the
while (condition)
....
end
block. So gets serves as a little method that will keep giving ruby the next line of the file until there is no more lines to give.

confirm conditional statement applies to >0 observations in Stata

This is something that has puzzled me for some time and I have yet to find an answer.
I am in a situation where I am applying a standardized data cleaning process to (supposedly) similarly structured files, one file for each year. I have a statement such as the following:
replace field="Plant" if field=="Plant & Machinery"
Which was a result of the original code-writing based on the data file for year 1. Then I generalize the code to loop through the years of data. The problem becomes if in year 3, the analogous value in that variable was coded as "Plant and MachInery ", such that the code line above would not make the intended change due to the difference in the text string, but not result in an error alerting the change was not made.
What I am after is some sort of confirmation that >0 observations actually satisfied the condition each instance the code is executed in the loop, otherwise return an error. Any combination of trimming, removing spaces, and standardizing the text case are not workaround options. At the same time, I don't want to add a count if and then assert statement before every conditional replace as that becomes quite bulky.
Aside from going to the raw files to ensure the variable values are standardized, is there any way to do this validation "on the fly" as I have tried to describe? Maybe just write a custom program that combines a count if, assert and replace?
The idea has surfaced occasionally that replace should return the number of observations changed, but there are good reasons why not, notably that it is not a r-class or e-class command any way and it's quite important not to change the way it works because that could break innumerable programs and do-files.
So, I think the essence of any answer is that you have to set up your own monitoring process counting how many values have (or would be) changed.
One pattern is -- when working on a current variable:
gen was = .
foreach ... {
...
replace was = current
replace current = ...
qui count if was != current
<use the result>
}

How can I check if a string is a valid file name for windows using R?

I've been writing a program in R that outputs randomization schemes for a research project I'm working on with a few other people this summer, and I'm done with the majority of it, except for one feature. Part of what I've been doing is making it really user friendly, so that the program will prompt the user for certain pieces of information, and therefore know what needs to be randomized. I have it set up to check every piece of user input to make sure it's a valid input, and give an error message/prompt the user again if it's not. The only thing I can't quite figure out is how to get it to check whether or not the file name for the .csv output is valid. Does anyone know if there is a way to get R to check if a string makes a valid windows file name? Thanks!
These characters aren't allowed: /\:*?"<>|. So warn the user if it contains any of those.
Some other names are also disallowed: COM, AUX, NUL, COM1 to COM9, LPT1 to LPT9.
You probably want to check that the filename is valid using a regular expression. See this other answer for a Java example that should take minimal tweaking to work in R.
https://stackoverflow.com/a/6804755/134830
You may also want to check the filename length (260 characters for maximum portability, though longer names are allowed on some systems).
Finally, in R, if you try to create a file in a directory that doesn't exist, it will still fail, so you need to split the name up into the filename and directory name (using basename and dirname) and try to create the directory first, if necessary.
That said, David Heffernan gives good advice in his comment to let Windows do the wok in deciding whether or not it can create the file: you don't want to erroneously tell the user that a filename is invalid.
You want something a little like this:
nice_file_create <- function(filename)
{
directory_name <- dirname(filename)
if(!file.exists(directory_name))
{
ok <- dir.create(directory_name)
if(!ok)
{
warning("The directory of that path could not be created.")
return(invisible())
}
}
tryCatch(
file.create(filename),
error = function(e)
{
warning("The file could not be created.")
}
)
}
But test it thoroughly first! There are all sorts of edge cases where things can fall over: try UNC network path names, "~", and paths with "." and ".." in them.
I'd suggest that the easiest way to make sure a filename is valid is to use fs::path_sanitize().
It removes control characters, reserved characters, and Windows-reserved filenames, truncating the string at 255 bytes in length.

Resources