Esper count with parameters - esper

I'd like to know if it's possible to use a "count" function or equivalent but with parameters specified, to only count specific results.
So I'd like to do something like:
select
...
"nbAccel", count(type='c8y_HarshBehavior' and behaviorType = "ACCELERATION")
"nbBraking", count(type='c8y_HarshBehavior' and behaviorType = "BRAKING")
"nbUnknown", count(type='c8y_HarshBehavior' and behaviorType = "UNKNOWN")
from
...
Let me show you what I want. I'm using the EPL Online tool.
Here is my EPL Statements (with the part I pasted above not working, of couse):
create schema EventCreated(
source String,
type String,
time Date,
behaviorType String
);
create schema CreateMeasurement(
source String,
type String,
time Date,
fragments Object
);
#Name("no_message_20min")
insert into
EventCreated
select
e.source as source,
"c8y_SilentTracker" as type,
new Date() as time
from pattern [
every e = EventCreated(
type != "c8y_HeartbeatReport" and
type != "c8y_ObdDisconnectionReport" and
type != "c8y_PowerOffReport" and
type != "c8y_SilentTracker")
-> (timer:interval(20 minute) and
not EventCreated(
source = e.source and
type != "c8y_HeartbeatReport"))];
#Name("create_context")
create context Trip
context bySource
partition by source from EventCreated,
context byEvents
start EventCreated(
type = "c8y_ObdConnectionReport" or
type = "c8y_PowerOnReport" or
type = "c8y_FixedReport" or
type = "c8y_HarshBehaviorReport") as startEvent
end EventCreated(
type = "c8y_ObdDisconnectionReport" or
type = "c8y_PowerOffReport" or
type = "c8y_SilentTracker") as endEvent;
#Name("context_end")
context Trip
insert into
CreateMeasurement
select
context.bySource.key1 as source,
"Trip" as type,
e.time as time,
{
"startedBy", context.byEvents.startEvent.type,
"startedAt", context.byEvents.startEvent.time,
"endedBy", e.type,
"endedAt", e.time,
"nbAccel", count(type='c8y_HarshBehavior' and behaviorType = "ACCELERATION"),
"nbBraking", count(type='c8y_HarshBehavior' and behaviorType = "BRAKING"),
"nbUnknown", count(type='c8y_HarshBehavior' and behaviorType = "UNKNOWN")
} as fragments
from
EventCreated e
output
last when terminated;
Here is my Time And Event Sequence:
EventCreated = {
source = 'tracker1',
type = 'c8y_ObdConnectionReport',
time = '2016-10-07T10:00:00.000'
}
t = t.plus(5 minutes)
EventCreated = {
source = 'tracker1',
type = 'c8y_HarshBehavior',
time = '2016-10-07 10:05:00.000',
behaviorType = "UNKNOWN"
}
t = t.plus(5 minutes)
EventCreated = {
source = 'tracker1',
type = 'c8y_HarshBehavior',
time = '2016-10-07 10:10:00.000',
behaviorType = "ACCELERATION"
}
t = t.plus(5 minutes)
EventCreated = {
source = 'tracker1',
type = 'c8y_HarshBehavior',
time = '2016-10-07 10:15:00.000',
behaviorType = "BRAKING"
}
t = t.plus(5 minutes)
EventCreated = {
source = 'tracker1',
type = 'c8y_Location',
time='2016-10-07 10:20:00.000'
}
t = t.plus(25 minutes)
EventCreated = {
source = 'tracker1',
type = 'c8y_Location',
time = '2016-10-07 10:45:00.000'
}
t = t.plus(5 minutes)
EventCreated = {
source = 'tracker1',
type = 'c8y_ObdDisconnectionReport',
time = '2016-10-07 10:50:00.000'
}
With a Beginning Of Time at 2016-10-07 10:00:00.000

Okay I found how to do it with the sum function like this:
"nbAccel", coalesce(sum(1, type='c8y_HarshBehavior' and behaviorType = "ACCELERATION"), 0),
"nbBraking", coalesce(sum(1, type='c8y_HarshBehavior' and behaviorType = "BRAKING"), 0),
"nbUnknown", coalesce(sum(1, type='c8y_HarshBehavior' and behaviorType = "UNKNOWN"), 0)

Related

sending parsed JSON data to views

