Merge remote-tracking branch 'origin/master'

This commit is contained in:
Milo 2019-04-07 00:04:13 +02:00
commit 30ed7e47f6
26 changed files with 212 additions and 76 deletions

View file

@ -3999,6 +3999,21 @@
"resolved": "https://registry.npmjs.org/nativescript-permissions/-/nativescript-permissions-1.2.3.tgz", "resolved": "https://registry.npmjs.org/nativescript-permissions/-/nativescript-permissions-1.2.3.tgz",
"integrity": "sha1-4+ZVRfmP5IjdVXj3/5DrrjCI5wA=" "integrity": "sha1-4+ZVRfmP5IjdVXj3/5DrrjCI5wA="
}, },
"nativescript-powerinfo": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/nativescript-powerinfo/-/nativescript-powerinfo-1.0.7.tgz",
"integrity": "sha1-ZXIq2bQwxIR7lRJT5kUmt1zsGXo=",
"requires": {
"typescript": "^1.8.10"
},
"dependencies": {
"typescript": {
"version": "1.8.10",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-1.8.10.tgz",
"integrity": "sha1-tHXW4N/wv1DyluXKbvn7tccyDx4="
}
}
},
"nativescript-theme-core": { "nativescript-theme-core": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/nativescript-theme-core/-/nativescript-theme-core-1.0.4.tgz", "resolved": "https://registry.npmjs.org/nativescript-theme-core/-/nativescript-theme-core-1.0.4.tgz",
@ -5861,6 +5876,12 @@
"resolved": "https://registry.npmjs.org/tns-core-modules-widgets/-/tns-core-modules-widgets-5.3.0.tgz", "resolved": "https://registry.npmjs.org/tns-core-modules-widgets/-/tns-core-modules-widgets-5.3.0.tgz",
"integrity": "sha512-mR8Pof0NhMRhPYcshQ54WyPrlbrqmTgrwxALtF1485fbCAHblz/2DqU7yGmTgC5LNdV7yhNeHYouoYg3TYOZbA==" "integrity": "sha512-mR8Pof0NhMRhPYcshQ54WyPrlbrqmTgrwxALtF1485fbCAHblz/2DqU7yGmTgC5LNdV7yhNeHYouoYg3TYOZbA=="
}, },
"tns-platform-declarations": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/tns-platform-declarations/-/tns-platform-declarations-5.3.1.tgz",
"integrity": "sha512-sTEx3eGOEqILzLTARIamuMlCL0fZ3REyVaCJ0n19Nq7OdjnQiTV6zGADl5yQ1mI4NLZVtAtLQgc90Qj9XYnMIw==",
"dev": true
},
"to-arraybuffer": { "to-arraybuffer": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",

View file

@ -24,6 +24,7 @@
"nativescript-angular": "~7.2.0", "nativescript-angular": "~7.2.0",
"nativescript-camera": "^4.4.0", "nativescript-camera": "^4.4.0",
"nativescript-geolocation": "^5.0.0", "nativescript-geolocation": "^5.0.0",
"nativescript-powerinfo": "^1.0.7",
"nativescript-theme-core": "~1.0.4", "nativescript-theme-core": "~1.0.4",
"reflect-metadata": "~0.1.12", "reflect-metadata": "~0.1.12",
"rxjs": "~6.3.0", "rxjs": "~6.3.0",
@ -35,7 +36,8 @@
"@nativescript/schematics": "~0.5.0", "@nativescript/schematics": "~0.5.0",
"@ngtools/webpack": "~7.2.0", "@ngtools/webpack": "~7.2.0",
"nativescript-dev-typescript": "~0.9.0", "nativescript-dev-typescript": "~0.9.0",
"nativescript-dev-webpack": "~0.21.0" "nativescript-dev-webpack": "~0.21.0",
"tns-platform-declarations": "^5.3.1"
}, },
"gitHead": "803cec054c44c99eaa59cdc267993e6346f6cb3a", "gitHead": "803cec054c44c99eaa59cdc267993e6346f6cb3a",
"readme": "NativeScript Application" "readme": "NativeScript Application"

