I once did a blog on combining graphis with external programs and received a terrific comment from a reader (-click here-) on implementing this entirely within R with ghostscript as seen below. I have been using this a bit lately and am wanting to share it with others. I'd like to modify it to make the function more intuitive and detecting the ghostscript type is one mod I'd like to do but can't. The unix vs. windows is easy via .Platform. The sticking point is the windows 32 vs. 64 that I struggle with.
How can I use R to detect which ghostscript version (gswin32c or gswin64c) is running? Merely looking at the computer's specifications isn't good enough because I run gswin32c on a Win 64 machine. The idea is to remove the os argument entirely or set it to NULL and have the function try to access this information.
mergePDF <- function(infiles, outfile, os = "UNIX") {
version <- switch(os,
UNIX = "gs",
Win32 = "gswin32c",
Win64 = "gswin64c")
pre = " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="
system(paste(paste(version, pre, outfile, sep = ""), infiles, collapse = " "))
}
pdf("file1.pdf", width = 10, height = 8)
plot(1:10, col="red", pch = 19)
dev.off()
pdf("file2.pdf", width = 16, height = 8)
plot(1:10)
dev.off()
mergePDF("file1.pdf file2.pdf", "mergefromR.pdf", "Win32")
Tyler, dude. Have I been demoted from being a Stack Ove-R-flow peer to a "reader" of your blog? Or is that a promotion ;)
This feels a little hackish to me, but should get the job done. Add this as the first few lines of the function and remove the os argument:
testme <- c(UNIX = "gs -version",
Win32 = "gswin32c -version",
Win64 = "gswin64c -version")
os <- names(which(sapply(testme, system) == 0))
I've used the -version switch so that R doesn't try to load Ghostscript unnecessarily.
On my Ubuntu system, when I run this, os returns, as expected, UNIX, and on my Windows system where I have the 32-bit version of Ghostscript installed, it returns Win32. Try it out on your 64-bit machine running the 32-bit GS and let me know how it works.
Update
After reading the help pages for system() and system2(), I learned about Sys.which(), which seems to be exactly what you're looking for. Here it is in action on my Ubuntu system:
Sys.which(c("gs", "gswin32c", "gswin64c"))
# gs gswin32c gswin64c
# "/usr/bin/gs" "" ""
names(which(Sys.which(c("gs", "gswin32c", "gswin64c")) != ""))
# [1] "gs"
Thus, OS specification can be skipped entirely in the mergePDF() function:
mergePDF <- function(infiles, outfile) {
gsversion <- names(which(Sys.which(c("gs", "gswin32c", "gswin64c")) != ""))
pre = " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="
system(paste(paste(gsversion, pre, outfile, sep = ""), infiles, collapse = " "))
}
You may want to do some error checking. If the length of gsversion is > 1 or is 0, for instance, you may want to stop the function and prompt the user to either install Ghostscript or to verify their Ghostscript version.
Related
I'm following the wiki https://help.ubuntu.com/community/Xen#Manually_Create_a_PV_Guest_VM
(section "
Set Up Initial Guest Configuration
")
I downloaded the netboot initrd.gz from https://mirror.arizona.edu/ubuntu//ubuntu/dists/bionic/main/installer-amd64/current/images/netboot/xen/
but in the .cfg , what should I specify for the "disk = " line? ---- my host box is not using LVM, so I'll have to use "file-backed storage" for PV disk image. (https://wiki.xenproject.org/wiki/Storage_options , indeed this worked when I gave --dir= instead of --lvm= when running the xml-create command in https://wiki.xenproject.org/wiki/Xen_Project_Beginners_Guide )
here is my current config:
yy#yy-70A4000HUX:~/ub_xen$ cat ub_xen.cfg
name = "ubud1"
kernel = "/home/yy/ub_xen/vmlinuz"
ramdisk = "/home/yy/ub_xen/initrd.gz"
#bootloader = "/usr/lib/xen-4.4/bin/pygrub"
memory = 1024
vcpus = 1
# Custom option for Open vSwitch
vif = [ 'bridge=xenbr0' ]
disk = [ 'vdev=hda,target=/home/yy/ub_xen/images' ]
# You may also consider some other options
# [[http://xenbits.xen.org/docs/4.4-testing/man/xl.cfg.5.html]]
yy#yy-70A4000HUX:~/ub_xen$
I ran the command with sudo xl create -c ub_xen.cfg
this worked fine first, giving me the regular install process on console, pulling install files from remote archive, but when it comes to the step of disk paritioning, it's showing me a "SCSI" partitioning choice, with no volumes / partitions/disks to be chosen.
I guess this is because I'm not setting the right value for "disk = [ ]" option. what should I use here if I use file-backed storage for PV (just like VMware does)?
thanks a lot
Yang
found it, huge thanks to the author here: https://www.systutorials.com/create-and-manage-virtual-machines-on-xen/
I just bought a GPU to put in a computer where I'm hosting a jupyter notebook. I tunnel the output of the jupyter notebook from the tower to my laptop via ssh. I'm running some code and the jupyter notebook freezes at the same line every time. Not only does the jupyter notebook freeze, but everything on the tower. If I have any other ssh connections, they freeze. If I use the GUI on the tower directly it's frozen. Nothing is responsive until I hit the power button to reset the computer.
The odd thing is, that while nothing is responding, nothing is timing out either. the ssh sessions keep their connections. the jupyter notebook homepage claims it's still connected. It's very odd, and I'm not sure this is a problem with the code or the tower somehow, so I'm not sure if I should post this here or somewhere else. But here's the code
def show_img(x):
x = x.clone().detach().permute(1,2,0).numpy()
print(x.shape)
x = rio.convert_tensor_to_rgb(x)
print(x.shape)
plt.figure(figsize=(8, 8))
plt.axis('off')
_ = plt.imshow(x)
# define generator discriminator, dataloader, other stuff....
G.cuda()
D.cuda()
g_optim = optim.RMSprop(G.parameters(), lr=lr)
d_optim = optim.RMSprop(D.parameters(), lr=lr)
g_losses = []
d_losses = []
i_losses = []
for epoch in range(n_epochs):
dataloader = DataLoader(train_dataset, batch_size=batch_size,
shuffle=True, pin_memory=True,
num_workers=num_workers)
g_loss = 0.0 # g_loss is the generator's loss
d_loss = 0.0 # d_loss is the discriminator's loss
i_loss = 0.0 # i_loss is the generator's loss for not being invertable
i_weight = 10 # prioritize being invertible ten times more than minimizing g_loss
x,y,z = train_dataset[0]
print("image")
show_img(x)
print("target")
show_img(y)
print("generated")
x,y = x.cuda(), y.cuda()
g = G(x.unsqueeze(0),y.unsqueeze(0))
print(g.shape)
show_img(g.squeeze().cpu())
loop = tqdm(total=len(dataloader), position=0, file=sys.stdout)
print("just to be sure") #prints this
for minibatch, (image, batchImage, exp_batch) in enumerate(dataloader): #this is the line it freezes on?
print("image ", image.shape, " batchImage ", batchImage.shape, " experiment batch ", exp_batch) # doesn't print this. already frozen
EDIT: GUI and ssh are responsive, but unusually slow. I guess the main problem is that the code is still freezing on said line of code, and I don't know why.
I found The problem. The batch size was 32, which was much to large given the size of the images. I think it justed crashed after trying to load them all.
I have a file called goodfile. Lets say the contents are
badline
goodline
badline
goodline
badline
badline
On a windows machine I want to filter this file to get only the "goodline"s before reading it to save on memory costs. Thankfully, the rtools installation comes with grep that should allow me to do that. I should be able to do
if(!pkgbuild::has_rtools()){
stop('install rtools')
}
rtoolsPath = pkgbuild::rtools_path()
grep = file.path(rtoolsPath,'grep.exe')
command = paste(grep, "goodline goodfile")
system(command)
and get
goodline
goodline
However when I try to pipe the output to a file by doing
command = paste(grep, "goodline goodfile > betterfile")
system(command)
I get
goodfile:goodline
goodfile:goodline
/usr/bin/grep: >: No such file or directory
/usr/bin/grep: betterfile: No such file or directory
This error message and the "betterfile" is not generated.
If I take the same command and run it on my command line, it just works, if I do the same system call with regular grep on R in linux machine it just works, so I can't see what the problem is.
I was able to find an alternative way to get the file by doing
system2(grep,
args = c('goodline','goodfile'),stderr = 'betterfile',stdout = 'betterfile')
but still curious why the pipe doesn't work
I'm wanting to plot live data from the serial port. I figured R would be a good tool for the job. I'm stumbling on trying to read data from the serial port (COM4). I've verified the data is coming in through terra term (and close the session before trying R), but I can't seem to get anything in R.
I've checked a few places, including these threads:
How to invoke script that uses scan() on Windows?
How to include interactive input in script to be run from the command line
I've also found this old thread on the R forum:
https://stat.ethz.ch/pipermail/r-help/2005-September/078929.html
These have gotten me this far, but I can't seem to actually get any data into R from the serial port.
At this point I can stream in the data in excel using VBA, but I'd like to do it in R for some nicer live plotting and filtering of the data.
Edit: Thanks for the help so far. I just got it working while writing up this edit, so here's the code:
#
# Reset environment
#
rm(list = ls()) # Remove environemnent variables
graphics.off() # Close any open graphics
#
# Libraries
#
library(serial)
#
# Script
#
con <- serialConnection(name = "test_con",
port = "COM11",
mode = "115200,n,8,1",
buffering = "none",
newline = 1,
translation = "cr")
open(con)
stopTime <- Sys.time() + 2
foo <- ""
textSize <- 0
while(Sys.time() < stopTime)
{
newText <- read.serialConnection(con)
if(0 < nchar(newText))
{
foo <- paste(foo, newText)
}
}
cat("\r\n", foo, "\r\n")
close(con)
foo ends up being a long string with new lines the way I want them:
3181, -53120, -15296, 2,
3211, -53088, -15328, 2,
3241, -53248, -15456, 1,
3271, -53216, -15424, 2,
3301, -53184, -15488, 2,
3331, -53344, -15360, 1,
3361, -53440, -15264, 1,
Thanks again for all the help!
i am working with the serial-package (here) available on CRAN. This was developed to do exactly that what you need. Reading and sending data form and to RS232 etc. connections.
I do really recommend this, because "mode.exe" seems not to work for virtual COM-ports. See NPort-Server etc.
Teraterm and Windows use a different mechanism to configure serial devices.
Are your system connection settings ok compared to what is configured in teraterm?
Re-check the configuration parameter in teraterm and then use them to set your COM4: configuration in R.
system("mode COM4: BAUD=115200 PARITY=N DATA=8 STOP=1")
see mode /? on your command prompt for further parameters
it might also be helpful to read data character by character using readChar()
It sometimes happens that teraterm doesn't close RS232 connections properly.
I realize that this is from five years ago but I found that in your code you do not have a handshake called.
I am working with something similar where I use PUTTY instead of teraterm, where I could see all of the following inputs for my COM device.
my command is as follow:
con <-serialConnection(name="Prolific USB-to-Serial Comm Port(Com3)",
port="COM3",
mode="9600,n,8,1",
newline=0,
translation="lf",
handshake = 'xonxoff'
)
I'd like to create a soft symbolic link to a file from within R on Windows (with Mklink). It fails because I cannot tell R to "run it as administrator". Is there any way I can do this?
I did manage to create hard symbolic file links, however:
path_src <- file.path(tempdir(), "test.txt")
write("Hello World!", file = path_src)
path_tgt <- file.path(tempdir(), "test_symlink.txt")
shell(sprintf("mklink /H %s %s",
normalizePath(path_tgt, mustWork = FALSE),
normalizePath(path_src)
))
Note how the file at path_tgt reflects the changes made to path_src:
write("HELLO WORLD!", file = path_src, append = TRUE)
Yet, this fails:
path_tgt_2 <- file.path(tempdir(), "test_symlink_2.txt")
> shell(sprintf("mklink /D %s %s",
normalizePath(path_tgt_2, mustWork = FALSE),
normalizePath(path_src)
))
Ihre Berechtigungen reichen nicht aus, um diesen Vorgang auszufhren.
Warning messages:
1: running command 'C:\Windows\system32\cmd.exe /c mklink /D C:\Users\Thyson\AppData\Local\Temp\Rtmpum73ZU\test_symlink_2.txt C:\Users\Thyson\AppData\Local\Temp\Rtmpum73ZU\test.txt' had status 1
2: In shell(sprintf("mklink /D %s %s", normalizePath(path_tgt_2, mustWork = FALSE), :
'mklink /D C:\Users\Thyson\AppData\Local\Temp\Rtmpum73ZU\test_symlink_2.txt C:\Users\Thyson\AppData\Local\Temp\Rtmpum73ZU\test.txt' Ausführung mit Fehlerkode 1 fehlgeschlagen
Note
Due to a German version of Windows I can't seem to get the errors in English. The first line translates to somewhat along the lines of "You don't have enough authorization in order to carry out this process"
Run R as administrator. Then when you run "Mklink" from within R, you are the administrator.
Actually, you can also use the R function file.symlink to create symbolic links.
Since 2016 (Windows 10 Insiders build 14972), you can also make symbolic links without administrator rights if you enable the developer mode (in Settings>Update and Security>For developers).
This works in the Windows console with mklink, but it doesn't seem that R's file.symlink() works (as of R 4.0.3), possibly because of the dwFlags that needs to be set.
For calling it from R, I needed to add " when the path contains spaces:
shell(sprintf('mklink "%s" "%s"',
normalizePath(link, mustWork = FALSE),
normalizePath(original)
))
For directories, you can also consider the use of Sys.junction() which is somewhat equivalent to symlinks.