Neural Network on Windows Phone 8.0 - windows-phone-8

I am trying to write using aforge(neural network) framework on Windows Phone 8 application and I installed PCL version here.
I wrote below code:
Pivotpage.xaml.cs
_inputDataGelen = new double[4] { 0.067, 0.033, 0.057, 0.021 };
double compute = network.Compute(_inputDataGelen)[0]; // (1)
//MessageBox.Show("Output is "+ Math.Round(compute));
I am trying same code on desktop application and I am getting compute as 0.00112.. or 0.01283.., 0.02123.., 0.03231.., 0.04159... So if I round to one digit 0,1,2,3,4...
But when I tried on Windows Phone 8 project, I am getting compute like a 0.9999995345.
What is my problem.
Thanks in advance. (sorry my language.)

Desktop code:
ActivationNetwork network = null; //global variable
bool dongu = false;
...
...
network = new ActivationNetwork(
new BipolarSigmoidFunction(2), //activation func.
4, //input count
20, //hidden layer count
1); //output count
//Learning Network
BackPropagationLearning backprob = new BackPropagationLearning(network);
backprob.LearningRate = 0.1;
backprob.Momentum = 0.0;
int iteration = 1;
double hata = 0.0;
//loop
while(!dongu)
{
hata = backprob.RunEpoch(_inputData, _outputData);
iteration++;
if (iteration > 10000 || hata < 0.0001)
break;
}
double a1 = Convert.ToDouble(textBox3.Text);
double a2 = Convert.ToDouble(textBox4.Text);
double a3 = Convert.ToDouble(textBox5.Text);
double a4 = Convert.ToDouble(textBox6.Text);
//Actually devide 100. Not 1000.
double[] girdi = { a1/1000, a2/1000, a3/1000, a4/1000 }; //normalize
textBox1.Text = network.Compute(girdi)[0].ToString() + " compute"; //output ile aynı değer geliyor
double find = network.Output[0]*100; //denormalize
//textBox2.Text = (network.Output[0]).ToString() + " output"; //compute ile aynı değer geliyor
//tam sayıya yuvarlama
find = Math.Round(find,1);
if (find >= 0.0 && find <= 1.7) //bu aralık optimize edilebilir
{
//MessageBox.Show("Iris-setosa");
textBox7.Text = "1";
}
else if (find > 1.7 && find <= 2.6)
{
//MessageBox.Show("Iris-versicolor");
textBox7.Text = "2";
}
else if (find > 2.6 && find <= 3.7)
{
//MessageBox.Show("Iris-virginica");
textBox7.Text = "3";
}
Train set is here
#Anders Gustafsson, this code working on desktop. If I enter 5.1, 3.5, 1.4, 0.2 double numbers I am giving output is 1.

Related

ion-input type number becomes unresponsive when holding down the delete key on device

