Microsoft Speech API (SAPI) UserTraining syntax - sapi

I've got a working autohotkey script which brings up the Windows Speech Recognition Training interface with custom text for input.
If you've ever done the training for Windows Speech Recognition, you know it has you say a short line of text, then once it recognizes that line, goes to a new screen with another short line of text.
I can't figure out how to "break" my two-sentence text into two separate training screens so the user won't have to read thousands of lines of training text all in the same breath with no mistakes.
If anyone figures this out I'll love you forever

Untested
hwnd:=WinExist("A")
Title:="My App's Training"
RC := ComObjCreate("SAPI.SpSharedRecoContext")
MyTrainingText := new TrainingText("Some custom text", Title)
MyTrainingText.get_MyMethod()
MyTrainingText := new TrainingText("Some more training text", Title)
MyTrainingText.get_MyMethod()
Class TrainingText
{
__New(x, y)
{
this.Text := x
this.Title := y
}
get_MyMethod()
{
Title := this.Title
trainingText := this.Text
if RC.Recognizer.IsUISupported("UserTraining")
{
RC.Recognizer.DisplayUI(ComObj(3,hwnd), Title, "UserTraining", traningText)
}
else MsgBox, Not supported
}
}

The user training text needs to be a double-null terminated string, also known as a multistring. Each null-terminated substring will be a separate utterance. I'm not familiar enough with AutoHotKey to know how to build one in that language.
In C#, a function to convert a string array to a multistring would look something like this:
static string StringArrayToMultiString(params string[] values)
{
if (values == null) throw new ArgumentNullException("values");
StringBuilder multiString = new StringBuilder();
foreach (string s in values)
{
multiString.Append(s);
multiString.Append('\0');
}
return multiString.ToString();
}

Related

Othello - Validating player moves

I'm in the process of making a recreation of Othello/Reversi with the use of a 2D Array. For each grid space I have a value stored in it("Black", "White" or ""). From there, I code what should and shouldn't be a legal move by the standards of the game rules. The problem is that it's difficult for me to understand how to translate the rules to code. How would any of you translate Othello's rules into a 2D Array based game.
I'm relatively new to coding and haven't had luck with trying to translate source code as this project needs to be my own VB.net 2010 coding, any advice helps.
I've tried everything from long if/elseif statements, many 2D loops, even a separate array that was supposed to validate moves itself. Nothing I've tried has been able to make it past the first move without breaking in some way.
Have some pseudocode. No idea what programming language that is supposed to be, I made it up on the spot.
is_valid_move(x,y,color): {
if (board[x,y] != empty) return false;
for dx = -1 to 1: {
for dy = -1 to 1: { // cycle through all directions
if (dx=0 && dy=0) next;
xx = x+dx; yy = y+dy;
while (valid_coords(xx, yy) && board[xx, yy]=enemy(color)): {
// skipping over enemy stones, there has to be at least one
xx = xx+dx; yy = yy+dy;
if (valid_coords(xx, yy) && board[xx, yy]=color)
return true; // this one is ours, we have captured something
}
}
}
return false; // no capture found, this is not a valid move
}

Remove a sentence in pdf by pdfbox

I do the job watermark of remove. i faced a problem how to remove a sentence in pdf file. I hava an idea that when processing operator(TJ Tj '),i record the ordre of such operator(TJ Tj ' ... showIdx). when the need to be removed sentence was found, i found the order index of operator ,and reprocess content stream,delete them.
the [op]<a https://stackoverflow.com/questions/58475104/filter-out-all-text-above-a-certain-font-size-from-pdf>[1] introduce PdfContentStreamEditor,but i can not get help from it.
BT
Tj showIdx2
TJ showIdx2
、
ET
BT
Tj showIdx3
TJ showIdx4
、
ET
···
[the case pdf file] <a https://github.com/zhongguogu/PDFBOX/blob/master/pdf/watermark.pdf >
the content in page header "本报告仅供-中庚基金管理有限公司-中庚报告邮箱使用 p2"
According to Google translate that line says that "this report is only for-Zhong Geng Fund Management Co., Ltd.-Zhong Geng Report Mailbox". This quite likely means that the report indeed was for Zhong Geng eyes only. But let's assume they decided to publish those reports more widely and you have the task of removing that soft restriction.
You mentioned the PdfContentStreamEditor from this answer.
Indeed you can use it similar to how it has been used in this answer where a string "[QR]" was to be removed from underneath some QR codes:
PDDocument document = ...
for (PDPage page : document.getDocumentCatalog().getPages()) {
PdfContentStreamEditor editor = new PdfContentStreamEditor(document, page) {
final StringBuilder recentChars = new StringBuilder();
#Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement)
throws IOException {
String string = font.toUnicode(code);
if (string != null)
recentChars.append(string);
super.showGlyph(textRenderingMatrix, font, code, displacement);
}
#Override
protected void write(ContentStreamWriter contentStreamWriter, Operator operator, List<COSBase> operands) throws IOException {
String recentText = recentChars.toString();
recentChars.setLength(0);
String operatorString = operator.getName();
if (TEXT_SHOWING_OPERATORS.contains(operatorString) && "本报告仅供-中庚基金管理有限公司-中庚报告邮箱使用 p2".equals(recentText))
{
return;
}
super.write(contentStreamWriter, operator, operands);
}
final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj", "'", "\"", "TJ");
};
editor.processPage(page);
}
document.save("watermark-RemoveByText.pdf");
(RemoveText test testRemoveByText)
Beware, though, this only works if the text to remove is drawn using one text showing instruction only and that instruction only draws the text to remove.
If instead the text to replace is drawn using multiple instructions following each other, you have to start collecting instructions as long as you have a potential match instead of dropping them immediately. As soon as the potential match turns out not to be a match after all, you'll have to super.write the collected instructions.
And if instead the text the replace is only part of what a single instruction draws, you'll have to doctor around with that instruction. Depending on one's script this may be very difficult, depending on how much it uses ligatures and stuff.
And the most complex situations may require you to collect all instructions while they're coming in, analyzing the whole of them, adapting identified instructions, and then forwarding the manipulated collected instructions to super.write.

