Java speech recognition API using the result listener - nullpointerexception

I am quite new to java programming and have been teaching myself through reading online and buying a few java programming books here and there.
However I am running into a problem when building a speech recognition program I have been working on for a few weeks now. It is giving me a nullpointer exception at the rec.addresultlistener coding line and I have absoloutely no idea why, because to my knowledge that line is there to tell the program to listen for a input in order to check it against the grammar. This program was previously giving me the same errors for the rec.allocate() coding line but that was fixed by declaring it null. Am I supposed to declare this as null as well?
Can someone please help me out here and also explain why?
//Create a recognizer that supports English
rec = Central.createRecognizer( new EngineModeDesc (Locale.ENGLISH));;
//Start up the recognizer
if(rec!=null){
rec.allocate();
//Load the grammar from a file, and enable it
System.out.println(new File(".").getAbsoluteFile());
FileReader reader = new FileReader("grammar2.0");
if (reader != null) System.out.println("no file");;
System.out.println(reader);
RuleGrammar gram = rec.loadJSGF(reader);
gram.setEnabled(true);
}
//Add the listener to get results
rec.addResultListener(new speech());
//commit the grammar
rec.commitChanges();
//Request focus and start listening
rec.requestFocus();
rec.resume();

Related

Problem with Prefix in Discord.js (including .toUpperCase())

Basically, I've been developing a bot for several weeks now using the discord.js library and recently encountered a small but crucial issue. Essentially when I declare my argument, I also made it so that the message content (message.content) would be capitalized using .toUpperCase(). Essentially in doing so regardless of the type of prefix you would enter (symbol wise) it would all be read by the program as valid.
For example only: !help - should work, however if I would enter .help, it would also be read as valid.
In any case, here's the code. I appreciate all the help!
bot.on('message', message =>{
let args = message.content.toUpperCase().substring(PREFIX.length).split(" ");
const sender = message.member;
switch(args[0])
{
case 'HELP':
message.reply("I've sent you some documentation on all the commands that you can use...").then(d_msg => {d_msg.delete(3000); });
message.delete(3000);
const attachment = new Attachment('./UtilityBot_Documentation.txt')
message.author.send('[Education] Bot - Documentation');
message.author.send(attachment);
break;
}
})
The discord.js tutorial covers an extremely similar problem to what you're trying to do. I recommend you check it out. The page I linked in specific is doing a very similar thing to you, but it's worth giving the whole thing a read through if you haven't done so already. In general, I would include the following line just above where you established args.
if (!message.content.startsWith(PREFIX)) return;
What I'm doing here is saying if the message does not start with the prefix, stop running until a new message is sent. I might be missing something, but certainly check out the tutorial. It's really well written.
https://discordjs.guide/creating-your-bot/commands-with-user-input.html#basic-arguments

Plugin that runs tests based on file of user

