How can I determine if user's input is empty? - parsing

I am writing code to generate a JavaCC parser, which will read a user's input and check if it is in any one of a set of languages defined in my code.
One condition on allowable input is that it must not be empty - i.e., the user must enter some block of characters (with length greater than or equal to 1) other than white space " ".
I would like to be able to determine if the user's input is empty, so that an error message can be printed out on the screen in that case.
I have written a production (a.k.a rule) that gets the user's input; it's called Input() and is declared to be void.
In the main method, I have tried to write code which determines if the user's input is empty, by writing:
if parser.Input() == null {
// print error message onto the screen
}
However, I get an error message on the terminal when I try to compile, stating that a 'void' type is not allowed here (I am sure this is referring to Input).
Could I please have a hint/hints for getting around this issue?

Write the Input production like this
boolean Input() : {
} {
<EOF>
{return true;}
|
... // other possibilities here
{return false;}
}
Then, in the main method, you can write
if( parser.Input() ) {
... // report error
}
This solves the problem of reporting the error.
However you may also want to report the language found. For that you could make an enumeration type and have Input return a member of the enumeration. EMPTY could be one of the possibilities.
Language lang = parser.Input() ;
switch( lang ) {
case EMPTY:
... // report error
break ;
case LANGA:
...
break ;
... // etc.
}

Change your type method so this can return a value and you can validate the result, when you do this but change the comparison like this:
if null==parser.Input(){
//print error message on screen
}
Another option is to validate data inside your Input method so you keep it like void.

Related

Should I use Exceptions while parsing complex user input

when looking for Information when and why to use Exceptions there are many people (also on this platform) making the point of not using exceptions when validating user-input because invalid input is not an exceptional thing to happen.
I now have the case where I have to parse a complex string of user input and map it to an Object-Tree basically, similar to a Parser.
Example in pseudo code:
input:
----
hello[5]
+
foo["ok"]
----
results in something like that:
class Hello {
int id = 5
}
class Add {}
class foo {
string name = 'ok'
}
Now in order to "validate" that input I have to parse it, having code that parses the input for validation and code to create the objects separately feels redundant.
Currently I'm using Exceptions while parsing single tokens to collect all Errors.
// one token is basically a single
try {
foreach (token in tokens) {
factory = getFactory(token) // throws ParseException
addObject(factory.create(token)) // throws ParseException
}
} catch (ParseException e) {
// e.g. "Foo Token expects value to be string"
addError(e)
}
is this bad use of exceptions?
An alternative would be to inject a validation class in every factory or mess around with return types (feels a bit dirty)
If exceptions work for your use case, go for it.
The usual problem with exceptions is that they don't let you fix things up and continue, which makes it hard to implement parser error recovery. You can't really fix up a bad input, and you probably shouldn't even in cases where you could, but error recovery lets you report more than one error from the same input, which is often considered convenient.
All of that depends on your needs and parsing strategy, so there's not a lot of information to go on here.

How to access shadowed DXL variables/functions?