I'm stuck because I can't send JSON data from URLSession func to views. I read the 90% of previous commends and watch lots of videos but I didn't migrate to my project. Here is my code blocks that I need help ;
This ones my json struct
struct APIResponse: Decodable{
let stocks: [Stocks]
}
struct Stocks: Decodable{
let id: Int
let difference: Float
let bid:Float
let isDown: Bool
let isUp: Bool
let offer: Float
let price: Float
let symbol: String
let volume: Double
}
this one is mine JsonDecode code block;
if let data2 = data2 {
do {
// let json = try JSONSerialization.jsonObject(with: data2, options: [])
let apiResponse = try JSONDecoder().decode(APIResponse.self, from: data2)
print(apiResponse.stocks[2].volume)
DispatchQueue.main.async {
completed()
}
}catch{
print(error)
}
}
}.resume()
when I watch videos about it they were [APIResponse].self but when I try that way my code is failed, in my way json parse is working (I can call like 'apiResponse.stocks[2].id') but I can't send this apiResponse data to views.
example of my JSON file
{
status = {
error = {
code = 0;
message = "";
};
isSuccess = 1;
};
stocks = (
{
bid = "31.5";
difference = "-0.2";
id = 1190;
isDown = 1;
isUp = 0;
offer = "31.6";
price = "31.81";
symbol = "P4jfFAYOTiLEih2Ic+NAkg==";
volume = "801457.5";
},
{
bid = "4.25";
difference = "-0.04";
id = 471;
isDown = 1;
isUp = 0;
offer = "4.26";
price = "4.31";
symbol = "zomIgqEl79jIE+TJ7xV4yQ==";
volume = "349264.21";
},
{
bid = "2.86";
difference = "-0.01";
id = 472;
isDown = 1;
isUp = 0;
offer = "2.87";
price = "2.87";
symbol = "2DlR317+autGo3fiKwNhFA==";
volume = "19279.4";
},
{
bid = 55;
difference = 1;
id = 473;
isDown = 0;
isUp = 1;
offer = "55.25";
price = "56.74";
symbol = "fvo0GQ+pqUmHXwm062Gatw==";
volume = "2647954.25";
}, {
bid = "1.22";
difference = "-0.04";
id = 465;
isDown = 1;
isUp = 0;
offer = "1.23";
price = "1.26";
symbol = "wR/24WChHVRFWZSUW1UdwQ==";
volume = "2206441.67";
}
);
}
First if you want to send your response back to the point from where initiated the API call you need to write completion handler and send your response model with the handler; you can take reference from Closures for Swift.
Also apart from that I noticed few errors in your decodable structure, for example you are expecting 'difference' as float type but the example JSON you have posted contains 'difference' as String and it applies for all your float and double values.
Also it will be a good practice If we will declare all the variable optional in decodable structure as if anytime any parameter won't come in response there won't be any problem in parsing it.

factory pattern in F#

With this type:
let Empty =
{
Buy = new Dictionary<int64, int64 * float>()
Sell = new Dictionary<int64, int64 * float>()
}
if I assign it to several entities through the code:
let a = Empty
let b = Empty
they'll represent the same dictionaries.
How can I generate a new instance every time?
let makeEmpty () = {
Buy = new Dictionary<int64, int64 * float>()
Sell = new Dictionary<int64, int64 * float>()
}

Update Nested object Value on Realm iOS