View file

@ -1,12 +1,3 @@
<AbsoluteLayout> <GridLayout>
<ns-side-drawer></ns-side-drawer> <page-router-outlet></page-router-outlet>
</GridLayout>
<StackLayout class="float-btn-container">
<ns-my-button (tap)=onTap($event) text="Nightr"></ns-my-button>
</StackLayout>
<StackLayout>
<ns-locationButton></ns-locationButton>
<ns-camera-button></ns-camera-button>
</StackLayout>
</AbsoluteLayout>

View file

@ -1,41 +1,8 @@
import { Component } from "@angular/core"; import { Component } from "@angular/core";
import * as dialogs from "tns-core-modules/ui/dialogs";
import { MyHttpPostService } from './services/my-http-post-service'
import { TouchGestureEventData, GestureEventData } from 'tns-core-modules/ui/gestures'
import { isEnabled, enableLocationRequest, getCurrentLocation, watchLocation, distance, clearWatch } from "nativescript-geolocation";
@Component({ @Component({
selector: "ns-app", selector: "ns-app",
moduleId: module.id, moduleId: module.id,
templateUrl: "./app.component.html", templateUrl: "./app.component.html",
styleUrls: ['./app.component.css'],
providers: [MyHttpPostService]
}) })
export class AppComponent { export class AppComponent {}
public user: string = "";
public pass: string = "";
returnMessage: string = "";
constructor(private myHttpPostSerivce: MyHttpPostService) { }
public onTap(args: GestureEventData): any {
this.submit();
dialogs.confirm("Should be result").then(result => {
console.log("Dialog result: " + result);
});
}
public submit(): void {
this.makePostRequest();
}
private makePostRequest(): void {
console.log('Reached makepostRequest');
this.myHttpPostSerivce
.postData({ username: this.user, password: this.pass })
.subscribe(res => {
console.log('This is res', res);
this.returnMessage = (<any>res).json.data.username;
});
}
}

View file

