Rows to columns in azure data explorer (kusto) - azure-data-explorer

I have a simple query:
let startDate = ago(7d);
let endDate = now();
let all_logs = materialize(MyTable | where TIMESTAMP > startDate and TIMESTAMP < endDate | where EventName == "SessionResult");
all_logs
| summarize
Total_Sessions = count(),
Successful_Sessions = countif(Successful == "True"),
Failed_Sessions = countif(Successful == "False")
| extend Success_Rate = round(100.0*Successful_Sessions/Total_Sessions, 2)
Which returns
How can I change this to:
Label Count Rate
Total_sessions 98 100
Successful_session 96 97.96
Failed_session 2 2.04
preferably without using the pivot plugin

you could try using the narrow() plugin: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/narrowplugin
For example:
let T = materialize(
MyTable
| where TIMESTAMP > startDate and TIMESTAMP < endDate
| where EventName == "SessionResult")
| summarize
Total_Sessions = count(),
Successful_Sessions = countif(Successful == "True"),
Failed_Sessions = countif(Successful == "False")
)
;
let total = toscalar(T | project total_sessions)
;
T
| evaluate narrow()
| project Label = Column, Count = Value, Rate = round(100.0 * tolong(Value) / total, 2)

Related

Creating advance lua array table from list view and call the array elements

