Crash when encode mutable map - ios

I got crash when try to encode to string a mutable map
internal class AsyncStorageHolder(
var manifest: MutableMap<String, String> = mutableMapOf(),
var hasCheatedStorageDirectory: Boolean = false,
var haveSetup: Boolean = false
)
private val asyncStorageHolder = IsolateState { AsyncStorageHolder() }
private fun writeManifest() {
val json = Json {
encodeDefaults = true
ignoreUnknownKeys = true
}
asyncStorageHolder.access {
val error: CPointer<ObjCObjectVar<NSError?>>? = null
val serialized = json.encodeToString(it.manifest) as NSString
serialized.writeToFile(
createStorageDirectoryPath(getManifestFilePath()),
true,
NSUTF8StringEncoding,
error
)
}
}
Log crash
DefaultAuthStateRepository.setState - setState error: kotlin.native.concurrent.FreezingException: freezing of Continuation # 147 has failed, first blocker is vn.momo.core.modules.storage.async.AsyncStorageModuleImpl.AsyncStorageHolder#2bc5be8

Related

Toggle a boolean within a struct in zig, possible?

To toggle* a boolean I normally use boolean = !boolean like this:
var boolean: bool = true;
boolean = !boolean;
std.debug.print("My bool is: {}\n", .{boolean}); //My bool is: false
But how do I achieve this for booleans within a struct? Or is it not possible?
const std = #import("std");
pub fn main() void {
//Struct with default values:
const animal = struct {
tail: bool = true,
wings: bool = false,
horns: bool = false,
paws: bool = true,
};
//Struct instances:
var has = animal{};
//This works alright:
//var hasno = animal{.tail = false, .wings = true, .horns = true, .paws = false};
//FAILS: error: expected type 'bool', found '#TypeOf(.enum_literal)'
var hasno = animal{ .tail = !.tail }; //, .wings = !.wings, .horns = !.horns, .paws = !.paws };
//Debug printing:
std.debug.print("Animal has tail: {}, wings: {}, horns: {}, paws: {}\n", .{ has.tail, has.wings, has.horns, has.paws });
std.debug.print("Animal has no tail: {}, wings: {}, horns: {}, paws: {}\n", .{ hasno.tail, hasno.wings, hasno.horns, hasno.paws });
}
Test code for yourself online in zig playground:
https://zig-play.dev
*give it the opposite value of what it was, without knowing what it was.
Like if (boolean == true) boolean = false; else boolean = true; But I'm wondering if it is possible with the (bang) operator for booleans within struct.
const std = #import("std");
const Animal = struct {
tail: bool,
};
pub fn main() void {
var animal = Animal { .tail = true };
std.debug.print("{}\n", .{ animal });
animal.tail = !animal.tail;
std.debug.print("{}\n", .{ animal });
}
Prints:
main.Animal{ .tail = true }
main.Animal{ .tail = false }

How to translate NSOutputStream to InputStream?

I try to write code for iOS to upload files via Ktor using Stream but I don't know how to connect iOS stream to Android streams or Kotlin cannels.
I use the below code for Android.
private suspend fun uploadFiles(
uriList: List<Uri>,
contentResolver: ContentResolver,
entity: String,
objectId: String
): Map<String, Boolean>? {
val inputStreamMap = mutableMapOf<String, InputStream>()
uriList.forEach {
val inputStream = contentResolver.openInputStream(it) ?: return#forEach
val fileName = contentResolver.query(
it, null, null, null, null
)?.run {
val displayNameIndex = getColumnIndex(OpenableColumns.DISPLAY_NAME)
moveToFirst()
val displayName = getString(displayNameIndex)
close()
displayName
} ?: return#forEach
inputStreamMap[fileName] = inputStream
}
val channels = inputStreamMap.mapValues {
object : OutgoingContent.WriteChannelContent() {
override suspend fun writeTo(channel: ByteWriteChannel) {
it.value.copyTo(channel.toOutputStream(), 1024)
}
override val contentType = ContentType.Application.OctetStream
override val contentLength: Long = it.value.available().toLong()
}
}
val result = useCases.uploadFiles(channels, entity, objectId)
inputStreamMap.values.forEach { it.close() }
return result
}

converting string to map in dart

