why hvplot does not run successfully - bokeh

loan_amnt_box = data.hvplot.box(
y='loan_amnt', subplots=True, by='loan_status', width=300, height=350,
title="Loan Status by Loan Amount ", xlabel='Loan Status', ylabel='Loan Amount'
)
installment_box = data.hvplot.box(
y='installment', subplots=True, by='loan_status', width=300, height=350,
title="Loan Status by Installment", xlabel='Loan Status', ylabel='Installment'
)
loan_amnt_box + installment_box
I run the above code and got the following error messages. Couldn't figure out what went wrong. Actually, I had no clue at all. Can anyone please take a look at this.

This is a Bug in Holoview, which should be solved by this change in the lastes version. The line of the error now looks like this:
#L276 legend_prop = 'legend_field' if bokeh_version >= LooseVersion('1.3.5') else 'legend'
Try to update holoviews using pip install holoviews -U. This should solve the problem. Afterwards run your example again.
The latest version of holoviews is 1.15.0.

Related

How to use rules_webtesting?

I want to use https://github.com/bazelbuild/rules_webtesting. I am using Bazel 5.2.0.
The whole project can be found here.
My WORKSPACE.bazel file looks like this:
load("#bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_webtesting",
sha256 = "3ef3bb22852546693c94e9b0b02c2570e74abab6f800fd58e0cbe79492e49c1b",
urls = [
"https://github.com/bazelbuild/rules_webtesting/archive/581b1557e382f93419da6a03b91a45c2ac9a9ec8/rules_webtesting.tar.gz",
],
)
load("#io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories")
web_test_repositories()
My BUILD.bazel file looks like this:
load("#io_bazel_rules_webtesting//web:py.bzl", "py_web_test_suite")
py_web_test_suite(
name = "browser_test",
srcs = ["browser_test.py"],
browsers = [
"#io_bazel_rules_webtesting//browsers:chromium-local",
],
local = True,
deps = ["#io_bazel_rules_webtesting//testing/web"],
)
browser_test.py looks like this:
import unittest
from testing.web import webtest
class BrowserTest(unittest.TestCase):
def setUp(self):
self.driver = webtest.new_webdriver_session()
def tearDown(self):
try:
self.driver.quit()
finally:
self.driver = None
# Your tests here
if __name__ == "__main__":
unittest.main()
When I try to do a bazel build //... I get (under Ubuntu 20.04 and macOS):
INFO: Invocation ID: 74c03efd-9caa-4174-9fda-42f7ff37e38b
ERROR: error loading package '': Every .bzl file must have a corresponding package, but '#io_bazel_rules_webtesting//web:repositories.bzl' does not have one. Please create a BUILD file in the same or any parent directory. Note that this BUILD file does not need to do anything except exist.
INFO: Elapsed time: 0.038s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)
The error message does not make sense to me, since there is a BUILD file in
https://github.com/bazelbuild/rules_webtesting/blob/581b1557e382f93419da6a03b91a45c2ac9a9ec8/BUILD.bazel
and https://github.com/bazelbuild/rules_webtesting/blob/581b1557e382f93419da6a03b91a45c2ac9a9ec8/web/BUILD.bazel.
I also tried a different version of Bazel - but with the same result.
Any ideas on how to get this working?
You need to add a strip_prefix = "rules_webtesting-581b1557e382f93419da6a03b91a45c2ac9a9ec8" in your http_archive call.
For debugging, you can look in the folder where Bazel extracts it: bazel-out/../../../external/io_bazel_rules_webtesting. #io_bazel_rules_webtesting//web translates to bazel-out/../../../external/io_bazel_rules_webtesting/web, so if that folder doesn't exist things won't work.

Dagster: Multiple and Conditional Outputs (Type check failed for step output xxx PySparkDataFrame)

