geolocalisation is very slow - c#-4.0

I've a application for the geolocalisation and I retrieve the current geoposition but the display on the application is VERY slow...
The constructor :
public TaskGeo()
{
InitializeComponent();
_geolocator = new Geolocator();
_geolocator.DesiredAccuracy = PositionAccuracy.High;
_geolocator.MovementThreshold = 100;
_geolocator.PositionChanged += _geolocator_PositionChanged;
_geolocator.StatusChanged += _geolocator_StatusChanged;
if (_geolocator.LocationStatus == PositionStatus.Disabled)
this.DisplayNeedGPS();
}
the code for the display on the app :
void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
// saving and display of the position
App.RootFrame.Dispatcher.BeginInvoke(() =>
{
this._CurrentPosition = args.Position;
this.lblLon.Text = "Lon: " + this._CurrentPosition.Coordinate.Longitude;
this.lblLat.Text = "Lat: " + this._CurrentPosition.Coordinate.Latitude;
this.LocationChanged(this._CurrentPosition.Coordinate.Longitude, this._CurrentPosition.Coordinate.Latitude);
});
}
And the code for the query :
private void LocationChanged(double lat, double lon)
{
ReverseGeocodeQuery rgq = new ReverseGeocodeQuery();
rgq.GeoCoordinate = new GeoCoordinate(lat, lon);
rgq.QueryCompleted += rgq_QueryCompleted;
rgq.QueryAsync();
}
How can I improve the code to display faster the position ? Thanks in advance !

Getting this sort of information is basically pretty slow. To quote the great Louis C. K. "It is going to space, give it a second". Because you've specified PositionAccuracy.High this means that the location must be found using GPS, which is comparatively slow, and not any of the faster fallback methods such as using local wi-fi or cell phone towers.
You could reduce your demands for accuracy overall or initially request a lower accuracy and then refine it once the information from the GPS is available. The second option is better. If you look at a map application they typically do this by showing you about where you are and then improving it after the GPS lock is acquired.

Related

How to get nearest PositionComponent in a good way?

I have a "player" and several "enemy" beside:
Now I just use a loop to get every distance:
void fireBullet() {
var enemies = gameRef.children.whereType<Enemy>();
if (enemies.isEmpty) return;
PositionComponent nearestEnemy = enemies.first;
enemies.forEach((element) {
if (element.distance(playerComponent) < nearestEnemy.distance(playerComponent)) {
nearestEnemy = element;
}
});
// fire bullet to enemy
}
I think it's not the best solution. If there's too many enemy, performance will degrade.
Is there any better way to get nearest PositionComponent?
There is no better built-in method unfortunately.
There are a few improvements that you can do to your game though that will make a big performance difference:
Use distance2, because then it won't have to do a square root operation behind the scenes.
Save the last distance calculation to avoid doing it twice.
Use query instead of whereType (the query is cached).
So it would be something like this:
void fireBullet() {
var enemies = gameRef.children.query<Enemy>();
if (enemies.isEmpty) return;
var nearestEnemy = enemies.first;
var nearestDistance = nearestEnemy.position.distance2(playerComponent);
enemies.forEach((element) {
final distance = element.position.distance2(playerComponent.position);
if (distance < distanceNearest) {
nearestEnemy = element;
nearestDistance = distance;
}
});
// fire bullet to enemy
}
I believe that you would have other performance issues before you hit performance issues with this code in the updated state.

Haxe for loop only uses last item