How does this duplicate checker loop work?

Hi I hope someone can help. I'm trying to understand the following java program that loops until it finds two integers from the user that are the same:
import java.util.Scanner;
public class whileloop {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int previous, input = in.nextInt();
while(in.hasNextInt()){
previous = input;
input = in.nextInt();
if (input == previous){
System.out.println("Duplicate input found!");
}
}
}
So from my understanding, the program will call the user to provide two integers from .nextInt(), store those values in the variables named "previous" and "input", and then will proceed to the while loop. What I don't understand is what occurs right before the if condition. What is the point of having "previous" equate to "input" and then asking input for another integer? If I remove previous = input and input = in.nextInt() I get an error that says that the variables have not been initialized.... which confuses me since I thought that the variables "previous" and "input" got initialized when the program asked the user for the two integers? Evidently I'm quite confused, and would really appreciate help.

selenium webdriver sendkeys intermittent issue

I have a web automation framework set up that works pretty well. I have a constant issue though that when using SendKeys to write to textboxes, quite often a letter gets missed out. So for example, if my dataset is "TestUserName", something like "TestUerName" gets sent example with a missing letter.
This is a big issue for me, as after the web tests concludes successfully I further check if the database was updated properly. So in the above example I would go to the UserName column and expect to find TestUserName, but the test would fail because TestUerName is found instead.
Any ideas please? I am using selenium 2.53.0.
My code below.
public void inputValue (Object [][] valuesFromExcel)
{
for (int rowNow = 0; rowNow < (valuesFromExcel.length); rowNow++)
{
String newValue = valuesFromExcel[rowNow][0].toString();
if (!newValue.equals(""))
{
WebElement currentElement = driver.findElement(By.id(valuesFromExcel[rowNow][1].toString()));
if (currentElement.getTagName().equals("input"))
{
currentElement.sendKeys(newValue);
}
else if (currentElement.getTagName().equals("select"))
{
new Select(currentElement).selectByVisibleText(newValue);
}
}
}
}
Thanks.
Instead of sending as a string, send it as char...
Convert the string to char and send each char one by one to the text box. Yes there will be a performance issue, but it works fine. It will not skip any of the letters

How do I execute Dynamically (like Eval) in Dart?

