Koa2 session page view count 2 times for each update - koa2

When you load the first time, it shows correctly. After, each update gets 2 page view count, not one.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['Shh, its a secret!'];
app.use(session(app));
app.use(async function(ctx) {
let n = ctx.session.views || 0;
ctx.session.views = ++n;
console.log(`times= ${n}`);
if (n === 1) {
ctx.body = 'Welcome here for the first time!';
} else {
ctx.body = `You visited this page ${n} times!`;
}
});
app.listen(3000);

Actually, I testet it right now and it seems to work correctly. What you have to consider, is, when typing your URL in the browser, some browsers already try to preload things. This also happened here.
What I then tried to be sure, that it works as expected: I shutted down the node/koa app, then in the browser cleared the session for that side (Developertools - Storage - Sessions), started node/koa app again and then on client side hit reload several times. Here, on server side I gut the correct output:
times= 1
times= 2
times= 3
times= 4
times= 5
and on client side the output was also correct.

Related

How to implement a server side pagination with Material ui and react?

Currently you can paginate towards the backend, with the next and previous option, but I can't do it with the rows per page option, how do I make the two options work? Thank you
Here is an image of the options
For paging you need:
know the number of records.
number of records displayed on page.
page number.
Send to server from client: number of records on page and page number)
Send to client from server: records between from, to
const count = 20; // for example we have 20 records
const size = 7; // there are 7 records on each page
// number of pages
const countPages = Math.ceil (20/7);
//show records on page 2:
const page = 2; // display 2nd page
const from = (page - 1) * size;
const to = Math.min (from + size- 1, count);
console.log(`we have ${count} records, ${size} per page` )
console.log('number of pages', countPages);
console.log(`on page ${page} records from ${from} to ${to}`);

Why Here Maps Routes App and Web Different