I wanted to convert a string to map.
String value = "{first_name : fname,last_name : lname,gender : male, location : { state : state, country : country, place : place} }"
into
Map = {
first_name : fname,
last_name : lname,
gender : male,
location = {
state : state,
country : country,
place : place
}
}
How do I convert the string into a map<String, dynamic> where the value consists of string, int, object, and boolean?
I wanted to save the string to a file and obtain the data from the file.
That's not possible.
If you can change the string to valid JSON, you can use
import 'dart:convert';
...
Map valueMap = json.decode(value);
// or
Map valueMap = jsonDecode(value);
The string would need to look like
{"first_name" : "fname","last_name" : "lname","gender" : "male", "location" : { "state" : "state", "country" : "country", "place" : "place"} }
You would have to change the way you create the string.
I'm guessing you are creating the string using the yourMap.toString() method. You should rather use json.encode(yourMap), which converts your map to valid JSON, which you can the parse with json.decode(yourString).
create two objects
class User {
final String firstName;
final String lastName;
final String gender;
final location;
User({
this.firstName,
this.lastName,
this.gender,
this.location,
});
User.fromJson(Map json)
: firstName = json['firstName'],
lastName = json['lastName'],
gender = json['gender'],
location = Location.fromJson(json['location']);
}
class Location {
final String state;
final String country;
final String place;
Location({
this.state,
this.country,
this.place,
});
Location.fromJson(Map json)
: state = json['state'],
country = json['country'],
place = json['place'];
}
then use it like this
var user = User.fromJson(value);
print(user.firstName);
or convert it to list like this
var user = User.fromJson(value).toList();
you can do like this ->
import 'dart:convert';
...
if your data like this **
{'bus1':'100Tk','bus2':'150TK','bus3':'200TK'}
**;
then you can do like this ->
Map valueMap = json.decode(value);
// or
Map valueMap = jsonDecode(value);
or if like this ->var data = {'1':'100TK','2':'200TK','3':'300TK'};
var dataSp = data.split(',');
Map<String,String> mapData = Map();
dataSp.forEach((element) => mapData[element.split(':')[0]] = element.split(':')[1]);
Note: Map first value was Int that's why I did that.
Make a wrapper class for the location where you define the methods fromMap, toMap
Yeah, that's not possible.
But i have workaround to fix that.
Remove space in ur invalid json
Fix ur invalid string json to valid string json
Convert valid string json to map
Here's the full code for above process:
import 'dart:convert';
void main() {
String value = "{first_name : fname,last_name : lname,gender : male, location : { state : state, country : country, place : place} }";
String jsonString = _convertToJsonStringQuotes(raw: value);
print("Test 1: $jsonString");
final Map<dynamic, dynamic> result = json.decode(jsonString);
print('Test 2: $result');
}
String _convertToJsonStringQuotes({required String raw}) {
/// remove space
String jsonString = raw.replaceAll(" ", "");
/// add quotes to json string
jsonString = jsonString.replaceAll('{', '{"');
jsonString = jsonString.replaceAll(':', '": "');
jsonString = jsonString.replaceAll(',', '", "');
jsonString = jsonString.replaceAll('}', '"}');
/// remove quotes on object json string
jsonString = jsonString.replaceAll('"{"', '{"');
jsonString = jsonString.replaceAll('"}"', '"}');
/// remove quotes on array json string
jsonString = jsonString.replaceAll('"[{', '[{');
jsonString = jsonString.replaceAll('}]"', '}]');
return jsonString;
}
To convert a string into a map<String, dynamic>, you can use the
following code:
String value = "{first_name : fname,last_name : lname,gender : male, location : { state : state, country : country, place : place} }";
String result = value
.replaceAll("{","{\"")
.replaceAll("}","\"}")
.replaceAll(":","\":\"")
.replaceAll(",","\",\"");
print(result);
Here, we first replace the opening and closing curly braces with double quotes, and then replace the colons and commas with quotes to create a valid JSON string. Then, we use the jsonDecode method to convert the JSON string into a map.
I found a way to cast that string
Ok, lets use a complex model to cast:
final testMap = {
'userName': 'Igor',
'age': 22,
'totalCash': 138.57,
'isMale:': true,
'userStatus': {
'isUserActive': true,
'isAPremiumUser': false,
},
'userTags': ['Flutter Developer', 'Proactive', 'Clean code'],
'userCourses': [
{
'title': 'How to use TDD in flutter',
'finished': false,
'coursePercentage': 47.4,
'buyDate': '1969-07-20T20:18:04.000Z',
'courseTag': ['New', 'Popular'],
'courseDetails': null,
},
{
'title': 'Clean arquiteture in flutter',
'finished': false,
'coursePercentage': 20.8,
'buyDate': '1969-07-20T20:18:04.000Z',
'courseTag': ['New'],
'courseDetails': {
'teacherName': 'Tayler Mostoult',
'totalSubscribers': 5402,
},
},
{
'title': 'Micro-frontends in flutter',
'finished': true,
'coursePercentage': 100.0,
'buyDate': '1969-07-20T20:18:04.000Z',
'courseTag': [],
'courseDetails': {},
},
]
};
Know, cast it to string:
final testMapInStringFormat = testMap.toString();
To convert this String to map, we can use:
final String response = _getJsonFromString(testMap.toString());
final Map jsonConvertido = jsonDecode(response); // Decoded, back to map format
The function that will effectively do the casting:
String _getJsonFromString(String rawText) {
// Will find, for exemple, the text: "{isUserActive:"
final regexMapKeyWithOpenBracket = RegExp('(?<={)(.*?):+');
// Will find, for exemple, the text: ", userCourses:"
final regexMapKeyWithCommaAndSpace = RegExp(r'(?<=, )([^\]]*?):');
final regexOnlyKeyInLine = RegExp(r'^.+:$');
final splitedSentences = rawText
.replaceAllMapped(regexMapKeyWithCommaAndSpace,
(Match match) => '\n${match.text.trim()}\n')
.replaceAllMapped(regexMapKeyWithOpenBracket,
(Match match) => '\n${match.text.trim()}\n')
.replaceAll(RegExp(r'}(?=,|]|}|$|\s+)'), '\n}\n')
.replaceAll(RegExp(r'(?<=(,|:|^|\[)\s?){'), '\n{\n')
.replaceAll(RegExp('\\[\\s?\\]'), '\n[\n]\n')
.replaceAll(RegExp('\\{\\s?\\}'), '\n{\n}\n')
.split('\n')
..removeWhere((element) => element.replaceAll(' ', '').isEmpty);
final List<String> correctLines = [];
for (String line in splitedSentences) {
final isMapKey = regexOnlyKeyInLine.hasMatch(line);
if (isMapKey) {
final lineWithoutFinalTwoDots = line.substring(0, line.length - 1);
final lineWithQuaot = _putQuotationMarks(lineWithoutFinalTwoDots);
correctLines.add('$lineWithQuaot:');
} else {
String l = line.trim();
// If it falls in this else, it is a value of a key or a map structure
final isNumber = double.tryParse(l) != null || int.tryParse(l) != null;
final isBolean = l == 'false' || l == 'true';
final isStructureCaracter = ['{', '}', '[', ']', ','].any((e) => e == l);
final isNull = l == 'null';
if (isStructureCaracter || isNumber || isBolean || isNull) {
correctLines.add(l);
continue;
}
final hasCommaInFinal = l.endsWith(',');
if (hasCommaInFinal) {
l = l.substring(0, l.length - 1);
}
// If you got to this point, i'm sure it's a value string, so lets add a double quote
final lineWithQuaot = _putQuotationMarks(l);
if (hasCommaInFinal) {
correctLines.add('$lineWithQuaot,');
} else {
correctLines.add(lineWithQuaot);
}
}
}
return correctLines.join('');
}
extension MatchExtension on Match {
String get text => input.substring(start, end);
}
String _putQuotationMarks(String findedText) {
if (!findedText.startsWith('\'') && !findedText.startsWith('"')) {
findedText = findedText[0] + findedText.substring(1);
}
if (!findedText.endsWith('\'')) {
final lastIndex = findedText.length - 1;
findedText = findedText.substring(0, lastIndex) + findedText[lastIndex];
}
return '"$findedText"';
}
Use below method
just pass String json data it will give Map data
jsonStringToMap(String data){
List<String> str = data.replaceAll("{","").replaceAll("}","").replaceAll("\"","").replaceAll("'","").split(",");
Map<String,dynamic> result = {};
for(int i=0;i<str.length;i++){
List<String> s = str[i].split(":");
result.putIfAbsent(s[0].trim(), () => s[1].trim());
}
return result;
}