After some hours doing some testing I figured out that my map contains the correct values, but the loop that I am using only seems to be using the last added value in this map. Am I missing something obvious here?
The function that adds items to the map: (controls is the map variable)
public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
{
var controllerName = "Thumbstick"+mLocation;
if(!controls.exists(controllerName)){
createRecycledActor(mActorType, 0, 0, Script.FRONT);
var lastActor = getLastCreatedActor();
var myPosition = GetPosition(controllerName, lastActor);
lastActor.setX(myPosition.x);
lastActor.setY(myPosition.y);
var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());
var controlUnit = new ControlUnit(lastActor, myPos, -1);
controls.set(controllerName, controlUnit);
trace("added key: " + controllerName +" with value: "+ lastActor);
} else {
trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
}
}
Upon creating 3 thumbsticks, the log states the following:
added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]
When the screen is touched, it should loop through each item in my map, but it is using the last added item 3 times to check the distance with, rather then all 3 items once. Here is the Listener that is being called when the screen is touched:
addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
{
for (unit in controls){
trace(lastDebugLine + "checking distance to " + unit.GetActor());
if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
break;
}
}
});
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!
Upon touching the screen, the log states the following:
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
I am quite new to the Haxe language, so my guess is that I am missing something obvious, even after I have followed the Haxe API very closely. This is the example used from the Haxe API page:
var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
for (value in map4) {
trace(value); // Monday \n Tuesday
}
All explanations are welcome!
Added ControlUnit class:
import com.stencyl.models.Actor;
class ControlUnit
{
static var actor;
static var center;
static var touchID;
public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int)
{
actor = mActor;
center = mPosition;
touchID = mTouchID;
}
public function GetActor():Actor{
return(actor);
}
public function GetCenter():Vector2{
return(center);
}
public function GetTouchID():Int{
return(touchID);
}
}
You just used static for vars in class definitions - they aren't instance aware/based.
Check 'properties', getters, setters etc. in https://haxe.org/manual/class-field-property.html
Are you sure that getLastCreatedActor() is returning a separate instance each time? If it's returning the same instance each time you will likely see what you're getting.
Isn't that because all of your keys map to the same value? Try mapping them to different values and test it.

Uncaught TypeError: Cannot read property 'copy' of undefined p5.js/node.js/socket.io

I'm having an error when the second client is connected. My code comparing the two clients current position by p5.Vector.dist() and there's an error, here it is.
And the line in p5.Vector.dist(p5.js:25914) is
p5.Vector.prototype.dist = function (v) {
var d = v.copy().sub(this); //This is the exact line where the error says from
return d.mag();
};
This is my code;
Client side;
//I use for loop to see all the contain of otherCircles
for(var x = 0; x < otherCircles.length; x++){
if(otherCircles[x].id != socket.id){ //To make sure i won't compare the client's data to its own because the data of all connected client's is here
console.log(otherCircles[x].radius); //To see if the data is not null
if(circle.eat(otherCircles[x])){
if(circle.radius * 0.95 >= otherCircles[x].radius){
otherCircles.splice(x,1);
console.log('ATE');
} else if(circle.radius <= otherCircles[x].radius * 0.95){
zxc = circle.radius;
asd = zxc;
circle.radius = null;
console.log('EATEN');
}
}
}
}
//Here's the eat function of the circle
function Circle(positionX,positionY,radius){
//The variables of Circle()
this.position = createVector(positionX, positionY);
this.radius = radius;
this.velocity = createVector(0, 0);
//Here's the eat function
this.eat = function(other) {
var distance = p5.Vector.dist(this.position, other.position); //Heres where the error
if (distance < this.radius + (other.radius * 0.25)) { //Compare there distance
return true;
} else {
return false;
}
}
}
The otherCircles[] contains;
And that is also the output of the line console.log(otherCircles[x].radius);.
I don't think the server side would be necessary because it only do is to receive the current position and size of the client and send the other clients position and size to. All there datas stored in otherCircles(). The line console.log(otherCircles[x].radius); result is not null, so I know there's data where being compared to the clients position, why I'm having an error like this.
It's going to be pretty hard to help you without an MCVE, but I'll try to walk you through debugging this.
You've printed otherCircles[x].radius, which is a good start. But if I were you, I'd want to know much more about otherCircles[x]. What variables and functions does it contain? I'd start by googling "JavaScript print function names of object" and try to figure out exactly what's in that object. What is the value of otherCircles[x].position?
From there, I'd also want to make sure that otherCircles[x].position is defined and an instance of p5.Vector. Does it have a copy() function?
I might also step through the code with a debugger- every browser has one, and you should become familiar with using it.
If you still can't get it work, then please post an MCVE that we can run by copy-pasting it. That means no server code, just hard-code your values so we can see the same error. I'd bet you find your problem while trying to narrow it down to a small example. But if not, we'll go from there. Good luck.

Distinct values in Azure Search Suggestions?

