Dialogflow fulfillment - How to add multiple agent.add() responses? - flutter

I have a list of firestore snapshot that I want to be as responses to an intent. I declare it into "res" varible and pass it into agent.add but it doesn't work. The "res" variable doesn't print anything.
Here is my code:
async function handlerReadFromDB(agent) {
let uId = agent.originalRequest.payload.uId;
console.log(uId);
const dataRef = db.collection('users').doc(`${uId}`).collection('medic_reminder');
const snapshot = await dataRef.get();
var med={};
var medObj = [];
var medRef={};
snapshot.forEach(doc => {
med=doc.data();
medObj.push({data: med});
});
var i;
var str="You need to take ";
for( i in medObj){
str = str +`${medObj[i].data.medName} at ${medObj[i].data.hour}:${medObj[i].data.min},`;
i++;
}
console.log(str);
return agent.add(`Yes, `+str);
}

Related

Unable to retrieve API keys for a Function App using ListWebAppFunctionKeysArgs

How can I retrieve API keys for a function app in Azure using ListWebAppFunctionKeysArgs?
I have the following method:
public static Output<Dictionary<string, string>?> Get(string resourceGroupName, FunctionApp functionApp)
{
var output =
Output.Tuple(functionApp.Name, functionApp.Name)
.Apply(async tuple => {
var current = Pulumi.Azure.Core.GetClientConfig.InvokeAsync().Result;
var subscriptionId = current.SubscriptionId;
var appName = tuple.Item1;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken.Value);
var url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{appName}/functions?api-version=2022-03-01";
var result = await httpClient.GetAsync(url);
if (!result.IsSuccessStatusCode) throw new Exception($"Error: Failed to retrive Azure function names from {appName}");
var json = await result.Content.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
var items = root.value.Select(async v => {
var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
Name = appName,
FunctionName = v.properties.name,
ResourceGroupName = resourceGroupName
});
return data.Properties;
});
var data = items.SelectMany(v => v.Result).ToList();
return new Dictionary<string, string>(data);
});
return output;
}
Here's the code that I'm struggling with:
var json = await result.Content.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
var items = root.value.Select(async v => {
var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
Name = appName,
FunctionName = v.properties.name,
ResourceGroupName = resourceGroupName
});
return data.Properties; // Property values are null
});
Here's the result:
In conclusion, how do I acquire API keys for a function app?

how to update a collection if you already called it MongoDB Mongoos

Ok so I have a problem in which I use a collection to gather some ratings data and work with it, by the time I finish the rating update process, I have new ratings that I would like to update the collection with. However I can't call update because I get the error "Cannot overwrite model once compiled." I understand that I already called once the model to work with the data and that's why I get the error. is there any way I can update the collection? Or I will just have to workaround by creating a new collection with the latest rating, and then matching the latest ratings collection with the one I use to work with the data.
This is my code
let calculateRating = async () => {
const getData = await matchesCollection().find().lean();
const playerCollection = await playersCollection();
const getDataPlayer = await playerCollection.find().lean();
let gamesCounting = [];
getDataPlayer.forEach((player) => {
player.makePlayer = ranking.makePlayer(1500);
});
for (let i = 0; i < getData.length; i++) {
const resultA = getDataPlayer.findIndex(({ userId }, index) => {
if (userId === getData[i].userA) {
return index;
}
});
const resultB = getDataPlayer.findIndex(
({ userId }) => userId === getData[i].userB
);
const winner = getData[i].winner;
if (getDataPlayer[resultA] === undefined) {
continue;
} else if (getDataPlayer[resultB] === undefined) {
continue;
}
gamesCounting.push([
getDataPlayer[resultA].makePlayer,
getDataPlayer[resultB].makePlayer,
winner,
]);
}
ranking.updateRatings(gamesCounting);
let ratingsUpdate = [];
getDataPlayer.forEach((item) => {
let newRating = item.makePlayer.getRating();
let newDeviation = item.makePlayer.getRd();
let newVolatility = item.makePlayer.getVol();
item.rating = newRating;
item.rd = newDeviation;
item.vol = newVolatility;
ratingsUpdate.push(item);
});
};
I try the work around with creating the new collection

List remains empty after adding elements in flutter firebase

