getch() like function in dart - c++

In the c/c++ languages, there is a function in the conio.h header file called getch() which lets you input only 1 character and doesn't echo it on the screen and once that character has been typed, it automatically goes to the next line of code without having to press enter.
I've tried using the stdin.readByteSync() in dart but it doesn't give me the functionality that getch() gives in c/c++. I'd like to know if there is a way to make a function or method in dart that behaves in the same manner as getch() does in c/c++. Thank you.

You just need to set the following option to false:
https://api.dart.dev/stable/2.8.2/dart-io/Stdin/lineMode.html
And if you are using Windows you also need to set the following to false first according to the documentation:
https://api.dart.dev/stable/2.8.2/dart-io/Stdin/echoMode.html
A simple working example, which are just repeating what you type, can be made like this. It does not work inside IntelliJ but works from CMD, PowerShell and Linux bash:
import 'dart:convert';
import 'dart:io';
void main() {
stdin.echoMode = false;
stdin.lineMode = false;
stdin.transform(utf8.decoder).forEach((element) => print('Got: $element'));
}
By doing this we can also do you own suggestion and use stdin.readByteSync() (just notice that if you get a UTF-8 input, a character can contain multiple bytes:
import 'dart:io';
void main() {
print(getch());
}
int getch() {
stdin.echoMode = false;
stdin.lineMode = false;
return stdin.readByteSync();
}

Thank you all for your contribution. However adding to the answer I got that went like this
import 'dart:io';
void main() {
print(getch());
}
int getch() {
stdin.echoMode = false;
stdin.lineMode = false;
return stdin.readByteSync();
}
I decided to add something to make it more like the getch() function in conio.h header file in c language. The code goes like this
import 'dart:io';
void main() {
print(getch());
}
String getch() {
stdin.echoMode = false;
stdin.lineMode = false;
int a = stdin.readByteSync();
return String.fromCharCode(a);
}
Although it only works on cmd, powershell and linux terminal and not on intelliJ, it is better than nothing. The most important thing is to get the foundation of dart for things like flutter and web. And with this little knowledge, I was put it into practice and make a simple and basic typing game in dart. The code is below:
import 'dart:io';
import 'dart:convert';
import 'dart:core';
void main() {
Stopwatch s = Stopwatch();
String sentence = 'In the famous battle of Thermopylae in 480 BC, one of the most famous battles in history, King Leonidas of Sparta said the phrase'
' Molon Labe which means \"come and take them\" in ancient greek to Xerxes I of Persia when the Persians asked the Spartans to lay'
' down their arms and surrender.';
List<String> sentenceSplit = sentence.split(' ');
int wordCount = sentenceSplit.length;
print('Welcome to this typing game. Type the words you see on the screen below\n\n$sentence\n\n');
for (int i=0; i<sentence.length; i++) {
if(i==1) {
s.start(); // start the timer after first letter is clicked
}
if(getch() == sentence[i]) {
stdout.write(sentence[i]);
}
else {
i--;
continue;
}
}
s.stop(); // stop the timer
int typingSpeed = wordCount ~/ (s.elapsed.inSeconds/60);
print('\n\nWord Count:\t$wordCount words');
print('Elapsed time:\t${s.elapsed.inSeconds} seconds');
print('Typing speed:\t$typingSpeed WPM');
}
String getch() {
stdin.echoMode = false;
stdin.lineMode = false;
int a = stdin.readByteSync();
return String.fromCharCode(a);
}
You can go ahead and advance to make it a way that when the user starts the
game again, it should show a different text so they don't get used to it. But anyway, that is it for this question. It is officially closed. Although, if you have anymore to add, feel free to drop it here. Thank you!

Related

How do I make an interactive command line interface?

I am trying to write a tool to compare my files but I found it difficult to interactive with. I want to support 2 operations: 1) load my files into memory 2) compare the files already loaded.
The idea is like below
while (true) {
getline(&line, &linesize, stdin);
if (strlen(line) < 2) continue;
token = strtok(line, DELIM);
if (!strcmp(token,"load")) {
puts("you want to load something");
} else if (!strcmp(token, "compare")) {
puts("you want to compare something");
} else if (!strcmp(token, "exit")) {
puts("exiting...");
exit(1);
} else {
puts("Cannot parse, try again");
}
}
In terminal, if I want to compare some MyVeryLongFileNameFile.foo and AnotherVeryLongFileNameFile.bar, I can just type diff My\tab Ano\tab \enter and it will auto completes the filenames for me.
I would like to also have these kind of features in my program, like using tab to autocomplete, using up/down to choose from previous commands, etc. How should I achieve this?
Using the ncurses.h library help you accomplish this.

