Assume I have an Appian common data type (CDT) called myTask which contains multiple fields taskName, taskQuarter, taskYear, taskId saved in a local variable (of an Interface) which looks for instance as follows
+ data (List of dictionary)
+ (Dictionary)
- taskName: "Plant trees." (Text)
- taskQuarter: 1 (Number (Integer))
- taskYear: 2020 (Number (Integer))
- taskId: 0 (Number (Integer))
+ (Dictionary)
- taskName: "Cut leaves." (Text)
- taskQuarter: 2 (Number (Integer))
- taskYear: 2020 (Number (Integer))
- taskId: 1 (Number (Integer))
In the local scope (of the interface), I would like to have an additional field for all records called taskLongName which would be the following concatenation (in pseudocode):
taskLongName = taskName + " " + taskYear + " Q" + taskQuarter
How do I do that, please?
It turned out to be rather simple: Assuming that you have an expression rule myGetAllTasks() defined, you could put the initial list of dictionaries into local!allTasks. Next, we use Appian's a!forEach() function:
a!localVariables(
local!allTasks: rule!myGetAllTasks().data,
local!taskLongNames:
a!foreach(
items: local!allTasks,
expression: concat(
fv!item.taskName, " for ",
fv!item.processYear, " Q",
fv!item.processQuarter
)
),
... <-- Here comes the configuration (code) defining the actual interface
)
I am wondering how to get battery temperature using
batteryGetTemperature()
Why do get error
And how to solve it
droid.batteryStartMonitoring()
print("Battery Percentage: " + str(droid.batteryGetLevel().result) + "%")
print("Battery Temperature: " + str(int(droid.batteryGetTemperature().result)/int(10)) + "°C")
droid.batteryStopMonitoring()
Those batteryGet… functions return None now.
I don't know why. It seems to work before.
Here's a working script I wrote long ago:
#-*-coding:utf8;-*-
#qpy:2
#qpy:console
from androidhelper import sl4a
droid=sl4a.Android()
droid.batteryStartMonitoring()
raw_input("\nBattery Data\nPress to continue…")
try:
data=droid.readBatteryData()
if data.error==None:
print "Data:"
for x in ["temperature","level","status","plugged","voltage","health","technology","battery_present"]:
print " "+x+":",data.result[x]
else:
print "ERROR!"
print data.error
except Exception as err:
print "ERROR!"
print err
finally:
droid.batteryStopMonitoring()
"""
ex.(id=0,result={"":""},error=None)
BatteryManagerFacade
batteryCheckPresent
ex.True
batteryGetHealth
1 - unknown;
2 - good;
3 - overheat;
4 - dead;
5 - over voltage;
6 - unspecified failure;
batteryGetLevel
%
batteryGetPlugType
-1 - unknown
0 - unplugged;
1 - power source is an AC charger
2 - power source is a USB port
batteryGetStatus
1 - unknown;
2 - charging;
3 - discharging;
4 - not charging;
5 - full;
batteryGetTechnology
ex.Li-ion
batteryGetTemperature
ex.310
batteryGetVoltage
ex.4248
batteryStartMonitoring
None
batteryStopMonitoring
None
readBatteryData
status
temperature
level
battery_present
plugged
health
voltage
technology
"""
I have a date and time format:
Interval Start Time
1/13/16 1:30:00
1/15/16 10:30:00
Desired Result
Interval Start Time
13/01/2016 13:30:00 (24 Hr)
15/01/2016 10:30:00
The Interval Time is between 08:00 to 17:30.
I would like it to be: 13/01/2016 13:30 and 15/01/2016 10:30:00 and I devised this In SSIS derived Column:
(DT_DATE)(SUBSTRING([Interval Start Time],3,2) + "-" +
SUBSTRING([Interval Start Time],1,1) + "-" +
SUBSTRING([Interval Start Time],6,2) + " " +
SUBSTRING([Interval Start Time],9,1) == 1 ? "13" :
SUBSTRING([Interval Start Time],9,1) == 2 ? "14" :
SUBSTRING([Interval Start Time],9,1) == 3 ? "15" :
SUBSTRING([Interval Start Time],9,1) == 4 ? "16" :
SUBSTRING([Interval Start Time],9,1) == 5 ? "17" :
"[Interval Start Time]" )
+ ":" + SUBSTRING([Interval Start Time],11,2))
The error I get in SSIS is:
...The expression might contain an invalid token, an incomplete token, or an invalid element...
and I am not sure if the formula is correct in what I want it to do either. Any help would be much appreciated.
Before present a possible solution here, I want you be aware about some errors in your approach. Using expressions for this requeriment is very complex and hard to maintain, besides what happen when your Interval Start Time column have dates from October (10) to December (12) months, your string lenght will change and your hardcoded solution via SUBSTRING calls will return absurd data and produce error while package is running.
SOLUTION: Use Script component.
After creating your source, add a Script Component and link the source to it.
Configure the Script component to include Interval Start Time column by selecting it in Input Columns tab.
Add an output column, name it as you want and choose database timestamp (DT_DBTIMESTAMP).
Go to Script tab, and press the Edit Script... button.
Use the below code to overwrite the Input0_ProcessInputRow function.
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
/*
* Add your code here
*/
var str_timestamp = Row.IntervalStartTime.ToString();
string[] arr = str_timestamp.Trim().Split(' ');
string[] date = arr[0].Split('/');
string[] time = arr[1].Split(':');
string formatedDate = "20" + date[2] + "-" + date[0].PadLeft(2, '0') + "-" + date[1].PadLeft(2, '0');
int hour = Convert.ToInt32(time[0]);
int hour_24 = hour < 8 ? hour + 12 : hour;
formatedDate += " " + hour_24 + ":" + time[1] + ":" + time[2];
Row.MyColumn = Convert.ToDateTime(formatedDate);
}
In Row.MyColumn, replace MyColumn by the given name of your output column.
Save changes in Visual Studio and close the editor.
Now you can add a destination after the Script component and you will see the formatted IntervalStartTime as you need.
Let me know if this helps.
I have some data in the following format.
# AB Tests
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
abTests:
productRanking:
version: 4
groups: [
ratio:
default: 1
us: 0.90
me: 0.0
value: "LessPopularityEPC"
,
ratio:
default: 0
us: 0.1
value: "CtrEpcJob"
,
ratio:
default: 0
me: 1.0
value: "RandomPerVisitor"
]
# Routes
I want the following output as a string array:
productRanking:LessPopularityEPC
productRanking:CtrEpcJob
productRanking:RandomPerVisitor
I am using the following code which will separate the key and values from the data & store them into an array
START_REGEXP = /# AB Tests/
END_REGEXP = /# Routes/
COMMENT_EXP = /#/
#Function to fetch the key:value & store them into array
def Automate_AB_tests.store_key_value(input_file)
prev_line = ""
curr_line = ""
array = []
flag = false
IO.foreach(input_file) do |line|
prev_line = curr_line
curr_line = line
flag = true if line =~ START_REGEXP
if flag
unless line =~ COMMENT_EXP
if line.include? 'version: '
key = prev_line
puts key #productRanking: sabt:
end
if line.include? 'value: '
value = line.delete('\n').delete('"').split[1] #LessPopularityEPC CtrlEpcJob RandomPerVisitor
array << "#{key}:#{value}"
end
end
flag = false if line =~ END_REGEXP
end
end
puts array
end
It is fetching the keys but not storing those keys into stringArray. If anyone can point out what's wrong with my code then it would be really great. I am getting output as below:
productRanking:
:LessPopularityEPC
:CtrEpcJob
:RadomPerVisitor
Since for some reason you apparently can't or won't install Node.js, which would make really, really short work of this, you're stuck doing an ugly hack.
I propose an alternate ugly hack: CSON isn't all that different from YAML. Do some simple substitutions to turn it into YAML and then parse that in Ruby.
Caveat emptor: Like all ugly hacks, this is super fragile. It will probably break as soon as you try to take a vacation. Use at your own risk.
require "yaml"
data = <<END
# AB Tests
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
abTests:
productRanking:
version: 4
groups: [
ratio:
default: 1
us: 0.90
me: 0.0
value: "LessPopularityEPC"
,
ratio:
default: 0
us: 0.1
value: "CtrEpcJob"
,
ratio:
default: 0
me: 1.0
value: "RandomPerVisitor"
]
# Routes
END
AB_TESTS_SECTION_EXPR = /^( +)abTests:\n.+(?=^\1[^ ])/m
# Extract text between "# AB Tests" and "# Routes"
ab_tests = data[AB_TESTS_SECTION_EXPR]
# Turn the CSON array into a YAML array by removing the square brackets and
# commas and inserting a `-` before each "ratio:"
yaml = ab_tests.gsub(/\s+\[$/, '')
.gsub(/ ratio:\s*$/, '- ratio:')
.gsub(/^\s*[,\]]\s*$/, '')
puts yaml
This will print the following valid YAML:
abTests:
productRanking:
version: 4
groups:
- ratio:
default: 1
us: 0.90
me: 0.0
value: "LessPopularityEPC"
- ratio:
default: 0
us: 0.1
value: "CtrEpcJob"
- ratio:
default: 0
me: 1.0
value: "RandomPerVisitor"
Now we just need to parse the YAML into Ruby and extract the data we need:
hsh = YAML.load(yaml)
hsh["abTests"].each do |key, val|
val["groups"].each do |group|
puts "#{key}:#{group['value']}"
end
end
# => productRanking:LessPopularityEPC
# productRanking:CtrEpcJob
# productRanking:RandomPerVisitor
I'm working on an nmea sentence project where I get a txt file with nmea sentences delimited by commas. I'm trying to use xlsxwriter to write the results into excel. The results I want are having the timestamp,latitude, longitude and altitude printed in rows that correspond to each other...but I keep getting the first iteration of my 'query' written out five times before the other iterations are written into xlsx. I know there must be a simple solution to this..can you tell me where I'm going wrong?
This is the beginning of my script so you have a full picture of what is going on
import os
import csv
from csv import *
import numpy
import matplotlib
from numpy import *
from matplotlib import *
import matplotlib.pyplot as plt
from matplotlib.pylab import *
import numpy as np
#to export to excel
import xlsxwriter
from xlsxwriter.workbook import Workbook
#to get the csv converter functions
import os
import subprocess
import glob
#to get the datetime functions
import datetime
from datetime import datetime
from pytz import timezone
import time
import calendar
#creates the path needed for incoming and outgoing files
path_in = 'C:/Python34/gps_txts/'
path_out = 'C:/Python34/output_files/'
#prints all the data in the file if you want
q_show_content = input('Print list of files type y:')
if q_show_content == 'y':
for root, dirs, files in os.walk(path_in):
print(root, dirs, files)
else:
print('ok')
data = [] #empty because we will store data into it
#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
"""Reads a CSV file and return it as a list of rows."""
for row in csv.reader(open(filename)):
data.append(row)
return data
#request of what file to look at
print ("- - - - - - - - - - - - -")
data_file = input('Which file do you want to look at?')
f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)
with f as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
plots = csv.reader(csvfile, delimiter=',')
#creates the workbook
output_filename = input('output filename:')
workbook = xlsxwriter.Workbook(path_out + output_filename + '.xlsx')
worksheet = workbook.add_worksheet()
#formatting definitions
bold = workbook.add_format({'bold': True})
date_format = workbook.add_format({'num_format': "m/d/yyyy hh:mm:ss"})
#print number of rows
print ("- - - - - - - - - - - - -")
rows = len(read_it)
print (data_file, " has "+ str(rows) + " rows of data")
print ("- - - - - - - - - - - - -")
#Counts the number of times a GPS command is observed
def list_gps_commands(data):
"""Counts the number of times a GPS command is observed.
Returns a dictionary object."""
gps_cmds = dict()
for row in data:
try:
gps_cmds[row[0]] += 1
except KeyError:
gps_cmds[row[0]] = 1
return gps_cmds
print(list_gps_commands(read_it))
print ("- - - - - - - - - - - - -")
#prints all the data in the file if you want
q_show_data = input('Print data inside ' + data_file + ' type y:')
if q_show_data == 'y':
for row in read_it:
print(row)
else:
print('ok')
This is the part I'm having an issue with
#Function process_gps_data for GPS
NMI = 1852.0
def process_gps_data(data):
"""Processes GPS data, NMEA 0183 format.
Returns a tuple of arrays: latitude, longitude, velocity [km/h],
time [sec] and number of satellites.
See also: http://www.gpsinformation.org/dale/nmea.htm.
"""
latitude = []
longitude = []
altitude = []
velocity = []
timestamp = []
num_sats = []
for row in data:
if row[0] == '$GPRMC': # Valid position/time sentence
y = (float(row[3][0:2]) + float(row[3][2:])/60.0)
if row[4] == "S":
y = -y
latitude.append(y)
x = (float(row[5][0:3]) + float(row[5][3:])/60.0)
if row[6] == "W":
x = -x
longitude.append(x)
print('x,y:',x,y)
velocity.append(float(row[7])*NMI/1000.0)
gpstime = row[1][0:6] # hhmmss
gdate = row[9] # ddmmyy
gpsdate = gdate[4:6]+gdate[2:4]+gdate[0:2] # yymmdd
real_time =gpsdate + gpstime
add_date_time = datetime.strptime(real_time, "%y%m%d%H%M%S")
print(add_date_time)
timestamp.append(add_date_time)
return (array(latitude), array(longitude), array(velocity), array(timestamp))
# how to call process_gps_data()
(lati, long, v, t_stamp) = process_gps_data(data)
print ("- - - - - - - - - - - - -")
print('lati:',lati)
print ("- - - - - - - - - - - - -")
print('long:',long)
print ("- - - - - - - - - - - - -")
print('v:',v)
print ("- - - - - - - - - - - - -")
print('date:', t_stamp)
print ("- - - - - - - - - - - - -")
#sets up the header row
worksheet.write('A1','TimeStamp',bold)
worksheet.write('B1', 'Latitude',bold)
worksheet.write('C1', 'Longitude',bold)
worksheet.write('D1', 'Velocity',bold)
worksheet.autofilter('A1:D1') #dropdown menu created for filtering
# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(row):
worksheet.write_column(r,0, t_stamp, date_format)
worksheet.write_column(r,1, lati)
worksheet.write_column(r,2, long)
worksheet.write_column(r,3, v)
workbook.close()
f.close()
I am using a dummy gps cache with these lines in a txt file. Notice the GPRMC have a different year in row[9] == 01,02,03
$GPRMC,002454,A,3553.5295,N,13938.6570,E,0.0,43.1,180701,7.1,W,A*3F
$GPRMB,A,,,,,,,,,,,,A,A*0B
$GPGGA,002455,3553.5295,N,13938.6570,E,1,05,2.2,18.3,M,39.0,M,,*7F
$GPRMC,002456,A,3553.5321,N,13938.6581,E,0.0,43.1,180702,7.1,W,A*3D
$GPRMC,104715.20,A,5100.2111,N,00500.0006,E,21.7,003.0,140803,01.,W*70
My results being printed out looks the way that they are expected to...
- - - - - - - - - - - - -
garmin etrex summit.txt has 5 rows of data
- - - - - - - - - - - - -
{'$GPRMC': 3, '$GPGGA': 1, '$GPRMB': 1}
- - - - - - - - - - - - -
Print data inside garmin etrex summit.txt type y:
ok
x,y: 139.64428333333333 35.892158333333334
2000-07-18 00:24:54
x,y: 139.64430166666668 35.892201666666665
2001-07-18 00:24:56
x,y: 5.00001 51.00351833333333
2003-08-14 10:47:15
- - - - - - - - - - - - -
lati: [ 35.89215833 35.89220167 51.00351833]
- - - - - - - - - - - - -
long: [ 139.64428333 139.64430167 5.00001 ]
- - - - - - - - - - - - -
v: [ 0. 0. 40.1884]
- - - - - - - - - - - - -
date: [datetime.datetime(2000, 7, 18, 0, 24, 54)
datetime.datetime(2001, 7, 18, 0, 24, 56)
datetime.datetime(2003, 8, 14, 10, 47, 15)]
- - - - - - - - - - - - -
But when i look at my produced xlsx file, I have the first five rows looking like this:
TimeStamp Latitude Longitude Velocity
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2002 00:24:56 35.89220167 139.6443017 0
8/14/2003 10:47:15 51.00351833 5.00001 40.1884
So my issue is that I get 5 of the same first 'query' and then the other 2 iteration of '$GPRMC'
Where am i going wrong?