Firebase fetch inside for loop not working properly - flutter

In my project, I took data from the android accessibility stream in a headless background function turned them into an array and split them into chunks for firebase limits, and used a for loop to iterate over them and check in firebase. Sometimes this is not working, especially since I can see the associability service runner but showing data from a bit ago. I think this happens when the user is offline and tried to fetch data from firebase. Can you please have a look at this code and tell me what the issue is and How I should solve it?
N.B: I changed some variable names for privacy purposes. There are no issues with them.
FlutterAccessibilityService.accessStream.listen((event) {
if (event.capturedText != null &&
event.capturedText != "" &&
isCold) {
text = event.capturedText!.toLowerCase();
List textList = getArray(text);
final sharedItems = getSimilarArray(fbtag, textList, sensitivity);
final sharedLocalItems =
getSimilarLocalArray(fbtag, textList, sensitivity);
final sharedAbsItems = getAbsLocalArray(fbtag, textList);
final sharedItemWithLastEval =
getSimilarArray(lastEvaluatedText, textList, sensitivity);
if (text != lastEventText &&
(sharedItemWithLastEval.length == 0 ||
lastEvaluatedText[0] == "first")) {
print("called related content");
print("bg currant text: " +
text.toString() +
" sensitivity: " +
sensitivity.toString() +
" minimumAbsMatch: " +
minimumAbsMatch.toString() +
" shared local items: " +
sharedLocalItems.toString() +
" shared abs items: " +
sharedAbsItems.toString() +
" shared items: " +
sharedItems.toString() +
" last : " +
lastEventText +
" last eval text: " +
lastEvaluatedText.toString() +
" Cold: " +
isCold.toString());
print("captured text: " + text.toString());
//GetRelatedContent(fbtag, event.capturedText);
print(sharedItems);
if (sharedLocalItems.length >= accuracy &&
sharedAbsItems.length >= minimumAbsMatch) {
print("main called");
List result = [];
lastEvaluatedText = sharedItems;
List chunkedList = chunking(sharedItems);
for (int i = 0; i < chunkedList.length; i++) {
FirebaseFirestore.instance
.collection('Content')
.where('keyWords', arrayContainsAny: chunkedList[i])
.get()
.then((value) {
for (int i = 0; i < value.docs.length; i++) {
result.add(value.docs[i].data());
print("sep");
print("result: " + result.toString());
}
if (i == chunkedList.length - 1) {
if (result.isNotEmpty) {
print("final result: " +
result[HighestMatchingIndex(sharedItems, result)[0]]
.toString());
print('result length called' +
' result: ' +
result.toString());
if (HighestMatchingIndex(sharedItems, result)[1] >=
accuracy) {
print('overlay called');
isCold = false;
Timer(Duration(seconds: 60), () {
print("Cold down");
isCold = true;
});
var FinalResult = result[
HighestMatchingIndex(sharedItems, result)[0]];
if (FinalResult['availableCountry']
.contains(country) &&
FinalResult['availableR']
.contains(r)) {
print("all passed");
String l = FinalResult[r]
[country] ??
FinalResult[r]['EN'];
String o =
FinalResult[r]['origin'];
ShowAlert(l, o, r);
}
}
}
}
});
}
}
//
}
lastEventText = text;
}
});

Related

LootLocker - How to show local rank