I'm executing the Dagster tutorial, and I got stuck at the Multiple and Conditional Outputs step.
In the solid definitions, it asks to declare (among other things):
output_defs=[
OutputDefinition(
name="hot_cereals", dagster_type=DataFrame, is_required=False
),
OutputDefinition(
name="cold_cereals", dagster_type=DataFrame, is_required=False
),
],
But there's no information where the DataFrame cames from.
Firstly I have tried with pandas.DataFrame but I faced the error: {dagster_type} is not a valid dagster type. It happens when I try to submit it via $ dagit -f multiple_outputs.py.
Then I installed the dagster_pyspark and gave a try with the dagster_pyspark.DataFrame. This time I managed to summit the DAG to the UI. However, when I run it from the UI, I got the following error:
dagster.core.errors.DagsterTypeCheckDidNotPass: Type check failed for step output hot_cereals of type PySparkDataFrame.
File "/Users/bambrozio/.local/share/virtualenvs/dagster-tutorial/lib/python3.7/site-packages/dagster/core/execution/plan/execute_plan.py", line 210, in _dagster_event_sequence_for_step
for step_event in check.generator(step_events):
File "/Users/bambrozio/.local/share/virtualenvs/dagster-tutorial/lib/python3.7/site-packages/dagster/core/execution/plan/execute_step.py", line 273, in core_dagster_event_sequence_for_step
for evt in _create_step_events_for_output(step_context, user_event):
File "/Users/bambrozio/.local/share/virtualenvs/dagster-tutorial/lib/python3.7/site-packages/dagster/core/execution/plan/execute_step.py", line 298, in _create_step_events_for_output
for output_event in _type_checked_step_output_event_sequence(step_context, output):
File "/Users/bambrozio/.local/share/virtualenvs/dagster-tutorial/lib/python3.7/site-packages/dagster/core/execution/plan/execute_step.py", line 221, in _type_checked_step_output_event_sequence
dagster_type=step_output.dagster_type,
Does anyone know how to fix it? Thanks for the help!
As Arthur pointed out, the full tutorial code is available on Dagster's github.
However, you do not need dagster_pandas, rather, the key lines missing from your code are:
if typing.TYPE_CHECKING:
DataFrame = list
else:
DataFrame = PythonObjectDagsterType(list, name="DataFrame") # type: Any
The reason for the above structure is to achieve MyPy compliance, see the Types & Expectations section of the tutorial.
See also the documentation on Dagster types.
I was stuck here, too, but luckily I found the updated source code.
They have updated the docs so that the OutputDefinition is defined beforehand.
Update your code before sorting and pipeline like below:
import csv
import os
from dagster import (
Bool,
Field,
Output,
OutputDefinition,
execute_pipeline,
pipeline,
solid,
)
#solid
def read_csv(context, csv_path):
lines = []
csv_path = os.path.join(os.path.dirname(__file__), csv_path)
with open(csv_path, "r") as fd:
for row in csv.DictReader(fd):
row["calories"] = int(row["calories"])
lines.append(row)
context.log.info("Read {n_lines} lines".format(n_lines=len(lines)))
return lines
#solid(
config_schema={
"process_hot": Field(Bool, is_required=False, default_value=True),
"process_cold": Field(Bool, is_required=False, default_value=True),
},
output_defs=[
OutputDefinition(name="hot_cereals", is_required=False),
OutputDefinition(name="cold_cereals", is_required=False),
],
)
def split_cereals(context, cereals):
if context.solid_config["process_hot"]:
hot_cereals = [cereal for cereal in cereals if cereal["type"] == "H"]
yield Output(hot_cereals, "hot_cereals")
if context.solid_config["process_cold"]:
cold_cereals = [cereal for cereal in cereals if cereal["type"] == "C"]
yield Output(cold_cereals, "cold_cereals")
You can also find the whole lines of codes from here.
Try first to install the dagster pandas integration:
pip install dagster_pandas
Then do:
from dagster_pandas import DataFrame
You can find the code from the tutorial here.

Notification sounds on RStudio server [duplicate]