I'm having an issue with an ion-input, which drops this error below when holding down the delete key.
"Error: Invalid argument '' for pipe 't'
at new Error (native)
at Error.v (file:///android_asset/www/build/polyfills.js:3:4864)
at e [as constructor] (file:///android_asset/www/build/main.js:94:11171)
at new e (file:///android_asset/www/build/main.js:14:10469)
at n (file:///android_asset/www/build/main.js:9:10302)
at t.transform (file:///android_asset/www/build/main.js:9:11000)
at file:///android_asset/www/build/main.js:1:17764
at e.detectChangesInternal (file:///android_asset/www/build/main.js:125:10032)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)
at e.t.internalDetectChanges (file:///android_asset/www/build/main.js:4:8640)
at e.detectChangesInternal (file:///android_asset/www/build/main.js:120:27362)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)
at t.detectChangesInNestedViews (file:///android_asset/www/build/main.js:4:28534)
at e.detectChangesInternal (file:///android_asset/www/build/main.js:80:24234)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)", source: file:///android_asset/www/build/main.js (29)
This one below is my ion-input:
<ion-input color="primary_light" [(ngModel)]="montco_ui" type="number
(keyup)="formataNumero()"></ion-input>
Also, I'm using this algorithm to handle 2 decimal places, which is working fine, since I guess the issue is related to the type number property on the ion-input.
formataNumero(separador: string = '.', decimais: number = 2) {
console.log('formataNumero called');
let a: any = this.montco_ui.split('');
let ns: string = '';
a.forEach((c: any) => { if (!isNaN(c)) ns = ns + c; });
ns = parseInt(ns).toString();
if (ns.length < (decimais + 1)) {
ns = ('0'.repeat(decimais + 1) + ns);
ns = ns.slice((decimais + 1) * -1);
}
let ans = ns.split('');
let r = '';
for (let i = 0; i < ans.length; i++)
if (i == ans.length - decimais) {
r = r + separador + ans[i]; else r = r + ans[i];
}
this.montco_ui = r;
}
Finally, this is the variable that keeps the value:
P.S.: I'm using Ionic 2 for my project.
public montco_ui: string = "0.00";

Hash txt strings in GAS, incorrect line ending

I want hash (md5) some txt strings in GAS, and have a problem, may be
incorrect line ending.
Example:
test
test
correct hash 76ce9f441de2ed5de337d391ad4516b7
using GAS i getting wrong hash: e8230113fbba92427c1c41cf34a80c13
function test() {
var data = 'test\
test';
Logger.log(data.MD5());
return (data.MD5());
}
String.prototype.MD5 = function(charset, toByte) {
charset = charset || Utilities.Charset.UTF_8;
var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, this, charset);
if (toByte) return digest;
var __ = '';
for (i = 0; i < digest.length; i++) {
var byte = digest[i];
if (byte < 0) byte += 256;
var bStr = byte.toString(16);
if (bStr.length == 1) bStr = '0' + bStr;
__ += bStr;
}
return __;
}
As already #Ameen mentioned you are checking different strings
function test(){
var s1 = 'test\ntest';
var s2 = 'test\r\ntest';
Logger.log(s1.MD5() === '76ce9f441de2ed5de337d391ad4516b7');
Logger.log(s2.MD5() === '76ce9f441de2ed5de337d391ad4516b7');
}
[19-03-22 18:03:11:441 MSK] false
[19-03-22 18:03:11:442 MSK] true
A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
It seems you're working under Windows.

Execute Code as Fast as Possible

I am using node.js with my WebStorm IDE to parse a large JSON file (~500 megabytes). Here is my code:
fs = require("fs");
fs.readFile('C:/Users/.../Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 1000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var symbol = hex.substring(156, 179);
var timestamp = hex.substring(132, 155);
var askSize = hex.substring(240, 251);
var bidSize = hex.substring(180, 191);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
function hex2a(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
if(JSON.parse(data)[i]._source.layers.data["data.len"] == 84 && realprice.length == 8 && +realprice <154 && +realprice >145) {
console.log(i + " " + hex2a(symbol.replace(/:/g, "")) + " sold for " + realprice + " at " + parseInt(timestamp.split(":").reverse().join(""), 16));
}
}
});
The problem I am running into however is that my IDE is parsing this file at an extremely slow speed, roughly 1 iteration a second. I do not think this is because I have a slow computer, for I have a high end rig with a core i7 7700k and a gtx 1070. I tried executing the code in the console with the same result. I tried trimming down the code and again I achieved the same speed:
fs = require("fs");
fs.readFile('C:/Users/Brandt Winkler Prins/Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 12000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
if(+realprice <154 && +realprice >145) {
console.log(realprice);
}
}
});
How should I execute my code to get my data as fast as possible?
You're running JSON.parse(data) every iteration, that might take quite some time for a 500MB json file.
The solution would be to move it out of the loop and reuse the parsed object:
var obj = JSON.parse(data);
for (...

Adobe Air - Detect if connection is WIFI, 3G, or EDGE

I need to determine which connection type a device is using.
Distinguishing between WIFI and 3G doesn't seem to be a problem on iOS (using the NetworkInfo ANE) and Android (using the native NetworkInfo class) but I've got no clue how to further distinguish between a fast (3G, 4G) and slow (EDGE) connection.
Is there a way to do this with Adobe Air?
Try this for detecting Mobile vs. Wifi on iOS. This requires the Adobe native extension "NetworkInfo"
import com.adobe.nativeExtensions.Networkinfo.InterfaceAddress;
import com.adobe.nativeExtensions.Networkinfo.NetworkInfo;
import com.adobe.nativeExtensions.Networkinfo.NetworkInterface;
var vNetworkInterfaces:Object;
if (flash.net.NetworkInfo.isSupported)
{
vNetworkInterfaces = getDefinitionByName('flash.net.NetworkInfo')['networkInfo']['findInterfaces']();
mytrace("fall 1" );
}
else
{
vNetworkInterfaces = getDefinitionByName('com.adobe.nativeExtensions.Networkinfo.NetworkInfo')['networkInfo']['findInterfaces']();
mytrace("fall 2" );
}
var hasWifi: Boolean = false;
var hasMobile: Boolean = false;
for each (var networkInterface:Object in vNetworkInterfaces)
{
if ( networkInterface.active && (networkInterface.name == "en0" || networkInterface.name == "en1") ) hasWifi = true;
if ( networkInterface.active && (networkInterface.name == "pdp_ip0" || networkInterface.name == "pdp_ip1" || networkInterface.name == "pdp_ip2") ) hasMobile = true;
mytrace( "active: " + networkInterface.active );
mytrace( "displayName: " + networkInterface.displayName );
mytrace( "name: " + networkInterface.name );
mytrace( "hwAddress: " + networkInterface.hardwareAddress );
mytrace( "--------------------" );
}
mytrace( "has Mobile Internet: " + hasMobile );
mytrace( "has Wifi Internet: " + hasWifi );
I dunno if there's a solution a direct solution but when you're downloading a file you could check the speed at which file is downloaded, by using getTimer function in conjunction with loaded bytes and a ratio of total bytes.
Example
function init()
{
startTime = getTimer();
loader = new Loader();
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoaderInit);
loader.load("some-site.com/myasset.png");
}
function onLoaderInit(e:ProgressEvent)
{
$timePassed = (getTimer() - startTime) * 0.001; //it's in millisecounds convert to secounds
$newBytes = loader.contentLoaderInfo.bytesLoaded - oldBytes;
var $rate:Number = $newBytes * $timePassed; //returns a value of bytes per sec.
startTime = getTimer();
oldBytes = loader.contentLoaderInfo.bytesLoaded;
}
Nice... if it works... dunno if there's a solution a direct solution but when you're downloading a file you could check the speed at which file is downloaded, by using getTimer function in conjunction with loaded bytes and a ratio of total bytes

Google maps - how to get building's polygon coordinates from address?

How to implement the following:
User defines an address
User defines a color
Service searches for a corresponding building on the google map
Service fills the found building on the map with the color
I know how to:
1.find lat/long of the address
2.draw the polygon
So, to do the task I need to get polygon coordinates of building from address. How to?
(1) Acquire image tile
(2) Segment buildings based on pixel color (here, 0xF2EEE6).
(3) Image cleanup (e.g. erosion then dilation) + algorithm to acquire pixel coordinates of polygon corners.
(4) Mercator projection to acquire lat/long of pixel
You can convert the address to geographic coordinates by the use of the Google Geocoding API.
https://maps.googleapis.com/maps/api/geocode/json?address=SOME_ADDRESS&key=YOUR_API_KEY
Then, you can use Python and a styled static map to obtain the polygon of the building (in pixel coordinates) at some location:
import numpy as np
from requests.utils import quote
from skimage.measure import find_contours, points_in_poly, approximate_polygon
from skimage import io
from skimage import color
from threading import Thread
center_latitude = None ##put latitude here
center_longitude = None ##put longitude here
mapZoom = str(20)
midX = 300
midY = 300
# Styled google maps url showing only the buildings
safeURL_Style = quote('feature:landscape.man_made|element:geometry.stroke|visibility:on|color:0xffffff|weight:1')
urlBuildings = "http://maps.googleapis.com/maps/api/staticmap?center=" + str_Center + "&zoom=" + mapZoom + "&format=png32&sensor=false&size=" + str_Size + "&maptype=roadmap&style=visibility:off&style=" + safeURL_Style
mainBuilding = None
imgBuildings = io.imread(urlBuildings)
gray_imgBuildings = color.rgb2gray(imgBuildings)
# will create inverted binary image
binary_imageBuildings = np.where(gray_imgBuildings > np.mean(gray_imgBuildings), 0.0, 1.0)
contoursBuildings = find_contours(binary_imageBuildings, 0.1)
for n, contourBuilding in enumerate(contoursBuildings):
if (contourBuilding[0, 1] == contourBuilding[-1, 1]) and (contourBuilding[0, 0] == contourBuilding[-1, 0]):
# check if it is inside any other polygon, so this will remove any additional elements
isInside = False
skipPoly = False
for othersPolygon in contoursBuildings:
isInside = points_in_poly(contourBuilding, othersPolygon)
if all(isInside):
skipPoly = True
break
if skipPoly == False:
center_inside = points_in_poly(np.array([[midX, midY]]), contourBuilding)
if center_inside:
# approximate will generalize the polygon
mainBuilding = approximate_polygon(contourBuilding, tolerance=2)
print(mainBuilding)
Now, you can convert the pixel coordinates to latitude and longitude by the use of little JavaScript, and the Google Maps API:
function point2LatLng(point, map) {
var topRight = map.getProjection().fromLatLngToPoint(map.getBounds().getNorthEast());
var bottomLeft = map.getProjection().fromLatLngToPoint(map.getBounds().getSouthWest());
var scale = Math.pow(2, map.getZoom());
var worldPoint = new google.maps.Point(point.x / scale + bottomLeft.x, point.y / scale + topRight.y);
return map.getProjection().fromPointToLatLng(worldPoint);
}
var convertedPointsMain = [];
for (var i = 0; i < pxlMainPolygons[p].length; i++) {
var conv_point = {
x: Math.round(pxlMainPolygons[p][i][1]),
y: Math.round(pxlMainPolygons[p][i][0])
};
convertedPointsMain[i] = point2LatLng(conv_point, map);
}
console.log(convertedPointsMain);
Might I humbly suggest you use OpenStreetMaps for this instead ?
It's a lot easier, because then you can use the OverPass API.
However, polygons might not match with google-maps or with state survey.
The latter also holds true if you would use google-maps.
// https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL
private static string GetOqlBuildingQuery(int distance, decimal latitude, decimal longitude)
{
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo()
{
NumberGroupSeparator = "",
NumberDecimalSeparator = ".",
CurrencyGroupSeparator = "",
CurrencyDecimalSeparator = ".",
CurrencySymbol = ""
};
// [out: json];
// way(around:25, 47.360867, 8.534703)["building"];
// out ids geom meta;
string oqlQuery = #"[out:json];
way(around:" + distance.ToString(nfi) + ", "
+ latitude.ToString(nfi) + ", " + longitude.ToString(nfi)
+ #")[""building""];
out ids geom;"; // ohne meta - ist minimal
return oqlQuery;
}
public static System.Collections.Generic.List<Wgs84Point> GetWgs84PolygonPoints(int distance, decimal latitude, decimal longitude)
{
string[] overpass_services = new string[] {
"http://overpass.osm.ch/api/interpreter",
"http://overpass.openstreetmap.fr/api/interpreter",
"http://overpass-api.de/api/interpreter",
"http://overpass.osm.rambler.ru/cgi/interpreter",
// "https://overpass.osm.vi-di.fr/api/interpreter", // offline...
};
// string url = "http://overpass.osm.ch/api/interpreter";
// string url = "http://overpass-api.de/api/interpreter";
string url = overpass_services[s_rnd.Next(0, overpass_services.Length)];
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("data", GetOqlBuildingQuery(distance, latitude, longitude));
string resp = PostRequest(url, reqparm);
// System.IO.File.WriteAllText(#"D:\username\Documents\visual studio 2017\Projects\TestPlotly\TestSpatial\testResponse.json", resp, System.Text.Encoding.UTF8);
// System.Console.WriteLine(resp);
// string resp = System.IO.File.ReadAllText(#"D:\username\Documents\visual studio 2017\Projects\TestPlotly\TestSpatial\testResponse.json", System.Text.Encoding.UTF8);
System.Collections.Generic.List<Wgs84Point> ls = null;
Overpass.Building.BuildingInfo ro = Overpass.Building.BuildingInfo.FromJson(resp);
if (ro != null && ro.Elements != null && ro.Elements.Count > 0 && ro.Elements[0].Geometry != null)
{
ls = new System.Collections.Generic.List<Wgs84Point>();
for (int i = 0; i < ro.Elements[0].Geometry.Count; ++i)
{
ls.Add(new Wgs84Point(ro.Elements[0].Geometry[i].Latitude, ro.Elements[0].Geometry[i].Longitude, i));
} // Next i
} // End if (ro != null && ro.Elements != null && ro.Elements.Count > 0 && ro.Elements[0].Geometry != null)
return ls;
} // End Function GetWgs84Points
I've been working on this for hours, the closest I have come is finding a request uri that returns a result with a polygon in it. I believe it specifies the building(boundary) by editids parameter. We just need a way to get the current editids from a building(boundary).
The URI I have is:
https://www.google.com/mapmaker?hl=en&gw=40&output=jsonp&ll=38.934911%2C-92.329359&spn=0.016288%2C0.056477&z=14&mpnum=0&vpid=1354239392511&editids=nAlkfrzSpBMuVg-hSJ&xauth=YOUR_XAUTH_HERE&geowiki_client=mapmaker&hl=en
Part of the result has what is needed:
"polygon":[{"gnew":{"loop":[{"vertex":[{"lat_e7":389364691,"lng_e7":-923341133},{"lat_e7":389362067,"lng_e7":-923342783},{"lat_e7":389361075,"lng_e7":-923343356},{"lat_e7":389360594,"lng_e7":-923342477},
I was intrigued on this problem and wrote a solution to it. See my github project.
The Google Maps API contains a GeocoderResults object that might be what you need. Specifically the data returned in the geometry field.