Is there a way to print the data at a specific address at runtime in Ada(maybe in binary)? I have a variable that is "corrupted" somehow, so I'm not able to do type'Image(var) to print out the data.
If you declare a variable like this:
Debug_View : Whatever_Type_You_Want
with Import => True,
Volatile => True,
Convention => Ada,
Address => Some_Address;
you can read out/adjust the memory contents at Some_Address.
In earlier versions of Ada, you would write this:
Debug_View : Whatever_Type_You_Want;
pragma Import (Ada, Debug_View);
pragma Volatile (Debug_View);
for Debug_View'Address use Some_Address;
Related
I'm trying to connect to MongoDB from my code using mongo_dart package.
So my approach is below,
import 'package:mongo_dart/mongo_dart.dart';
class MongoDB {
late Db db;
MongoDB(
{hosts = const ['myserver1', 'myserver2', 'myserver3'],
port = '27017',
username = 'admin',
password = 'mypassword',
dbname = 'mydb',
authSource = 'admin'}) {
db = Db.pool(
hosts.map((elem) => "mongodb://$username:$password#$elem:$port/$dbname?authSource=$authSource").toList());
}
When executing this code an exception occurs which has the message Expected a value of type 'List<String>', but got one of type 'List<dynamic>' on .toList().
All the parameters are string types, but why does it happen?
Please be aware that i am not an expert on Dart's type inference, but this is probably what is happening:
The host argument for your MongoDB constructor omits specific type information, which does not give the analyzer enough information to infer that you always want a List<String>. So it assumes it to be dynamic
There are multiple way to fix this:
Specify the type in the arguments of the constructor: MongoDB({List<String> hosts = const ['myserver1', 'myserver2', 'myserver3'], ...})
Specify that your map will always return a String and thus toList() will produce a List<String>: hosts.map<String>((elem) => "mongodb://$username:$password#$elem:$port/$dbname?authSource=$authSource").toList()
In C, before using the scanf or gets "stdio.h" functions to get and store user input, the programmer has to manually allocate memory for the data that's read to be stored in. In Rust, the std::io::Stdin.read_line function can seemingly be used without the programmer having to manually allocate memory prior. All it needs is for there to be a mutable String variable to store the data it reads in. How does it do this seemingly without knowledge about how much memory will be required?
Well, if you want a detailed explanation, you can dig a bit into the read_line method which is part of the BufRead trait. Heavily simplified, the function look like this.
fn read_line(&mut self, target: &mut String)
loop {
// That method fills the internal buffer of the reader (here stdin)
// and returns a slice reference to whatever part of the buffer was filled.
// That buffer is actually what you need to allocate in advance in C.
let available = self.fill_buf();
match memchr(b'\n', available) {
Some(i) => {
// A '\n' was found, we can extend the string and return.
target.push_str(&available[..=i]);
return;
}
None => {
// No '\n' found, we just have to extend the string.
target.push_str(available);
},
}
}
}
So basically, that method extends the string as long as it does not find a \n character in stdin.
If you want to allocate a bit of memory in advance for the String that you pass to read_line, you can create it using String::with_capacity. This will not prevent the String to reallocate if it is not large enough though.
I wonder, if a dart or flutter method exists, which returns complete type information about the structure of a variable's value as a string.
E.g., if some print( someValue.toString() ); emits this
{"user":"userName","state":"valid"}
I don't know if it is a Map or a String.
But how do I get a string, which describes a variable's value / structure?
Something, that's like PHP's print_r(), which print stuff like this:
Array
(
[a] => Apfel
[b] => Banane
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
There is nothing like print_r() available natively in Dart.
However, it would be possible to use the following functionalities to build e.g. a function like print_r() from PHP.
You can evaluate the type of someValue using runtimeType.
String someValueType = someValue.runtimeType.toString();
String someValueString = someValue.toString();
If you want to compare, you can also use is. More on that here.
Dart is a strongly typed language, which means that you could also enforce types (List a; String b), which makes a function like print_r() redundant for Dart.
If it is about server-side code you can use reflection to create a function that produces such an output for every value.
If it is about your own classes, you can implement toString() to make the objects render themselves this way when they are printed
class Person {
Foo(this.firstName, this.lastName);
String firstName;
String lastName;
#override
String toString() => '''
firstName: $firstName
lastName: $lastName
''';
}
print(new Person('John', 'Doe'));
Best way to do is
print(”$someValue“);
It will return a structured string which similar to JSON.
In my question Dart 2.X List.cast() does not compose the answer requires converting a List<dynamic> to a List<String> as such:
List<String> ls = (json['data'] as List).cast<String>().map((s) => s.toUpperCase()).toList();
My experience from other languages had me write this first:
List<String> ls = (json['data'] as List<String>).map((s) => s.toUpperCase()).toList();
Note that this compiles but fails at runtime in Dart 2.
Why does Dart typecasting for a List require a function as List).cast<String>() as opposed to simply using the Dart as "typecast operator" such as as List<String>?
---- Edit ----
I am using the most recent Dart 2.0.0-dev.43.0 and get inconsistent runtime behavior with as typecasts/assertions. Isn't the .cast<>() function creating a new iterable the same as a .map()? Changing my code to this works:
List<String> ls = (json['data'] as List).map((s) => (s as String).toUpperCase()).toList();
This seems to take advantage that the first cast to List is a List<dynamic>. Thus the .map function parameter is also a dynamic.
My second example above with to as List<String> works in some places in our code but not others. Note that IntelliJ correctly infers the types in all of the above examples - it's the runtime where the failure happens. I'm guessing that the inconsistent behavior is due to Dart 2.x being still in development.
---- 2nd Edit ----
Here are my test cases that I have in one of my class constructors:
Map<String, dynamic> json = { "data": ["a", "b", "c"] };
//List<String> origBroken = json["data"].map( (s) => s.toUpperCase() ).toList();
// Sometimes works - sometimes gives "Ignoring cast fail from JSArray to List<String>" at runtime!!!
List<String> wonky = (json["data"] as List<String>).map( (s) => s.toUpperCase() ).toList();
print("Wonky $wonky");
List<String> fix1 = (json["data"] as List).cast<String>().map( (s) => s.toUpperCase() ).toList();
List<String> fix2 = (json["data"] as List).map( (s) => (s as String).toUpperCase() ).toList();
List<String> explicit2 = (json["data"] as List<dynamic>).map( (dynamic s) => (s as String).toUpperCase() ).toList();
// From accepted answer of the linked question - compile error because .cast() doesn't take parameters
// error: Too many positional arguments: 0 expected, but 1 found.
//List<String> notBroken = (json['data'] as List).cast<String>((s) => s.toUpperCase()).toList();
List<String> notBrokenFixed = (json['data'] as List<String>).cast<String>().map((String s) => s.toUpperCase()).toList();
The problem is the warning Ignoring cast fail from JSArray to List<String> sometimes given by the wonky assignment. When I say sometimes it's because it changes unpredictably as I make changes to the main application that uses the library that contains this code - without making changes to this class or even the library.
At the time I wrote the first edit above, wonky wasn't working. I just tried it again now and it's working. I have not changed any code in this library - I have been working in the main application which has a dependency on this code's library.
Some background, this is a multi-library project being converted from Angular/Typescript. These test cases are based on the processing we do to deserialize JSON into Dart classes. We map JSON (dynamic) strings into various data structures such as enums, Option<> and Either<> (from dartz) using class constructor initializers.
A couple weeks ago the runtime warning started happening I believe because of Breaking Change: --preview-dart-2 turned on by default.
I understand that this warning will soon be an error. So I traced the warning back to these conversions that map from JSON dynamic data (Yes, dynamic data is an edge case in Dart but it's what dart:convert provides).
We are developing on Mac using DDC with the most recent Dart 2.0.0-dev.43.0, angular 5.0.0-alpha+8, build_runner 0.8.0, IntelliJ 2018.1 and running on Chrome 65.0.3325.181.
---- Final Edit ----
There is an instability in the current development build/runtime that is behind this issue. No, I don't have a reproducible example. Changing and rebuilding our main app will cause this code in an unmodified library dependency to sometimes give the runtime warning Ignoring cast fail from JSArray to List<String>.
The suspect code from the original part of this question (also wonky above)
List<String> ls = (json['data'] as List<String>).map((s) => s.toUpperCase()).toList();
casts the dynamic JSON data to a List<String>. The types are fully constrained and the Dart analyzer/IntelliJ infers s to be Static type: String.
The runtime warning that sometimes occurs and related answers to use .cast() is what led to this question. At this time I'll believe the analyzer and ignore the runtime warning.
In Dart 2 generic types are reified.
as ... is more like an assertion, if the values type doesn't match as causes a runtime exception.
cast<T>() is a method introduced in Dart 2 on Iterable that actually creates a new iterable of type Iterable<T> (or in your case the subclass List<T>) filled with the values of the original interable.
Update
You can use print('wonky: ${wonky.runtimeType}'); to see what the actual type is.
If the type matches your requirement, you can use as to communicate it to the analyzer that it's safe to assume this type.
If the type doesn't match, for example because it is List instead of List<String>, then you can use .cast<String>() to actually make it a List<String>.
List<String> broken = (json['data'] as List)
.cast<String>((s) => s.toUpperCase()).toList();
Here you seem to try to use cast for casting and mapping, but that is not valid.
map() can do both though
List<String> notBroken = (json['data'] as List)
.map<String>((s) => s.toUpperCase()).toList();
The following example (1) reads a file and prints the contents without explicitly assigning the file contents to a variable (ie. “.then(stdout.write)”). However, if I want to do more than just print the contents (2), I need to assign the contents to a variable (I think).
Is it possible to achieve that (print the contents and do more), without assigning the text of the file to a variable?
In the first example, is an implicit variable created? Or, put another way, does example1 use less resources by not creating an explicit variable?
//Example 1:
import 'dart:io';
void main() {
new File(new Options().script)
.readAsString(encoding: Encoding.ASCII)
.then(stdout.write)
.catchError((oError) => print(oError));
print("Reading file ...\n");
}
//Example 2:
import 'dart:io';
void main() {
new File(new Options().script)
.readAsString(encoding: Encoding.ASCII)
.then((String sText) {
stdout.write(sText+"\n\n");
print ('Completed');
})
.catchError((oError) => print(oError));
print("Reading file ...\n");
}
In the first example, this:
.then(stdout.write)
is equivalent to this:
.then((String sText) {
stdout.write(sText);
})
Technically there's one more function call, and you have one more variable, which should cost you a few bytes (I'm not sure on the exact implementation). Strings are immutable; you are only receiving a reference to the String, so you are not saving resources (other than the function call and a few bytes of memory) by using second version.
Whatever it is you want to do with the contents of the String probably will involve using resources, of course, but that shouldn't be an issue unless the file is huge.