When I run R scripts I go do something else on a different desktop. If I don't check frequently, I never know when something is finished. Is there a way to invoke a beep (like a system beep) or get R to play a sound or notify growl via some code at the end of my script?
I have a package (beepr) with the sole purpose of making notification sounds in R which should work cross-platform. Run the following to install beepr and make a sound:
install.packages("beepr")
library(beepr)
beep()
More info at github: https://github.com/rasmusab/beepr
alarm()
The alarm function. It works by sending \a to the console
On MacOSX you can let the computer speak:
system("say Just finished!")
and you can also change the artificial voice that will speak:
system("say -v Kathy Just finished!")
You can pick any voice that is available on your computer. On Yosemite you can see which voices are installed in System Preferences -> Dictation & Speech -> Text to Speech.
You should have it tweet when it's done: http://cran.r-project.org/web/packages/twitteR/index.html
alarm doesn't work on my Windows machine so I created a function that does actually make noise.
beep <- function(n = 3){
for(i in seq(n)){
system("rundll32 user32.dll,MessageBeep -1")
Sys.sleep(.5)
}
}
This clearly could only work on Windows but I don't guarantee it will even run on an arbitrary Windows computer. I've only tested it on my machine but I figured I'd post it in case anybody has the same problem with alarm that I do.
cat('Hello world!\a')
How about something reasonably OS independent for OSes with GUIs and web-browsers? It even works on RStudio Server!
browseURL('https://www.youtube.com/watch?v=QH2-TGUlwu4')
Not only that, you can also also put some epic music from Youtube when the program is done looping :) (For Ubuntu/Debian:)
system("xdg-open 'http://www.youtube.com/watch?v=9jK-NcRmVcw'")
UPDATE:
With macOS 10.9 (Mavericks) and later, you can post notifications using plain AppleScript:
theTitle <- "A Title"
theMsg <- "A message here"
cmd <- paste("osascript -e ", "'display notification ", '"', theMsg, '"', ' with title ', '"', theTitle, '"', "'", sep='')
system(cmd)
This removes the need to install terminal-notifier, referenced below.
--
I've got terminal-notifier installed on my Mac to get desktop notifications from the command line. You can then wrap up a call to the system() command like this (change the path, obviously):
notify <- function(msgString='Message from R', titleString='Message from R', speakIt=FALSE) {
cmd <- paste('~/terminal-notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier -message ', '"', msgString, '" -title "', titleString, '"', sep='')
system(cmd)
if (speakIt) {
system(paste('say', msgString))
}
}
You can call the function like this
notify("R is done", "Message from R", speakIt=TRUE)
to get a message like this:
Update: Included #VLC's say command.
Please use shell.exec("url") to open some YouTube clip on Windows
Or if you're using GNU/Linux distro and have pcspkr module blacklisted (PC speaker was always annoying me), try combining system with some auditive/visual notification, e.g.
system("aplay -t wav /usr/share/sounds/phone.wav") # for auditive bell (an I mean it literary)
system("zenity --title=\"R script info\" --text=\"Script has finished with zero exit status\" --info") # for GTK dialog
You can check zenity manual if you prefer alert in, say, notification area... But, with system function, you can do pretty much anything: send an email, run some other script, reboot the machine, sudo rm -rf *.*, etc. anything... and I mean it.
But this stands only IF you're running GNU/Linux (or UNIX) distribution, otherwise, stick to Windows specific commands, though in that case, I can't give you much info...
Inspired by beepr, this is the function I'm currently using for these kind of problems :D
work_complete <- function() {
cat("Work complete. Press esc to sound the fanfare!!!\n")
on.exit(beepr::beep(3))
while (TRUE) {
beepr::beep(4)
Sys.sleep(1)
}
}
How about playing some music?
shell.exec("foo/Born.to.be.wild.mp3")
take a look at this package: RPushBullet
An R interface to the Pushbullet messaging service which provides fast
and efficient notifications (and file transfer) between computers,
phones and tablets
RPushbullet is completely free and multi platform. As for your question, you can use this library to send a Push to your browser, but obviously it becomes amazing when you need something than can notify you while you are away.
Moreover, the creator of the R package is the same of the well known Rcpp, Dirk Eddelbuettel. I'd say it's worth a shot!
Do this:
song <- function() {
for(i in 1:2) {
for(i in 1:4) {
for(i in 1:4) {
beep(7)
Sys.sleep(0.25)
beep()
Sys.sleep(0.22)
}
beep(2)
}
beep(11)
}
beep(4)
}
song()
You can jam out to it.
How about using Windows SpeechSynthesizer?
message <- "job done!"
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
paste0("$speak.Speak('", message, "');\"")
))
This may by nicely used in iterating operations and read something like "First job done", "Second job done" etc.:
say_something <- function(message) {
message <- paste0("$speak.Speak('", message, "');\"")
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
message
))
}
operations <- c("1st.", "2nd.", "3rd.")
lapply(operations, function(x) say_something(message=paste(x, "job done")))
*Note, that this uses system defaul language settings. The example is based on english lector, it can be changed using SelectVoice method. To check available lectors use:
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
"$speak.GetInstalledVoices().VoiceInfo")
)
That gives:
Gender : Female
Age : Adult
Name : Microsoft Paulina Desktop
Culture : pl-PL
Id : TTS_MS_PL-PL_PAULINA_11.0
Description : Microsoft Paulina Desktop - Polish
SupportedAudioFormats : {}
AdditionalInfo : {[Age, Adult], [Gender, Female], [Language, 415], [Name, Microsoft Paulina Desktop]...}
Gender : Male
Age : Adult
Name : Microsoft David Desktop
Culture : en-US
Id : TTS_MS_EN-US_DAVID_11.0
Description : Microsoft David Desktop - English (United States)
SupportedAudioFormats : {}
AdditionalInfo : {[Age, Adult], [Gender, Male], [Language, 409], [Name, Microsoft David Desktop]...}
Finally a function to select the lector by his "name" like "David", "Paulina" or "Hazel":
say_something <- function(message , voice) {
voice <- paste0("\"$speak.SelectVoice('Microsoft ", voice, " Desktop');" )
message <- paste0("$speak.Speak('", message, "');\"")
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
voice,
message
))
}
operations <- c("1st.", "2nd.", "3rd.")
lapply(operations, function(x) say_something(message=paste(x, "job done"), voice="David"))
Dason's answer is great, obviously, because it will work on basically any Windows machine without requiring anything except R itself.
But one thing I have been wondering is how to make these functions actually beep after a code is run.
If you do something like this:
beepR <- function(x, n = 3){
for(i in seq(n)){
system("rundll32 user32.dll,MessageBeep -1")
Sys.sleep(.5)
}
return(x)
}
You can just pipe anything to it and it will return whatever you piped, so you can do like. See the example below.
fa <- psych::fa(x, 1) |> beepR()
I'm using here the native pipe |> that was introduced in R 4.1, but you can use the %>% pipe from the maggitr package if you like; they work the exact same way. Anyway, that will beep as soon as the analysis ends, and the variable fa will contain the results of the factor analysis.
Of course, here I used the beep function that Dason provided you, but you could just as easily add anything where I indicated below.
beepR <- function(x){
# your code here #
return(x)
}
If you wish to add that function every time RStudio opens, refer to RStudio's Managing R with .Rprofile, .Renviron, Rprofile.site, Renviron.site, rsession.conf, and repos.conf to learn how to use a .Rprofile file.
You can use notify-send command:
system("notify-send \"R script finished running\"")
Because of these many ideas, I have created a solution without Internet access, because I work with a VPN client with Windows. So it plays a typical Windows sound, which is usually on any Windows operating system.
#Function with loop, press Esc to stopp
alarm2 <- function(){
while(TRUE){
system("cmd.exe",input="C:/Windows/WinSxS/amd64_microsoft-windows-shell-sounds_31bf3856ad364e35_10.0.17134.1_none_fc93088a1eb3fd11/tada.wav")
Sys.sleep(1)
}
}
Function without loop
alarm3 <- function(){
system("cmd.exe",input="C:/Windows/WinSxS/amd64_microsoft-windows-shell-sounds_31bf3856ad364e35_10.0.17134.1_none_fc93088a1eb3fd11/tada.wav")
Sys.sleep(1)
}
The following code produces a beep and does not depend on a .mp3 or .wav file:
switch(Sys.info()[['sysname']],
Linux = {
system('play -n synth 0.1 tri 1000.0')}
)
Combining some ideas on the thread, I implement this:
options(error = function() {
if (interactive()) {
# require("beepr"); beep(10)
system("mplayer /usr/share/sounds/freedesktop/stereo/dialog-warning.oga ")
system("notify-send -u normal 'R session' 'An error occured!'")
}
})
I regularly use stop() on interactive session like Rstudio, on scripts I am working and want to re-run to a point. This way I can switch to another desktop while waiting. I may test it to '.Rprofile'