I encountered an error in a script I was debugging because somebody had created a variable with a name matching a built-in function, rendering the function inaccessible. I got strange errors when I tried to use the function, like:
incorrect arguments for (-)
incorrect arguments for (by)
incorrect arguments for ([)
incorrect arguments for (=)
Example code:
int length
// ...
// ...
string substr
string str = "big long string with lots of text"
substr = str[0:length(str)-2]
Is there a way to access the original length() function in this situation? I was actually just trying to add debug output to the existing script, not trying to modify the script, when I encountered this error.
For now I have just renamed the variable.
Well, in the case that you had no chance to modify the code, e.g. because it is encrypted you could do sth like
int length_original (string s) { return length s }
<<here is the code of your function>>
int length (string s) {return length_original s }

Is there a way to print a console message with Flutter?

I'm debugging an app, but I need to know some values in the fly, I was wondering if there's a way to print a message in console like console.log using Javascript.
I appreciate the help.
print() is probably what you are looking for. Here's some more info on debugging in flutter.
You can use
print()
function or
debugPrint()
The debugPrint() function can print large outputs.
There are more helpful methods in import 'dart:developer' library and one of them is log().
example:
int i = 5;
log("Index number is: $i");
//output
[log] Index number is: 5
void log(String message, {DateTime time, int sequenceNumber, int level
= 0, String name = '', Zone zone, Object error, StackTrace stackTrace})
Emit a log event.
This function was designed to map closely to the logging information
collected by package:logging.
[message] is the log message
[time] (optional) is the timestamp
[sequenceNumber] (optional) is a monotonically increasing sequence number
[level] (optional) is the severity level (a value between 0 and 2000); see the package:logging Level class for an overview of the
possible values
[name] (optional) is the name of the source of the log message
[zone] (optional) the zone where the log was emitted
[error] (optional) an error object associated with this log event
[stackTrace] (optional) a stack trace associated with this log event
Read more.:
print() is from dart:core and its implementation:
/// Prints a string representation of the object to the console.
void print(Object object) {
String line = "$object";
if (printToZone == null) {
printToConsole(line);
} else {
printToZone(line);
}
}
debugPrint():
/// Prints a message to the console, which you can access using the "flutter"
/// tool's "logs" command ("flutter logs").
///
/// If a wrapWidth is provided, each line of the message is word-wrapped to that
/// width. (Lines may be separated by newline characters, as in '\n'.)
///
/// By default, this function very crudely attempts to throttle the rate at
/// which messages are sent to avoid data loss on Android. This means that
/// interleaving calls to this function (directly or indirectly via, e.g.,
/// [debugDumpRenderTree] or [debugDumpApp]) and to the Dart [print] method can
/// result in out-of-order messages in the logs
// read more here: https://api.flutter.dev/flutter/foundation/debugPrint.html
DebugPrintCallback debugPrint = debugPrintThrottled;
/// Alternative implementation of [debugPrint] that does not throttle.
/// Used by tests.
debugPrintSynchronously(String message, { int wrapWidth })
/// Implementation of [debugPrint] that throttles messages. This avoids dropping
/// messages on platforms that rate-limit their logging (for example, Android).
void debugPrintThrottled(String message, { int wrapWidth })
Read more.
Note that only the print() is taking any type and print to the console. debugPrint() and log() only take String. So, you have to add .toString() or use string interpolation like I shown in provided example snippet.
I tend to do something similar to this
Foo foo;
try{
foo = _someMethod(); //some method that returns a new object
} catch (e) {
print('_someMethod: Foo Error ${foo.id} Error:{e.toString()}'); /*my custom error print message. You don't need brackets if you are printing a string variable.*/
}
Use debug print to avoid logging in production application.
debugPrint("Message");
You can also disable or change debug print implementation in main.dart or any other file like this:
debugPrint = (String message, {int wrapWidth})
{
debugPrintThrottled(message);//Or another other custom code
};
print, debugPrint and others have got some word limit restrictions, if you have something long to print on console, you can:
Create this method:
void printWrapped(String text) {
final pattern = RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
Usage:
printWrapped("Your very long string ...");
Source
One more answer for Concatenate with String:
// Declaration
int number = 10;
//Button Action
RaisedButton(
child: Text("Subtract Me"),
onPressed: () {
number = number - 1;
print('You have got $number as result');
print('Before Value is ${number - 1} and After value is ${number + 1}');
},
),
//Output:
flutter: You have got 9 as result
flutter: Before Value is 8 and After value is 10
debugPrint()
Might as well use rather than print() as it attempts to reduce log line drop or being out of order on Android kernel
Refs:
Logging in Flutter
I think this might help you, because, I was also got stuck in many ways of knowing the output of my code in the dart file, hence I got the solution by following the steps, shown in the video.
https://www.youtube.com/watch?v=hhP1tE-IHos
here I have shown an instance of how it works after following the video.
check the left side column where it shows about the value which profile variable carry i.e., null
you can simply use print('whatever you want to print') same as console.log() in javascript.
for more info you can check here.
Note that the print() and log() options both add their own labels at the start of the line, and apply additional formatting that can cause long lines to be truncated. In the case of a dart:io app, you can bypass this interception and mangling entirely by going directly to stdout/stderr, etc. as in stdout.write(), stdout.writeln(), etc. Likewise if you are looking to log explicitly to one or the other. I ran into this issue when adding CLI args to a flutter application.
I use something like this. The print() function can print data up to some limit. So I use this log.
import 'dart:developer';
debugLog({String tag = '', required dynamic value}) {
log("TAG $tag : ${value.toString()}");
}

element.setCustomValidity( num message )

In Darts API, the method
element.setCustomValidity(num message)
has a number as the argument. I was expecting the type of the message to be a String. Is this an error?
I created an issue https://github.com/Polymer/core-input/issues/41
The Dart element uses information from JS comments to generate type annotations and the comment in the JavaScript element contains the wrong type information.
As a workaround you can call the JS function directly:
void setCustomValidity(CoreInput inp, String message) {
inp.jsElement.callMethod('setCustomValidity', ["Give me more!"]);
}
see also Taking total control of PaperInput validation

Metatrader MQL4: Can't define function default values in .mqh file

I can't understand how to define default values for functions in my library. Default values tend to be ignored and I get "wrong parameters count" error message.
Here is my example. I created simple test library experts\libraries\test.mq4:
void test(int i = 0) // Note the default value for "i"
{
}
Then I created .mqh file as experts\include\test.mqh:
#import "test.ex4"
void test(int i = 0); // Note the default value for "i"
#import
Now I create simple expert "experts\simpletest.mq4":
#include <test.mqh>
int start()
{
// Should be able to call test() function without providing any arguments,
// because it has default value.
// If I change this line to test(0), everything compiles correctly
test(); // Causes "wrong parameters count" compilation error
return(0);
}
And I get the following error for test() function call:
')' - wrong parameters count
If I change this function call to test(0), everything compiles, but I should be able to call test() function without providing any parameters, because I have default value for first parameter in .mqh file, like this: void test(int i = 0);
Why it doesn't use the default value?
I search google for any clue, but can't find any references about this problem. Anybody knows?
This is not possible as stated in the MQL Documentation:
MQL4-library functions imported within other modules cannot have parameters initialized by default values.

Resources