I am offloading my search feature on a relational database to Azure Search. My Products tables contains columns like serialNumber, PartNumber etc.. (there can be multiple serialNumbers with the same partNumber).
I want to create a suggestor that can autocomplete partNumbers. But in my scenario I am getting a lot of duplicates in the suggestions because the partNumber match was found in multiple entries.
How can I solve this problem ?
The Suggest API suggests documents, not queries. If you repeat the partNumber information for each serialNumber in your index and then suggest based on partNumber, you will get a result for each matching document. You can see this more clearly by including the key field in the $select parameter. Azure Search will eliminate duplicates within the same document, but not across documents. You will have to do that on the client side, or build a secondary index of partNumbers just for suggestions.
See this forum thread for a more in-depth discussion.
Also, feel free to vote on this UserVoice item to help us prioritize improvements to Suggestions.
I'm facing this problem myself. My solution does not involve a new index (this will only get messy and cost us money).
My take on this is a while-loop adding 'UserIdentity' (in your case, 'partNumber') to a filter, and re-search until my take/top-limit is met or no more suggestions exists:
public async Task<List<MachineSuggestionDTO>> SuggestMachineUser(string searchText, int take, string[] searchFields)
{
var indexClientMachine = _searchServiceClient.Indexes.GetClient(INDEX_MACHINE);
var suggestions = new List<MachineSuggestionDTO>();
var sp = new SuggestParameters
{
UseFuzzyMatching = true,
Top = 100 // Get maximum result for a chance to reduce search calls.
};
// Add searchfields if set
if (searchFields != null && searchFields.Count() != 0)
{
sp.SearchFields = searchFields;
}
// Loop until you get the desired ammount of suggestions, or if under desired ammount, the maximum.
while (suggestions.Count < take)
{
if (!await DistinctSuggestMachineUser(searchText, take, searchFields, suggestions, indexClientMachine, sp))
{
// If no more suggestions is found, we break the while-loop
break;
}
}
// Since the list might me bigger then the take, we return a narrowed list
return suggestions.Take(take).ToList();
}
private async Task<bool> DistinctSuggestMachineUser(string searchText, int take, string[] searchFields, List<MachineSuggestionDTO> suggestions, ISearchIndexClient indexClientMachine, SuggestParameters sp)
{
var response = await indexClientMachine.Documents.SuggestAsync<MachineSearchDocument>(searchText, SUGGESTION_MACHINE, sp);
if(response.Results.Count > 0){
// Fix filter if search is triggered once more
if (!string.IsNullOrEmpty(sp.Filter))
{
sp.Filter += " and ";
}
foreach (var result in response.Results.DistinctBy(r => new { r.Document.UserIdentity, r.Document.UserName, r.Document.UserCode}).Take(take))
{
var d = result.Document;
suggestions.Add(new MachineSuggestionDTO { Id = d.UserIdentity, Namn = d.UserNamn, Hkod = d.UserHkod, Intnr = d.UserIntnr });
// Add found UserIdentity to filter
sp.Filter += $"UserIdentity ne '{d.UserIdentity}' and ";
}
// Remove end of filter if it is run once more
if (sp.Filter.EndsWith(" and "))
{
sp.Filter = sp.Filter.Substring(0, sp.Filter.LastIndexOf(" and ", StringComparison.Ordinal));
}
}
// Returns false if no more suggestions is found
return response.Results.Count > 0;
}
public async Task<List<string>> SuggestionsAsync(bool highlights, bool fuzzy, string term)
{
SuggestParameters sp = new SuggestParameters()
{
UseFuzzyMatching = fuzzy,
Top = 100
};
if (highlights)
{
sp.HighlightPreTag = "<em>";
sp.HighlightPostTag = "</em>";
}
var suggestResult = await searchConfig.IndexClient.Documents.SuggestAsync(term, "mysuggestion", sp);
// Convert the suggest query results to a list that can be displayed in the client.
return suggestResult.Results.Select(x => x.Text).Distinct().Take(10).ToList();
}
After getting top 100 and using distinct it works for me.
You can use the Autocomplete API for that where does the grouping by default. However, if you need more fields together with the result, like, the partNo plus description it doesn't support it. The partNo will be distinct though.

Why code running on Azure is so slow?

