How to sample random numbers in Watson Assistant? - ibm-watson

I'm using IBM Watson Assistant for creating a chatbot. I'm using the web interface with the intents, entities and dialog flow|tree (I don't know how it is called, I'm just calling it web interface).
I would like to define an array of the numbers [1,2,3,4,5]. Then one node should sample a random number without replacement from that array (e.g. 2), i.e. the remaining array is then [1,3,4,5]. After some time another node should pick another number at random from the array (say 4). And so on. How can this be implemented? I know about variables (e.g. $var) but I don't know how to represent arrays and sample random numbers.
Thank you so much for your answers in advance. And happy new year to everybody.

As a general rule about what might be possible we use the doc for the Spring Expression Language. Based on that, you could select a value from some data structure $some_array like this:
{
"context": {
"randomNumber": "<? (new java.util.Random().nextInt($some_array.size())) ?>"
}
}
After that, you access your value using
{
"context": {
"element": "<? $some_array.get($randomNumber) ?>",
"shorter_array": "<? $some_array.remove($randomNumber) ?>"
}
}
Now there are some issues (probably the bug mentioned in the comment), as the remove method should be the one from the gson JsonArray and behave like this:
Removes the element at the specified position in this array. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the array.
However, it returns the array with the element removed, not the element itself.
1) In your Dialog Node, define slots
2) In the first one, generate the random value (if array defined and not empty)
3) In the second, get the element and remove
Note, that even though this works, you should probably not use it in a production version of your Chatbot. Instead, put most of the logic in your application (including the control of the dialogue). The Web Interface is very difficult to test and the way the variables are parsed might change at some point.

Related

How can I filter large amount of JSON in OpenRefine?

