How to set OPT programmatically with MS SAPI - sapi

Given the following which can be loaded into MS SAPI 5.1:
<GRAMMAR LANGID="409">
<RULE NAME="top rule" TOPLEVEL="ACTIVE">
<OPT>hello</OPT>
<P>my name is fred</P>
</RULE>
</GRAMMAR>
How can I do the same programmatically, specifically with regard to the optional element.
I would guess it is done here:
state.AddWordTransition(nextState, "hello", " ", SpeechGrammarWordType.SGLexical, s, id, ref propValue, 1F);
...and it is probably the propValue. But what is the syntax (e.g, propValue="OPT=true" - does not work of course)
Thanks!

Optional words need an epsilon (empty) transition to the next state, so add:
state.AddWordTransition(nextState, NULL, NULL, SpeechGrammarWordType.SGLexical, s, id, ref propValue, 1F);
to add the epsilon transition.

Related

How to make a table of icons and text in Rmarkdown

In several web pages for courses I have a Resources page that lists some recommended
books, using icons of the cover and text that contains links to related materials.
I can do this, as shown below, but the code in my .Rmd file is unnecessarily complex, making it
a chore to add new books.
How can I simplify this code in the chunks? I use several functions defined below
```{r do-books, echo=FALSE}
width <- "160px"
tab(class="cellpadding", width="800px",
tr(
tabfig("fox", "images/books/car-3e.jpg",
"https://us.sagepub.com/en-us/nam/an-r-companion-to-applied-regression/book246125", width=width),
tabtxt("Fox & Weisberg,", a("An R Companion to Applied Regression",
href="https://us.sagepub.com/en-us/nam/an-r-companion-to-applied-regression/book246125"),
". A comprehensive introduction to linear models, regression diagnostics, etc.", br()
# "Course notes at", aself("http://ccom.unh.edu/vislab/VisCourse/index.html")
)
),
tr(
tabfig("Wickham", "images/books/ggplot-book-2ndEd.jpg",
"https://www.springer.com/gp/book/9780387981413", width=width),
tabtxt("Hadley Wickham,", a("ggplot2: Elegant Graphics for Data Analysis",
href="https://www.springer.com/gp/book/9780387981413"),
". The printed version of the ggplot2 book. The 3rd edition is online at",
a("https://ggplot2-book.org/", href= "https://ggplot2-book.org/")
)
)
)
```
The functions tabfig and tabtext are defined in a sourced file:
library(htmltools)
# table tags
tab <- function (...)
tags$table(...)
td <- function (...)
tags$td(...)
tr <- function (...)
tags$tr(...)
# an <a> tag with href as the text to be displayed
aself <- function (href, ...)
a(href, href=href, ...)
# thumnail figure with href in a table column / row
tabfig <- function(name, img, href, ...) {
td(
a(class = "thumbnail", title = name, href = href,
img(src = img, ...)
)
)
}
tabtxt <- function(text, ...) {
td(text, ...)
}

Printing the value of the configuration