Below is the data that I have fetched from server and save to realm DB, When I try to updating scheduler_data values and stop values, but they doesn't update
(
{
"form_id" = 3703;
id = 180;
"parent_id" = 0;
"scheduler_data" = {
repeat = 7;
"schedule_for" = task;
"start_date" = "2018-08-17T11:55:41.867Z";
"start_time" = "2018-08-17T11:59:44.289Z";
stop = {
field = COL1;
operation = "equal_to";
value = "time";
};
state = 58;
territory = GHTY67;
}
)
Here the code for to update Value
SaveTaskDatabase is the table name
for saveData in realm.objects(SaveTaskDatabase.self).filter("unq_id == %#",taskUni_ID){
try! realm.write {
saveData.scheduler_data?.stop?.operation = "add"
saveData.scheduler_data?.stop?.field = "muliple"
saveData.scheduler_data?.stop?.value = "baseOnValue"
}
}

NSDictionary annidate in swift

I have this json result.
I would take the field "alert".
I try this:
var alert: NSString = jsonResult["features"]["properties"]["alert"]
but this is the error: does not have a member named 'subscript'.
I can not how to access a field in a nested dictionary
{
features = (
{
geometry = {
coordinates = (
"-97.95359999999999",
"37.2382",
5
);
type = Point;
};
id = usb000si7g;
properties = {
alert = green;
cdi = "5.8";
code = b000si7g;
detail = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/usb000si7g.geojson";
dmin = "0.017";
felt = 1258;
gap = 38;
ids = ",usb000si7g,";
mag = "4.3";
magType = mwr;
mmi = "4.94";
net = us;
nst = "<null>";
place = "8km SE of Harper, Kansas";
rms = "0.51";
sig = 864;
sources = ",us,";
status = reviewed;
time = 1412272884590;
title = "M 4.3 - 8km SE of Harper, Kansas";
tsunami = "<null>";
type = earthquake;
types = ",cap,dyfi,general-link,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,";
tz = "-300";
updated = 1412614943519;
url = "http://earthquake.usgs.gov/earthquakes/eventpage/usb000si7g";
};
type = Feature;
}
);
metadata = {
api = "1.0.13";
count = 1;
generated = 1412617232000;
status = 200;
title = "USGS Significant Earthquakes, Past Week";
url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson";
};
type = FeatureCollection;
}
I don't know what to do. swift is changed every beta.
As #Kirsteins said is his answer, you have to do a lot of unwrapping, and it's recommended to use a JSON library.
If you still want to stick with hand made extraction, then I suggest you to made it programmatically, such as adding an extension to NSDictionary as follows:
extension NSDictionary {
func objectForTreeKeys<T>(keys:[String]) -> T? {
var dict: NSDictionary? = self
var retValue: T?
for key in keys {
var value: AnyObject? = dict?.objectForKey(key)
if let unwrapped = value as? NSDictionary {
dict = unwrapped
} else if let unwrapped = value as? T {
retValue = unwrapped
break
} else {
retValue = nil
break
}
}
return retValue
}
}
You pass an array of keys to the function, and it traverses all nested dictionaries until:
a value of type T is encountered
a value having type different than NSDictionary and T is found
a nil value is found
In the first case, it returns the value of T type - in the other cases it returns nil.
You can use it as follows:
let ret: String? = jsonResult.objectForTreeKeys(["features", "properties", "alert"])
As you can see, it's a generic method, and the return type is inferred from the type of the variable the result is assigned to - so it's necessary to explicitly define its type, which must be optional (String? in this specific case).

EntityFunctions.CreateDateTime issue with leap Year in linq to entity

When i have a leap year in my database (ex.: 29th Feb 2012). The EntityFunctions.CreateDateTime functions throws System.Data.SqlClient.SqlException: Conversion failed when converting date and/or time from character string.
My Code is as follows in my asp.net mvc (C#) application:
from u in _entities.tt_Users
let _start_date = u.Start_Date
let _startDate = _start_date.Day
let _startmonth = _start_date.Month
let _startyear = _start_date.Year
let _starthour = u.Start_Time.Value.Hours
let _startminutes = u.Start_Time.Value.Minutes
let _startseconds = u.Start_Time.Value.Seconds
let _startDateWithTime = EntityFunctions.CreateDateTime(_startyear, _startmonth, _startDate, _starthour, _startminutes, _startseconds)
let _startDateWithZeroTime = EntityFunctions.CreateDateTime(_startyear, _startmonth, _startDate, 0, 0, 0)
let _start_datetime = u.Is_Include_Time ? _startDateWithZeroTime : _startDateWithTime
let _end_date = u.End_Date
let _endDate = _end_date.Day
let _endmonth = _end_date.Month
let _endyear = _end_date.Year
let _endhour = u.End_Time.Value.Hours
let _endminutes = u.End_Time.Value.Minutes
let _endseconds = u.End_Time.Value.Seconds
let _endDateWithTime = EntityFunctions.CreateDateTime(_endyear, _endmonth, _endDate, _endhour, _endminutes, _endseconds)
let _endDateWithZeroTime = EntityFunctions.CreateDateTime(_endyear, _endmonth, _endDate, 0, 0, 0)
let _end_datetime = u.Is_Include_Time ? _endDateWithZeroTime : _endDateWithTime
let _cur_Start_date = u.Is_Include_Time ? _userStartDate : _gMTStartDate
let _cur_End_date = u.Is_Include_Time ? _userEndDate : _gMTEndDate
where u.User_Id == 1 && !u.Is_Deleted
&& _start_datetime >= _cur_Start_date && _end_datetime <= _cur_End_date
select new
{
u.User_id,
u.User_Name,
u.Login_Name,
u.Email_Address
};
Here _userStartDate, _userEndDate, _gMTStartDate and _gMTEndDate are parameters from my function.
If the column "Is_Include_Time" is true, then i have to include TimeSpan also from the table. But for the leap year Its throwing the error.
Any suggestions?
I just encountered the same problem. I have some values in database rows that i need to convert to a datetime. I found out that I can use the following construct:
DateTime startDate = new DateTime(1, 1, 1);
var counters = from counter in entities.Counter
let date = SqlFunctions.DateAdd("day", counter.DayOfMonth-1, SqlFunctions.DateAdd("month", counter.Month-1, SqlFunctions.DateAdd("year", counter.Year-1, startDate)))
where date >= dateFrom && date <= dateTo
orderby date
select new
{
Value = counter.CounterValue,
Date = date
};
I'm not sure of the performance impact, but it does work.
Best regards,
Tor-Odd
try to use a declared variable outside the linq expression as I suggested here
This is the way that I deal with
var minDate = Convert.ToDateTime("1900-01-01 00:00:00");
return source.Where(x => EntityFunctions.DiffDays(x.ReviewedDate, minDate) > 0).ToList();

Resources