How to split a regular expression into parts?

I need to break down a regular expression into its basic parts. For instance, given the regex [a-d]+[r-z]* I need to split it into [a-d]+ and [r-z]*. This is of course a very simple example, and regex syntax can get very complex...
Is there a (relatively) simple way to achieve this, or am I doomed to reverse-engineer a regex parser?
I need this to find out if a given string is a part of matching input for a given regular expression.
You can brute-force it this way:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class RegexSplitter {
private static boolean tryRegex(String regex) {
try {
Pattern.compile(regex);
return true;
} catch(PatternSyntaxException pse) {
return false;
}
}
public static void main(String args[]) {
String input = "[a-d]+[r-z]*";
List<String> results = new ArrayList<>();
int start = 0;
int end = 1;
boolean good = false;
while(end < input.length()) {
String part = input.substring(start, end);
if(!tryRegex(part)) {
if(good) {
good = false;
results.add(input.substring(start, end - 1));
start = end-1;
}
} else {
good = true;
}
++end;
}
if(tryRegex(input))
results.add(input.substring(start,end));
System.out.println(results);
}
}
// Output: [[a-d]+, [r-z]*]
It's hacky and heuristic, but it may work for your purposes.
Not sure if that's what you're asking, but there are several tools out there like RegexBuddy that you can use to analyze regexes.
Some languages like Python provide debug modes for regexes:
>>> import re
>>> re.compile(r"[a-d]+[r-z]*", re.DEBUG)
max_repeat 1 4294967295
in
range (97, 100)
max_repeat 0 4294967295
in
range (114, 122)

Adobe Air - native process communication with exe fails