While modifying the toy language SIMPLE from the tutorial, I thought it would be helpful to have a statement that would just print the current configuration so that I could see the internal state of the program as it ran. To that end I added to Stmta printConfig command. In the semantics then I figured all I had to do was rewrite this to a call to print taking the body of the T cell so I added
rule <k> printConfig; => print(cfg); </k>
<T> cfg </T>
The kompiler throws an error saying that there is an unexpected end parenthesis, specifically the one for print(cfg). I'd encountered a similar issue previously and in that case the error turned out to be due to the typing of the components of the two statements I had. I'm wondering then if there is a way to "cast" the value in the T cell as an Exp so I can print it.
If there is a better way I can debug my semantics that does not involve this I am very open to that as well. Thank you!
Well one issue I can see is that you have <k> and <T> cells next to each other in your rule, but they don't have a sibling relationship in the initial configuration.
The SIMPLE configuration looks like this, where the <k> cell is a grandchild of the <T> cell:
configuration <T color="red">
<threads color="orange">
<thread multiplicity="*" color="yellow">
<k color="green"> $PGM:Stmts ~> execute </k>
<control color="cyan">
<fstack color="blue"> .List </fstack>
<xstack color="purple"> .List </xstack>
</control>
<env color="violet"> .Map </env>
<holds color="black"> .Map </holds>
<id color="pink"> 0 </id>
</thread>
</threads>
<genv color="pink"> .Map </genv>
<store color="white"> .Map </store>
<busy color="cyan"> .Set </busy>
<terminated color="red"> .Set </terminated>
<input color="magenta" stream="stdin"> .List </input>
<output color="brown" stream="stdout"> .List </output>
<nextLoc color="gray"> 0 </nextLoc>
</T>
So if you want to write your rule, you at least have to do this:
syntax Stmt ::= "printConfig" ";"
rule <T> ... <k> printConfig; => print(CFG); ... </k> ... </T> #as CFG
Notice that I made three changes here, (1) I used capital letters for the variable CFG (which is conventional in K), (2) I added the ... to the end of the <k> cell, which allows you to use printConfig; anywhere instead of just at the end of a program, and (3) I used an _#as_ pattern to match both the super-term <T> ... </T> as well as the sub-term <k> ... </k> at the same time, giving the name CFG to the super-term.
_#as_ patterns are documented in the Pending Documentation.
Hope that helps!

Can't change the language in microsoft cognitive services spellchecker

Here is the Microsoft Python example of using spellchecker API:
import http.client, urllib.parse, json
text = 'Hollo, wrld!'
data = {'text': text}
# NOTE: Replace this example key with a valid subscription key.
key = 'MY_API_KEY'
host = 'api.cognitive.microsoft.com'
path = '/bing/v7.0/spellcheck?'
params = 'mkt=en-us&mode=proof'
headers = {'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/x-www-form-urlencoded'}
# The headers in the following example
# are optional but should be considered as required:
#
# X-MSEdge-ClientIP: 999.999.999.999
# X-Search-Location: lat: +90.0000000000000;long: 00.0000000000000;re:100.000000000000
# X-MSEdge-ClientID: <Client ID from Previous Response Goes Here>
conn = http.client.HTTPSConnection(host)
body = urllib.parse.urlencode(data)
conn.request ("POST", path + params, body, headers)
response = conn.getresponse()
output = json.dumps(json.loads(response.read()), indent=4)
print (output)
And it works well for mkt=en-us. But if I try to change it, for example to 'fr-FR'. It always answers me with a blank response to any input text.
{
"_type": "SpellCheck",
"flaggedTokens": []
}
Has anybody encountered the similar problem? May it be connected with my trial api key (though they do not mention that trial supports only English)?
Well, I've found out what the problem was. 'mode=proof' — advanced spellchecker currently available only if 'mkt=en-us' (for some Microsoft reasons it does not available even if 'mkt=en-uk'). For all other languages, you should use 'mode=spell'.
The main difference between 'proof' and 'spell' is described like this:
The Spell mode finds most spelling mistakes but doesn't find some of the grammar errors that Proof catches (for example, capitalization and repeated words).

R markdown: simplify creating tables of figures and text