Say I have a CE Lua form and some variables:
form.Show()
list = form.CEListView1
tab_player = {}
p_name = 'Joe'
p_gen = 'Male'
table.insert(tab_player,{player_name = p_name, player_gen = p_gen})
-- and then add some elements from List View to same record index
for idx = list.ItemIndex + 1, list.Items.Count-1 do
mtrl_name = list.Items[idx].Caption
mtrl_qty = list.Items[idx].SubItems[0]
mtrl_unit = list.Items[idx].SubItems[1]
mtrl_price = list.Items[idx].SubItems[2]
mtrl_tprice = list.Items[idx].SubItems[3]
table.insert(tab_player, {v_itemname = mtrl_name, v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit, v_itemprice = mtrl_price, v_itemttlprice = mtrl_tprice})
end
-- check
for index, data in ipairs(tab_player) do
print(index)
for key, value in pairs(data) do
print('\t', key, value)
end
end
Result, it's created 9 tab_player record indexes (depending how many items on list view).
What I want is like this structure for one record index:
tab_player =
{
player_name = p_name,
player_gen = p_gen,
{
v_itemname = mtrl_name,
v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit,
v_itemprice = mtrl_price,
v_itemttlprice = mtrl_tprice},
{
v_itemname = mtrl_name,
v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit,
v_itemprice = mtrl_price,
v_itemttlprice = mtrl_tprice},
{
v_itemname = mtrl_name,
v_itemqty = mtrl_qty,
v_itemunit = mtrl_unit,
v_itemprice = mtrl_price,
v_itemttlprice = mtrl_tprice}
-- and so on
}
How CE Lua script to get the structure as I want?
If done, then how CE Lua script call the data from tab_player to fill player name editbox, player gen editbox and fill the items to CE List View?
EDIT:
What I want to be produce an array table with structure below:
list = UDF1.CEListView1
tab_player = {}
player_name = 'Joe'
player_gen = 'Male'
-- this is list view items contain:
--- row 1, column 1 to 5
mtrl_name = list.Items[1].Caption -- Milk
mtrl_qty = list.Items[1].SubItems[0] -- 300
mtrl_unit = list.Items[1].SubItems[1] -- ml
mtrl_price = list.Items[1].SubItems[2] -- 3975
mtrl_tprice = list.Items[1].SubItems[3] -- 3975
--- row 2, column 1 to 5
mtrl_name = list.Items[2].Caption -- Sugar
mtrl_qty = list.Items[2].SubItems[0] -- 1
mtrl_unit = list.Items[2].SubItems[1] -- Kg
mtrl_price = list.Items[2].SubItems[2] -- 18000
mtrl_tprice = list.Items[2].SubItems[3] -- 18000
--- row 3, column 1 to 5 and so om
the tab_player should be:
tab_player = {
-- index 0 or record 1
{player_name = 'Joe', player_gen = 'Male',
-- row 1, column 1 to 5
{
item_name = 'Milk',
item_qty = 300,
item_unit = 'ml',
item_price = 3975,
item_tprice = 3975
},
-- row 2, column 1 to 5
{
item_name = 'Sugar',
item_qty = 2,
item_unit = 'Kg',
item_price = 9000
item_tprice = 18000
},
-- row 3, column 1 to 5
{
item_name = 'bla bla bla',
item_qty = 1,
item_unit = 'bla',
item_price = 1000000
item_tprice = 1000000
}
-- and so on
}
How to create, print multidimensional and call back the item from the array table as above?.

sqllite query to count across rows

I create an audit trail to record every change in one of my project databases.
I have a table called DatabaseAudit with the columns and some sample values below. Type can be "Insert", "Update", or "Delete"
Id, Timestamp, Type, RecordId
1, 637052212796419902, Update, 13
2, 637052213295073040, Update, 15
3, 637052213388962058, Update, 22
4, 637052213494632806, Update, 3
5, 637052213604466165, Update, 25
When Type = "Insert" or "Update", I record the actual values in a table called TableAudit with the columns below
DatabaseAuditId, ColumnName, PreviousValue, NewValue
1, Col1, False, True
1, Col2, , P
2, Col1, False, True
2, Col2, , P
3, Col1, False, True
3, Col2, , M
4, Col1, True, False
4, Col2, , P
5, Col1, False, True
5, Col2, , M
I am having a hard time generating a query. For example, I'd like the count of the number of DatabaseAudit entries where the Col1 new value is "True" and Col2 new value is "P". Which for this example would be 2.
Try this one:
WITH q1 AS (SELECT DISTINCT Count(*) FROM TableAudit WHERE
(ColumnName = 'Col1' AND NewValue = 'True') OR
(ColumnName = 'Col2' AND NewValue = 'P')
Group by DatabaseAuditId
)
SELECT count(*) FROM q1
Hope it helps.
SELECT count(*) AS MatchCount
FROM (SELECT id
FROM DatabaseAudit AS d
JOIN TableAudit AS t ON d.Id = t.DatabaseAuditId
WHERE (t.ColumnName, t.NewValue) = ('Col1', 'True')
OR (t.columnName, t.NewValue) = ('Col2', 'P')
GROUP BY d.Id
HAVING count(*) = 2);
MatchCount
----------
2
For each DatabaseAuditId with ColumnName = 'Col1' and NewValue = 'True' check if there is a row with the same DatabaseAuditId and ColumnName = 'Col2' and NewValue = 'P' with EXISTS:
select count(*) counter
from TableAudit t
where t.ColumnName = 'Col1' and t.NewValue = 'True'
and exists (
select 1 from TableAudit
where DatabaseAuditId = t.DatabaseAuditId and ColumnName = 'Col2' and NewValue = 'P'
)
See the demo.
Results:
| counter |
| ------- |
| 2 |

NameError: global name 'key_str' is not defined

in below script i am getting the error
if not any(d['KEY'] == key_str for d in records):
NameError: global name 'key_str' is not defined
I am transposing a input file set of columns to rows and rows to columns.
please help:
if "Sales-Target" in fdmContext["LOCNAME"]:
filename = fdmContext["FILENAME"]
dim_cols = 7
period_dim_index = 0
input_filename = (os.path.abspath("E:/FDMEE/")+"\%s" % filename)
months = ['M%s' % x for x in range(1,13)]
first_row = True
headers = []
records = []
output_filename = "%s_out.%s" % (input_filename.split(".")[0],input_filename.split(".")[1])
input_f = open(input_filename)
for line in input_f:
if first_row:
headers = line.split(",")
headers = [x.rstrip() for x in headers]
else:
data = line.split(",")
for i in range(dim_cols,len(headers)):
key = data[:dim_cols]
del key[period_dim_index]
key.append(headers[i])
key_str = "_".join(key)
if not any(d['KEY'] == key_str for d in records):
record = {}
record["ACCOUNT"] = headers[i]
record["KEY"] = key_str
record["PERIODS"] = {}
for j in range(0,dim_cols):
if j == period_dim_index:
record["PERIODS"][data[j]] = data[i].rstrip()
else:
record[headers[j]] = data[j]
records.append(record)
else:
record = (d for d in records if d["KEY"] == key_str).next()
record["PERIODS"][data[period_dim_index]] = data[i].rstrip()
first_row = False
input_f.close()
output_f = open(output_filename,"w")
row=[]
[row.append(x) for x in headers[:dim_cols] if headers.index(x) != period_dim_index]
row.append("ACCOUNT")
[row.append(x) for x in months]
output_f.write("%s\n" % ",".join(row))
for record in records:
row = [record[x] for x in headers[:dim_cols] if headers.index(x) != period_dim_index]
row.append(record["ACCOUNT"])
for month in months:
if month in record["PERIODS"].keys():
row.append(record["PERIODS"][month])
else:
row.append("0")
output_f.write("%s\n" % ",".join(row))
output_f.close()

JavaCC: encountered... Was expecting one of... error

I'm getting this error when trying to run a parser written in JavaCC on a sample (syntactically valid) file:
Exception in thread "main" ParseException: Encountered "8;" at line 13, column 17.
Was expecting one of:
<INT_CONST> ...
"<" ...at jimpleParser.generateParseException(jimpleParser.java:2421)
at jimpleParser.jj_consume_token(jimpleParser.java:2292)
at jimpleParser.expr(jimpleParser.java:1038)
(shortened for conciseness)
I cannot work out why it is throwing an error. "8" should be a valid token. Here is the function in question:
String expr():
{
Token t1 = null, t2 = null;
String f1 = null, f2 = null, f3 = null;
}
{
(LOOKAHEAD(3)
f1 = imm() {System.out.println(f1);}
| f1 = new_expr()
| t1 = <LBR> f2 = nonvoid_type() t2 = <RBR> f3 = imm()
{f1 = t1.image.concat(f2.concat(t2.image.concat(f3)));}
| LOOKAHEAD(2)
f2 = imm() t1 = <INSTANCEOF> f3 = nonvoid_type()
{f1 = f2.concat(t1.image.concat(f3));}
| f1 = invoke_expr()
| LOOKAHEAD(2)
f1 = reference()
| LOOKAHEAD(2)
f1 = binop_expr()
| f1 = unop_expr())
{return f1;}
}
which should in turn call imm shown here:
String imm():
{
String f1 = null;
}
{
(f1 = constant()
| f1 = local_name())
{return f1;}
}
which should in turn call constant shown here:
String constant():
{
Token t1 = null, t2 = null;
String f1 = null;
}
{
(t1 = <INT_CONST> {f1 = t1.image; System.out.println(f1);}
| t1 = <FLOAT_CONST> {f1 = t1.image;}
| t1 = <MIN_INT_CONST> {f1 = t1.image;}
| t1 = <MIN_FLOAT_CONST> {f1 = t1.image;}
| t1 = <STRING_CONST> {f1 = t1.image;}
| t1 = <CLASS> t2 = <STRING_CONST> {f1 = t1.image.concat(t2.image);}
| t1 = <NULL> {f1 = t1.image;})
{return f1;}
}
8 should be an INT_CONST. Relevant token specifications are shown here:
<INT_CONST: ((<OCT_CONST> | <DEC_CONST> | <HEX_CONST>) ("L")?)>
<DEC_CONST: (<DEC_DIGIT>)+>
<DEC_DIGIT: ["0"-"9"]>
Any help would be much appreciated. Thanks
Note that it is not "8" that is causing the problem, but "8;". Although "8" is an INT_CONST, "8;" is not. So the longest match rule is kicking in and some other token production that does match "8;" is winning. See the FAQ http://www.engr.mun.ca/~theo/JavaCC-FAQ/ question 3.3. Without seeing all of your .jj file, I can't tell you which token it is, but if you put a break point on the code that constructs the error message you can easily see what the .kind field of the unexpected token holds.
Try this in your token section, it would definitely solve your problem:
TOKEN:
{
<DEC_DIGIT: (["0"-"9"])>
|
<INT_CONST: ((<OCT_CONST> | <DEC_CONST> | <HEX_CONST>) ("L")?)>
|
<DEC_CONST: (<DEC_DIGIT>)+>
// The rest of your tokens....
}

Datatable calendar on VisualBasic

I have a request to show a grid similar to a calendar showing on columns the day and on row months.
Something like this
Month |Sun|Mon|Tue|Wed|Thu|Fri|Sat|Sun|Mon|Tue|Wed|Thu|Fri|Sat|Sun|Mon|Tue|Wed|...|Thu|
January | 1| 2| 3| 4| 5| 6| 7| 8| 9| 10| 11|...................| 31|
Febrary | | | | 1| 2| 3| 4| 5| 6| 7|...........................| 29|
...
December| 30| 31| | | | | 1| 2| 3| 4|............................
Is there a way to do this, considering that The Start day of the year must be the real day name, not a constant and this must be generated dynamically
I try this but my idea goes off!
Private Sub GenerateCalendar(ByVal year As Integer)
Dim colsCount As Integer = 3
If Bisiesto(año) Then
colsCount = colsCount + 366
Else
colsCount = colsCount + 365
End If
Dim dtCalendar As New DataTable
dtCalendar.Columns.Add("Mes")
Dim dayMonthYear As Date = New Date(year , 1, 1)
'Showing the distribution of the first month
While dayMonthYear.Year = año And dayMonthYear.Month = 1
Dim dtColumn As DataColumn = New DataColumn()
dtColumn.ColumnName = WeekdayName(Weekday(dayMonthYear)) & dayMonthYear.Day & dayMonthYear.Month
dtColumn.Caption = WeekdayName(Weekday(dayMonthYear))
dtCalendar.Columns.Add(dtColumn)
dayMonthYear = diaMesAño.AddDays(1)
End While
Dim row As DataRow = dtCalendario.NewRow()
'Here I need to distribute the days on its column day
dtCalendario.Rows.Add(row)
wdgCalendario.DataSource = dtCalendar
wdgCalendario.DataBind()
End Sub
Public Function LeapYear(ByVal year As Integer)
Dim isLeapYear As Boolean = False
If year Mod 4 = 0 Then
If (year Mod 100 = 0) And Not (year Mod 400 = 0) Then
isLeapYear = False
Else
isLeapYear = True
End If
Else
isLeapYear = False
End If
Return isLeapYear
End Function
Note: You cannot have duplicate column names in the DataTable, so i have appended the weekday with the number of week in month. But see it for yourself:
Private Function GetCalendarTable(year As Int32) As DataTable
Dim curCulture = System.Globalization.CultureInfo.CurrentCulture
Dim firstYearDate = New Date(year, 1, 1)
Dim currentDate = firstYearDate
Dim tblCalendar = New DataTable
tblCalendar.Columns.Add(New DataColumn("MonthName"))
Dim maxDiff = 0
For m = 1 To 12
'find max difference between first year's weekday and month's first weekday
'if the latter is earlier in the week, it is considered to be in the next week
Dim monthFirstWeekDay = New Date(year, m, 1).DayOfWeek
Dim diff = (7 + (monthFirstWeekDay - firstYearDate.DayOfWeek)) Mod 7
If diff > maxDiff Then
maxDiff = diff
End If
Next
Dim weekDayNum = curCulture.Calendar.GetDaysInMonth(year, 1) + maxDiff
' Create DataColumns with weekday as ColumnsName
For wd = 1 To weekDayNum
Dim weekday = currentDate.ToString("ddd")
Dim weekInMonth = (From col In tblCalendar.Columns.Cast(Of DataColumn)()
Where col.ColumnName Like String.Format("{0} W#", weekday)).Count + 1
Dim columnName = String.Format("{0} W{1}", weekday, weekInMonth)
tblCalendar.Columns.Add(New DataColumn(columnName))
currentDate = currentDate.AddDays(1)
Next
' Create the DataRows(every month)
For m = 1 To 12
Dim daysInMonth = curCulture.Calendar.GetDaysInMonth(year, m)
Dim firstMonthDate = New Date(year, m, 1)
Dim daysBefore = (7 + (firstMonthDate.DayOfWeek - firstYearDate.DayOfWeek)) Mod 7
Dim daysBehind = tblCalendar.Columns.Count - (daysBefore + daysInMonth) - 1
Dim monthDays = From d In Enumerable.Range(1, daysInMonth)
Select New With {.Day = d.ToString}
Dim emptyDaysBefore = From d In Enumerable.Range(1, daysBefore)
Select New With {.Day = ""}
Dim emptyDaysAfter = From d In Enumerable.Range(1, daysBehind)
Select New With {.Day = ""}
Dim monthName = curCulture.DateTimeFormat.GetMonthName(m)
' piece together parts
Dim allFields = ({New With {.Day = monthName}}.
Union(emptyDaysBefore).
Union(monthDays).
Union(emptyDaysAfter).
Select(Function(d) d.Day)).ToArray
tblCalendar.Rows.Add(allFields)
Next
Return tblCalendar
End Function

Resources