extracting data from nested dictionary by python - dictionary

I am trying to extract data from a JSON file, and am still not clear about the error coming. My data is like this:
"Tracker":{"Sep 30, 2021":{"DC":4,"DN":"0:0",
DC = {}
for day, daily_data in read_content['Tracker'].items():
for value in daily_data['Disturbances Count']:
DC[datetime] = value
Im getting the following error
---------------------------------------------------------------------------
TypeError: 'int' object is not iterable

The solution for the above code only to add str
DC = {}
for day, daily_data in read_content['Tracker'].items():
for value in str(daily_data['Disturbances Count']):
DC[datetime] = value

Related

How can I create a BLf file based on a measurement data?

I'm trying to make a certain BLF CAN data file.
After I created an arbitary measurements table, I try to encode messages and write on BLF format by folloing codes.
The BLF file was made, however, it doesn't have any data at all.
Please let me know what the problem is.
What I tried :
import cantools
import can
db = cantools.database.load_file('T_Fuel_HB.dbc')
ex_msg = db.get_message_by_name("DEVICE_56604591_0")
time = 0
write_created = can.BLFWriter("sample_created.blf")
for i in range(10) :
r_int = np.random.randint(0, 100)
data_created = ex_msg.encode({'C_1_T_Air' : r_int, 'C_2_T_EG_room' : r_int, 'C_3_T_Pump_room' : r_int, 'C_4_T_Fuel_tank' : r_int})
msg_created = can.Message(timestamp = time, arbitration_id = ex_msg.frame_id, data = data, channel=0)
print(msg_created, r_int)
time += 2
write_created.on_message_received(msg_created)
What I expected :
filename = "VDK14.blf"
log = can.BLFReader(filename)
log = list(log)
for msg in log :
write.on_message_received(msg)
-> When I use the BLF file with existing log data, it's no problem to read the file thru CANanalyzer.

Converting docx.files to pdf.files with docx2pdf

Not sure what I am doing wrong.
I want to convert multiple docx.files to pdf.files - each file into a separate one.
I decided to use the "doconv"-package with following command:
docx_files <- list.files(pattern=paste0("Protokollnr_"))[39:73]
docx_files %>% length
lapply(1:35, function(x) {
docx2pdf(input = docx_files[[x]],
output = tempfile(fileext = ".pdf"))})
I does not say anything specific in the error message - only that it cannot be converted.
Is it that I should have specified the file path - now I only define the file name in my WD.
The object "docx_files" contain:
c("Protokollnr_1.docx", "Protokollnr_10.docx", "Protokollnr_11.docx",
"Protokollnr_12.docx", "Protokollnr_13.docx", "Protokollnr_14.docx",
"Protokollnr_15.docx", "Protokollnr_16.docx", "Protokollnr_17.docx",
"Protokollnr_18.docx", "Protokollnr_19.docx", "Protokollnr_2.docx",
"Protokollnr_20.docx", "Protokollnr_21.docx", "Protokollnr_22.docx",
"Protokollnr_23.docx", "Protokollnr_24.docx", "Protokollnr_25.docx",
"Protokollnr_26.docx", "Protokollnr_27.docx", "Protokollnr_28.docx",
"Protokollnr_29.docx", "Protokollnr_3.docx", "Protokollnr_30.docx",
"Protokollnr_31.docx", "Protokollnr_32.docx", "Protokollnr_33.docx",
"Protokollnr_34.docx", "Protokollnr_35.docx", "Protokollnr_4.docx",
"Protokollnr_5.docx", "Protokollnr_6.docx", "Protokollnr_7.docx",
"Protokollnr_8.docx", "Protokollnr_9.docx")
The error message is:
Error in docx2pdf(input = docx_files[[x]], output = tempfile(fileext = ".pdf")) :
could not convert C:/Users/Nadine/OneDrive/Documents/Arbeit_Büro_papa/Protokolle_Sallapulka/fertige_Protokolle/Protokollnr_1.docx
Many thanks,
Nadine
I'd recommend specifying the file path since the function requires the following format:
docx2pdf(input, output = gsub("\\.docx$", ".pdf", input))

Create HEX attachment for Quality Notification

I have this piece of code to download the hex content of a file with import parameter file id. I want to insert a new attachment for a notification, but I don't know how to get started.
METHOD GET_SINGLE_ATTACHMENT_CONTENT.
" VARIABLES
DATA: HEXCONT TYPE TABLE OF SOLIX.
DATA: DOCDATA TYPE SOFOLENTI1.
DATA: LV_LENGTH TYPE I.
" CHECK TO CONTINUE FUNCTION MODULE
IF FILE_ID IS INITIAL. "type = SOFOLENTI1-DOC_ID.
MESSAGE 'Document ID is empty.' TYPE 'E' RAISING DOC_ID_EMPTY.
ENDIF.
" GET BINARY CONTENT OF FILE
CALL FUNCTION 'SO_DOCUMENT_READ_API1'
EXPORTING
DOCUMENT_ID = FILE_ID
IMPORTING
DOCUMENT_DATA = DOCDATA
TABLES
CONTENTS_HEX = HEXCONT.
IF SY-SUBRC <> 0.
MESSAGE 'Error downloading file.' TYPE 'E' RAISING FILE_DOWNLOAD_ERROR.
ENDIF.
" CONVERT TO XSTRING
LV_LENGTH = DOCDATA-DOC_SIZE.
CALL FUNCTION 'SCMS_BINARY_TO_XSTRING'
EXPORTING
INPUT_LENGTH = LV_LENGTH
IMPORTING
BUFFER = EV_RETURN "type XSTRING
TABLES
BINARY_TAB = HEXCONT.
IF SY-SUBRC <> 0.
MESSAGE 'Error downloading file.' TYPE 'E' RAISING FILE_DOWNLOAD_ERROR.
ENDIF.
ENDMETHOD.
I've read about function modules like 'SO_DOCUMENT_INSERT_API1' and it has the file information but not the file content (preferably hex content). Any idea on how to get started with this?
Maybe you can do something with the approach I used. Check this example below.
Start with parsing your data to hex
Insert the document with so_document_insert_api1
Link it to your notification with the fm binary_relation_create
" TYPES
TYPES: BEGIN OF TYPE_FILE,
NAME TYPE STRING,
TYPE TYPE STRING,
QMNUM TYPE QMNUM,
USER TYPE CHAR64,
HEXCONT TYPE XSTRING,
END OF TYPE_FILE.
" VARIABLES AND OBJECTS
DATA: LT_RETURN TYPE TABLE OF BAPIRET2.
DATA: LT_HEXCONT TYPE TABLE OF SOLIX.
DATA: LS_DOCDATA TYPE SODOCCHGI1.
DATA: LS_DOCINFO TYPE SOFOLENTI1.
DATA: LS_FILE TYPE TYPE_FILE.
DATA: LV_DOCTYPE TYPE SOODK-OBJTP.
DATA: LV_FOLDER_ID TYPE SOOBJINFI1-OBJECT_ID.
DATA: LV_LENGTH TYPE I.
DATA: OBJ_NOTIF TYPE BORIDENT.
DATA: OBJ_ATTACH TYPE BORIDENT.
DATA: P_QMNUM TYPE QMNUM.
LV_FOLDER_ID = 'FOL40000000000004'.
" CONVERT HEX CONTENT TO BINARY
CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
EXPORTING
BUFFER = LS_FILE-HEXCONT
IMPORTING
OUTPUT_LENGTH = LV_LENGTH
TABLES
BINARY_TAB = LT_HEXCONT.
" SET VALUES
LS_DOCDATA-OBJ_DESCR = LS_FILE-NAME.
LS_DOCDATA-OBJ_LANGU = 'E'.
LS_DOCDATA-OBJ_NAME = 'MESSAGE'.
LS_DOCDATA-DOC_SIZE = XSTRLEN( LS_FILE-HEXCONT ).
LV_DOCTYPE = LS_FILE-TYPE.
UNPACK LS_FILE-QMNUM TO P_QMNUM.
" CREATE ATTACHMENT
CALL FUNCTION 'SO_DOCUMENT_INSERT_API1'
EXPORTING
FOLDER_ID = LV_FOLDER_ID
DOCUMENT_DATA = LS_DOCDATA
DOCUMENT_TYPE = LV_DOCTYPE
IMPORTING
DOCUMENT_INFO = LS_DOCINFO
TABLES
CONTENTS_HEX = LT_HEXCONT.
" CREATE LINK TO OBJECT (Notification)
OBJ_NOTIF-OBJKEY = P_QMNUM.
OBJ_NOTIF-OBJTYPE = 'BUS2038'.
OBJ_ATTACH-OBJKEY = LS_DOCINFO-DOC_ID.
OBJ_ATTACH-OBJTYPE = 'MESSAGE'.
CALL FUNCTION 'BINARY_RELATION_CREATE'
EXPORTING
OBJ_ROLEA = OBJ_NOTIF
OBJ_ROLEB = OBJ_ATTACH
RELATIONTYPE = 'ATTA'.
" COMMIT
COMMIT WORK.
Is is necessary to open the contenct as hex?
You probably just want to read / write on a file. Try open OPEN DATASET
https://help.sap.com/doc/abapdocu_752_index_htm/7.52/en-US/abapset_dataset.htm

r mongolite - date query

Question
Using the mongolite package in R, how do you query a database for a given date?
Example Data
Consider a test collection with two entries
library(mongolite)
## create dummy data
df <- data.frame(id = c(1,2),
dte = as.POSIXct(c("2015-01-01","2015-01-02")))
> df
id dte
1 1 2015-01-01
2 2 2015-01-02
## insert into database
mong <- mongo(collection = "test", db = "test", url = "mongodb://localhost")
mong$insert(df)
Mongo shell query
To find the entries after a given date I would use
db.test.find({"dte" : {"$gt" : new ISODate("2015-01-01")}})
How can I reproduce this query in R using mongolite?
R attempts
So far I have tried
qry <- paste0('{"dte" : {"$gt" : new ISODate("2015-01-01")}}')
mong$find(qry)
Error: Invalid JSON object: {"dte" : {"$gt" : new ISODate("2015-01-01")}}
qry <- paste0('{"dte" : {"$gt" : "2015-01-01"}}')
mong$find(qry)
Imported 0 records. Simplifying into dataframe...
data frame with 0 columns and 0 rows
qry <- paste0('{"dte" : {"gt" : ', as.POSIXct("2015-01-01"), '}}')
mong$find(qry)
Error: Invalid JSON object: {"dte" : {"gt" : 2015-01-01}}
qry <- paste0('{"dte" : {"gt" : new ISODate("', as.POSIXct("2015-01-01"), '")}}')
mong$find(qry)
Error: Invalid JSON object: {"dte" : {"gt" : new ISODate("2015-01-01")}}
#user2754799 has the correct method, but I've made a couple of small changes so that it answers my question. If they want to edit their answer with this solution I'll accept it.
d <- as.integer(as.POSIXct(strptime("2015-01-01","%Y-%m-%d"))) * 1000
## or more concisely
## d <- as.integer(as.POSIXct("2015-01-01")) * 1000
data <- mong$find(paste0('{"dte":{"$gt": { "$date" : { "$numberLong" : "', d, '" } } } }'))
as this question keeps showing up at the top of my google results when i forget AGAIN how to query dates in mongolite and am too lazy to go find the documentation:
the above Mongodb shell query,
db.test.find({"dte" : {"$gt" : new ISODate("2015-01-01")}})
now translates to
mong$find('{"dte":{"$gt":{"$date":"2015-01-01T00:00:00Z"}}}')
optionally, you can add millis:
mong$find('{"dte":{"$gt":{"$date":"2015-01-01T00:00:00.000Z"}}}')
if you use the wrong datetime format, you get a helpful error message pointing you to the correct format: use ISO8601 format yyyy-mm-ddThh:mm plus timezone, either "Z" or like "+0500"
of course, this is also documented in the mongolite manual
try mattjmorris's answer from github
library(GetoptLong)
datemillis <- as.integer(as.POSIXct("2015-01-01")) * 1000
data <- data_collection$find(qq('{"createdAt":{"$gt": { "$date" : { "$numberLong" : "#{datemillis}" } } } }'))
reference: https://github.com/jeroenooms/mongolite/issues/5#issuecomment-160996514
Prior converting your date by multiplying it with 1000, do this: options(scipen=1000), as the lack of this workaround will affect certain dates.
This is explained here:

IndexError: list index out of range, scores.append( (fields[0], fields[1]))

I'm trying to read a file and put contents in a list. I have done this mnay times before and it has worked but this time it throws back the error "list index out of range".
the code is:
with open("File.txt") as f:
scores = []
for line in f:
fields = line.split()
scores.append( (fields[0], fields[1]))
print(scores)
The text file is in the format;
Alpha:[0, 1]
Bravo:[0, 0]
Charlie:[60, 8, 901]
Foxtrot:[0]
I cant see why it is giving me this problem. Is it because I have more than one value for each item? Or is it the fact that I have a colon in my text file?
How can I get around this problem?
Thanks
If I understand you well this code will print you desired result:
import re
with open("File.txt") as f:
# Let's make dictionary for scores {name:scores}.
scores = {}
# Define regular expressin to parse team name and team scores from line.
patternScore = '\[([^\]]+)\]'
patternName = '(.*):'
for line in f:
# Find value for team name and its scores.
fields = re.search(patternScore, line).groups()[0].split(', ')
name = re.search(patternName, line).groups()[0]
# Update dictionary with new value.
scores[name] = fields
# Print output first goes first element of keyValue in dict then goes keyName
for key in scores:
print (scores[key][0] + ':' + key)
You will recieve following output:
60:Charlie
0:Alpha
0:Bravo
0:Foxtrot

Resources