How to parse output from sse.client in Python? - python-2.7

I am new to Python and am trying to get my ahead around parsing SSE client code. I am using the SSE Client library. My code is very basic and follows the sample exactly. Here it is:
from sseclient import SSEClient
devID = "xxx"
AToken = "xxx"
sparkURL = 'https://api.spark.io/v1/devices/' + devID + '/events/?access_token=' + AToken
messages = SSEClient(sparkURL)
for msg in messages:
print(msg)
print(type(msg))
The code runs without a problem and I see some blank lines and SSE data coming through. Here is the sample output:
<class 'sseclient.Event'>
{"data":"0 days, 0:54:43","ttl":"60","published_at":"2015-04-09T22:43:52.084Z","coreid":"xxxx"}
<class 'sseclient.Event'>
<class 'sseclient.Event'>
{"data":"0 days, 0:55:3","ttl":"60","published_at":"2015-04-09T22:44:12.092Z","coreid":"xxx"}
<class 'sseclient.Event'>
The actual output above looks like a dictionary, but its type is "sseclient.Event". I am trying to figure out how to parse the output so I can pull out one of the fields and nothing I have tried has worked.
Sorry if this is basic questions, but can someone provide some simple guidance on how I would either convert the entire output to a dictionary or perhaps just pull out one of the fields?
Thank you in advance!

I figured this out. In case anyone else experiences the same problem, here is how I got it to work. The key was using msg.data and not just msg. I then converted the out using the JSON library and am good to go.
messages = SSEClient(sparkURL)
for msg in messages:
outputMsg = msg.data
if type(outputMsg) is not str:
outputJS = json.loads(outputMsg)
FilterName = "data"
#print( FilterName, outputJS[FilterName] )
print(outputJS[FilterName])

Related

How do i convert cpr's get response into a json object?

I was looking for a easy to understand library that make HTTP REST Requests in C++ and then i came across CPR. I was successfully able to get the response from the server but i find it difficult to access the returned JSON object.
API Get Request:
auto r = cpr::Get(cpr::Url{ "https://example.net/api/token" },
cpr::Parameters{ {"username", login}, {"password", password},
{"hwid", "TestChecker"}, {"obt", "1"}});
r.status_code;
r.header["application/json"];
r.text;
I tried to pass r.text into nlohmann::json j = r.text; and access the particular object i wanted like this string xx = j["token"];
As expected, it threw an error.
I'd really appreciate it if anyone could tell me how to achieve what i failed to do.
Edit : Added References
CPR : https://www.codeproject.com/Articles/1244632/Making-HTTP-REST-Request-in-Cplusplus
nlohmann/json : https://github.com/nlohmann/json
I did play around a bit with the code and finally figured it out.
Basically what i wanted to do was to convert a "JSON String" into a JSON Object.
I achieved it by using the method nlohmann::json::parse();
Json j = Json::parse(r.text);
string xx = j["token"];

How to get placeholder size in TensorFlow C++ API?

I want to use C++ to load TensorFlow model. And I want to know size of model's input, which is the placeholder in the model.
I google this problem, but I just find this link in stackoverflow :
C++ equivalent of python: tf.Graph.get_tensor_by_name() in Tensorflow?
Although I can get node, but tensorflow document don't tell me how to access the size of the node. So is there anyone know something about this?
Thank you so much!
OK,after many times attempts. I have find a workaround solution, It maybe tricky but works well.
At first, we can get the placeholder node using following code:
GraphDef mygd = graph_def.graph_def();
for (int i = 0; i < mygd.node_size(); i++)
{
if (mygd.node(i).name() == input_name)
{
auto node = mygd.node(i);
}
}
Then through the NodeDef.pd.h(tensorflow/core/framework/node_def.pb.h), we can get AttrValue through code like below:
auto attr = node.attr();
Then through the attr_value.cc(tensorflow/core/framework/attr_value.cc), we can get the shape attr value through code like below:
tensorflow::AttrValue shape = attr["shape"];
and the shape AttrValue is the structure used to store shape information. We can get the detail information through the function SummarizeAttrValue in tensorflow/core/framework/attr_value_util.h
string size_summary = SummarizeAttrValue(shape);
And then we can get the string format of shape like below:
[?,1024]

How to get Body of the email using c++ builder

I want to get the email body from my Gmail account for an email so i use this code i found it in an example for how to read emails using c++ builder pop3
the code to extract body used
TIdText *EText;
int message = SpinEdit1->Value;
MyPoP3->Retrieve(message, MyEmail);
Edit1->Text = MyEmail->Subject + " | " + MyEmail->From->Address;
Memo1->Clear();
for (int i = 0; i < MyEmail->MessageParts->Count; i++) {
Memo1->Lines->Add(MyEmail->MessageParts->Items[i]->ContentType);
EText = dynamic_cast<TIdText*>(MyEmail->MessageParts->Items[i]);
Memo1->Lines->Add(EText->Body);
}
the problem is that i got undefine symbol to TidText and what i tried is to change it from TIdText to TIdMessage, but i got that i can't convert to it.
also i tried to try this without loop or something MyEmail->Body->Text
this return empty string.
the video i got this code from it here i don't know maybe the c++ builder he use is old. now i want to know how to extract the body text from the email address.
Thanks in advance.
the problem is that i got undefine symbol to TidText
Your code is missing an #include <IdText.hpp> statement.
what i tried is to change it from TIdText to TIdMessage, but i got that i can't convert to it.
Because TIdMessage does not contain nested TIdMessage objects.
also i tried to try this without loop or something MyEmail->Body->Text this return empty string.
If your email is MIME encoded, its text is not stored in the TIdMessage::Body property, but in a nested TIdText object within the TIdMessage::MessageParts collection. You have to look at the TIdMessage::ContentType property to know what kind of structure the email contains. For instance, if the CT begins with text/, the text is in the TIdMessage::Body. But if the CT begins with multipart/, the text is somewhere in the TIdMessage::MessageParts instead.
You should read this blog article on Indy's website for an example of how emails might be structured:
HTML Messages
the video i got this code from it here i don't know maybe the c++ builder he use is old.
No, it is not.

