Activate js when snowing in users location - javascript

So I have js that I want to only activate if it is snowing in the users area.
Here is a JSFiddle Here
<h1 onclick="snowStorm.toggleSnow();">
text
</h1>
<script src="https://web.archive.org/web/20161109225359/http://live.superedu.ml/snow.js"></script>
<script>
snowStorm.followMouse = false;
snowStorm.freezeOnBlur = true;
snowStorm.autoStart = false;
</script>
if you click test it activates snow.
how would I make this to activate the snow when it is snowing where the user is. thank you

First, you need to know if it's snowing or not at the user's location. So the very first thing you need to know is where they are. For this you use an IP geolocation service. Google it. One of them is https://freegeoip.net/
Next you need to ask a weather service about the weather.
Look into https://darksky.net/dev/docs/forecast
In order to ask something to a service like DarkSky API you will need to tell them the location you are interested in for the forecast, which is where you use the location coordinates you received from the geolocation service above.
You will then receive a response "object" from the DarkSky API, which will contain a bunch of information, amongst which the precipitation info as described below:
precipType optional
The type of precipitation occurring at the given time. If defined, this property will have one of the following values: "rain", "snow", or "sleet" (which refers to each of freezing rain, ice pellets, and “wintery mix”). (If precipIntensity is zero, then this property will not be defined.)
https://darksky.net/dev/docs/response
After which you can code something along the lines of
if (data.precipType === 'snow') { // do something }
Overall, it goes like this:
Send request to GeoIP (where is ip 8.8.8.8 ?)
Receive response from GeoIP (it's at lat:1.2345 lon:1.432)
Send request to DarkSky (what's the weather today at lat:1.2345 lon:1.432 ?)
Receive response from DarkSky (snow!)
… do stuff …
How
In order to succeed at this exercise, you will ned to familiarise a bit with basic asynchronous programming in JS, and how to send an AJAX request, and consume the response you receive.
In short you need to learn how to write code that is able to start function B only after function A is done (after an unknown amount of time, like when requesting over the net)
So things will look more like this:
1. Send request to GeoIP (where is ip 8.8.8.8 ?)
2. Receive response from GeoIP (it's at lat:1.2345 lon:1.432)
3. Send request to DarkSky (what's the weather today at lat:1.2345 lon:1.432 ?)
4. Receive response from DarkSky (snow!)
5. … do stuff …
Good keywords to search for this are jQuery AJAX, callbacks, and a tad more advanced, Promises. But start with the first two.
Good luck!

Related

Is there any way to create a "Free-write" section for a Chatbot?

Quite new here and have been using Dialogflow and rasa to try making a chatbot for user reports, Stuck at a certain segment where I want the user to "report" to the bot what it has done for the day, regardless of the content the bot will reply with a "Thanks for your time" response and saves the user's response, I can't seem to figure this out, as the bot will try to analyze the layer of texts the user sends and then goes to default fallback intent....
You will need FormAction for free write action (given you don't want any intent for it).
In the actions.py, add following code
class FormFreeText(FormAction):
def name(self):
return "form_free_text"
#staticmethod
def required_slots(tracker):
return ["free_text"]
def slot_mappings(self):
return {
"free_text": self.from_text()
}
def submit(self, dispatcher, tracker, domain):
return []
In domain.yml, add following lines
slots:
free_text:
type: unfeaturized
responses:
utter_ask_free_text:
- text: "Please enter the text for your report"
actions:
- form_free_text
In stories.md, add the following lines where ever you want user input.
- form_free_text
- form{'name':'form_free_text'}
- form{'name':null}
There are some naming convenstions like using utter_ask to ask any question using FormAction.
I hope this helps.
In DialogFlow your option is to use a fulfilment which allows to drive the conversation logic using events, for example:
user answers what's wrong or good about the day
webhook receives the payload with the answer and the associated intent (or better define an action)
webhook triggers an event (EVENT_DONE)
the event (EVENT_DONE) belongs to an intent (THANK_YOU) which sends a response to the user
In Rasa the options are to either train an intent (inform) with training data (you can still capture/recognise what the user talks about) or use an FormAction where user input is captured in a slot (even if you don't really need to use/store it)

using third party api on watson assistant

i'm using the open weather map api in order to get information on the current weather and then integrate it with watson assistant (i used this as a reference for the watson assistant code) before deploying on the terminal. here's my code:
var city = "Seattle";
weather.setCity(city);
function processResponse(err, response){
if(err){
console.log(err);
return;
}
var endConversation = false;
if(response.intents[0]){
if(response.intents[0].intent=="CurrentWeather"){
weather.getDescription(function(err, desc){
weather.getTemperature(function(err, temp){
console.log("It is " + desc + " today with a temperature of " + temp + " degrees Celsius.");
)};
)};
}
else if(response.intents[0].intent=="end_conversation"){
console.log(response.output.text);
endConversation = true;
}
}
if(!endConversation){
var newMessageFromUser = prompt(">> ");
service.message({
workspace_id: workspace_id,
input: {
text: newMessageFromUser
},
context: response.context
},processResponse);
}
}
it works, but then the response looks like this:
>> what is the weather today in seattle
>>
It is few clouds today with a temperature of 29 degrees Celsius.
>> bye
['See ya!']
whenever i use any third party apis, instead of responding right after i enter the trigger keywords, the terminal asks me to input another entry (in the scenario above, i entered nothing) before responding. however, when i try to enter keywords related to intents whose responses are just retrieved right away from the watson assistant (as is with end_conversation), the terminal responds right away.
Is there a way for me to force the terminal to only ask once?
There are different ways to get around entering something before the actual response.
Take a look at client-based dialog actions. The key is to use the skip_user_input flag and check it within your application. Basically, it would indicate to your application that you need to process some data. The app would it send back to Watson Assistant to respond. There is also the server-based dialog action. In that case Watson Assistant is invoking an IBM Cloud Functions action. A tutorial using that approach is here, interfacing with a Db2 database.
Another technique is what I call replaced markers. You would have Watson Assistant returns an answer with placeholders. Your app would replace those markers.
Third, you are using JavaScript with asynchronous processing. It seems that your empty prompt is processed while you fetch the weather data. The IF for the weather is independent of the empty prompt. Try fixing that.
following Michal Bida's advice, I tried implementing the third party API in cloud function and it worked. simply created a php function using the php implementation of the openweather map api and followed the steps on how to create an action in php through this tutorial. for the implementation, i followed this tutorial on how to implement actions in watson assistant. it now works even when directly invoked from the chat bot at the side of the watson assistant.
an example of a response it returns will be:
{"weather":"It is raining today in Seattle with a temperature of 15 degrees Celsius"}

Twilio Nodejs - How to place call to twilio and gather entered digits to call another person

I'm trying to figure out how to create calls from my Twilio number after I've dialed into it and entered a number. After reading the docs I see that this is done with the gather feature, which can then be redirected to another Twiml document to handle the response. However, I can't quite get it to work. I'm extremely confused on how to execute Twiml correctly and how to access the request parameters in another Twiml doc. I've also looked into Twimlets but I wasn't able to construct what I needed there correctly either.
I've gone back and tried to just make a simple voice message play when only my number calls. If it's not me calling then it needs to be redirected to a Twiml url which will try to connect to my phone. If that fails it will prompt the caller to leave a message.
//Handle incoming call requests
app.post('/call', function(req, res) {
var twiml = new twilio.TwimlResponse();
res.type('text/xml');
if ( req.body.From === "+1555555555") {
twiml.say('Hello', {voice: alice});
res.send(twiml.toString());
} else {
// Do something here.
}
});
I've found the correct solution for my problem. I wasn't initiating the twilio.TwimlResponse() correctly.
In order to solve this issue, I needed to use == instead of === so that my req.body.from value wouldn't get coerced.

How to pass data between Django module/app functions without using database in asynchronous web service

I've got a web service under development that uses Django and Django Channels to send data across websockets to a remote application. The arrangement is asynchronous and I pass information between the 2 by sending JSON formatted commands across websockets and then receive replies back on the same websocket.
The problem I'm having is figuring out how to get the replies back to a Javascript call from a Django template that invokes a Python function to initiate the JSON websocket question. Since the command question & data reply happen in different Django areas and the originating Javascript/Python functions call does not have a blocking statement, the Q&A are basically disconnected and I can't figure out how to get the results back to the browser.
Right now, my idea is to use Django global variables or store the results in the Django models. I can get either to work, but I beleive the Django global variables would not scale beyond multiple workers from runserver or if the system was eventually spread across multiple servers.
But since the reply data is for different purposes (for example, list of users waiting in a remote lobby, current debugging levels in remote system, etc), the database option seems unworkable because the reply data is varying structure. That, plus the replies are temporal and don't need to be permanently stored in the database.
Here's some code showing the flow. I'm open to different implementation recommendations or a direct answer to the question of how to share information between the 2 Django functions.
In the template, for testing, I just have a button defined like this:
<button id="request_lobby">Request Lobby</button>
With a Javascript function. This function is incomplete as I've yet to do anything about the response (because I can't figure out how to connect it):
$("#request_lobby").click(function(){
$.ajax({
type: "POST",
url: "{% url 'test_panel_function' %}",
data: { csrfmiddlewaretoken: '{{ csrf_token }}', button:"request_lobby" },
success: function(response){
}
});
});
This is the Django/Python function in views.py . The return channel for the remote application is pre-stored in the database as srv.server_channel when the websocket is initially connected (not shown):
#login_required
def test_panel_function(request):
button = request.POST.get('button', '')
if button == "request_lobby" :
srv = Server.objects.get(server_key="1234567890")
json_res = []
json_res.append({"COMMAND": "REQUESTLOBBY"})
message = ({
"text": json.dumps(json_res)
})
Channel(srv.server_channel).send(message)
return HttpResponse(button)
Later, the remote application sends the reply back on the websocket and it's received by a Django Channels demultiplexer in routing.py :
class RemoteDemultiplexer(WebsocketDemultiplexer):
mapping = {
"gLOBBY" : "gLOBBY.receive",
}
http_user = True
slight_ordering = True
channel_routing = [
route_class(RemoteDemultiplexer, path=r"^/server/(?P<server_key>[a-zA-Z0-9]+)$"),
route("gLOBBY.receive" , command_LOBBY),
]
And the consumer.py :
#channel_session
def command_LOBBY(message):
skey = message.channel_session["server_key"]
for x in range(int(message.content['LOBBY'])):
logger.info("USERNAME: " + message.content[str(x)]["USERNAME"])
logger.info("LOBBY_ID: " + message.content[str(x)]["LOBBY_ID"])
logger.info("OWNER_ID: " + message.content[str(x)]["IPADDRESS"])
logger.info("DATETIME: " + message.content[str(x)]["DATETIME"])
So I need to figure out how to get the reply data in command_LOBBY to the Javascript/Python function call in test_panel_function
Current ideas, both of which seem bad and why I think I need to ask this question for SO:
1) Use Django global variables:
Define in globals.py:
global_async_result = {}
And include in all relevant Django modules:
from test.globals import global_async_result
In order to make this work, when I originate the initial command in test_panel_function to send to the remote application (the REQUESTLOBBY), I'll include a randomized key in the JSON message which would be round-tripped back to command_LOBBY and then global_async_result dictionary would be indexed with the randomized key.
In test_panel_function , I would wait in a loop checking a flag for the results to be ready in global_async_result and then retrieve them from the randomized key and delete the entry in global_async_result.
Then the reply can be given back to the Javascript in the Django template.
That all makes sense to me, but uses global variables (bad), and seems that it wouldn't scale as the web service is spread across servers.
2) Store replies in Django mySQL model.py table
I could create a table in models.py to hold the replies temporarily. Since Django doesn't allow for dynamic or temporary table creations on the fly, this would have to be a pre-defined table.
Also, because the websocket replies would be different formats for different questions, I could not know in advance all the fields ever needed and even if so, most fields would not be used for differing replies.
My workable idea here is to create the reply tables using a field for the randomized key (which is still routed back round-trip through the websocket) and another large field to just store the JSON reply entirely.
Then in test_panel_function which is blocking in a loop waiting for the results, pull the JSON from the table, delete the row, and decode. Then the reply can be given back to the Javascript in the Django template.
3) Use Django signals
Django has a signals capability, but the response function doesn't seem to be able to be embedded (like inside test_panel_function) and there seems to be no wait() function available for an arbitrary function to just wait for the signal. If this were available, it would be very helpful

Angular $http service, how to cancel / unsubscribe pending requests?

I have an AngularJS application which perform
- 1 request to fetch the main user profile, that contains references to the user friends,
- and then 1 request per friend to retrieve the friend profile.
When we click on a friend's profile, we load this profile as the main profile.
I am in the RDF / semantic web world, so I can't model these interactions differently, this is not the point of the question.
This is an early version of the application I'm trying to build, that can help you understand what's my problem: http://sebastien.lorber.free.fr/addressbook/app/
The code looks like:
$scope.currentProfileUri = 'http://bblfish.net/people/henry/card#me';
$scope.$watch('currentProfileUri', function() {
console.debug("Change current profile uri called with " + $scope.currentProfileUri);
loadFullProfile($scope.currentProfileUri);
})
// called when we click on a user's friend
$scope.changeCurrentProfileUri = function changeCurrentProfileUri(uri) {
$scope.currentProfileUri = uri;
}
function loadFullProfile(subject) {
$scope.personPg = undefined;
// we don't want to capture the scope variable in the closure because there may be concurrency issues is multiple calls to loadFullProfile are done
var friendsPgArray = [];
$scope.friendPgs = friendsPgArray;
fetchPerson(subject).then(function(personPg) {
$scope.personPg = personPg
fetchFriends(personPg,function onFriendFound(relationshipPg) {
friendsPgArray.push(relationshipPg);
});
},function(error) {
console.error("Can't retrieve full profile at "+uri+" because of: "+error);
});
}
So the friends are appended to the UI as they come, when the http response is available in the promise.
The problem is that the function changeCurrentProfileUri can be called multiple times, and it is possible that it is called by while there are still pending requests to load the current users's friends.
What I'd like to know is if it's possible, on changeCurrentProfileUri call, to cancel the previous http requests that are still pending? Because I don't need them anymore since I'm trying to load another user profile.
These pending requests will fill an instance of friendsPgArray that is not in the scope anymore and won't be put in the scope, so it is just useless.
Using Java Futures, or frameworks like RxScala or RxJava, I've seen there's generally some kind of "cancel" or "unsubscribe" method which permits to de-register interest for a future result. Is it possible to do such a thing with Javascript? and with AngularJS?
Yes, it is! Please, see this section of angular $http service docs. Note timeout field in config object. It does, I think, exactly what you need. You may resolve this pormise, then request will be marked as cancelled and on error handler will be called. In error handler you may filter out this cases by there http status code - it will be equal to 0.
Here is fiddle demonstrating this

Categories

Resources