Is anyone using the gyroscope on Moto 360? The values are quite strange. Whew I twisted my wrist, I got peak values like 100 rad/s; while on Samsung Gear Live, I only got values around 8 rad/s. Is this some kind of calibration issue?
and according to the information provided by Sensor.toString() on Moto 360, the maximun value is 34.9
{Sensor name="Gyro Sensor", vendor="Motorola", version=1, type=4, maxRange=34.9, resolution=0.01, power=0.45, minDelay=40000}
I even got values like below when I put it on the desk.
10-02 17:16:55.054 7354-7354/ D/gyro﹕ -18.242777 8.1562507E-4 2.7187503E-4
10-02 17:16:55.775 7354-7354/ D/gyro﹕ -18.242777 8.1562507E-4 -0.0040781256
code to register gyro:
...
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
mGyroscopeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mSensorManager.registerListener(this, mGyroscopeSensor, 40000);
...
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
Log.d("gyro", event.timestamp + "\t" + event.values[0] + "\t" + event.values[1] + "\t" + event.values[2]);
}
}
Related
I have a HashMap :
HashMap<string, Integer> hmap = new HashMap<>();
where I want to increase the HashMap value. In order to avoid the nullPointer Exception if the key doesn't exist, I check it! Let's say the data are:
//201803271 - 1000
//201803271 - 1000
//201803272 - 1000
//inside a loop i read the data...
if (hmap.get("201803271") != null) {
hmap.put("201803271", hmap.get("201803271") + 1000);
}else{
hmap.put("201803271", 1000);
}
//end of loop
which works as I get:
201803271 - 2000
201803272 - 1000
But, I read this question How to update a value, given a key in a java hashmap? and there is a solution to use the Java 8 method getOrDefault. I tried it
hmap.put("201803271", count.getOrDefault("201803271", 1000) + 1000)
However, with this solution I get wrong results...
201803271 - 3000
201803272 - 2000
What am I missing?
Java 8 introduced merge method to Map interface just for this type of problem:
hmap.merge("201803271", 1000, Integer::sum);
It means "put 1000 for this key but if this key already has a value add 1000 to it".
The reason your solution wasn't working is that you were getting 1000 by default and then adding 1000 to it. To do this correctly with getOrDefault, you would want to replace 1000 with 0 in getOrDefault. hmap.put("201803271", count.getOrDefault("201803271", 0) + 1000))
You could do it like this:
map.put(key, map.getOrDefault(key, 0) + inc);
or
map.compute(key, (k, v) -> v == null ? inc : v + inc);
I have AFL which is working fine for crude oil. out of 10 trades, 8 trades are targets hitting. I have code for place orders auto trades. the auto trade code is working fine with other AFL codes but the problem is in below algorithm the BUY and SELL Boolean value is not giving to IF condition. But IIF(Buy .... conditions are working fine.
My main question is why BUY Sell True or false is not working in the last status in AFL. Kindly help me to resolve this.
_SECTION_BEGIN("T+4 day ");
Title = " ..:: duy ::.. - Filter of Stock " + " " + FullName() + " " + Date( ) ;
// 4-Day-Range Switch
prev=AMA2(C,1,0);
d=IIf(C>Ref(Max(Max(H,Ref(H,-20)),Max(Ref(H,-10),Ref(H,-15))),-1),Min(Min(L,Ref(L,-20)),Min(Ref(L,-10),Ref(L,-15))),
IIf(C<Ref(Min(Min(L,Ref(L,-20)),Min(Ref(L,-10),Ref(L,-15))),-1),Max(Max(H,Ref(H,-20)),Max(Ref(H,-10),Ref(H,-15))),PREV));
a=Cross(Close,d);
b=Cross(d,Close);
state=IIf(BarsSince(a)<BarsSince(b),1,0);
s=state>Ref(state,-1);
ss=state<Ref(state,-1);
sss=state==Ref(state,-1);
col=IIf(state == 1 ,51,IIf(state ==0,4,1));
Plot(C,"",Col,128);
Buy=s;
Sell=ss;
PlotShapes( shapeUpArrow * s ,6,0,L);
PlotShapes( shapeDownArrow *ss ,4,0,H);
dist = 0.8*ATR(10);
dist1 = 2*ATR(10);
for( i = 0; i < BarCount; i++ )
{
if( Buy )
{
PlotText( "\nBuy:" + L[ i ] + "\nT= " + (L*1.005) + "\nSL= " + (L*0.9975), i, L[ i ]-dist, colorGreen, colorWhite );
}
if( Sell )
{
PlotText( "Sell:" + H[ i ] + "\nT= " + (H*0.995) + "\nSL= " + (H*1.0025), i, H[ i ]+dist1, colorRed, colorWhite );
}
}
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
if ( LastValue(Buy)==1)
{
quantity=2;
orderId=placeOrderFuture("MCX", "FUTCOM", ChartSymbol, "BUY", "INTRADAY", "MARKET", quantity, 0, defaultTriggerPrice(), "19-APR-2018", defaultStrategyId(), defaultComments());
//orderId = placeOrderUsingParams(tradeType, AT_ORDER_TYPE, AT_QUANTITY, buyPrice, defaultTriggerPrice(), 1);
}
if ( LastValue(Sell) == 1 )
{
quantity=2;
orderId=placeOrderFuture("MCX", "FUTCOM", ChartSymbol, "SELL", "INTRADAY", "MARKET", quantity, 0, defaultTriggerPrice(), "19-APR-2018", defaultStrategyId(), defaultComments());
//orderId = placeOrderUsingParams("SELL", AT_ORDER_TYPE, AT_QUANTITY, sellPrice, defaultTriggerPrice(), 1);
}
LastValue documentation
With if statements, you need to specify a specific bar. And according to the documentation, LastValue may look into the future. I can't say for sure what's happening with your code, but the loops/if/switch can be tricky. This tutorial Looping in Amibroker might give you some insights into how they work.
You may try SelectedValue instead. If you haven't got any bars selected, it automatically defaults to the last bar. I use this for my realtime trading.
bi = SelectedValue(BarIndex());
if(Buy[bi])
{
...
}
On an unrelated note, your text plots aren't going to plot unfiltered signals, put your ExRem code under your initial Buy and Sell conditions.
I am looking into good design principles and would just like some feedback.
I want to go through every user in my application that is a patient, check their scheduled activities, see if there is one upcoming and send them an email. It looks a little like this:
List<Patient> listOfAllPatients = patientRepositoryJPA.findAll();
if (listOfAllPatients.size() != 0) {
for (Patient patient : listOfAllPatients) {
user = userRepositoryJPA.findByUsername(patient.getUsername());
Timestamp currentTimeAndDate = new Timestamp(System.currentTimeMillis());
Long closestDate = Integer.toUnsignedLong(31);;
List<Activity> activities = activityRepositoryJPA.findByPatientAndStartDateTimeAfter(patient, currentTimeAndDate);
for (Activity activity : activities) {
Timestamp activityDateAndTime = activity.getStartDateTime();
Long difference = getTimeDifferenceByMinutes(currentTimeAndDate, activityDateAndTime);
if (difference < closestDate) {
LocalDateTime upcomingDate = activity.getStartDateTime().toLocalDateTime();
emailHandler.sendEmail(javaMailSender, "Upcoming Activity Reminder", "The activity, " + activity.getName() + " is starting soon! (" +
upcomingDate.getHour() + ":" + upcomingDate.getMinute() + ")", user);
}
}
}
Now here I loop through every patient in the application and then through each of their activities. If there were many user (millions) surely there would be some bottlenecks or something here.
Does anybody have any advice on how big companies would handle data like this?
Or is what I am doing fine? Thanks.
After some advice, I have improved it to this:
Timestamp currentTimeAndDate = new Timestamp(System.currentTimeMillis());
LocalDateTime add31Minutes = LocalDateTime.now().plus(31, ChronoUnit.MINUTES);
Timestamp noLaterThanDateAndTime = Timestamp.valueOf(add31Minutes);
for (Activity activity : activityRepositoryJPA.findByStartDateTimeBetween(currentTimeAndDate, noLaterThanDateAndTime)) {
Patient patient = activity.getPatient();
LocalDateTime upcomingDate = activity.getStartDateTime().toLocalDateTime();
emailHandler.sendEmail(javaMailSender, "BAA - Upcoming Activity Reminder", "The activity, " + activity.getName() + " is starting soon! (" +
upcomingDate.getHour() + ":" + upcomingDate.getMinute() + ")", patient.getUser());
}
Now I find all activities between now and 31 minutes time in 1 query.
I have a DRF model created in h2o flow that is supposed to be binomial and flow indicates that it is binomial
but I am having a problem where, importing it into h2o steam and deploying it to the prediction service, the model does not seem to be recognized as binomial. The reason I think this is true is shown below. The reason this is a problem is because I think it is what is causing the prediction service to NOT show the confidence value for the prediction (this reasoning is also shown below).
In the prediction service, I can get a prediction label, but no values filled in the index-label-probability table.
Using the browser inspector (google chrome), the prediction output seems to depend on a file called predict.js.
In order to get the prediction probability values to show in the prediction service, it seems like this block of code needs to run to get to this line. Opening the predict.js file within the inspector on the prediction service page and adding some debug output statements at some of the top lines (indicated with DEBUG/ENDDEBUG comments in the code below), my showResults() function then looks like:
function showResult(div, status, data) {
////////// DEBUG
console.log("showResult entered")
////////// ENDDEBUG
var result = '<legend>Model Predictions</legend>'
////////// DEBUG
console.log(data)
console.log(data.classProbabilities)
console.log("**showResult: isBinPred=" + isBinaryPrediction)
////////// ENDDEBUG
if (data.classProbabilities) {
////////// DEBUG
console.log("**showResult: data.classProbabilities not null")
////////// ENDDEBUG
// binomial and multinomial
var label = data.label;
var index = data.labelIndex;
var probs = data.classProbabilities;
var prob = probs[index];
result += '<p>Predicting <span class="labelHighlight">' + label + '</span>';
if (probs.length == 2) {
result += ' based on max F1 threshold </p>';
}
result += ' </p>';
result += '<table class="table" id="modelPredictions"> \
<thead> \
<tr> \
<th>Index</th> \
<th>Labels</th> \
<th>Probability</th> \
</tr> \
</thead> \
<tbody> \
';
if (isBinaryPrediction) {
var labelProbabilitiesMapping = [];
outputDomain.map(function(label, i) {
var labelProbMap = {};
labelProbMap.label = outputDomain[i];
labelProbMap.probability = probs[i];
if (i === index) {
labelProbMap.predicted = true;
}
labelProbMap.originalIndex = i;
labelProbabilitiesMapping.push(labelProbMap);
});
labelProbabilitiesMapping.sort(function(a, b) {
return b.probability - a.probability;
});
var limit = labelProbabilitiesMapping.length > 5 ? 5 : labelProbabilitiesMapping.length;
for (var i = 0; i < limit; i++) {
if (labelProbabilitiesMapping[i].predicted === true) {
result += '<tr class="rowHighlight">'
} else {
result += '<tr>'
}
result += '<td>' + labelProbabilitiesMapping[i].originalIndex + '</td><td>' + labelProbabilitiesMapping[i].label + '</td> <td>' + labelProbabilitiesMapping[i].probability.toFixed(4) + '</td></tr>';
}
} else {
for (var label_i in outputDomain) {
if (parseInt(label_i) === index ){
result += '<tr class="rowHighlight">'
} else {
result += '<tr>'
}
result += '<td>' + label_i + '</td><td>' + outputDomain[label_i] + '</td> <td>' + probs[label_i].toFixed(4) + '</td></tr>';
}
}
result += '</tbody></table>';
}
else if ("cluster" in data) {
// clustering result
result = "Cluster <b>" + data["cluster"] + "</b>";
}
else if ("value" in data) {
// regression result
result = "Value <b>" + data["value"] + "</b>";
}
else if ("dimensions" in data) {
// dimensionality reduction result
result = "Dimensions <b>" + data["dimensions"] + "</b>";
}
else {
result = "Can't parse result: " + data;
}
div.innerHTML = result;
}
and clicking the "predict" in the prediction service now generates the console output:
If I were to add a statement isBinaryPrediction = true to forcec the global variable to true (around here) and run the prediction again, the console shows:
indicating that the variable outputDomain is undefined. The variable outputDomain seems to be set in the function showModel. This function appears to run when the page loads, so I can't edit it in the chrome inspector to see what the variable values are. If anyone knows how to fix this problem (getting the prediction probability values to show up for h2o steam's prediction service for binomial models) it would a big help. Thanks :)
The UI has not been updated to handle MOJOs yet and there seems to be a bug. You're welcome to contribute: https://github.com/h2oai/steam/blob/master/CONTRIBUTING.md
My solution is very hacky, but works for my particular case (ie. I have a DRF, binomial model in h2o steam that is not being recognized as a binary model (how I know this is shown in this answer)).
Solution:
In my original post, there was a variable outputDomain that was undefined. Looking at the source code, that variable is set to (what is supposed to be) the domain labels of the output response for the model, here. I changed this line from outputDomain = domains[i1]; to outputDomain = domains[i1-1];. My output after clicking the predict button looks like:
From the official linux download for h2o steam, you can access the prediction service predict.js file by opening steam-1.1.6-linux-amd64/var/master/assets/ROOT.war/extra/predict.js, then saving changes and relaunching the jetty server $ java -Xmx6g -jar var/master/assets/jetty-runner.jar var/master/assets/ROOT.war.
Causes?:
I suspect the problem has something to do with that fact that the global variable isBinaryPrediction in predict.js seems to remain false for my model. The reason that isBinaryPrediction is false seems to be because in the function showInputParameters(), data.m has no field _problem_type. Using console.dir(data, {depth: null}) in the inspector console to see the fields of data.m, I see that the expectedd field data.m._problem_type does not exist and so returns undefined, thus isBinaryPrediction is never set true (here).
Why this is happening, I do not know. I have only used DRF models in steam so far and this may be a problem with that model, but I have not tested. If anyone knows why this may be happening, please let me know.
I want to record a data processing time in esper and I choose Bollinger Band as example. In Bollinger Band, there is called Moving Average (MA). that MA obtained from the result of calculate the stock price average. In this case, I set win:length(20). So, the MA can be obtained from the result of calculate the stock price average from 20 events that exists in the data window view. The following is code that i created.
public class BollingerBand {
static double startTime, finishTime;
public static void main (String [] args){
Configuration configuration = new Configuration();
configuration.addEventType("Stock", Stock.class);
EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(configuration);
AdapterInputSource source = new AdapterInputSource("BollingerBand.csv");
EPStatement statement = epService.getEPAdministrator().createEPL("insert into Aggregation " +
"select prevcount(symbol), symbol, avg(price) as SimpleMovingAverage, stddev(price) as StandardDeviation, " +
"last(price) as price, last(timestamp) as date from Stock.std:groupwin(symbol).win:length(20)" +
" group by symbol having count(*) >=20");
statement.addListener(new UpdateListener() {
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
// TODO Auto-generated method stub
//System.out.println("Event Receive : "+newEvents[0].getUnderlying());
startTime = System.currentTimeMillis();
System.out.println("\nStart time : " + startTime + " miliseconds\n");
}
});
EPStatement statement2 = epService.getEPAdministrator().createEPL("select symbol, " +
"SimpleMovingAverage + 2*StandardDeviation as UpperBand," +
"SimpleMovingAverage as MiddleBand," +
"SimpleMovingAverage - 2*StandardDeviation as LowerBand," +
"price," +
"4*StandardDeviation/SimpleMovingAverage as Bandwidth," +
"(price - (SimpleMovingAverage - (2 * StandardDeviation))) / ((SimpleMovingAverage + " +
"(2 * StandardDeviation)) - (SimpleMovingAverage - (2 * StandardDeviation))) as PercentB," +
"date from Aggregation");
statement2.addListener(new UpdateListener() {
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
// TODO Auto-generated method stub
//System.out.println("Event Receive : "+newEvents[0].getUnderlying());
finishTime = System.currentTimeMillis();
System.out.println("Start time : " + startTime + " miliseconds");
System.out.println("Finish time : " + finishTime + " miliseconds");
System.out.println("Processing time : " + (finishTime-startTime) + " miliseconds");
}
});
(new CSVInputAdapter(epService, source, "Stock")).start();
}
}
From the above code, time will be recorded if the average has calculated. But what i need is I want the time is recorded when the 20th event and next event enter to data window view. It's as the start time and finish time obtained from bollinger band calculation result. My question is how to record time of the 20th event and in the same time next event enter to the window view data. please help
The CSV adapter doesn't provide a callback when events are sent. You could easily change its code however. Or you could use a different CSV reader and send the events via runtime API.
Maybe have some sort of TickCounter in which there's a map that takes a key value pair of (item_count and timestamp). You update this in your second UpdateListener and of course you can always lookup the item of key 20.
By the way, I've used your Bollinger Band Calculation but using Storm and the EsperBolt. Blogged about it here:
http://chanchal.wordpress.com/2014/07/08/using-esperbolt-and-storm-to-calculate-bollinger-bands/