I'm struggling with Adobe Air native process communication. I'd like to pass an c++ exe shellcommands stored at processArgs when started. The c++ program uses this arguments to choose device channel and symbolrate of an CAN-Bus-Adapter. The c program itself creates an json database for an html page. While the c program is processing i'd like to get some feedback of the program and if it exits adobe air should create a link for the html page with the function onExit. The c program uses standart output of iostream lib ("cout", "cerr") to send messages to adobe air.
Adobe Air script:
var process;
function launchProcess()
{
if(air.NativeProcess.isSupported)
{
setupAndLaunch();
}
else
{
air.Introspector.Console.log("NativeProcess not supported.");
}
}
function setupAndLaunch()
{
var cpp_device = $( "#device option:selected" ).val();
var cpp_channel= $("#channel option:selected").text();
var cpp_symbolRate= $("#symbolRate option:selected").val();
air.Introspector.Console.log("CHANNEL",cpp_channel);
air.Introspector.Console.log("Device",cpp_device);
air.Introspector.Console.log("Symbol Rate",cpp_symbolRate);
var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
var file = air.File.applicationDirectory.resolvePath("InteractiveDocumentation.exe");
nativeProcessStartupInfo.executable = file;
var processArgs = new air.Vector["<String>"]();
processArgs.push(cpp_device);
processArgs.push(cpp_channel);
processArgs.push(cpp_symbolRate);
nativeProcessStartupInfo.arguments = processArgs;
process = new air.NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(air.IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(air.IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
process.addEventListener(air.NativeProcessExitEvent.EXIT, onExit);
}
function onOutputData(event)
{
air.Introspector.Console.log("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}
function onErrorData(event)
{
air.Introspector.Console.log("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));
}
function onExit(event)
{
air.Introspector.Console.log("Process exited with ",event.exitCode);
$("#output").html("Start");
}
function onIOError(event)
{
air.Introspector.Console.log(event.toString());
}
$(function()
{
$("#start").click(function()
{
air.Introspector.Console.log("START");
launchProcess();
});
});
the c program is quite long, and here i post only the main part
int main( int argc, char *argv[])
{
//! get shell commands for init
// echo shell commands
for( int count = 0; count < argc; count++ )
{
cout << " argv[" << count << "] "
<< argv[count];
}
// handle data
intDevice = (int)(argv[1][0] - '0');
intChannel = (int)(argv[2][0] - '0');
intChannel -= 1;
intSymbolRate = atoi(argv[3]);
//! class function calls
useDll CanFunction;
try
{
CanFunction.initProg();
CanFunction.ecuScan();
CanFunction.openSession();
CanFunction.readECU();
CanFunction.stopProg();
return 0;
}
//! exception handling
catch(int faultNumber)
{
....
}
}
First I used only the onExit listener and everything works fine. After I used start conditions adobe air only responses if i call no class functions except the CanFunction.initProg() and the onExit function was called but skipped the jQuery command to create the link. If I add the class function calls, the c program is called and the json database created but Adobe Air doesnt received any responses. The json database is still created. This confuses me.
My c program uses some *.dll files to communicate with the bus so i could imagine that it is a windows problem. But it is still weird.
Has anybody an idea why adobe air communication doesnt work with my c program if i call my class functions or why the jQuery command is skipped?
Or is there a better solution to call a c++ exe from adobe air?

I can't grab single characters by voice from the user in the GDK

So I need to grab single characters from the user in google glass. This is for entering passwords, captchas, spelling user names, etc. I've tried using the sample code:
private static final int SPEECH_REQUEST = 0;
private void displaySpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
startActivityForResult(intent, SPEECH_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SPEECH_REQUEST && resultCode == RESULT_OK) {
List<String> results = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
String spokenText = results.get(0);
// Do something with spokenText.
}
super.onActivityResult(requestCode, resultCode, data);
}
But it seems to try and always interpret what I'm saying as words. It works okay for numbers, but when trying to spell characters like a password, I get random results.
You could try using this method and passing in an array of letters, you can also run this within an activity so you could keep on the same page, just adding each letter to a view as it is heard and carry on listening until you it hears 'finish' or something similar.

Glass Throwing Error

I have some questions regarding my block of code. I've tried running it in Netbeans and it doesn't seem to like this block of code on Google Glass. I compiled it using Eclipse and it seems to compile correctly as well.
package com.openglassquartz.helloglass;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class OnlineRetrieval {
boolean activeGame;
public boolean checkGame() { //Method for which to check if there is a current game going on.
try {
URL url = new URL("http://danielchan.me/league/active.txt");
Scanner s = new Scanner(url.openStream()); //All errors point to this line of code??
int temporary_Reading = s.nextInt();
if(temporary_Reading == 1) {
return activeGame = true;
} else {
return activeGame = false;
}
} catch(IOException ex) {
ex.printStackTrace();
}
return activeGame;
}
}
From the LaunchService Class.
OnlineRetrieval OR = new OnlineRetrieval();
boolean temp_Check = OR.checkGame();
01-14 16:38:32.187: E/AndroidRuntime(18639): at com.openglassquartz.helloglass.OnlineRetrieval.checkGame(OnlineRetrieval.java:20)
01-14 16:38:32.187: E/AndroidRuntime(18639): at com.openglassquartz.helloglass.CardLaunchService.onStartCommand(CardLaunchService.java:77)
How can I fix this? It seems to work on Netbeans when I tried outputting it but not in Google Glass.
Two things to look at (it looks like your stack trace is cut off in your post):
Did you add the android.permission.INTERNET permission to your application's manifest?
Is this code being called in the main UI thread? Network operations must be executed in a background thread – you may want to look at the AsyncTask class as a way of handling this.