Regex TypeError: Cannot read property '1' of null

My datepicker regular expression is trying matches on a null aray. How do I fix it? Not sure what clazz should equal if the array is null. I'm thinking a simple if (matches[1]) { etc } but I'm not sure what to do if matches is null. Clazz is used elsewhere twice in the code. Do I just set clazz to null or zero?
var matches = exp.match(IS_REGEXP);
var clazz = scope.$eval(matches[1]);
Edit: Here's where they use clazz
if (data.lastActivated !== newActivated) {
if (data.lastActivated) {
$animate.removeClass(data.lastActivated.element, clazz);
}
if (newActivated) {
$animate.addClass(newActivated.element, clazz);
}
data.lastActivated = newActivated;
}
Here's IS_REGEXP
11111111 22222222
var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/;
Double Edit:
Here's the whole function
function addForExp(exp, scope) {
var matches = exp.match(IS_REGEXP);
var clazz = scope.$eval(matches[1]);
var compareWithExp = matches[2];
var data = expToData[exp];
if (!data) {
var watchFn = function(compareWithVal) {
var newActivated = null;
instances.some(function(instance) {
var thisVal = instance.scope.$eval(onExp);
if (thisVal === compareWithVal) {
newActivated = instance;
return true;
}
});
if (data.lastActivated !== newActivated) {
if (data.lastActivated) {
$animate.removeClass(data.lastActivated.element, clazz);
}
if (newActivated) {
$animate.addClass(newActivated.element, clazz);
}
data.lastActivated = newActivated;
}
};
expToData[exp] = data = {
lastActivated: null,
scope: scope,
watchFn: watchFn,
compareWithExp: compareWithExp,
watcher: scope.$watch(compareWithExp, watchFn)
};
}
data.watchFn(scope.$eval(compareWithExp));
}
Setting clazz to null or empty string shall do, if clazz is all your concern.
var clazz = matches ? scope.$eval(matches[1]) : '';
But with compareWithExp, it might be better to exit from the whole logic when there is no match:
if ( ! matches ) return;