I am developing a Plugin for IntelliJ for teaching purposes, where students write some code and the teacher can write tests and the students can run those tests and see if they are doing it all correctly. It would be great if I would get the file the user is writing in as a java class so that I can run the functions of that class from within another function and test it as if I would have written it.
What I have as of now:
In the Main Toolbar I have a button, where the students should be able to run the tests. I have a class that extends AnAction, now I have no Idea what I should write in it:
#Override
public void actionPerformed(AnActionEvent e) {
}
I have been going through the IntelliJ documentation for some time now and as by now I do not get any further. I sure hope that the experienced developers that can be found here can manybe give me a hint or two.
Thanks a lot in advance :)
If I understand correctly, the students would be programming within a project within IntelliJ?
Then you can get the path to the project that they are working on using the AnActionEvent event.
Project project = event.getProject();
String projectBasePath = project.getBasePath();
You could use this to send the entire src folder to your computer and do what it is that you need to do there?
But, it also sounds like you would want the students to run the test functions on their side via the plugin. In that case, one option that I know of is to again use the project.getBasePath(), or get them to select a file using a GUI, and then use ProcessBuilder to compile, run, test, etc their Java classes. You can run any Windows / shell command this way and pipe the output into the IDE, or your own tool window.
public void actionPerformed(AnActionEvent event) {
Project project = event.getProject();
String projectBasePath = project.getBasePath();
ProcessBuilder pb = new ProcessBuilder();
pb.directory(projectBasepath);
pb.command("cmd", "/k", "javac src\*.java")
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(newInputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
... // anything else you need to do
}
Let me know if this makes sense - maybe I can help you out more if you give me more specific questions.

Hadoop Map reduce Testing - custom record reader

I have written a custom record reader and looking for sample test code to test my custom reader using MRUnit or any other testing framework. Its working fine as per the functionality but I would like to add test cases before I make an install. Any help would be appreciable.
In my opinion, a custom record reader is like any iterator. For testing my record reader I have been able to work without MRUnit or any other hadoop junit frameworks. The test executes quickly and the footprint is small too. Initialize the record reader in your test case and keep iterating on it. Here is a pseudocode from one of my tests. I can provide you more details if you want to proceed in this direction.
MyInputFormat myInputFormat = new MyInputFormat();
//configure job and provide input format configuration
Job job = Job.getInstance(conf, "test");
conf = job.getConfiguration();
// verify split type and count if you want to verify the input format also
List<InputSplit> splits = myInputFormat.getSplits(job);
TaskAttemptContext context = new TaskAttemptContextImpl(conf, new TaskAttemptID());
RecordReader<LongWritable, Text> reader = myInputFormat.createRecordReader(splits.get(1), context);
reader.initialize(splits.get(1), context);
for (; number of expected value;) {
assertTrue(reader.nextKeyValue());
// verify key and value
assertEquals(expectedLong, reader.getCurrentKey());
}

cue.enter event for video tag doesn't work?

I tried the following code (using the javascript commands for the html5 video tag) and it failed. I'm wondering if there is something very visible that I'm doing wrong. I'm trying to make the video pause whenever a cue is entered...
here is the code:
var cue0 = new TextTrackCue(20.200,20.200, ' woman in defensive karate pose');
cue0.id = 'cue0';
cue0.onenter="function() {myPlayer.pause();}";
Could be a lot of problems from your code. I see, that startTime is equal to endTime, which means, that your cue is never entered.
I made a simple working example
cue = new TextTrackCue(5, 15, "woman in defensive karate pose");

Connecting to a UDP data stream with Mathematica

I have an app on my iPhone called iSeismometer which reads the iPhone's accelerometers and acts as a server which streams this data via UDP (I can set the IP address and port number). The question is how to read this data stream with Mathematica? Apparently, Dreeves has been looking into this 12 years ago, so I imagine something must have happened in the meantime.
Update
I got two great answers so far; one from WReach and one from Mark McClure. Both are using JLink to get at the data. This seems like a fine approach. However, I was reminded of some work I did on the WII balance board. Using a few free programs (GlovePIE and PPJoy) I got this bluetooth peripheral to appear as a joystick to Windows, and therefore also to Mathematica (via ControllerState). Of course, bluetooth and UDP are quite different, but could something along the same lines be made to work too?
JLink is definitely the way to go. I prefer to keep my Java code and my Mathematica code separate by compiling a Java programwhich I then call from Mathematica. I set up a Notebook and companion Java program that you can grab here:
http://facstaff.unca.edu/mcmcclur/UDPFiles.tar.gz
Here is the essential Mathematica code:
Needs["JLink`"];
InstallJava[];
AddToClassPath[NotebookDirectory[]];
udpReader = JavaNew["myClient"];
i = 0;
While[True && i++ < 100,
Print[udpReader#udpReadOne[10552]]]
The updReader class is defined by the following Java code.
// A simple UDP client to read from iseismometer:
// http://www.iseismometer.com/
// You can run this from the command line via "java myClient"
// to check that your iseismometer setup is correct or you can
// call the the udpReadOne method from another program.
import java.io.*;
import java.net.*;
import java.util.*;
public class myClient {
public static void main() throws IOException {
DatagramSocket socket = new DatagramSocket(10552);
byte[] buffer = new byte[500];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while(true) {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(received);
}
}
public static String udpReadOne(int port) throws IOException {
DatagramSocket socket = new DatagramSocket(port);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
socket.close();
return received;
}
}
Note that you can use the main method of the myClient class to check that your setup is working without Mathematica, essentially taking one potential issue out of the loop.
Assuming the set-up discussed in a blog entry on the iSeismometer web site, a couple of options come to mind.
Import
The first option would be to use an external program to capture the packets, and then use Import to bring in the results, e.g.
Import["!someexternalprog", "Lines"]
Alas, the Python program mentioned in the blog post will not work well here since it runs in an endless loop that must be manually terminated. The Import approach would only work if that program were modified to stop after a fixed number of packets or a time limit or something.
JLink
An alternate approach can be implemented without leaving the comfy Mathematica environment by using JLink. Well, perhaps it is a stretch to say that we are staying within Mathematica since a fair amount of funny-looking Java code is mixed in with the Mathematica code. Nevertheless, it does illustrate the utility of the built-in Java distribution that ships with every copy of Mathematica:
Needs["JLink`"]
LoadJavaClass["java.util.Arrays"];
ClearAll#ListenToISeismometer
ListenToISeismometer[port_] :=
JavaBlock#Module[{socket, packet, listen, record = Null, listening = True}
, packet = JavaNew["java.net.DatagramPacket", JavaNew["[B", 1024], 1024]
; listen[] :=
If[$Failed =!= Quiet[socket#receive[packet], Java::excptn]
, record =
JavaNew[
"java.lang.String"
, java`util`Arrays`copyOfRange ## packet /# {getData[], getOffset[], getLength[]}
]#toString[] // Sow
]
; Row[{Button["Stop", listening = False], Dynamic[record]}, " "] // PrintTemporary
; AbortProtect[
socket = JavaNew["java.net.DatagramSocket", port]
; socket#setSoTimeout[1000]
; Reap[While[listening, listen[]]; socket#close[]][[2, 1]]
]
]
Some shortcuts have been taken with respect to exception handling, packet decoding and the like in order to keep this example at a manageable length.
ListenToISeismometer needs to be given the UDP port number to listen upon. Let's use the same port as in the blog post, 10552:
In[33]:= data = ListenToISeismometer[10552];
The function will listen to all UDP events on that port until told to stop. A button is presented for this purpose, with each packet flashing by along side as received.
When the button is pressed, the function returns a list of the packets received:
In[34]:= data // Column
Out[34]= 1,83575.099,0.029,0.044,0.094
1,83575.781,0.056,0.033,0.099
1,83575.924,0.047,0.054,0.094
1,83575.613,0.096,0.092,0.057
1,83575.748,0.073,0.049,0.061
1,83575.577,0.008,0.089,0.020
...
JLink makes this possible, but there is no escaping the fact that the use of JLink requires a working knowledge of Java.