When using jupyter_client how do I get data in HTML?

I'm wondering if jupyter_client is able to return code sent in to the execute function as HTML somehow?
I'm also wondering if I can do the same with stdout and stderr, as well as markdown?
If jupyter_client cannot do this, is there a jupyter library that does?
Adapting the solution from here might help. This adaptation takes the request of 1+1 or msg_id=c.execute('1+1') and returns the result formatted in html as bold red text with this display(HTML('<div style="color:Red;"><b>' + res + '</b></div>')) using IPython's display module. The kernel info status has been commented out but left for reference.
from subprocess import PIPE
from jupyter_client import KernelManager
from IPython.display import display, HTML
from queue import Empty
km = KernelManager(kernel_name='python3')
km.start_kernel()
# print(km.is_alive())
try:
c = km.client()
msg_id=c.execute('1+1')
state='busy'
data={}
while state!='idle' and c.is_alive():
try:
msg=c.get_iopub_msg(timeout=1)
if not 'content' in msg: continue
content = msg['content']
if 'data' in content:
data=content['data']
if 'execution_state' in content:
state=content['execution_state']
except Empty:
pass
res = data['text/plain']
# print(data)
display(HTML('<div style="color:Red;"><b>' + res + '</b></div>'))
except KeyboardInterrupt:
pass
finally:
km.shutdown_kernel()
# print(km.is_alive())
Also see here for more info.