Grails 3 "MissingMethodException" error on domain class save() method (and other methods)

Domain Class:
package com.myapp.gorm.log
import com.myapp.gorm.security.User
import com.myapp.gorm.system.TransactionJournal
class LogJournal {
static constraints = {
message nullable: false
category nullable: false
user1 nullable: false
}
static mapping = {
dateCreated column: "ts"
lastUpdated column: "ts_update"
}
LogMessage message
LogCategory category
User user1
User user2
String value
TransactionJournal transaction
Date dateCreated
Date lastUpdated
boolean equals(o) {
if (this.is(o)) return true
if (getClass() != o.class) return false
LogJournal that = (LogJournal) o
if (category != that.category) return false
if (dateCreated != that.dateCreated) return false
if (id != that.id) return false
if (lastUpdated != that.lastUpdated) return false
if (message != that.message) return false
if (transaction != that.transaction) return false
if (user1 != that.user1) return false
if (user2 != that.user2) return false
if (value != that.value) return false
return true
}
int hashCode() {
int result
result = message.hashCode()
result = 31 * result + category.hashCode()
result = 31 * result + user1.hashCode()
result = 31 * result + (user2 != null ? user2.hashCode() : 0)
result = 31 * result + (value != null ? value.hashCode() : 0)
result = 31 * result + (transaction != null ? transaction.hashCode() : 0)
result = 31 * result + dateCreated.hashCode()
result = 31 * result + (lastUpdated != null ? lastUpdated.hashCode() : 0)
result = 31 * result + id.hashCode()
return result
}
}
Error:
groovy.lang.MissingMethodException: No signature of method: c com.domainboost.gorm.log.LogJournal.save() is applicable for argument types: () values: []
Possible solutions: save(), save(boolean), save(java.util.Map), wait(), last(), any()
Or other domain classes work normally, only this one has a problem. I see grails cannot perform any method on this class instance.
There are no any validation errors.
Where I call this domain class (it's logback: appender):
class SystemAppender extends AppenderBase<ILoggingEvent> {
static appInitialized = false
#Override
public void append(ILoggingEvent event) {
if (appInitialized) {
LogMessage logMessage = LogMessage.findByMessage(event.getMessage())
if (!logMessage) {
logMessage = new LogMessage()
logMessage.message = event.getMessage()
logMessage.save(flash: true)
}
String categoryStr = event.argumentArray[0]
LogCategory logCategory = LogCategory.findByCategory(categoryStr)
if (!logCategory) {
logCategory = new LogCategory()
logCategory.category = categoryStr
logCategory.save(flash: true)
}
User user1 = null
if (event.argumentArray.contains(1)) {
user1 = event.argumentArray[1]
}
User user2 = null
if (event.argumentArray.contains(2)) {
user1 = event.argumentArray[2]
}
TransactionJournal tj = null
if (event.argumentArray.contains(3)) {
tj = event.argumentArray[3]
}
LogJournal logJournal = new LogJournal()
logJournal.category = logCategory
logJournal.message = logMessage
logJournal.user1 = user1
logJournal.user2 = user2
logJournal.transaction = tj
LogJournal.save()
}
}
}
And how I test this in grails console
import org.slf4j.Logger
import org.slf4j.LoggerFactory
def Logger logger = LoggerFactory.getLogger("sysLog")
logger.info("message", "category")
Error is on
LogJournal.save()
The code which ended with an error is in GormStaticApi.groovy
#CompileStatic(TypeCheckingMode.SKIP)
def methodMissing(String methodName, Object args) {
FinderMethod method = gormDynamicFinders.find { FinderMethod f -> f.isMethodMatch(methodName) }
if (!method) {
throw new MissingMethodException(methodName, persistentClass, args)
}
So it seems that method "save" is not found..
WTF ?
This
LogJournal.save()
Is looking for a static method on the class. You want a lower case initial letter to call save on the instance variable:
logJournal.save()

Resources