@ -1,11 +1,14 @@
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module"; import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { AppComponent } from "./app.component"; import { AppComponent } from "./app.component";
import { HomePageComponent } from "./home-page/home-page.component";
import { MyButtonComponent } from './component/my-button/my-button.component'; import { MyButtonComponent } from './component/my-button/my-button.component';
import { NativeScriptHttpClientModule } from "nativescript-angular/http-client"; import { NativeScriptHttpClientModule } from "nativescript-angular/http-client";
import { MyLocationButtonComponent } from './component/locationButton/locationButton.component'; import { MyLocationButtonComponent } from './component/locationButton/locationButton.component';
import { CameraButtonComponent } from './component/camera-button/camera-button.component'; import { CameraButtonComponent } from './component/camera-button/camera-button.component';
import { ResultPageComponent } from './result-page/result-page.component';
// Uncomment and add to NgModule imports if you need to use two-way binding // Uncomment and add to NgModule imports if you need to use two-way binding
// import { NativeScriptFormsModule } from "nativescript-angular/forms"; // import { NativeScriptFormsModule } from "nativescript-angular/forms";
@ -18,6 +21,12 @@ import { CameraButtonComponent } from './component/camera-button/camera-button.c
AppComponent AppComponent
], ],
imports: [ imports: [
NativeScriptRouterModule,
NativeScriptRouterModule.forRoot([
{ path: "", redirectTo: "/home-page", pathMatch: "full" },
{ path: "home-page", component: HomePageComponent},
{ path: "result-page", component: ResultPageComponent}
]),
NativeScriptModule, NativeScriptModule,
NativeScriptHttpClientModule, NativeScriptHttpClientModule,
], ],
@ -26,6 +35,8 @@ import { CameraButtonComponent } from './component/camera-button/camera-button.c
MyLocationButtonComponent, MyLocationButtonComponent,
MyButtonComponent, MyButtonComponent,
CameraButtonComponent, CameraButtonComponent,
ResultPageComponent,
HomePageComponent,
], ],
providers: [], providers: [],
schemas: [ schemas: [

View file

@ -1,4 +1,4 @@
<StackLayout> <StackLayout>
<Button text="{{title}}" class="btn btn-primary" (tap)="onTap()"></Button> <Button text="{{title}}" class="btn btn-primary" (tap)="onTap($event)"></Button>
<Label text="{{lat}}"></Label> <Label text="{{lat}}"></Label>
</StackLayout> </StackLayout>

View file

@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core'; import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { TouchGestureEventData, GestureEventData } from 'tns-core-modules/ui/gestures'
import { MyGeoLocationService} from '../../services/my-geo-location.service'; import { MyGeoLocationService} from '../../services/my-geo-location.service';
@Component({ @Component({
selector: 'ns-locationButton', selector: 'ns-locationButton',
@ -11,12 +12,15 @@ export class MyLocationButtonComponent implements OnInit {
lat = "start"; lat = "start";
geoLocationService = new MyGeoLocationService(); geoLocationService = new MyGeoLocationService();
@Output() tap: EventEmitter<GestureEventData> = new EventEmitter<GestureEventData>();
constructor() { constructor() {
} }
ngOnInit() { ngOnInit() {
} }
onTap() { onTap(args: GestureEventData): any {
this.tap.emit(args);
this.geoLocationService.getLocation().then(location => { this.geoLocationService.getLocation().then(location => {
this.lat = ""+location.latitude; this.lat = ""+location.latitude;
}).catch(error => { }).catch(error => {

View file

@ -0,0 +1,5 @@
.float-btn-container
{
margin-top: 35%;
margin-left: 20%;
}

View file

@ -0,0 +1,14 @@
<ActionBar title="Home" class="action-bar"></ActionBar>
<ScrollView class="page">
<AbsoluteLayout>
<StackLayout class="float-btn-container">
<ns-my-button (tap)=onTap($event) text="Nightr"></ns-my-button>
</StackLayout>
<StackLayout>
<ns-locationButton></ns-locationButton>
<ns-camera-button></ns-camera-button>
<Button class="btn btn-primary" text="Result page" [nsRouterLink]="['/result-page']"></Button>
</StackLayout>
</AbsoluteLayout>
</ScrollView>

View file

@ -0,0 +1,49 @@
import { Component, OnInit } from "@angular/core";
import * as dialogs from "tns-core-modules/ui/dialogs";
import { MyHttpPostService } from '../services/my-http-post-service'
import { RouterExtensions } from "nativescript-angular/router";
import { TouchGestureEventData, GestureEventData } from 'tns-core-modules/ui/gestures'
import { isEnabled, enableLocationRequest, getCurrentLocation, watchLocation, distance, clearWatch } from "nativescript-geolocation";
@Component({
selector: "home-page",
moduleId: module.id,
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css'],
providers: [MyHttpPostService]
})
export class HomePageComponent implements OnInit {
public user: string = "";
public pass: string = "";
returnMessage: string = "";
constructor(private myHttpPostSerivce: MyHttpPostService, private routerExtensions: RouterExtensions) { }
public onTap(args: GestureEventData): any {
this.routerExtensions.navigateByUrl("/result-page");
this.submit();
dialogs.confirm("Should be result").then(result => {
console.log("Dialog result: " + result);
});
}
public submit(): void {
this.makePostRequest();
}
private makePostRequest(): void {
console.log('Reached makepostRequest');
this.myHttpPostSerivce
.postData({ username: this.user, password: this.pass })
.subscribe(res => {
console.log('This is res', res);
this.returnMessage = (<any>res).json.data.username;
});
}
ngOnInit(): void {
}
goBack(): void {
this.routerExtensions.back();
}
}

View file

@ -0,0 +1 @@
/* Add mobile styles for the component here. */

View file

@ -0,0 +1,7 @@
<ActionBar title="Result" class="action-bar"></ActionBar>
<ScrollView class="page">
<AbsoluteLayout>
<Button class="btn btn-primary" text="Home" [nsRouterLink]="['/home-page']"></Button>
</AbsoluteLayout>
</ScrollView>

View file

@ -0,0 +1,21 @@
import { Component, OnInit } from '@angular/core';
import { RouterExtensions } from 'nativescript-angular/router';
@Component({
selector: 'result-page',
templateUrl: './result-page.component.html',
styleUrls: ['./result-page.component.css'],
moduleId: module.id,
})
export class ResultPageComponent implements OnInit {
constructor(private routerExtensions: RouterExtensions) { }
ngOnInit(): void {
}
goBack(): void {
this.routerExtensions.back();
}
}

View file

@ -0,0 +1,22 @@
import { Injectable } from '@angular/core';
import { android as androidApp, ios as iosApp } from "tns-core-modules/application";
import { ios as iosUtils } from "tns-core-modules/utils/utils";
@Injectable({
providedIn: 'root'
})
export class MyBatteryInfoService {
public getBatteryLife() {
if (iosApp){
iosUtils.getter(UIDevice, UIDevice.currentDevice).batteryMonitoringEnabled = true;
let battery = +(iosUtils.getter(UIDevice, UIDevice.currentDevice).batteryLevel * 100);
}else{
androidApp.registerBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED,(context: android.content.Context, intent: android.content.Intent) =>{
let level = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
let scale = intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1);
let percent = (level / scale) * 100.0;
});
}
}
}

View file

@ -10,7 +10,6 @@ export class MyHttpPostService {
constructor(private http: HttpClient) { } constructor(private http: HttpClient) { }
postData(data: any) { postData(data: any) {
console.log('logged data is', data);
let options = this.createRequestOptions(); let options = this.createRequestOptions();
return this.http.post(this.serverUrl, { data }, { headers: options }); return this.http.post(this.serverUrl, { data }, { headers: options });
} }

View file

@ -11,4 +11,4 @@ var app_module_1 = require("./app/app.module");
// so we provide a wrapper platform object, platformNativeScriptDynamic, // so we provide a wrapper platform object, platformNativeScriptDynamic,
// that sets up a NativeScript application and can bootstrap the Angular framework. // that sets up a NativeScript application and can bootstrap the Angular framework.
platform_1.platformNativeScriptDynamic().bootstrapModule(app_module_1.AppModule); platform_1.platformNativeScriptDynamic().bootstrapModule(app_module_1.AppModule);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIm1haW4udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSwwR0FBMEc7QUFDMUcsMERBQTRFO0FBRTVFLCtDQUE2QztBQUU3QyxnRkFBZ0Y7QUFDaEYsMEVBQTBFO0FBQzFFLHNFQUFzRTtBQUN0RSx5REFBeUQ7QUFDekQseUVBQXlFO0FBQ3pFLHdFQUF3RTtBQUN4RSxtRkFBbUY7QUFDbkYsc0NBQTJCLEVBQUUsQ0FBQyxlQUFlLENBQUMsc0JBQVMsQ0FBQyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiLy8gdGhpcyBpbXBvcnQgc2hvdWxkIGJlIGZpcnN0IGluIG9yZGVyIHRvIGxvYWQgc29tZSByZXF1aXJlZCBzZXR0aW5ncyAobGlrZSBnbG9iYWxzIGFuZCByZWZsZWN0LW1ldGFkYXRhKVxuaW1wb3J0IHsgcGxhdGZvcm1OYXRpdmVTY3JpcHREeW5hbWljIH0gZnJvbSBcIm5hdGl2ZXNjcmlwdC1hbmd1bGFyL3BsYXRmb3JtXCI7XG5cbmltcG9ydCB7IEFwcE1vZHVsZSB9IGZyb20gXCIuL2FwcC9hcHAubW9kdWxlXCI7XG5cbi8vIEEgdHJhZGl0aW9uYWwgTmF0aXZlU2NyaXB0IGFwcGxpY2F0aW9uIHN0YXJ0cyBieSBpbml0aWFsaXppbmcgZ2xvYmFsIG9iamVjdHMsXG4vLyBzZXR0aW5nIHVwIGdsb2JhbCBDU1MgcnVsZXMsIGNyZWF0aW5nLCBhb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ER5bmFtaWMoKS5ib290c3RyYXBNb2R1bGUoQXBwTW9kdWxlKTtcclxuIl19

View file

@ -10,7 +10,7 @@ from typing import List
import requests_cache import requests_cache
from flask import Flask, jsonify, logging, request from flask import Flask, jsonify, logging, request
from .strategies import miloStrats, iss, cars_in_traffic, tide_strat, upstairs_neighbour, bing from .strategies import miloStrats, iss, cars_in_traffic, tide_strat, upstairs_neighbour, bing, svm_strat, battery
from .util import Context from .util import Context
app = Flask(__name__) app = Flask(__name__)
@ -30,6 +30,8 @@ strategies = {
"tide": tide_strat.is_tide, "tide": tide_strat.is_tide,
"upstairs_neighbour": upstairs_neighbour.check_games, "upstairs_neighbour": upstairs_neighbour.check_games,
"bing": bing.clock, "bing": bing.clock,
"svm_parking": svm_strat.perform_svm_pred,
"battery_level": battery.battery_level,
} }

View file

@ -0,0 +1,21 @@
from ..util import Context, Prediction
def battery_level(context: Context) -> Prediction:
"""
If the battery is low, it's probably bedtime soon.
"""
p = Prediction()
if context.battery > 60:
p.reasons.append("Battery level's good, so it's probably still early in the day.")
elif context.battery > 30:
p.reasons.append("Battery level's getting low, so it's probably around dinnertime.")
elif context.battery > 10:
p.reasons.append("Your phone is dying, so it's bedtime soon?")
else:
p.reasons.append("Your phone's practically dead, so it's probably around four in the morning.")
p.probability = 1 - (context.battery / 100) # night is inverse proportional to battery level
return p

View file

@ -11,7 +11,7 @@ def clock(context: Context) -> Prediction:
It's nighttime if Bing says it's daytime. It's nighttime if Bing says it's daytime.
""" """
p = Prediction() p = Prediction()
p.weight = 0.05 p.weight = 0.02
headers = { headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'} 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
@ -22,7 +22,7 @@ def clock(context: Context) -> Prediction:
time = datetime.strptime(time_str, "%H:%M") time = datetime.strptime(time_str, "%H:%M")
night = time.hour < 6 or time.hour >= 22 night = time.hour < 6 or time.hour >= 22
time_description = "" if night else "daytime" time_description = "nighttime" if night else "daytime"
time_description_oppersite = "daytime" if night else "nighttime" time_description_oppersite = "daytime" if night else "nighttime"
p.reasons.append(f"Bing says its {time_description}.") p.reasons.append(f"Bing says its {time_description}.")

View file

@ -1,5 +1,4 @@
import itertools import itertools
import logging
from datetime import datetime from datetime import datetime
from math import pi, sqrt, sin, cos, atan2 from math import pi, sqrt, sin, cos, atan2
@ -14,7 +13,7 @@ tf = TimezoneFinder(in_memory=True)
def night_on_iss(context: Context) -> Prediction: def night_on_iss(context: Context) -> Prediction:
""" """
It is night if it is night on the ISS and it is currently orbiting above us. It is night if it is night on the ISS and it is currently orbiting above us. http://www.isstracker.com/
""" """
p = Prediction() p = Prediction()

View file

@ -17,7 +17,7 @@ def is_restaurant_open(name, open, close) -> Prediction:
soup = BeautifulSoup(r.content, features='html5lib') soup = BeautifulSoup(r.content, features='html5lib')
listing_groups = soup.find_all('div', {'class': 'listing-group'}) listing_groups = soup.find_all('div', {'class': 'listing-group'})
p.reasons.append("Hopefully we are not banned from Just-eat ..") #p.reasons.append("Hopefully we are not banned from Just-eat ..")
nice_group = None nice_group = None
for x in listing_groups: for x in listing_groups:
@ -32,10 +32,12 @@ def is_restaurant_open(name, open, close) -> Prediction:
all_listings = nice_group.find_all('a', {'class': 'mediaElement'}) all_listings = nice_group.find_all('a', {'class': 'mediaElement'})
if any(name in x['href'] for x in all_listings): if any(name in x['href'] for x in all_listings):
p.reasons.append(f"{name} is currently open. We conclude from this, that there is {1 / 11}% chance of it being night outside!") p.reasons.append(f"Our favorite pizza place, {name}, is currently open.")
p.reasons.append(f"We conclude from this, that there is {1 / 11}% chance of it being night outside")
p.probability = 1 / 11 p.probability = 1 / 11
else: else:
p.reasons.append(f"{name} is not open. We can conclude from this, that there is {1 - (1/11)}% chance of it currently being night outside! ") p.reasons.append(f"Our favorite pizza place, {name}, is closed.")
p.reasons.append(f"We can conclude from this, that there is {1 - (1/11)}% chance of it currently being night outside!")
p.probability = 1 - (1 / 11) p.probability = 1 - (1 / 11)
return p return p

View file

@ -18,11 +18,11 @@ def camImgStrat(context : Context) -> Prediction:
p.probability = 1 - round((average/255),3) p.probability = 1 - round((average/255),3)
if average < 128: if average < 128:
p.weight = round(1 - (average/255), 3) p.weight = round(1 - (average/255), 3)
p.reasons.append('Image was dark') p.reasons.append('Camera image was dark, so the sun has probably set.')
else: else:
p.weight = round(average / 255, 3) p.weight = round(average / 255, 3)
p.reasons.append('Image was light') p.reasons.append('Camera image was light, so the sun is still shining.')
return p return p
@ -38,10 +38,10 @@ def australiaStrat(context : Context) -> Prediction:
if hour > 22 or hour < 6: if hour > 22 or hour < 6:
p.probability = 0.0 p.probability = 0.0
p.reasons.append('It\'s night-time in Australia') p.reasons.append('It\'s night-time in Australia, so it must be day-time here.')
else: else:
p.probability = 1.0 p.probability = 1.0
p.reasons.append('It\'s day-time in Australia') p.reasons.append('It\'s day-time in Australia, so it must be night-time here.')
return p return p
@ -49,10 +49,7 @@ def tv2newsStrat(context : Context) -> Prediction:
""" """
The number of articles releases in the last few hours on TV2.dk The number of articles releases in the last few hours on TV2.dk
""" """
print('before')
r = requests.get('http://mpx.services.tv2.dk/api/latest') r = requests.get('http://mpx.services.tv2.dk/api/latest')
print('after')
data = r.json() data = r.json()
publish_dates = [(x['pubDate'])//1000 for x in data[:5]] publish_dates = [(x['pubDate'])//1000 for x in data[:5]]

View file

@ -0,0 +1 @@
{"help": "https://portal.opendata.dk/api/3/action/help_show?name=datastore_search", "success": true, "result": {"include_total": true, "resource_id": "2a82a145-0195-4081-a13c-b0e587e9b89c", "fields": [{"type": "int", "id": "_id"}, {"type": "text", "id": "date"}, {"type": "text", "id": "garageCode"}, {"type": "int4", "id": "totalSpaces"}, {"type": "int4", "id": "vehicleCount"}], "records_format": "objects", "records": [{"_id": 1, "date": "2019/04/06 22:30:01", "garageCode": "NORREPORT", "totalSpaces": 80, "vehicleCount": 61}, {"_id": 2, "date": "2019/04/06 22:30:01", "garageCode": "SCANDCENTER", "totalSpaces": 1240, "vehicleCount": 442}, {"_id": 6, "date": "2019/04/06 22:30:01", "garageCode": "SALLING", "totalSpaces": 700, "vehicleCount": 290}, {"_id": 7, "date": "2019/04/06 22:30:01", "garageCode": "DOKK1", "totalSpaces": 1000, "vehicleCount": 0}, {"_id": 8, "date": "2019/04/06 22:30:01", "garageCode": "Navitas", "totalSpaces": 449, "vehicleCount": 161}, {"_id": 9, "date": "2019/04/06 22:30:01", "garageCode": "NewBusgadehuset", "totalSpaces": 105, "vehicleCount": 99}, {"_id": 3, "date": "2019/04/06 22:30:01", "garageCode": "BRUUNS", "totalSpaces": 953, "vehicleCount": 598}, {"_id": 4, "date": "2019/04/06 22:30:01", "garageCode": "MAGASIN", "totalSpaces": 378, "vehicleCount": 65}, {"_id": 5, "date": "2019/04/06 22:30:01", "garageCode": "KALKVAERKSVEJ", "totalSpaces": 210, "vehicleCount": 278}, {"_id": 10, "date": "2019/04/06 22:30:01", "garageCode": "Urban Level 1", "totalSpaces": 319, "vehicleCount": 32}, {"_id": 11, "date": "2019/04/06 22:30:01", "garageCode": "Urban Level 2+3", "totalSpaces": 654, "vehicleCount": 66}], "_links": {"start": "/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c", "next": "/api/3/action/datastore_search?offset=100&resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c"}, "total": 11}}

View file

@ -1,3 +1,5 @@
from pathlib import Path
from sklearn import svm from sklearn import svm
from sklearn.externals import joblib from sklearn.externals import joblib
import requests import requests
@ -5,11 +7,9 @@ import glob
import json import json
import numpy as np import numpy as np
from .strat_utils import write_json from .strat_utils import write_json
from ..util import Context, Prediction from ..util import Context, Prediction
def write_data(time): def write_data(time):
write_json("https://portal.opendata.dk/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c", "parking_aarhus", time) write_json("https://portal.opendata.dk/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c", "parking_aarhus", time)
@ -38,7 +38,7 @@ def train():
joblib.dump(classifier, "nightness_classifier.pkl") joblib.dump(classifier, "nightness_classifier.pkl")
def predict(X): def predict(X):
classifier = joblib.load("nightness_classifier.pkl") classifier = joblib.load(str(Path(__file__).parent.joinpath("nightness_classifier.pkl")))
prob = classifier.predict_proba(np.array(X).reshape(1, -1)) prob = classifier.predict_proba(np.array(X).reshape(1, -1))
return prob[0, 1] return prob[0, 1]
@ -50,9 +50,9 @@ def perform_svm_pred(context: Context) -> Prediction:
records = data.json()['result']['records'] records = data.json()['result']['records']
X = [house['vehicleCount'] / house['totalSpaces'] for house in records] X = [house['vehicleCount'] / house['totalSpaces'] for house in records]
X = [min(x, 1) for x in X] X = [min(x, 1) for x in X]
p.reasons.append("Since we only have two data points") p.reasons.append("We only have two data points")
p.reasons.append("Since our only two data points have 11 dimensions") p.reasons.append("Our only two data points have 11 dimensions")
p.reasons.append("Since we are using a SVM") p.reasons.append("We are using a SVM")
p.probability = predict(X) p.probability = predict(X)
return p return p

View file

@ -34,7 +34,7 @@ def check_games(context: Context) -> Prediction:
last_game_in_hours = (((datetime.now() - last_played_game).seconds)/60/60) last_game_in_hours = (((datetime.now() - last_played_game).seconds)/60/60)
if last_game_in_hours < 2: if last_game_in_hours < 2:
p.reasons.append("Alexanders upstairs neighbour is currently playing league") p.reasons.append("Alexander's upstairs neighbour is currently playing league")
p.probability = 0.8 p.probability = 0.8
else: else:
last_game_in_hours = min(24.0, last_game_in_hours) last_game_in_hours = min(24.0, last_game_in_hours)

View file

@ -9,8 +9,8 @@ import numpy as np
@dataclass @dataclass
class Context: class Context:
battery: int = 100 battery: int = 55
position: Dict[str, float] = field(default_factory=lambda: {'latitude': 53.0, 'longitude': 9.0}) position: Dict[str, float] = field(default_factory=lambda: {'latitude': 53.0, 'longitude': 9.0}) # Denmark somewhere
image: np.ndarray = None image: np.ndarray = None
# App settings # App settings