Is there a way to make R beep/play a sound at the end of a script?

When I run R scripts I go do something else on a different desktop. If I don't check frequently, I never know when something is finished. Is there a way to invoke a beep (like a system beep) or get R to play a sound or notify growl via some code at the end of my script?
I have a package (beepr) with the sole purpose of making notification sounds in R which should work cross-platform. Run the following to install beepr and make a sound:
install.packages("beepr")
library(beepr)
beep()
More info at github: https://github.com/rasmusab/beepr
alarm()
The alarm function. It works by sending \a to the console
On MacOSX you can let the computer speak:
system("say Just finished!")
and you can also change the artificial voice that will speak:
system("say -v Kathy Just finished!")
You can pick any voice that is available on your computer. On Yosemite you can see which voices are installed in System Preferences -> Dictation & Speech -> Text to Speech.
You should have it tweet when it's done: http://cran.r-project.org/web/packages/twitteR/index.html
alarm doesn't work on my Windows machine so I created a function that does actually make noise.
beep <- function(n = 3){
for(i in seq(n)){
system("rundll32 user32.dll,MessageBeep -1")
Sys.sleep(.5)
}
}
This clearly could only work on Windows but I don't guarantee it will even run on an arbitrary Windows computer. I've only tested it on my machine but I figured I'd post it in case anybody has the same problem with alarm that I do.
cat('Hello world!\a')
How about something reasonably OS independent for OSes with GUIs and web-browsers? It even works on RStudio Server!
browseURL('https://www.youtube.com/watch?v=QH2-TGUlwu4')
Not only that, you can also also put some epic music from Youtube when the program is done looping :) (For Ubuntu/Debian:)
system("xdg-open 'http://www.youtube.com/watch?v=9jK-NcRmVcw'")
UPDATE:
With macOS 10.9 (Mavericks) and later, you can post notifications using plain AppleScript:
theTitle <- "A Title"
theMsg <- "A message here"
cmd <- paste("osascript -e ", "'display notification ", '"', theMsg, '"', ' with title ', '"', theTitle, '"', "'", sep='')
system(cmd)
This removes the need to install terminal-notifier, referenced below.
--
I've got terminal-notifier installed on my Mac to get desktop notifications from the command line. You can then wrap up a call to the system() command like this (change the path, obviously):
notify <- function(msgString='Message from R', titleString='Message from R', speakIt=FALSE) {
cmd <- paste('~/terminal-notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier -message ', '"', msgString, '" -title "', titleString, '"', sep='')
system(cmd)
if (speakIt) {
system(paste('say', msgString))
}
}
You can call the function like this
notify("R is done", "Message from R", speakIt=TRUE)
to get a message like this:
Update: Included #VLC's say command.
Please use shell.exec("url") to open some YouTube clip on Windows
Or if you're using GNU/Linux distro and have pcspkr module blacklisted (PC speaker was always annoying me), try combining system with some auditive/visual notification, e.g.
system("aplay -t wav /usr/share/sounds/phone.wav") # for auditive bell (an I mean it literary)
system("zenity --title=\"R script info\" --text=\"Script has finished with zero exit status\" --info") # for GTK dialog
You can check zenity manual if you prefer alert in, say, notification area... But, with system function, you can do pretty much anything: send an email, run some other script, reboot the machine, sudo rm -rf *.*, etc. anything... and I mean it.
But this stands only IF you're running GNU/Linux (or UNIX) distribution, otherwise, stick to Windows specific commands, though in that case, I can't give you much info...
Inspired by beepr, this is the function I'm currently using for these kind of problems :D
work_complete <- function() {
cat("Work complete. Press esc to sound the fanfare!!!\n")
on.exit(beepr::beep(3))
while (TRUE) {
beepr::beep(4)
Sys.sleep(1)
}
}
How about playing some music?
shell.exec("foo/Born.to.be.wild.mp3")
take a look at this package: RPushBullet
An R interface to the Pushbullet messaging service which provides fast
and efficient notifications (and file transfer) between computers,
phones and tablets
RPushbullet is completely free and multi platform. As for your question, you can use this library to send a Push to your browser, but obviously it becomes amazing when you need something than can notify you while you are away.
Moreover, the creator of the R package is the same of the well known Rcpp, Dirk Eddelbuettel. I'd say it's worth a shot!
Do this:
song <- function() {
for(i in 1:2) {
for(i in 1:4) {
for(i in 1:4) {
beep(7)
Sys.sleep(0.25)
beep()
Sys.sleep(0.22)
}
beep(2)
}
beep(11)
}
beep(4)
}
song()
You can jam out to it.
How about using Windows SpeechSynthesizer?
message <- "job done!"
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
paste0("$speak.Speak('", message, "');\"")
))
This may by nicely used in iterating operations and read something like "First job done", "Second job done" etc.:
say_something <- function(message) {
message <- paste0("$speak.Speak('", message, "');\"")
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
message
))
}
operations <- c("1st.", "2nd.", "3rd.")
lapply(operations, function(x) say_something(message=paste(x, "job done")))
*Note, that this uses system defaul language settings. The example is based on english lector, it can be changed using SelectVoice method. To check available lectors use:
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
"$speak.GetInstalledVoices().VoiceInfo")
)
That gives:
Gender : Female
Age : Adult
Name : Microsoft Paulina Desktop
Culture : pl-PL
Id : TTS_MS_PL-PL_PAULINA_11.0
Description : Microsoft Paulina Desktop - Polish
SupportedAudioFormats : {}
AdditionalInfo : {[Age, Adult], [Gender, Female], [Language, 415], [Name, Microsoft Paulina Desktop]...}
Gender : Male
Age : Adult
Name : Microsoft David Desktop
Culture : en-US
Id : TTS_MS_EN-US_DAVID_11.0
Description : Microsoft David Desktop - English (United States)
SupportedAudioFormats : {}
AdditionalInfo : {[Age, Adult], [Gender, Male], [Language, 409], [Name, Microsoft David Desktop]...}
Finally a function to select the lector by his "name" like "David", "Paulina" or "Hazel":
say_something <- function(message , voice) {
voice <- paste0("\"$speak.SelectVoice('Microsoft ", voice, " Desktop');" )
message <- paste0("$speak.Speak('", message, "');\"")
system2(command = "PowerShell",
args = c("-Command",
"\"Add-Type -AssemblyName System.Speech;",
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
voice,
message
))
}
operations <- c("1st.", "2nd.", "3rd.")
lapply(operations, function(x) say_something(message=paste(x, "job done"), voice="David"))
Dason's answer is great, obviously, because it will work on basically any Windows machine without requiring anything except R itself.
But one thing I have been wondering is how to make these functions actually beep after a code is run.
If you do something like this:
beepR <- function(x, n = 3){
for(i in seq(n)){
system("rundll32 user32.dll,MessageBeep -1")
Sys.sleep(.5)
}
return(x)
}
You can just pipe anything to it and it will return whatever you piped, so you can do like. See the example below.
fa <- psych::fa(x, 1) |> beepR()
I'm using here the native pipe |> that was introduced in R 4.1, but you can use the %>% pipe from the maggitr package if you like; they work the exact same way. Anyway, that will beep as soon as the analysis ends, and the variable fa will contain the results of the factor analysis.
Of course, here I used the beep function that Dason provided you, but you could just as easily add anything where I indicated below.
beepR <- function(x){
# your code here #
return(x)
}
If you wish to add that function every time RStudio opens, refer to RStudio's Managing R with .Rprofile, .Renviron, Rprofile.site, Renviron.site, rsession.conf, and repos.conf to learn how to use a .Rprofile file.
You can use notify-send command:
system("notify-send \"R script finished running\"")
Because of these many ideas, I have created a solution without Internet access, because I work with a VPN client with Windows. So it plays a typical Windows sound, which is usually on any Windows operating system.
#Function with loop, press Esc to stopp
alarm2 <- function(){
while(TRUE){
system("cmd.exe",input="C:/Windows/WinSxS/amd64_microsoft-windows-shell-sounds_31bf3856ad364e35_10.0.17134.1_none_fc93088a1eb3fd11/tada.wav")
Sys.sleep(1)
}
}
Function without loop
alarm3 <- function(){
system("cmd.exe",input="C:/Windows/WinSxS/amd64_microsoft-windows-shell-sounds_31bf3856ad364e35_10.0.17134.1_none_fc93088a1eb3fd11/tada.wav")
Sys.sleep(1)
}
The following code produces a beep and does not depend on a .mp3 or .wav file:
switch(Sys.info()[['sysname']],
Linux = {
system('play -n synth 0.1 tri 1000.0')}
)
Combining some ideas on the thread, I implement this:
options(error = function() {
if (interactive()) {
# require("beepr"); beep(10)
system("mplayer /usr/share/sounds/freedesktop/stereo/dialog-warning.oga ")
system("notify-send -u normal 'R session' 'An error occured!'")
}
})
I regularly use stop() on interactive session like Rstudio, on scripts I am working and want to re-run to a point. This way I can switch to another desktop while waiting. I may test it to '.Rprofile'

Resources