Since getting started in Dart I've been watching for a way to execute Dart (Text) Source (that the same program may well be generating dynamically) as Code. Like the infamous "eval()" function.
Recently I have caught a few hints that the communication port between Isolates support some sort of "Spawn" that seems like it could allow this "trick". In Ruby there is also the possibility to load a module dynamically as a language feature, perhaps there is some way to do this in Dart?
Any clues or a simple example will be greatly appreciated.
Thanks in advance!
Ladislav Thon provided this answer on the Dart forum:
I believe it's very safe to say that Dart will never have eval. But it will have other, more structured ways of dynamically generating code (code name mirror builders). There is nothing like that right now, though.
There are two ways of spawning an isolate: spawnFunction, which runs an existing function from the existing code in a new isolate, so nothing you are looking for, and spawnUri, which downloads code from given URI and runs it in new isolate. That is essentially dynamic code loading -- but the dynamically loaded code is isolated from the existing code. It runs in a new isolate, so the only means of communicating with it is via message passing (through ports).
You can run a string as Dart code by first constructing a data URI from it and then passing it into Isolate.spawnUri.
import 'dart:isolate';
void main() async {
final uri = Uri.dataFromString(
'''
void main() {
print("Hellooooooo from the other side!");
}
''',
mimeType: 'application/dart',
);
await Isolate.spawnUri(uri, [], null);
}
Note that you can only do this in JIT mode, which means that the only place you might benefit from it is Dart VM command line apps / package:build scripts. It will not work in Flutter release builds.
To get a result back from it, you can use ports:
import 'dart:isolate';
void main() async {
final name = 'Eval Knievel';
final uri = Uri.dataFromString(
'''
import "dart:isolate";
void main(_, SendPort port) {
port.send("Nice to meet you, $name!");
}
''',
mimeType: 'application/dart',
);
final port = ReceivePort();
await Isolate.spawnUri(uri, [], port.sendPort);
final String response = await port.first;
print(response);
}
I wrote about it on my blog.
Eval(), in Ruby at least, can execute anything from a single statement (like an assignment) to complete involved programs. There is a substantial time penalty for executing many small snippets over most any other form of execution that is possible.
Looking at the problem closer, there are at least three different functions that were at the base of the various schemes where eval might be used. Dart handles at least 2 of these in at least minimal ways.
Dart does not, nor does it look like there is any plan to support "general" script execution.
However, the NoSuchMethod method can be used to effectively implement the dynamic "injection" of variables into your local class environment. It replaces an eval() with a string that would look like this: eval( "String text = 'your first name here';" );
The second function that Dart readily supports now is the invocation of a method, that would look like this: eval( "Map map = SomeClass.some_method()" );
After messing about with this it finally dawned on me that a single simple class can be used to store the information needed to invoke a method, for a class, as a string which seems to have general utility. I can replace a big maintenance prone switch statement that might otherwise be necessary to invoke a series of methods. In Ruby this was almost trivial, however in Dart there are some fairly less than intuitive calls so I wanted to get this "trick" in one place, which fits will with doing ordering and filtering on the strings such as you may need.
Here's the code to "accumulate" as many classes (a whole library?) into a map using reflection such that the class.methodName() can be called with nothing more than a key (as a string).
Note: I used a few "helper methods" to do Map & List functions, you will probably want to replace them with straight Dart. However this code is used and tested only using the functions..
Here's the code:
//The used "Helpers" here..
MAP_add(var map, var key, var value){ if(key != null){map[key] = value;}return(map);}
Object MAP_fetch(var map, var key, [var dflt = null]) {var value = map[key];if (value==null) {value = dflt;}return( value );}
class ClassMethodMapper {
Map _helperMirrorsMap, _methodMap;
void accum_class_map(Object myClass){
InstanceMirror helperMirror = reflect(myClass);
List methodsAr = helperMirror.type.methods.values;
String classNm = myClass.toString().split("'")[1]; ///#FRAGILE
MAP_add(_helperMirrorsMap, classNm, helperMirror);
methodsAr.forEach(( method) {
String key = method.simpleName;
if (key.charCodeAt(0) != 95) { //Ignore private methods
MAP_add(_methodMap, "${classNm}.${key}()", method);
}
});
}
Map invoker( String methodNm ) {
var method = MAP_fetch(_methodMap, methodNm, null);
if (method != null) {
String classNm = methodNm.split('.')[0];
InstanceMirror helperMirror = MAP_fetch(_helperMirrorsMap, classNm);
helperMirror.invoke(method.simpleName, []);
}
}
ClassMethodMapper() {
_methodMap = {};
_helperMirrorsMap = {};
}
}//END_OF_CLASS( ClassMethodMapper );
============
main() {
ClassMethodMapper cMM = new ClassMethodMapper();
cMM.accum_class_map(MyFirstExampleClass);
cMM.accum_class_map(MySecondExampleClass);
//Now you're ready to execute any method (not private as per a special line of code above)
//by simply doing this:
cMM.invoker( MyFirstExampleClass.my_example_method() );
}
Actually there some libraries in pub.dev/packages but has some limitations because are young versions, so that I can recommend you this library expressions to dart and flutter.
A library to parse and evaluate simple expressions.
This library can handle simple expressions, but no blocks of code, control flow statements and so on. It supports a syntax that is common to most programming languages.
There I create an example of code to evaluate arithmetic operations and comparations of data.
import 'package:expressions/expressions.dart';
import 'dart:math';
#override
Widget build(BuildContext context) {
final parsing = FormulaMath();
// Expression example
String condition = "(cos(x)*cos(x)+sin(x)*sin(x)==1) && respuesta_texto == 'si'";
Expression expression = Expression.parse(condition);
var context = {
"x": pi / 5,
"cos": cos,
"sin": sin,
"respuesta_texto" : 'si'
};
// Evaluate expression
final evaluator = const ExpressionEvaluator();
var r = evaluator.eval(expression, context);
print(r);
return Scaffold(
body: Container(
margin: EdgeInsets.only(top: 50.0),
child: Column(
children: [
Text(condition),
Text(r.toString())
],
),
),
);
}
I/flutter (27188): true