Unparsable MOF Query When Trying to Register Event

Update 2
I accepted an answer and asked a different question elsewhere, where I am still trying to get to the bottom of this.
I don't think that one-lining this query is the answer, as I am still not getting the required results (and multi-lining queries is allowed in .mof, as shown in the URLs in comments to the answer ...
Update
I rewrote the query as a one-liner as suggested, but still got the same error! As it was still talking about lines 11-19 I knew there must be another issue. After saving a new file with the change, I reran mofcomp and it appears to have loaded, but the event which I have subscribed to simply does not work.
I really feel that there is not enough documentation on this topic and it is hard to work out how I am meant to debug this - any help on this would be much appreciated, even if this means using a different more appropriate method.
I have the following .mof file, which I would like to use to register an event on my system :
#pragma namespace("\\\\.\\root\\subscription")
instance of __EventFilter as $EventFilter
{
Name = "Event Filter Instance Name";
Query = "Select * from __InstanceCreationEvent within 1 "
"where targetInstance isa \"Cim_DirectoryContainsFile\" "
"and targetInstance.GroupComponent = \"Win32_Directory.Name=\"c:\\\\test\"\"";
QueryLanguage = "WQL";
EventNamespace = "Root\\Cimv2";
};
instance of ActiveScriptEventConsumer as $Consumer
{
Name = "TestConsumer";
ScriptingEngine = "VBScript";
ScriptText =
"Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
"Set objFile = objFSO.OpenTextFile(\"c:\\test\\Log.txt\", 8, True)\n"
"objFile.WriteLine Time & \" \" & \" File Created\"\n"
"objFile.Close\n";
// Specify any other relevant properties.
};
instance of __FilterToConsumerBinding
{
Filter = $EventFilter;
Consumer = $Consumer;
};
But whenever I run the command mfcomp myfile.mof I am getting this error:
Parsing MOF file: myfile.mof
MOF file has been successfully parsed
Storing data in the repository...
An error occurred while processing item 1 defined on lines 11 - 19 in file myfile.mof:
Error Number: 0x80041058, Facility: WMI
Description: Unparsable query.
Compiler returned error 0x80041058
This error appears to be caused by incorrect syntax in the query, but I don't understand where I have gone wrong with this - is anyone able to advise?
There are no string concatenation or line continuation characters being used in building "Query". To keep it simple, you could put the entire query on one line.

MAPI, HrQueryAllRows: Filter messages on subject

I'm pretty much new to MAPI and haven't wrote much C++ Code.
Basically I want to read all emails in the inbox and filter them based on their subject text. So far I'm using the source code provided at the microsoft msdn website which basically reads all emails from the inbox. What I want now is to not get all emails but filter them on the subject, lets say: I want all emails in my Inbox with the subject title "test".
So far I figuered out that the following line of code retrieves all the mails:
hRes = HrQueryAllRows(lpContentsTable, (LPSPropTagArray) &sptCols, &sres, NULL, 0, &pRows);
The parameter &sres is from the type SRestriction.
I tried to implement a filter on 'test' in the subject:
sres.rt = RES_CONTENT;
sres.res.resContent.ulFuzzyLevel = FL_FULLSTRING;
sres.res.resContent.ulPropTag = PR_SUBJECT;
sres.res.resContent.lpProp = &SvcProps;
SvcProps.ulPropTag = PR_SUBJECT;
SvcProps.Value.lpszA = "test";
ScvProps is from the type SPropValue.
If i execute the application then I get 0 lines returned. If I change the String test to an empty String then I get all emails.
I'm assuming i'm using the "filter" option wrong, any ideas?
Edit: When I change the FuzzyLevel to:
sres.res.resContent.ulFuzzyLevel = FL_SUBSTRING;
then I can look for subjects that contain a single character but as soon as I add a second character I get 0 rows as result. I'm pretty sure this is just some c++ stuff that I don't understand that causes all this problems ...
I figured the problem out.
Replacing
sres.res.resContent.ulFuzzyLevel = FL_FULLSTRING;
sres.res.resContent.ulPropTag = PR_SUBJECT;
SvcProps.ulPropTag = PR_SUBJECT;
with
sres.res.resContent.ulFuzzyLevel = FL_SUBSTRING;
sres.res.resContent.ulPropTag = PR_SUBJECT_A;
SvcProps.ulPropTag = PR_SUBJECT_A;
fixed the problem.