I'm using OpenRefine to pull in information on publisher policies using the Sherpa Romeo API (Sherpa Romeo is a site that aggregates publisher policies). I've got that.
Now I need to parse the returned JSON so that those with certain pieces of information remain. The results I'm interested in need to include the following:
'any_website',
'any_repository',
'institutional_repository',
'non_commercial_institutional_repository',
'non_commercial_repository'
These pieces on information all fall under an array called "permitted_oa". For some reason, I can't even work out how to just pull out that array. I've tried writing grel expressions such as
value.parseJson().items.permitted_oa
but it never reutrns anything.
I wish I could share the JSON but it's too big.
I can see a couple of issues here.
Firstly the Sherpa API response items is an array (i.e. a list of things). When you have an array in the JSON, you either have to select a particular item from the array, or you have to explicitly work through the list of things in the array (aka iterate across the array) in your GREL. If you've previously worked with arrays in GREL you'll be familiar with this, but if you haven't
value.parseJson().items[0] -> first item in the array
value.parseJson().items[1] -> second item in the array
value.parseJson().items[2] -> third item in the array etc. etc.
If you know there is only ever going to be a single item in the array then you can safely use value.parseJson().items[0]
However, if you don't know how many items will be in the array and you are interested in them all, you will have to iterate over the array using a GREL control such as "forEach":
forEach(value.parseJson().items, v, v)
is a way of iterating over the array - each time the GREL finds an item in the array, it will assign it to a variable "v" and then you can do a further operation on that value using "v" as you would usually use "value" (see https://docs.openrefine.org/manual/grel#foreache1-v-e2 for an example of using forEach on an array)
Another possibility is to use join on the array. This will join all the things in an array into a string.
value.parseJson().items.join("|")
It looks like the Sherpa JSON uses Arrays liberally so you may find more arrays you have to deal with to get to the values you want.
Secondly, in the JSON you pasted "oa_permitted" isn't directly in the "item" but in another array called "publisher_policy" - so you'll need to navigate that as well. So:
value.parseJson().items[0].publisher_policy[0].permitted_oa[0]
would get you the first permitted_oa object in the first publisher_policy in the first item in the items array. If you wanted to (for example) get a list of locations from the JSON you have pasted you could use:
value.parseJson().items[0].publisher_policy[0].permitted_oa[0].location.location.join("|")
Which will give you a pipe ("|") separated list of locations based on the assumption there is only a single item, single publisher_policy and singe permitted_oa - which is true in the case of the JSON you've supplied here (but might not always be true)

Alexa Custom Slot Type: No value in intent

I've already posted this question to the amazon developer forum but don't receive an answer there. I guess Stackoverflow should've been the first choice from the beginning:
From my understanding if I use a Custom Slot Type even if the list of its possible values does not contain the spoken word the spoken word is still passed to the function. The documentation says
A custom slot type is not the equivalent of an enumeration. Values outside the list may still be returned if recognized by the spoken language understanding system.
Now I have a Custom Slot Type LIST_OF_PERSONS with values Matthias|Max and an utterance of
EmployeeDetailsIntent {Person}
If I call this intend with a value not in LIST_OF_PERSONS the Intent still gets called but the JSON does not contain a "value" key for the Slot:
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.a943e233-0713-4ea5-beba-d9287edb6083",
"locale": "de-DE",
"timestamp": "2017-03-09T14:38:29Z",
"intent": {
"name": "EmployeeDetailsIntent",
"slots": {
"Person": {
"name": "Person"
}
}
}
}
Is this "works as designed" or a bug? How do I access the spoken word in the Intent then? As this.event.request.intent.slots.Person.value is undefined?
My code lives in AWS lambda and I'm using the nodejs alexa-sdk Version 1.0.7. The language of my Skill is German.
(disclaimer: this post summarises my own "workaround". It might or might not be the "best way". Seems to have worked for me so thought I would share / document it here briefly)
I've recently bumped into similar issues for an utterance that looks like this:
"tell me about {townName}"
If I say "tell me about London", it works.
If I say "tell me about" (deliberately missing a {townName}), the program "dies" (and returns a JSON looking similar to your one, with undefined this.event.request.intent.slots.townName.value)
Though I'm not 100% sure whether this is meant to be a "feature" (i.e. we need to write smarter code to work around this) or "problem" (i.e. Alexa team needs to address or fix). This scenario has caused a real issue when it came to the certification process for me recently.
To get through this, I've implemented a workaround (or fix, whatever you call it) to avoid Alexa from "dying" as a result of this edge case.
From the Alexa skill-sample-nodejs-trivia index.js file, I've found a snippet function that helped me work around this (I've edited it a bit for my example for simplicity):
function isAnswerSlotValid(intent) {
var answerSlotFilled = intent && intent.slots &&
intent.slots.townName && intent.slots.townName.value;
return answerSlotFilled
}
(i.e. this function returns True for valid values for the slot townName and and False for undefined / otherwise).
When it comes to defining the intent, I could use this function to "get around" an empty slot value scenario:
var startHandlers = Alexa.CreateStateHandler(states.START,{
// bla bla bla//
"AnswerIntent": function() {
// handel missing slot value
var answerSlotValid = isAnswerSlotValid(this.event.request.intent);
if (answerSlotValid && moreConditions) {
// do something fun
}
else {
// handle empty slot scenario
}
}
// bla bla bla//
}
Would be interested to see if there are better / more "proper" solutions to this to handle empty / undefined slots more elegantly.
I have seen this happen when an intent has both utterances with and without a slot. For example:
myIntent what makes a car go fast
myIntent what makes a {CAR_TYPE} go fast
where CAR_TYPE has a list of different types of cars.
myIntent still needs to define the slot CAR_TYPE for the myIntent in the schema, but the first intent doesn't use it.
In this case, it might be best to include 'car' in CAR_TYPE and eliminate the first utterance. In other cases though, the sentence grammar really doesn't permit it, so you need to expect an empty slot like you're seeing.
I believe the issue is that utterances using a Custom Slot Type must be used with at least one other value.
For example
EmployeeDetailsIntent get {Person}
will work, while
EmployeeDetailsIntent {Person}
will not
Had same thing, get custom slot name, but value was missing in Json Input. Worked with normal slots. Using Alexa Developer Console. Had to add an "ID" value to my custom slot values and then I started getting values. I thought I had tried that before but maybe I had not put an ID on each value. That did the trick for me though where the other answers did not work for me.

pebblekit js send array to pebble C by appmessage

I am trying to code my first Pebble C app which is based on a pebble.js app I made. I am basically showing the bus schedules.
My question, How can I pass the information from pebblekit js to the pebble C by appmessage so that I can construct a menu? how can I pass an multiple dimension array by appmessage to the watch?
here is an example of the json my pebblekit js has to send to the watch:
{
"buses":[
{
"bus_number":"55",
"stops":[
{
"stop_id":"109698",
"stop_times":[
{
"arrival_time":"21:22:25",
"departure_time":"21:22:25"
},
{
"arrival_time":"21:52:25",
"departure_time":"21:52:25"
},
...
]
},
...
}
}
Unfortunately there is no way to send an array natively. This is the general framework of how I go about it in my apps. I won't post code because it varies depending on the project.
Add the MessageQueue library to your project. This library is great for sending lots of data at a time or many different pieces quickly.
Create a sendArray function which simply loops through each of the objects in the array and sends them to Pebble with MessageQueue.sendAppMessage()
On the C side, in your inbox handler, check for a certain key which you expect to be sent with the array object. For example, if each array object has a temperature key in it, check for that key and then you'll know the rest of the data should be there too.
3.1. Insert all of this data you just got on the C side from the DictionaryIterator into some sort of struct which you have created to represent the array item.
3.2. After processing all of that data, insert that updated struct into an array.
Keeping a stack count for that array is usually a good idea too.
Let me know if you need any more help or if I can explain anything better.

How can I create arrays within a loop (within another loop) and pass them back out in Javascript?

I'm using Google Docs Spreadsheet API to keep track of a competition between some of my friends. I have some big ideas, but I'm stumped right now. I'm trying to create 20 different arrays inside of loops (see below) and then evaluate each one outside of the loop, and I really don't want to write 20 "if...then" statements.
NOTE: the following SUMMARY may or may not help you answer my question. You might want to skip down to the code, then read this if you need it :)
Summary of the program: Each player assigns point values in favor of one possible outcome of a set of binary-outcome events. As the events happen, players either gain the points assigned if their outcome occurs, or gain no points if the opposite outcome occurs. My goal is to 1) figure out exactly when a player is eliminated, and 2) highlight all remaining events that must be won for them to have a chance at tying for first.
Instead of trying to somehow evaluate all possibilities (5 players picking, 2^16 outcomes... I have zero computer science knowledge, but this seems like an incredibly huge task even for the modern computer) I've come up with an alternate idea. The script loops through each player, against each other opponent. It calculates the maximum number of points a player can score based on their value assignments and the already determined game. For one player and one opponent, it checks the best possible outcome by the player against that opponent, and if there is any opponent he cannot beat, even in the best case, then he is eliminated.
This part is easy-- after the loop runs inside the loop, I just adjust a global variable that I created earlier, and when the outer loop is done, just grab those variables and write them to the sheet.
Unfortunately, this misses the case of where he could have a best case against each individual opponent, but not against multiple opponents at once.
So the next step is what I'm trying to do now. I'm not even sure I can give a good explanation without just showing you the entire spreadsheet w/script, but I'll try. So what I want to do now is calculate the "value" of each event for each player against a given other player. If both player and opponent assigned points in favor of the same event outcome for one event, the event's value is the difference between the picks (positive if player picked higher, negative if lower), and it's the SUM if they picked opposite event outcomes. Now, I do the same thing as before-- take a best-case scenario for a player against a given opponent-- but now I check by how much the player can beat the opponent in a best-case scenario. Then I evaluate the (absolute value of the) event value against this difference, and if it's greater, then the event is a must win (or must lose if the event value is negative). And, if an event is both a "must-win" and a "must lose" event, then the player is eliminated.
The problem is that this second step requires me to create a new array of values for each player-opponent combination, and then do things with the values after they're created.
I realize one approach would be to create 20 different arrays, and throughout the entire loops, keep checking "if (player == "1" && opponent == 2){}" and populate the arrays accordingly, but this seems kind of ridiculous. And more importantly, this entire project is my attempt at learning javascript, so what's the point in using a time-intensive workaround that doesn't teach me anything new?
I'm trying to understand square bracket notation, since it seems to be the answer to my question, but a lot of people are also suggesting that it's impossible to create variable names by concatenating with the value of another variable... so anyway, here's what I'm trying. I'd really appreciate either a fix to my approach, or a better approach.
for (var player=1; player<6; player++){
if(player==1){look up certain columns in the spreadsheet and save them to variables}
//ditto for other players
for(var opponent=1; opponent<6; opponent++){
if(player!=opponent){
if(opponent==1){save more values to variables}
//ditto for other players
for(var row=9; row<24; row++) {
//Now the script goes down each row of an array containing the original
//spreadsheet info, and, based on information determined by the variables
//created above, get values corresponding to the player and opponent.
//So what I'd like to do here is create "array[1,2]==" and then "array[1,3]=="
//and so forth, creating them globally (I think I understand that term by now)
//so I can refer to them outside of the loops later to do some evaluatin'.
}
}}
//get array[1,2]...array[5,4] and do some operations with them.
Thanks for getting through this little novel... really looking forward to your advice and ideas!
How can I create arrays within a loop (within another loop)?
Code update 2
As you said: "i am trying to understand square bracket notation" You may take a look at my new demo and the code:
function getTeam(){
var array = [[1,2,3],[4,5,6],[7,8,9]]; // arrays within arrays
// array myTeam
var myTeam = [[],[],[],[]];
var playerNames = ["John", "Bert", "Dave", "Milton"];
var ages =[];
var weight = 104;
// loop over the team arrayadd each player (name, age and weight) to the team
for (i=0; i < myTeam.length; i++){
// fill the age array in a loop
for (j=0;j<myTeam.length;j++) {
ages[j] = 23 + j;
}
myTeam[i].push([playerNames[i], ages[i], weight]);
}
return myTeam;
}
And pass them back out in Javascript
Could you elaborate on this part?
Update
var valuesOfPlayers=[];
for (var player=1; player<6; player++){
// look up certain columns in the spreadsheet and save them to variables
// you could call a funcntion and return the values you
// collected in an array within an array as in the demo above
valuesOfPlayers[player] = lookupColumnValues(player);
for(var opponent=1; opponent<6; opponent++){
if(player!=opponent){
// save more values to variables
valuesOfPlayers[player] = addValuesToVar(player);
}
for(var row=9; row<24; row++) {
// if you collect the values in your first and second if clause
// what other information do you want to collect
// Please elaborate this part?
}
}}
One workaround:
I could create an array before the execution of the loops.
At the start of each loop, I could push a string literal to the array containing the value of player and opponent.
After the loops are done, I could split the array into multiple arrays, or just evaluate them in one big array using regular expressions.
I'd still rather create new arrays each time-- seems like it is a more universal way of doing this, and learning how would be more educational for me than using this workaround.

Sorting and managing numerous variables

My project has classes which, unavoidably, contain hundreds upon hundreds of variables that I'm always having to keep straight. For example, I'm always having to keep track of specific kinds of variables for a recurring set of "items" that occur inside of a class, where placing those variables between multiple classes would cause a lot of confusion.
How do I better sort my variables to keep from going crazy, especially when it comes time to save my data?
Am I missing something? Actionscript is an Object Oriented language, so you might have hundreds of variables, but unless you've somehow treated it like a grab bag and dumped it all in one place, everything should be to hand. Without knowing what all you're keeping track of, it's hard to give concrete advice, but here's an example from a current project I'm working on, which is a platform for building pre-employment assessments.
The basic unit is a Question. A Question has a stem, text that can go in the status bar, a collection of answers, and a collection of measures of things we're tracking about what the user does in that particular type of questions.
The measures are, again, their own type of object, and come in two "flavors": one that is used to track a time limit and one that isn't. The measure has a name (so we know where to write back to the database) and a value (which tells us what). Timed ones also have a property for the time limit.
When we need to time the question, we hand that measure to yet another object that counts the time down and a separate object that displays the time (if appropriate for the situation). The answers, known as distractors, have a label and a value that they can impart to the appropriate measure based on the user selection. For example, if a user selects "d", its value, "4" is transferred to the measure that stores the user's selection.
Once the user submits his answer, we loop through all the measures for the question and send those to the database. If those were not treated as a collection (in this case, a Vector), we'd have to know exactly what specific measures are being stored for each question and each question would have a very different structure that we'd have to dig through. So if looping through collections is your issue, I think you should revisit that idea. It saves a lot of code and is FAR more efficient than "var1", "var2", "var3."
If the part you think is unweildy is the type checking you have to do because literally anything could be in there, then Vector could be a good solution for you as long as you're using at least Flash Player 10.
So, in summary:
When you have a lot of related properties, write a Class that keeps all of those related bits and pieces together (like my Question).
When objects have 0-n "things" that are all of the same or very similar, use a collection of some sort, such as an Array or Vector, to allow you to iterate through them as a group and perform the same operation on each (for example, each Question is part of a larger grouping that allows each question to be presented in turn, and each question has a collection of distractors and another of measures.
These two concepts, used together, should help keep your information tidy and organized.
While I'm certain there are numerous ways of keeping arrays straight, I have found a method that works well for me. Best of all, it collapses large amounts of information into a handful of arrays that I can parse to an XML file or other storage method. I call this method my "indexed array system".
There are actually multiple ways to do this: creating a handful of 1-dimensional arrays, or creating 2-dimensional (or higher) array(s). Both work equally well, so choose the one that works best for your code. I'm only going to show the 1-dimensional method here. Those of you who are familiar with arrays can probably figure out how to rewrite this to use higher dimensional arrays.
I use Actionscript 3, but this approach should work with almost any programming or scripting language.
In this example, I'm trying to keep various "properties" of different "activities" straight. In this case, we'll say these properties are Level, High Score, and Play Count. We'll call the activities Pinball, Word Search, Maze, and Memory.
This method involves creating multiple arrays, one for each property, and creating constants that hold the integer "key" used for each activity.
We'll start by creating the constants, as integers. Constants work for this, because we never change them after compile. The value we put into each constant is the index the corresponding data will always be stored at in the arrays.
const pinball:int = 0;
const wordsearch:int = 1;
const maze:int = 2;
const memory:int = 3;
Now, we create the arrays. Remember, arrays start counting from zero. Since we want to be able to modify the values, this should be a regular variable.
Note, I am constructing the array to be the specific length we need, with the default value for the desired data type in each slot. I've used all integers here, but you can use just about any data type you need.
var highscore:Array = [0, 0, 0, 0];
var level:Array = [0, 0, 0, 0];
var playcount:Array = [0, 0, 0, 0];
So, we have a consistent "address" for each property, and we only had to create four constants, and three arrays, instead of 12 variables.
Now we need to create the functions to read and write to the arrays using this system. This is where the real beauty of the system comes in. Be sure this function is written in public scope if you want to read/write the arrays from outside this class.
To create the function that gets data from the arrays, we need two arguments: the name of the activity and the name of the property. We also want to set up this function to return a value of any type.
GOTCHA WARNING: In Actionscript 3, this won't work in static classes or functions, as it relies on the "this" keyword.
public function fetchData(act:String, prop:String):*
{
var r:*;
r = this[prop][this[act]];
return r;
}
That queer bit of code, r = this[prop][this[act]], simply uses the provided strings "act" and "prop" as the names of the constant and array, and sets the resulting value to r. Thus, if you feed the function the parameters ("maze", "highscore"), that code will essentially act like r = highscore[2] (remember, this[act] returns the integer value assigned to it.)
The writing method works essentially the same way, except we need one additional argument, the data to be written. This argument needs to be able to accept any
GOTCHA WARNING: One significant drawback to this system with strict typing languages is that you must remember the data type for the array you're writing to. The compiler cannot catch these type errors, so your program will simply throw a fatal error if it tries to write the wrong value type.
One clever way around this is to create different functions for different data types, so passing the wrong data type in an argument will trigger a compile-time error.
public function writeData(act:String, prop:String, val:*):void
{
this[prop][this[act]] = val;
}
Now, we just have one additional problem. What happens if we pass an activity or property name that doesn't exist? To protect against this, we just need one more function.
This function will validate a provided constant or variable key by attempting to access it, and catching the resulting fatal error, returning false instead. If the key is valid, it will return true.
function validateName(ID:String):Boolean
{
var checkthis:*
var r:Boolean = true;
try
{
checkthis = this[ID];
}
catch (error:ReferenceError)
{
r = false;
}
return r;
}
Now, we just need to adjust our other two functions to take advantage of this. We'll wrap the function's code inside an if statement.
If one of the keys is invalid, the function will do nothing - it will fail silently. To get around this, just put a trace (a.k.a. print) statement or a non-fatal error in the else construct.
public function fetchData(act:String, prop:String):*
{
var r:*;
if(validateName(act) && validateName(prop))
{
r = this[prop][this[act]];
return r;
}
}
public function writeData(act:String, prop:String, val:*):void
{
if(validateName(act) && validateName(prop))
{
this[prop][this[act]] = val;
}
}
Now, to use these functions, you simply need to use one line of code each. For the example, we'll say we have a text object in the GUI that shows the high score, called txtHighScore. I've omitted the necessary typecasting for the sake of the example.
//Get the high score.
txtHighScore.text = fetchData("maze", "highscore");
//Write the new high score.
writeData("maze", "highscore", txtHighScore.text);
I hope ya'll will find this tutorial useful in sorting and managing your variables.
(Afternote: You can probably do something similar with dictionaries or databases, but I prefer the flexibility with this method.)

Resources