I have a web app running on Azure shared web site mode. A simple method where I add items to a list and sort this list, when the list size is about 300 items, takes 0.3s on my machine and 10s after deploy (on azure machine).
Does anybody has any idea why Azure is so slow?
Is any configuration I do it wrong? I use default one but replaced FREE mode with SHARED mode because I thought this would help but it seems it does not.
UPDATE:
public ActionResult GetPosts(String selectedStreams, int implicitSelectedVisualiserId, int userId)
{
DateTime begin = DateTime.UtcNow;
List<SearchQuery> selectedSearchQueries = searchQueryRepository.GetSearchQueriesOfStreamsIds(selectedStreams == String.Empty ? new List<int>() : selectedStreams.Split(',').Select(n => int.Parse(n)).ToList());
var implicitSelectedVisualiser = VisualiserModel.ToVisualiserModel(visualiserRepository.GetVisualiser(implicitSelectedVisualiserId));
var twitterSearchQueryOfImplicitSelectedVisualiser = searchQueryRepository.GetSearchQuery(implicitSelectedVisualiser.Stream.Name, Service.Twitter, userId);
var instagramSearchQueryOfImplicitSelectedVisualiser = searchQueryRepository.GetSearchQuery(implicitSelectedVisualiser.Stream.Name, Service.Instagram, userId);
var facebookSearchQueryOfImplicitSelectedVisualiser = searchQueryRepository.GetSearchQuery(implicitSelectedVisualiser.Stream.Name, Service.Facebook, userId);
var manualSearchQueryOfImplicitSelectedVisualiser = searchQueryRepository.GetSearchQuery(implicitSelectedVisualiser.Stream.Name, Service.Manual, userId);
List<SearchResultModel> approvedSearchResults = new List<SearchResultModel>();
if (twitterSearchQueryOfImplicitSelectedVisualiser != null || instagramSearchQueryOfImplicitSelectedVisualiser != null || facebookSearchQueryOfImplicitSelectedVisualiser != null
|| manualSearchQueryOfImplicitSelectedVisualiser != null)
{
// Define search text to be displayed during slideshow;
SearchModel searchModel = new SearchModel();
// Set slideshow settings from implicit selected visualiser.
ViewBag.CurrentVisualiser = implicitSelectedVisualiser;
// Load search results from selected visualisers.
foreach (SearchQuery searchQuery in selectedSearchQueries)
{
approvedSearchResults.AddRange(
SearchResultModel.ToSearchResultModel(
searchResultRepository.GetSearchResults
(searchQuery.Id,
implicitSelectedVisualiser.Language)));
// Add defined query too.
searchModel.SearchValue += " " + searchQuery.Query;
}
// Add defined query for implicit selected visualiser.
if (twitterSearchQueryOfImplicitSelectedVisualiser != null)
searchModel.SearchValue += " " + twitterSearchQueryOfImplicitSelectedVisualiser.Query;
if (instagramSearchQueryOfImplicitSelectedVisualiser != null)
searchModel.SearchValue += " " + instagramSearchQueryOfImplicitSelectedVisualiser.Query;
if (facebookSearchQueryOfImplicitSelectedVisualiser != null)
searchModel.SearchValue += " " + facebookSearchQueryOfImplicitSelectedVisualiser.Query;
ViewBag.Search = searchModel;
// Also add search results from implicit selected visualiser
if (twitterSearchQueryOfImplicitSelectedVisualiser != null)
approvedSearchResults.AddRange(SearchResultModel.ToSearchResultModel(searchResultRepository.GetSearchResults(twitterSearchQueryOfImplicitSelectedVisualiser.Id, implicitSelectedVisualiser.Language)));
if (instagramSearchQueryOfImplicitSelectedVisualiser != null)
approvedSearchResults.AddRange(SearchResultModel.ToSearchResultModel(searchResultRepository.GetSearchResults(instagramSearchQueryOfImplicitSelectedVisualiser.Id, implicitSelectedVisualiser.Language)));
if (facebookSearchQueryOfImplicitSelectedVisualiser != null)
approvedSearchResults.AddRange(SearchResultModel.ToSearchResultModel(searchResultRepository.GetSearchResults(facebookSearchQueryOfImplicitSelectedVisualiser.Id, implicitSelectedVisualiser.Language)));
if (manualSearchQueryOfImplicitSelectedVisualiser != null)
approvedSearchResults.AddRange(SearchResultModel.ToSearchResultModel(searchResultRepository.GetSearchResults(manualSearchQueryOfImplicitSelectedVisualiser.Id, implicitSelectedVisualiser.Language)));
// if user selected to show only posts from specific number of last days.
var approvedSearchResultsFilteredByDays = new List<SearchResultModel>();
if (implicitSelectedVisualiser.ShowPostsFromLastXDays != 0)
{
foreach (SearchResultModel searchResult in approvedSearchResults)
{
var postCreatedTimeWithDays = searchResult.PostCreatedTime.AddDays(implicitSelectedVisualiser.ShowPostsFromLastXDays + 1);
if (postCreatedTimeWithDays >= DateTime.Now)
approvedSearchResultsFilteredByDays.Add(searchResult);
}
}
else
{
approvedSearchResultsFilteredByDays = approvedSearchResults;
}
// Order search results (posts to be displayed by created datetime).
var approvedSearchResultsOrdered = new List<SearchResultModel>();
if (implicitSelectedVisualiser.PostsSortOrder == PostsSortOrder.CREATED_DATE_ASC)
{
approvedSearchResultsOrdered = approvedSearchResultsFilteredByDays.OrderBy(s => s.PostCreatedTime).ToList(); ;
}
else if (implicitSelectedVisualiser.PostsSortOrder == PostsSortOrder.CREATED_DATE_DESC)
{
approvedSearchResultsOrdered = approvedSearchResultsFilteredByDays.OrderByDescending(s => s.PostCreatedTime).ToList(); ;
}
else if (implicitSelectedVisualiser.PostsSortOrder == PostsSortOrder.RANDOM)
{
var rnd = new Random();
approvedSearchResultsOrdered = approvedSearchResultsFilteredByDays.OrderBy(x => rnd.Next()).ToList();
}
// Load background images;
var visualiserImages = visualiserImageRepository.GetImages(implicitSelectedVisualiser.Id);
//foreach (SearchResultModel searchResultModel in approvedSearchResultsOrdered)
//{
// searchResultModel.BackgroundImagePath = TwitterUtils.GetRandomImageBackgroundForDisplay(visualiserImages);
//}
ViewBag.BackgroundImagePath = TwitterUtils.GetRandomImageBackgroundForDisplay(visualiserImages);
approvedSearchResults = approvedSearchResultsOrdered;
}
DateTime end = DateTime.UtcNow;
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception(String.Format("User {0}: Preparing {1} posts for visualiser took {2} seconds", MySession.Current.LoggedInUserName, approvedSearchResults.Count(), (end - begin).TotalMilliseconds / 1000)));
return PartialView("_DisplayPostsNew", approvedSearchResults);
}
This isn't surprising actually. The servers used in Windows Azure are currently mostly 1.6 GHz machines. The larger sized machine you use the more cores you get, but they are all the same speed. This likely is a much slower CPU than the development machine you use.
On Windows Azure Web Sites when you move to Shared mode you are still in a multi-tenant environment, so you could be seeing some noisy neighbors here. The difference between Free and Shared is that many of the quotas for free are removed since you are paying. When you move to Standard then you are assigned a Virtual Machine dedicated to your web sites (up to 100 of them), so that is the best case scenario since you are the only one using the resources at that point.
There was a thread on this on the MSDN forums a while back : http://social.msdn.microsoft.com/Forums/windowsazure/en-US/0d0a3a88-eac4-4b9e-8b10-4a547cbf653b/performance-of-azure-servers-slow-cpus?forum=windowsazuredevelopment
They have started offering different hardware configurations with more memory for Virtual Machines and Cloud Services and such, but I'm not sure the CPUs have been changed. It's hard to find the CPU stated on WindowsAzure.com anymore, but on the pricing calculator for Web Sites it references 1.6Ghz machines when you move the slider to Standard.
Actually I found the issue.
Locally, I tested with a few hundreds of records in my DB while in Azure DB I have over 70 000 records in that table which affects performance of the algorithm...
One mistake I did in the code above: I have filtered records from DB by specific date AFTER taking all out. By filtering directly in Linq, I increased the performance from 10s to 0.3s in Azure too.

Resources