We have here api on both mobile apps(Android and Ios) and web app(client dashboard) - and we have a problem encountered when we add truck parameters in api request - sometimes routes differ on mobile API and web API, we used totally same parameters, bu in the end routes still different, and we cant figure what else to change to make them same.
Here's one test example:
point1 = 37.7793808,-122.4184174(San Francisco),
point2 = 40.7559247,-73.9846107(New York),
vehicleWidth = 300 feet,
vehicleHeight = 400 feet,
vehicleLength = 200 feet,
limitedVehicleWeight = 50 lbs,
web part request:
var routingParameters = {
'mode': 'fastest;truck;traffic:enabled;boatFerry:-1',
'representation': 'display',
'routeAttributes': 'waypoints,summary,shape,legs'
};
var feet = 0.3048;
var ton = 0.00045359237;
routingParameters.vehicleWidth = (300 * feet);
routingParameters.vehicleHeight = (400 * feet) + 'm';
routingParameters.vehicleLength = (200 * feet) + 'm';
routingParameters.limitedVehicleWeight = (50 * ton) + 't';
for (var x = 0; x < points.length; x++) {
var point = points[x];
routingParameters['waypoint' + x] = 'geo!' + point.lt + ',' + point.lng;
}
var router = platform.getRoutingService();
var onResult = function (result) {
And then we display route.
As a result we have this route
Same stuff on app side(Ios example):
v
ar stops = [NMAWaypoint.init(geoCoordinates: NMAGeoCoordinates(latitude: Double(trip.startLatitude) ?? 0, longitude: Double(trip.startLongitude) ?? 0), waypointType: .stopWaypoint)]
stops.append(NMAWaypoint.init(geoCoordinates: NMAGeoCoordinates(latitude: Double(trip.endLatitude) ?? 0, longitude: Double(trip.endLongitude) ?? 0), waypointType: .stopWaypoint) )
let routingMode = NMARoutingMode.init(routingType: NMARoutingType.fastest, transportMode: NMATransportMode.truck, routingOptions: NMARoutingOption.avoidBoatFerry)
let dimensions = TruckDimensions.getSingleEntity()
routingMode.vehicleWidth = dimensions.width.floatValue * feet
routingMode.vehicleHeight = dimensions.height.floatValue * feet
routingMode.vehicleLength = dimensions.length.floatValue * feet
routingMode.limitedVehicleWeight = dimensions.weight.floatValue * ton
let penalty = NMADynamicPenalty.init()
penalty.trafficPenaltyMode = NMATrafficPenaltyMode.optimal
coreRouter.dynamicPenalty = penalty
progress = coreRouter.calculateRoute(withStops: stops, routingMode: routingMode) { (result, error) in
And as result we're getting totally different route:
We found all the parameters that sent by default with app request and tried to do same on web part(at least one that we found on documentation, as its quite empty):
But nothing helped, routed still different. Our guess that web and mobile API uses different calculations on api side, but we cant find any proofs. How can we have both app side and web side api's with trucks parameters give us same routes? This is critical part of the logic.
Thank you
The base algorithms are or started the same, but the code base has diverged between the mobile SDK and web services in the last years.
The Web services have newer features like HSP (historical speed patterns), but the mobile SDK service does not (and can not). Therefore you might get slightly different results.
The mobile SDK route calculation might also be done in offline mode, where the algorithm is different for sure.

in angularjs, With time, $interval delay is reducing automatically. would it be an issue by having multiple $intervals in single controller?

I have an AngularJs app. in a single controller, i have to pull data from 3 different source and display the data in 3 different sections. (in top , mid and bottom section). data in each section would vary in a set delay. for top section, i have used Set interval and clear interval. for mid and bottom section , i have used $interval.For mid section, the delay is set to 7 and for bottom section, it is set to 10 sec.
when i launch the application, everything works fine. but with time, the mid and bottom section varies in every 2 or 3 seconds instead of 7 and 10 respectively. i dont know where i am doing the mistake. i have not added $interval.cancel as i want the mid and bottom section to bring the data in 7 and 10 sec delay continuously without stopping. i am also using socket to bring the data for all the sections. I have not used $scope.on'Destory' . i don't if that has any impact here. below is the code. Any help would be greatly appreciated.
socket.on('midsection', function (data) {
tableJson = [];
SplicedJson = [];
jsoninput = [];
jsoninput.push(data);
// splitting single array in to two array's so that we can display them one after the other after some delay
SplicedJson.push(jsoninput[0].splice(0, 6));
tableJson.push(jsoninput[0]);
$scope.tableData = tableJson;
//Creating interval and setting counter just to swap the json source for display
var Counter = 1;
$interval(function () {
Counter++;
if (Counter % 2 === 0) {
$scope.tableData = SplicedJson;
}
else {
$scope.tableData = tableJson;
}
}, 7000);
});
socket.on('lastSection', function (data) {
if (data.length > 3) {
array1.push(data[0]["publisher"]);
array1.push(data[1]["publisher"]);
array1.push(data[2]["publisher"]);
array2.push(data[0]["title"]);
array2.push(data[1]["title"]);
array2.push(data[2]["title"]);
$scope.msg = array1;
$scope.msg2 = array2;
$interval(function () {
data = shuffle(data); // caling custom built shuffle fn to shuffle the data to display random data everytime
console.log('Shuffled', data);
array1= [];
array2= [];
array1.push(data[0]["publisher"]);
array1.push(data[1]["publisher"]);
array1.push(data[2]["publisher"]);
array2.push(data[0]["title"]);
array2.push(data[1]["title"]);
array2.push(data[2]["title"]);
$scope.msg = array1;
$scope.msg2 = array2;
},10000);
}
});
Code # connection launch is below
io.on('connection', function (socket) {
socket.join(socket.handshake.query.room)
var entExFilepath = './midsectionData.json';
var parsedJSON = JSON.parse(fs.readFileSync(entExFilepath, 'utf8'));
fs.watchFile(entExFilepath, function () {
parsedJSON = JSON.parse(fs.readFileSync(entExFilepath, 'utf8'));
io.sockets.emit('midsection', parsedJSON);
});
io.sockets.emit('midsection', parsedJSON);
if (feedresults.length > 3) {
io.sockets.emit('lastsection', feedresults);
}
I found the cause for this issue. the problem was when i send the data for mid and last section, i was doing socket.emit which was equivalent to broadcasting the answer to all the clients.So Whenever a new request comes to the server, socket.emit was being called and sent the data to the client. (which means it also calls the internal block when ever a new request comes. so the interval is called again and again).I should have done like below. This resolved the issue.
//io.sockets.emit('lastsection', feedresults);
io.sockets.in(socket.handshake.query.room).emit('lastsection', feedresults);// This should send the data to the current client
Hope this helps others

in CakePHP I want to have 2 cookies as they need different expiry times...can I do this?

I have been trying like this -
// ================
// = set a Cookie for the users city =
// ================
function set($cityId = null){
$this->components[] = 'RequestHandler';
$this->components[] = 'Cookie';
$this->Cookie->name = 'Exampleoffers';
//$this->Cookie->time = 3600; // or '1 hour'
//$this->Cookie->path = '/bakers/preferences/';
$this->Cookie->domain = 'www.example.co.uk';
$this->Cookie->secure = false;
$this->Cookie->key = 'kkjdDqSI232qs*&sXOw!';
$cities = ($this->City->find('list'));
if($cities[$cityId]) {
$this->Cookie->write ("Deal.city_id", (int) $cityId, false, "+2 months");
} else {
$this->Cookie->write ("Deal.city_id", key($cities), false, "+2 months");
}
however, I am not sure if it is clashing with my Authsome cookie (?) or something else, but I am unable to read this value back.
Is there some way to specify which cookie you want to read() from in CakePHP?
Is there a way to have a cookie with 2 diffferent values of expiry times? - i.e. a cookie has User.id with a expiry of 1 week, and a Deal.city_id with a expiry of 2 months, say? Or am I right to think I DO need 2 cookies?
many thanks for any tips. It's cake 1.3 btw !
You can, remember cookies are saved on the system so if you only save the cookie one time on that system it will have the set values, however, you cannot have 2 cookies with the same name set, which means that when you go and save the cookies you'll have to do this:
$this->Cookie->write('Name1', $data, false, $time);
$this->Cookie->write('Name2', $data, false, $time);
If you don't, one will overwrite the other.
EDIT: Adding some links in case you have more doubts:
API page of CookieComponent: http://api13.cakephp.org/class/cookie-component
Cookbook page of CookieComponent: http://book.cakephp.org/view/1280/Cookies

Channel API closes a channel

First off, thank you #Moishe for the very useful API. I'm having a little timeout problem, maybe someone knows the answer. Here's how I open the channel:
var openChannel = function () {
var channel = new goog.appengine.Channel($('#token').val());
var socket = channel.open();
socket.onopen = function () {};
socket.onmessage = function (m) {
var message = JSON.parse(m.data);
// do stuff
};
socket.onerror = function (error) { alert(error); };
socket.onclose = openChannel;
};
openChannel();
This works fine, I post my messages and they go to the other clients pretty quickly. But if I stay on the page for roughly 15 minutes, the server loses track of my channel. In dev, it throws an error (which I saw was a known bug: http://www.mail-archive.com/google-appengine#googlegroups.com/msg44609.html). But in prod, it still ignores messages on that channel after about 15 minutes.
We fixed it by adding a setInterval(getSomeUrl, everyMinute) to the page, but we'd rather not have to do that. I noticed in Moishe's last commit for the trivia game sample that he took out a keep-alive. I didn't understand how he replaced it, and what he meant by onopen is reliable:
http://code.google.com/p/trivia-quiz/source/browse/trunk/src/index.html
Update: Server side code is
class Home(BaseHandler):
def get(self):
self.checkUser()
if self.user:
userId = self.user.user_id()
token = channel.create_channel(userId)
chatClients[userId] = token
self.model['token'] = token
players = self.checkChatRoom()
self.model['users'] = players
self.model['messages'] = map(lambda k:db.get(k), self.chat_room.messages) # TODO: Replace this line and the next with a query
self.model['messages'] = sorted(self.model['messages'], key=lambda m: m.timestamp, reverse=True)
self.writeTemplate('index.html')
BaseHandler is just a base class I use for all my GAE handlers, it provides checkUser which redirects if the user isn't logged in, and it provides writeTemplate which takes what's in self.model and writes it in a template. It's just a proof of concept, so no cache or anything else other than what's above.

Resources