In my game, I am able to show the GlobalRank, however, I would also like to show the position of a player in Ranking according to the global results.
So in the bottom line, there should be the local (on this device) results.
Basically, on the left bottom corner, I want to get the RANK from the LootLocker, but I am struggling to get the rank...
IEnumerator ShowScores()
{
yield return new WaitForSeconds(2);
LootLockerSDKManager.GetScoreList(ID, maxScores, (response) =>
{
if (response.success)
{
LootLockerLeaderboardMember[] scores = response.items;
for (int i = 0; i < scores.Length; i++)
{
playerNames[i].text = (scores[i].member_id +"");
playerScores[i].text = (scores[i].score +"");
playerRank[i].text = (scores[i].rank + "");
//Rank of the localPlayer
Rank.text = (scores["here_Should_Be_This_Player_ID"].rank + "");
LootLockerSDKManager.GetPlayerName
// Entries[i].text = (scores[i].rank + ". " + scores[i].score + ". " + scores[i].member_id);
}
if (scores.Length < maxScores)
{
for (int i = scores.Length; i < maxScores; i++)
{
// Entries[i].text = (i + 1).ToString() + ". none";
}
}
}
else
{
}
});
}
Fixed it with the LootLocker support team
Step 1 - load LootLocker and get the resonse
Step 2 - load the rank and get the resonse2
Step 3 - use the "Response2.rank from the LootLocker
Rank.text = (response2.rank + "");
string playerIdentifier = "PlayerNameRecordOnThisDevice";
LootLockerSDKManager.StartSession(playerIdentifier, (response) =>
{
if (response.success)
{
Debug.Log("session with LootLocker started");
}
else
{
Debug.Log("failed to start sessions" + response.Error);
}
LootLockerSDKManager.GetMemberRank(ID, playerIdentifier, (response2) =>
{
if (response2.statusCode == 200)
{
Debug.Log("GetMemberRank Successful");
}
else
{
Debug.Log("GetMemberRank failed: " + response2.Error);
}
Rank.text = (response2.rank + "");
});
}); ```

Splitting a string Value into chunks of a certain size

public static void SplittingStringIntoChunksCounts(string InputValue)
{
int ChunkSize = 5;
InputValue = "TestingManualTestingAutomTesting";
Dictionary<string, int> dictValue = new Dictionary<string, int>();
for (int i = 0; i < InputValue.Length; i += chunkSize)
{
if (i + chunkSize <= InputValue.Length)
{
Console.WriteLine(InputValue.Substring(i, chunkSize));
string tempValue = InputValue.Substring(i, chunkSize);
if (dictValue.ContainsKey(tempValue))
//if (!dictValue.ContainsKey(tempValue))
{
dictValue[tempValue]++;
//dictValue[tempValue] = 0;
}
else { dictValue[tempValue] = 1; }
// dictValue[tempValue]++;
}
}
foreach (var item in dictValue)
{
Console.WriteLine("Input User== " + " " + item.Key + " " + "Number of Time" + " " + item.Value);
}
}
foreach (var item in dictValue)
{
Console.WriteLine("Input User== " + " " + item.Key + " " + "Number of Time" + " " + item.Value);
}

JavaScript - Hangman - Logic Issue

I'm trying to get my Hangman game to check if the letter is found in the word, but as of now it's checking if that letter is found in every character of the word. It won't allow me to guess again after the first guess.
setScreen("WelcomeScreen");
//variables
var WordArray = ["apple", "word", "quiz"];
var currentWord = "";
var wrongCounter = 0;
var bodyPartCounter = 0;
var Guess = "";
//Welcome Screen Code
onEvent("letsGoBtn", "click", function () {
setScreen("playingHangmanScreen");
generateWord();
setUpScreenElements();
});
function generateWord() {
currentWord = WordArray[randomNumber(0,2)];
console.log(currentWord);
}
function setUpScreenElements(){
for (var i = 0; i < currentWord.length; i++) {
showElement("letterArea" + [i]);
}
var showCorrectHint = "hintWord" + currentWord;
showElement(showCorrectHint);
console.log(showCorrectHint);
}
//Guessing Code
onEvent("submitBtn", "click", function () {
Guess = getText("guessInputTxt");
console.log("The guess for " + currentWord + " is: " + Guess);
checkGuess();
});
function checkGuess() {
for (var i = 0; i < currentWord.length; i++) {
if (Guess == currentWord.charAt([i])) {
setText("letterArea" + [i], Guess);
console.log("Correctly guessed letter is: " + currentWord.charAt([i]));
}
else {
wrongCounter++;
console.log("wrongCounter for " + currentWord + " is: " + wrongCounter);
if (wrongCounter == currentWord.length) {
bodyPartCounter++;
showElement("wrongGuessImg" + bodyPartCounter);
setText("livesLeftNumber", (6-bodyPartCounter));
}
if (bodyPartCounter === 6) {
setScreen("gameOverScreen");
}
}
}
resetGuessInput();
}
function resetGuessInput () {
setText("guessInputTxt", " ");
Guess = " ";
wrongCounter = 0;
}
//Game Over Screen and Play Again Button
onEvent("playAgainBtn", "click", function () {
hideElement("hintWord" + currentWord);
generateWord();
setUpScreenElements();
setScreen("playingHangmanScreen");
for (var i = 0; i <currentWord.length; i++) {
setText("letterArea" + [i], " ");
}
for (var j = 1; j < 7; j++) {
hideElement("wrongGuessImg" + [j]);
}
bodyPartCounter = 0;
wrongCounter = 0;
setText("livesLeftNumber", "6");
});
//Victory Screen
onEvent("goHomeBtn", "click", function() {
setScreen("WelcomeScreen");
});
I've attached the code, as well as, included the link to see the app in action.
Here's a link to the app
Thanks in advance!
The checkGuess function needs to first determine where the letter appears in the word (or not), and then update the board one time, instead of updating it for each character:
function checkGuess() {
var foundAtIndex = -1;
for (var i = 0; i < currentWord.length; i++) {
if (Guess == currentWord.charAt([i])) {
foundAtIndex = i;
break;
}
}
if (foundAtIndex >= 0) {
setText("letterArea" + [foundAtIndex], Guess);
// etc...
Luckily, Javascript provides a nice IndexOf function for strings, so you can remove the loop entirely and condense that first part into:
var foundAtIndex = currentWord.indexOf(Guess);

How do you append text in CodeMirror

I know you use
editor.setValue("");
to set one value but how do you append in CodeMirror?
IE:
editor.appendText();?
Use replaceRange. For example editor.replaceRange(myString, CodeMirror.Pos(editor.lastLine())). Re-setting the entire editor is needlessly expensive.
Here is a little script I wrote to add code to any editor (in Joomla):
function addCodeToEditor(code_string, editor_id, merge, merge_target){
if (Joomla.editors.instances.hasOwnProperty(editor_id)) {
var old_code_string = Joomla.editors.instances[editor_id].getValue();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
Joomla.editors.instances[editor_id].setValue(_string.trim());
return true;
}
} else {
Joomla.editors.instances[editor_id].setValue(code_string.trim());
return true;
}
} else {
var old_code_string = jQuery('textarea#'+editor_id).val();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
jQuery('textarea#'+editor_id).val(_string.trim());
return true;
}
} else {
jQuery('textarea#'+editor_id).val(code_string.trim());
return true;
}
}
return false;
}
The advantage it this script is you can work with multiple editors on the page.

Copy MongoDb indexes between databases

I am trying to copy mongo indexes between two environments. Checked the API and found no direct method of doing it. So I started writing a script that connects to one db, iterates over the collections, grabs indexes, mutates them (because getIndexes() and ensureIndex()) have different format), connects to the other db, wipes the indexes and copies the new ones in.
This all feels slightly over the top so I think that I must be missing something.
Any suggestions/good practices? Apart from having an index creation strategy.
Cheers!
Please run it on the database that you want to copy indexes.
db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
indexes.forEach(function (c) {
opt = ''
ixkey = JSON.stringify(c.key, null, 1).replace(/(\r\n|\n|\r)/gm,"")
ns = c.ns.substr(c.ns.indexOf(".") + 1, c.ns.length)
for (var key in c) {
if (key != 'key' && key != 'ns' && key != 'v') {
if (opt != '') { opt+= ','}
if (c.hasOwnProperty(key)) {
if (typeof(c[key]) == "string") {
opt += (key + ': "' + c[key] + '"')
} else {
opt+= (key + ": " + c[key])
}
}
}
}
if (opt != '') { opt = '{' + opt + '}'}
print ('db.' + ns + '.ensureIndex(' + ixkey + ','+ opt + ')')
})});
I've updated script of Adamo Tonete
db.getCollectionNames().forEach(function(col) {
var indexes = db[col].getIndexes();
indexes.forEach(function (c) {
var fields = '', result = '', options = {};
for (var i in c) {
if (i == 'key') {
fields = c[i];
} else if (i == 'name' && c[i] == '_id_') {
return;
} else if (i != 'name' && i != 'v' && i != 'ns') {
options[i] = c[i];
}
}
var fields = JSON.stringify(fields);
var options = JSON.stringify(options);
if (options == '{}') {
result = "db." + col + ".createIndex(" + fields + "); ";
} else {
result = "db." + col + ".createIndex(" + fields + ", " + options + "); ";
}
result = result
.replace(/{"floatApprox":-1,"top":-1,"bottom":-1}/ig, '-1')
.replace(/{"floatApprox":(-?\d+)}/ig, '$1')
.replace(/\{"\$numberLong":"(-?\d+)"\}/ig, '$1');
print(result);
});
});
Try with this script:
var i, c,
co_name, co_new,
co_old, co_old_i,
_db = db.getSiblingDB('logs'),
_colls = ['activity.games', 'activity.session', 'activity.social', 'activity.store'];
for (i in _colls){
co_name = _colls[i];
co_old = _db[co_name];
co_old_i = co_old.getIndexes();
if(co_old.count() > 0){
co_old.renameCollection(co_name + '.old');
_db.createCollection(co_name);
co_new = _db[co_name];
for(c in co_old_i){
co_new.ensureIndex(co_old_i[c].key);
}
}
}
https://gist.github.com/alejandrobernardis/8261327
Regards,
A
Here is a version to recreate them all with options, and with the new createIndex command instead of ensureIndex (since mongoDB 3.0). With that, it's very easy to copy (recreate) all indexes from one DB to another.
function createIndex2( coll, keys, options ) {
var ret = db[coll].createIndex(keys, options)
if (ret.createdCollectionAutomatically) print( "Collection " + coll + " was created")
if (ret.errmsg || (ret.note != "all indexes already exist" && ret.ok != 1)) {
ret.coll = coll
ret.keys = keys
ret.options = options
print(tojson(ret))
} else {
//print( "Everything normal", JSON.stringify(ret))
}
}
db.getCollectionInfos().forEach(function(coll) {
//print( JSON.stringify( coll ))
if (coll.type === "collection" ) {
db[coll.name].getIndexes().forEach(function(index) {
if ("_id_" !== index.name) {
//print( JSON.stringify( index ))
var indexKey = index.key // save the key, and transform index into the "options"
delete index.key
delete index.ns // namespace - not necessary
delete index.v // not necessary
index.background = true // optional: force background to be true
//native version: print("db." + coll.name + ".createIndex(" + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
// this gives much more debug info
print("createIndex2(\"" + coll.name + "\", " + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
}
});
}
});
The result looks like that if using the "native" version, otherwise, it will display only errors:
db.dishes.createIndex({"submenu":1},
{"name":"submenu_1","ns":"dishly.dishes","background":true})
db.dishes.createIndex({"loc":"2dsphere"},
{"name":"loc_2dsphere","ns":"dishly.dishes","2dsphereIndexVersion":3,"background":true})
db.dishes.createIndex({"rs":-1},
{"name":"rs_-1","ns":"dishly.dishes","partialFilterExpression":{"rs":{"$gte":3}},"background":true})
db.dishes.createIndex({"loc":"2d","type":1,"status":1,"FSid":1,"rs":-1},
{"name":"loc_2d_type_1_status_1_rs_-1","ns":"dishly.dishes","background":true,"partialFilterExpression":{"rs":{"$gte":2}}})
db.dishes.createIndex({"_fts":"text","_ftsx":1,"loc.0":1,"loc.1":1,"rs":-1},
{"name":"d2_menu_submenu_text__loc__rs","ns":"dishly.dishes","background":true,"weights":{"d2":1,"menu":1,"submenu":1},"default_language":"english","language_override":"language","textIndexVersion":3})