I am using Rstudio and not sure how options "run" and "source" are different.
I tried googling these terms but 'source' is a very common word and wasn't able to get good search results :(
Run and source have subtly different meanings. According to the RStudio documentation,
The difference between running lines from a selection and invoking
Source is that when running a selection all lines are inserted
directly into the console whereas for Source the file is saved to a
temporary location and then sourced into the console from there
(thereby creating less clutter in the console).
Something to be aware of, is that sourcing functions in files makes them available for scripts to use. What does this mean? Imagine you are trying to troubleshoot a function that is called from a script. You need to source the file containing the function, to make the changes available in the function be used when that line in the script is then run.
A further aspect of this is that you can source functions from your scripts. I use this code to automatically source all of the functions in a directory, which makes it easy to run a long script with a single run:
# source our functions
code.dir <- "c:\temp"
code.files = dir(code.dir, pattern = "[.r]")
for (file in code.files){
source(file = file.path(code.dir,file))
}
Sometimes, for reasons I don't understand, you will get different behavior depending on whether you select all the lines of code and press the run the button or go to code menu and chose 'source.' For example, in one specific case, writing a gplot to a png file worked when I selected all my lines of code but the write failed to when I went to the code menu and chose 'source.' However, if I choose 'Source with Echo,' I'm able to print to a png file again.
I'm simply reporting a difference here that I've seen between the selecting and running all your lines and code and going to code menu and choosing 'source,' at least in the case when trying to print a gplot to a png file.
An important implication of #AndyClifton's answer is:
Rstudio breakpoints work in source (Ctrl-Shift-S) but not in run (Ctrl-Enter)
Presumably the reason is that with run, the code is getting passed straight into the console with no support for a partial submission.
You can still use browser() though with run though.
print() to console is supported in debugSource (Ctrl-Shift-S) as well as run.
The "run" button simply executes the selected line or lines. The "source" button will execute the entire active document. But why not just try them and see the difference?
I also just discovered that the encoding used to read the function sourced can also be different if you source the file or if you add the function of the source file to your environment with Ctrl+Enter!
In my case there was a regex with a special character (ยต) in my function. When I imported the function directly (Ctrl+Enter) everything would work, while I had an error when sourcing the file containing this function.
To solve this issue I specified the encoding of the sourced file in the source function (source("utils.R", encoding = "UTF-8")).
Run will run each line of code, which means that it hits enter at the beginning of each line, which prints the output to the console. Source won't print anything unless you source with echo, which means that ggplot won't print to pngs, as another posted mentioned.
A big practical difference between run and source is that if you get an unaccounted for error in source it'll break you out of the code without finishing, whereas run will just pass the next line to the console and keep going. This has been the main practical difference I've seen working on cleaning up other people's scripts.
When using RSTudio u can press the run button in the script section - it will run the selected line.
Next to it you have the re - run button, to run the line again. and the source button next to it will run entire chuncks of code.
I found a video about this topic:
http://www.youtube.com/watch?v=5YmcEYTSN7k
Source/Source with echo is used to execute the whole file whereas Run as far as my personal experience goes executes the line in which your cursor is present.
Thus, Run helps you to debug your code. Watch out for the environment. It will display what's happening in the stack.
To those saying plots do not show. They won't show in Plots console. But you can definitely save the plot to disc using Source in RStudio. Using this snippet:
png(filename)
print(p)
dev.off()
I can confirm plots are written to disc. Furthermore print statements are also outputted to the console
Related
I have code where I'm writing to a file, and the next time I run the code after the code successfully runs, it gives me the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:'minicube_HE022222.fits'
So every single time I have to change the name of the fits file and then there are no errors. It's just really frustrating having to change the filename everytime I run the code. Here is my code snippet:
new_hdu = fits.HDUList([fits.PrimaryHDU(mini_data), fits.ImageHDU(mini_error)])
new_hdu[0].header = qso_header
new_hdu.writeto('minicube_HE022222.fits',overwrite=True)
new_hdu.close()
I get the error at:
new_hdu.writeto('minicube_HE022222.fits',overwrite=True)
I close the file after writing to it but that doesn't help either.
Any suggestions are appreciated.
Update:
Here is another portion of a code where this error occurs:
hdus=[]
hdus.append(fits.PrimaryHDU())
hdus.append(fits.ImageHDU(par[0,:,:],name='amp_Hb'))
hdus.append(fits.ImageHDU(par[1,:,:],name='amp_OIII5007'))
hdus.append(fits.ImageHDU(par[2,:,:],name='amp_OIII5007_br'))
hdus.append(fits.ImageHDU(par[3,:,:],name='amp_Hb_br'))
hdus.append(fits.ImageHDU(par[4,:,:],name='amp_Hb1'))
hdus.append(fits.ImageHDU(par[5,:,:],name='amp_Hb2'))
hdus.append(fits.ImageHDU(par[6,:,:],name='amp_Fe5018_1'))
hdus.append(fits.ImageHDU(par[7,:,:],name='amp_Fe5018_2'))
hdus.append(fits.ImageHDU(par[8,:,:],name='m'))
hdus.append(fits.ImageHDU(par[9,:,:],name='c'))
hdu = fits.HDUList(hdus)
hdu.writeto('subcube_par_HE12_lsq.fits',overwrite=True)
It's only at the 'xxx.writeto' where the error occurs. If there's another way I can write to a file or update the existing file with the new data, please let me know. Thanks
As this comment notes, the way file I/O works on Windows is such that you can't overwrite a file if you have that file already open in another process. Are you writing this file and opening it in another program? If you have that file open in any other program then you can't overwrite it.
Do you need to be able to make in-place updates the file while it is open in another program? If so that may still be possible, but you can't use HDUList.writeto() as that effectively deletes the existing file and replaces it with a new one (rather than updating the existing file in-place).
Also, how are you running this code? Is it in a script? You mentioned having to change the filename every time but you could design things such that you wouldn't have to. I noticed that you have the filename hard-coded in your code, and that can and should be fixed if you want to write a more versatile script. For example, you could accept the filename as command-line argument. You could also have the script append a number to the filename or something if the file already exists.
All that said, you should figure out why you have the same file open in multiple programs.
One small usage aside:
The new_hdu.close() in your example doesn't actually do anything. The HDUList.close() method only makes sense when you open an existing FITS file from disk. Here you're creating an HDUList (the data structure representing a FITS file) in memory, and calling the high-level HDUList.writeto() which opens a file, writes the in-memory data to that file, and the closes the file. So the .close() in this case is a no-op. I'm guessing maybe you added it to try to fix your problem, but it's actually not relevant.
I want to step through an R script. I saw the "debug" command while searching for how to do this but that seems to only apply to functions. This script doesn't have any functions.
The "browser" command looked promising so I put "browser()" as the first line of my script but it didn't seem to do anything when I ran it.
How do I get the script to pause on the first line so I can step through it?
I was racking my brain trying to figure this out (stepping through a script without a specific function to call) in RStudio's IDE Version 0.98.1102.
Solution for a new script in RStudio:
Create a new R script (ctrl+shift+n)
Enter code in the file
Set a break point by
a) clicking left of the code line number where you want to set a break point (red dot) or
b) adding browser() to the code line where you want to set a break point
Save the file
Enter debugging mode and source the file by
a) checking the Source on Save box (above the Source window) and then saving the file,
b) clicking the Source button at the top-right of the Source window,
c) entering debugSource("<yourfilename>") + enter in the Console, or
d) entering ctrl+shift+s
Go through the debugging process
For more steps on debugging in RStudio, see this help file
(dated April 23, 2015 12:59).
I'm partial to RStudio, so I recommend the following:
Download RStudio
Open your R Script
put your cursor on the first line
click ctrl + enter (PC/Linux) or command + return (Mac)
repeat!
A nice feature of RStudio is that RStudio server can run great on a headless server. You then connect to the server via http in a web browser on your local machine. I use this configuration when running R on EC2 instances. RStudio maintains state so if I lose internet access on my train ride, when I get signal back RStudio picks up exactly where I left off and my remote machine has no idea that I disconnected and reconnected. Note that RStudio server is currently only supported on FC/CentOS and Debian/Ubuntu. Although it may compile under other variants of *nix.
One popular way is to do this from your 'IDE' or editor -- Emacs / ESS do it very well, others do it too.
The basic idea is that you send either the line under the cursors, or function, or block, ... to the associated R process. Several other editors support this, including RStudio. My preference is still with ESS, but I am sure you can find something suitable.
Lastly, browser() et al can do that from within the R process but it is a little less pointy-clickety. Read the documentation, or books like Chambers "Software for Data Analysis" (Springer, 2008).
For an R only solution, which evaluates complete expressions rather than individual lines, try this:
sourcep <- function(file){
coms <- parse(file)
for (i in seq_along(coms)){
print(coms[[i]])
eval(coms[[i]],envir=.GlobalEnv)
mess <- paste("Expression",i,"of",length(coms),"parsed. Press <return> to continue.")
cat(mess)
readLines(n=1)
}
}
You call this as you would call source (though this is much more basic and doesn't include any of its options). Basically, it uses parse to create a list of the parsed, but unevaluated expressions from your source file, then iterates through this list to print the expression, evaluate it in the global environment and then put a message to indicate the progess. The final line is the one that creates the pausing: a call to read a single line from stdin().
You mention in a comment that you run your code with Rscript, but to debug you need to run it interactively. In other words, to get browser to "work", start up a regular R console and source your script. Since the first line of the script is browser(), you'll immediately get back to the prompt, at which you can use "n" to single step through the code. But, since it's a full-blown R prompt, you can also check or change any variable value just by typing its name or assigning to it. (Or indeed, invoke arbitrary R functions.)
As suggested in another answer, inserting browser() at the beginning of your script, getting an interactive session by running R rather than Rscript, and then using source('myscript.Rscript') from R will do the trick if your script does not require commadline arguments (e.g. like those processed by argparse).
If you do need to run with commandline args, you can simply invoke R with the --args options (e.g. R --no-restore --no-save --args <your commandline args here>) and the sourced script will see the arguments as if it had been invoked using Rscript. There are other solutions to the question of how to pass commandline args to source, but they don't target this specific use case where source will be called only once.
I've sort of got Fsi.exe working as expected on a Mac OS X (Snow Leopard) with Mono. I just noticed a little bit of odd behavior with cut and paste and I was wondering if anyone had seen this.
I've defined the following alias for fsi:
alias fsi='ledit mono ~/FSharp-1.9.7.8_2/bin/fsi.exe --gui-'
ledit is an Ocaml utility that seems to make the keyboard input work correctly--without it, fsi just never seems to read the input. To see what I mean, try Fsi.exe without ledit and enter
let square x = x * x;;
without ledit, it just never seems to parse the input. I mean it never comes back to the ">" prompt after you enter the string. With ledit, the ">" prompt comes back immediately.
Of course the --gui- keeps fsi from displaying all the messages about the lack of System.Drawing etc.
So this all seems to work. The oddity is when I copy and paste code into the FSI, certain characters seem to repeat over and over again. It seems to be conditioned by the size of the buffer I'm pasting in. When I paste small snippets there seems to be no problem. But if I paste in larger chunks, there's this oddity.
If I do the following:
open System.IO;;
then paste this code snippet in FSI:
let buildFileList basepath filespec =
seq {
yield! Directory.GetFiles(basepath, filespec, System.IO.SearchOption.AllDirectories)
}
That works fine. But if I copy and paste in a bigger chunk of code ending with that, it repeats the portion up to the yield! over and over again. It seems to be somehow related to fsi attempting to parse the code as it's being pasted in because the same code pasted in will cause parsing errors (like FS0010) when it's pasted at the end of a long chunk but won't cause an error when it's isolated.
If I #load the entire file, it parses correctly as well so I think my code is ok.
This oddity in copy/paste seems to happen both with and without ledit on the command line. I don't mind researching this issue myself but I'm kind of stumped about where I should proceed with this. I'm copying from GVim if that makes a difference but anyone have any idea where I might proceed in trying to isolate the cause of this odd behavior? I suppose I could take the extra step of copying into TextEdit first and then trying to copy into fsi but any ideas beyond that?
To bottom line this: has anyone else seen this odd behavior? If not, any suggestions about how I might proceed in trying to isolate the cause of this odd behavior?
When I encountered this behavior on my Mac, I went a different route. Instead of using ledit, I employed fsi's --readline option, seen below (where ${FSHARP} is my install path).
mono ${FSHARP}/fsi.exe --readline+ --gui-
You may also want to check your terminal settings. My terminal (for example) is declared as xterm-color, and I have unchecked delete sends CTRL-H. I think those are the only relevant settings, but don't hold me to it.
I want to understand if code snippets are what I am looking for here.
I wind up writing the same line of code over and over during a refactoring.
Is there anyway I can create a shortcut that will spit out a line of code that I need?
Another easier option is to drag the code blocks that you re-use frequently onto the general tab of your toolbox area. You could even organize them with their own tab name and all.
alt text http://blogs.telerik.com/Libraries/MetaBlog/WindowsLiveWriter-VisualStudioTooltipsunpluggedDragandDro_EF10-generalTabDragged.sflb
Are you repeating the same line of code over and over on many different days?
Or are you encountering a situation where you have the same line to write many times as a part of a single task, but today's line of code will be different to tomorrows?
If you have the same line/block of code that you use often, a snippet is a good way to capture that in a reusable form (better, IMHO, than copy/paste because you can parameterise them).
However, if you're just looking for a quick way to repeat the same line that's come up now, check out Visual Studio's ability to record keystrokes.
Try this:
Put your cursor on a blank line inside a C# method.
Select Tools|Macros|Record Temporary Macro (often this is Control-Shift-R)
Type "example();" and press return
Select Tools|Macros|Stop Recording
You've just created a temporary macro that you can play back at any time - usually the keystroke for this is Control-Shift-P.
The key to this technique is that the macro records everything you do - with some practise, you can record edits to a line of code and repeat those edits on other lines.
I've used this in the past to create repetative code blocks - like assigning sets of properties from one object to another.
Depending on the code snippet, it would almost always be arguable that this line of code belongs in a util method, rather than copypasta.. But otherwise, yeah - a snippet is probably the best place.
Code Snippets sound like the right approach, although you could investigate Macros inside Visual Studio, which can be very powerful.
One advantage of a code snippet over adding it to the toolbox is that you can define the parts of the code that you want to change. I wrote a code snippet that generated something like the following code:
public class *className*Collection : List<*className*>
Where I only typed className once and it was automatically filled into the other parts.
Background
Lately I've become a fanatic that everything I type while working on a computer should be compatible with "DRY". If there's anything I have to type more than once in any context, I want some kind of user-aware auto-complete option to do some of the work for me -- always -- no exceptions.
Having to work under Windows, I've looked at GUI solutions to make this insane goal a reality.
The (almost) optimal solution
If you have a moment, open up Firefox 3.0 and type a few keystrokes into the address bar. You will notice that it performs a kind of Incremental Autocomplete based on space-separated sub-strings of whatever you type. Another place in Firefox that does something similar is the about:config URL.
This is sub-optimal, because I don't want this in Firefox only. I want to use this everywhere.
The Question
Does anyone out there know of a widget or app that does nothing but insanely good incremental auto-complete that can be used as a general purpose "run everywhere" tool? Something that allows the user to: 1) maintain one or more "completion candidate files"; 2) pick one of those files as the source for Firefox 3.0 style completion; 3) return the result (or blank if the user canceled), and do those three things only?
Details
Here's how it should work:
STEP1: user saves or more csv file(s) (or other easy-edit format) somewhere in his hard-drive
STEP2: user creates a Windows Script Host script or a batch file (or whatever) instantiates the FilterAsYouType GUI
STEP3: user runs the script file, and the script file instantiates the GUI, telling it which CSV file to use as the source of all potential completions
STEP4: the user either chooses one of the completions, supplies his own text that is not in the list, or cancels out without supplying anything
STEP5: when the user is done the script saves the result to a variable and does something with it
Here is some pseudo-code for the script:
include "GenericTypeaheadWidget";
var gengui = new GenericTypaheadWidget('c:\docs\favorite_foods.csv');
var fave_food = gengui.get_user_input();
if(fave_food != ''){
alert('you chose '+fave_food+'!');
}
The rationale
The goal is to just have a way to always be able to do auto-completions from a list of arbitrary items, even if the list is a couple thousand items, and not have to rely on it being built into some IDE or standalone application that only accepts certain kinds of input or has an overly-complicated API relative to the simplicity of this task.
CSV (or text or sqlite database) would provide a way for me to self-generate "candidate lists" or "history logs" and then just use those logs as the source of the possible completions.
The disclaimer
I've tried several GUI "launcher" programs, command-line engines like power-shell and scripting shells, the regular plain old command-line history with varying degrees of satisfaction. The problem with these is they all do extra superfluous stuff like searching directories or built-in commands. I just want nothing but whatever is in the CSV file I happen to be pointing at.
I'm wondering if there is any simple tool that does nothing but what I'm describing above.
UPDATE: It looks like this question is very closely related to Graphical Command Shell, which captures the essential idea presented here.
You should really try Launchy - it's exactly what you're looking for, a "run anything" with intelligent autocompletion. It completely changes the way you interact with a Windows PC.
And it has open source-code, so you can borrow its autocompletion code if you want to roll your own interface.