I have tried to add session model to a list of sessions like this but the list reamains empty. My database has the following structure
void getData()
{
var Ref = fb.ref("sessions");
Ref.onValue.listen((event){
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for( var k in children)
{
var ref = fb.ref("sessions/${k.key}");
ref.onValue.listen((event) {
var snp = event.snapshot;
Iterable<DataSnapshot> chi = snp.children;
for(var v in chi)
{
Session s = new Session();
s.timeStamp = v.key.toString();
s.date = k.key.toString();
s.session = v.value.toString();
sessions.add(s);
}
});
}
sessions.refresh();
print(sessions);
totalsessions.value = sessions.length;
});
}
Output
I/flutter (11551): []
Data is loaded from Firebase (and most modern cloud APIs) asynchronously, and while that is going on your main code continues to execute.
It's easiest to see this if you run in a debugger or add some logging statements like this:
var ref = fb.ref("sessions");
print("Before attaching first onValue");
ref.onValue.listen((event) {
print("In first onValue");
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for( var k in children) {
var ref = fb.ref("sessions/${k.key}");
ref.onValue.listen((event) {
print("In second onValue");
});
}
print("After second onValue");
});
print("After first onValue");
When you run this code, it prints:
Before first onValue
After first onValue
In first onValue
After second onValue
In second onValue
This may not be what you expect, but it does explain why your sessions is empty when you print it. By the time your print(sessions) runs, the sessions.add(s) hasn't happened yet.
This problem is incredibly common, and the solution is always the same: any code that needs the data from the database has to be inside the callback that runs when that data is available.
So:
var ref = fb.ref("sessions");
ref.onValue.listen((event){
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for(var k in children) {
var ref = fb.ref("sessions/${k.key}");
ref.onValue.listen((event) {
var snp = event.snapshot;
Iterable<DataSnapshot> chi = snp.children;
for(var v in chi) {
Session s = new Session();
s.timeStamp = v.key.toString();
s.date = k.key.toString();
s.session = v.value.toString();
sessions.add(s);
}
sessions.refresh();
print(sessions);
totalsessions.value = sessions.length;
});
}
});
In your case though, we can simplify the code a lot further. Since you get a read sessions, the snapshot you get contains all data under that path in the database. So you don't need additional listeners to get each specific sessions, but can get the data from the children.
Something like:
var ref = fb.ref("sessions");
ref.onValue.listen((event){
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for(var child in children) {
Iterable<DataSnapshot> grandchildren = child.children;
for(var grandchild in grandchildren) {
Session s = new Session();
s.timeStamp = grandchild.key.toString();
s.date = child.key.toString();
s.session = grandchild.value.toString();
sessions.add(s);
}
sessions.refresh();
print(sessions);
totalsessions.value = sessions.length;
}
});

How do I retrieve the files from localstorage by the extension name ".log"?

I am new to angular/js/ionic. I have a really quick question.
How do I retrieve data from localstorage when I don't really know the index name? I just want to grab whatever ends with ".log"?
I understand that the code below will try to retrieve the data by the index 'notes'.
var logFile = angular.fromJson(window.localStorage['notes'] || '[]');
var localLogFile = function() {
for(var i = 0; i < localStorage.length; i++) {
var keyName = localStorage.key(i);
var extension = keyName.substring(keyName.lastIndexOf("."));
if(extension == ".log") {
return localStorage.getItem(keyName);
}
}
};
var logFile = angular.fromJson(localLogFile());

Append divs changing his content dynamic

I have a dif called cdefualt that has some inputs from a form inside of it and I want to do something like this to clone it and change that input names:
var i = 2;
function add() {
var item = $('#cdefault').clone();
item.attr({'style': ''});
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
item.id = $xpto;
$('#'+$xpto+' input[id="gtitle1"]').attr('name', $xpto);
$('#'+$xpto+' textarea[id="gmessage1"]').attr('name',$xpto2);
$(item).appendTo('#ccontainer');
i++;
}
But this doesnt work. I've tried this already as well but it only works twice (for the original and first clone):
var i = 2;
function add() {
var item = $('#cdefault').clone();
item.attr({'style': ''});
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
$('#cdefault input[id="gtitle1"]').attr('id', $xpto);
$('#cdefault textarea[id="gmessage1"]').attr('id',$xpto2);
$('#cdefault input[name="gtitle1"]').attr('name', $xpto);
$('#cdefault textarea[name="gmessage1"]').attr('name', $xpto2);
$(item).appendTo('#ccontainer');
i++;
}
Even tryed this way:
function add() {
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
var div = document.getElementById('cdefault');
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = $xpto;
clone.style.display = '';
$("#"+$xpto+" input[id='gtitle1']").attr('name', $xpto);
$("#"+$xpto+" textarea[id='gmessage1']").attr('name',$xpto2);
document.getElementById('ccontainer').appendChild(clone);
i++;
}
http://jsfiddle.net/Theopt/xNfSd/
fixed. changed cdefault id to id0 and this java script:
var i = 2;
var c = 0;
function add() {
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
var klon = $( '#id'+ c );
klon.clone().attr('id', 'id'+(++c) ).insertAfter( '#inserthere' );
document.getElementById('id'+(c)).style.display = '' ;
$("#id"+(c)+" input[id='gtitle1']").attr('name', $xpto);
$("#id"+(c)+" textarea[id='gmessage1']").attr('name',$xpto2);
i++;
}