For R markdown Rmd web pages I want to generate tables containing in the first column thumbnail images (that link to a larger image or a web site) and
descriptive text in the 2nd column. One example is the following image:
I know I can create this manually in raw HTML, but that is very fiddly and time-consuming. There must be some easier way.
On a different page, I tried a markdown / pandoc table, but that didn't work, and I reverted to manual coding of HTML
icon | title
--------------------------------------------------+--------------------------
<img src="images/books/R-Graphics.jpg" height=50> |Paul Murrell, *R Graphics*, 2nd Ed.
<img src="images/books/R-graphics-cookbook.jpg" height=50> | Winston Chang, R Graphics Cookbook
<img src="images/books/lattice.png" height=50> | Deepayan Sarkar, *lattice*
<img src="images/books/ggplot2.jpg" height=50> | Hadley Wickham, *ggplot2*
Perhaps the htmltools package would be useful here, but I can't quite see how to use it in my Rmd files for this application.
Probably forgot escaping quotes? This works fine for me:
---
title: "The Mighty Doge"
output: html_document
---
```{r}
library(knitr)
create_thumbnail <- function(file) {
paste0("<img src=\"", file, "\" style=\"width: 50px;\"/>")
}
df <- data.frame(Image = rep("unnamed.png", 5),
Description = rep("Doge", 5))
df$Image <- create_thumbnail(df$Image)
kable(df)
```
Here is an approach that uses htmltools and seems much more flexible, in that I can control the details somewhat more easily.
I'm not familiar with bootstrap <div> constructs, so I used HTML table constructs. I had to define functions for tr(), td() etc.
```{r html-setup, echo=FALSE}
library(htmltools)
# table tags
tab <- function (...)
tags$table(...)
td <- function (...)
tags$td(...)
tr <- function (...)
tags$tr(...)
# an <a> tag with href as the text to be displayed
aself <- function (href, ...)
a(href, href=href, ...)
```
Then functions to construct my table entries the way I wanted:
```{r table-functions, echo=FALSE}
# thumnail figure with href in a table column
tabfig <- function(name, img, href, width) {
td(
a(class = "thumbnail", title = name, href = href,
img(src = img, width=width)
)
)
}
tabtxt <- function(text, ...) {
td(text, ...)
}
```
Finally, use them to input the entries:
## Blogs
```{r do-blogs, echo=FALSE}
width="160px"
tab(
tr(
tabfig("FlowingData", "images/blogs/flowingdata.png", "http://flowingdata.com/", width=width),
tabtxt("Nathan Yau,", aself("flowingdata.com/"),
"A large number of blog posts illustrating data visualization methods with tutorials on how do do these with R and other software.")
),
tr(
tabfig("Junk Charts", "images/blogs/junkcharts.png", "http://junkcharts.typepad.com/", width=width),
tabtxt("Kaiser Fung,", aself("http://junkcharts.typepad.com/"),
"Fung discusses a variety of data displays and how they can be improved.")
),
tr(
tabfig("Data Stories", "images/blogs/datastories.png", "http://datastori.es/", width=width),
tabtxt("A podcast on data visualization with Enrico Bertini and Moritz Stefaner,",
aself("http://datastori.es/"),
"Interviews with over 100 graphic designers & developers.")
)
)
```
I still need to tweak the padding, but this gives me more or less what I was after:

Calling Drools Agenda after completion of iteration of Arraylist in DRL file

I am iterating a list in the DRL file. I need to call the new Agenda after completion of the loop. But the following code calls the Agenda "B to C" for all iterations
rule "Difference in offsets"
dialect "java"
lock-on-active
when
$notification : NotificationVO()
wtOffset:Integer() from $notification.getWeightOffset();
then
System.out.println("Hello loop1");
$notification.getOffsetChngesInterval().
add((wtOffset-$notification.getInitialOffset()));
update($notification);
drools.setFocus("B to C");
rule "Last activity"
dialect "java"
salience 2
no-loop true
auto-focus false
agenda-group "B to C"
when
$notification:NotificationVO
($notification.getOffsetChngesInterval()!=null)
then
System.out.println("Rule2---"+
$notification.getOffsetChngesInterval().size());
end
In the above code i want to focus the agenda-group "B to C" only after completing the iteration of $notification.getWeightOffset();.
Two comments. (1) The abundant usage of rule attributes is something to be avoided. (2) Rule "Difference in offsets" implements a procedural paradigm: map elements of one list to create another list.
That said, I'd do the calculation of the "changes intervals" on the right hand side of a rule that triggers when there are more "weight offsets" that "changes intervals". (I'm guessing that this is a good condition.)
rule "Difference in offsets"
dialect "java"
when
$ntf: NotificationVO( weightOffset.size() > offsetChngesInterval.size(),
$initOff: initialOffset )
then
for( Integer ioff: $ntf.getWeightOffset ){
$ntf.getOffsetChngesInterval().add(ioff - $initOff );
}
update( $ntf );
System.out.println( $ntf.getOffsetChngesInterval().size());
end