Get next token type in Ace Editor - ace-editor

With the session you are able to get a token using:
token = session.getTokenAt(row, column);
token.type; // text.xml
Is there a way to get the next token type?
token = session.getTokenAt(row, column);
token.type; // text.xml
token = session.getNextToken(token);
token.type; // meta.tag.punctuation.end-tag-open.xml
I have a value that has a data URI string and I would like to skip to the next token.
Example XML:
<data>
abcdef...
abcdef...
...5000 more rows...
</data>
Example XML attribute:
<data src="abcdef...5000 characters..." />

use token iterator
var TokenIterator = require("ace/token_iterator").TokenIterator;
var stream = new TokenIterator(session, row, column);
next = stream.stepForward()
https://github.com/ajaxorg/ace/blob/v1.2.8/lib/ace/mode/folding/latex.js#L87

Related

XmlDocument - xpath returns nothing

I'm trying to read this science.org feed: https://www.science.org/rss/news_current.xml
with this simple code:
using var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = httpClient.Send(request);
var content = await response.Content.ReadAsStringAsync();
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(content);
var items = xmlDoc.DocumentElement?.SelectNodes("//item");
if (items != null)
{
Console.WriteLine($"{url}: items={items.Count}");
}
but I get 0 items...
(the 'content' variable is good and contains the right xml data)
It works for other RSS feeds.
any idea of what I'm doing wrong?
Note that the root element includes this default namespace declaration: xmlns="http://purl.org/rss/1.0/", which means that the names of elements within the document are qualified by that namespace URI, unless they have an explicit namespace prefix. Your item elements have no prefix, which means they do belong to that RSS namespace.
So instead of querying for elements named item, you will need to include a namespace prefix in your query, e.g. //rss:item, and of course to allow that prefix to make sense to the SelectNodes method, you'll need to bind the rss prefix to the namespace URI http://purl.org/rss/1.0/. See the documentation for SelectNodes for information about how to handle the namespace.
You can also use XPath 2 and do e.g.
using System.Xml;
using Wmhelp.XPath2;
var doc = new XmlDocument(new NameTable());
doc.Load(#"https://www.science.org/rss/news_current.xml");
var xmlNamespaceMgr = new XmlNamespaceManager(doc.NameTable);
xmlNamespaceMgr.AddNamespace("", "http://purl.org/rss/1.0/");
var items = doc.XPath2SelectNodes("//item", xmlNamespaceMgr);
Console.WriteLine(items.Count);
by using the NuGet package https://www.nuget.org/packages/XPath2.

Unable to extract a value from json and use it in subsequent request

My test receives the following json in response.
{"result":"success","additional-info":"{\"q-list\":[{\"tag\":\"un2-new tag2-empty\",\"description\":\"some description2\",\"q-id\":\"5c86fb8a-d9ce-4978-be4c-2c4b547c7868\",\"creation-year\":2020,\"creation-month\":11,\"creation-hour\":8,\"creation-minute\":48}],\"pagination-info\":{\"page-state\":\"004400100038000800000000000000080800000000000000302435633836666238612d643963652d343937382d626534632d326334623534376337383638f07ffffffef07ffffffe9fde9512dc65b09db4b903cca66a71aa0004\",\"partition-info\":{\"year\":2020,\"month\":11}}}"}
I want to extract q-id from the response and the use it in next request. I have created the following extractor.
and am using it as follows:
But I see that the value is not getting extracted.
What am I doing wrong?
Happy to accept other answers. I was able to solve the issue by using beanshell script. However, I still don't know why extracting value from Regular Expression Extractor didn't work.
Beanshell script
import com.eclipsesource.json.*;
//prev.setSuccessful(false);
try {
String jsonString = prev.getResponseDataAsString(); //response as string
log.info("received json string: "+jsonString);
JsonObject responseAsJsonObject = JsonObject.readFrom(jsonString); //convert response string as json
log.info("converted to object: "+responseAsJsonObject);
String additionalInfoString = responseAsJsonObject.get("additional-info").asString(); //get additional info string from json object
log.info("additional info as string: "+additionalInfoString);
JsonObject additionalInfoJsonObject = JsonObject.readFrom(additionalInfoString); //convert additional info string to json
log.info("additional info as object: "+additionalInfoJsonObject);
JsonArray questionListObject = additionalInfoJsonObject.get("questions-list").asArray(); //get questions list array
log.info("questions list: "+questionListObject );
JsonObject firstQuestionFromList = questionListObject.get(0).asObject(); //get 1st question
log.info("first question: "+firstQuestionFromList);
String questionID = firstQuestionFromList.get("question-id").asString();
log.info("question id of 1st question "+questionID);
vars.put("questionIDFromBeanShell",questionID); //use this in next request
// prev.setSuccessful(true);
} catch (Exception e){
log.info("error in processing beanshell script: ", e);
prev.setSuccessful(false);
}

NSDictionary to Json in Xamarin.iOS

I am trying to convert the NSDictionary into Json using NSJsonSerialization.Serialize. But i am not getting expected output
Code in Xamarin.iOS
var dictionary = new NSDictionary(
new NSString("userName"), new NSString("450012"),
new NSString("password"), new NSString("Abc134"),
new NSString("companyId"), new NSString("CM1")
);
request.Body = NSJsonSerialization.Serialize(dictionary, 0, out error);
the problem is that value of dictionary variable is showing
{{password":Abc134,companyId:CM1,userName:450012}}
instead of
{password:Abc134,companyId:CM1,userName:450012}
it is adding one curly braces at the front and back
is there any way to generate proper json string for user input values
There's nothing wrong with your json. If you print it in the console you will see that the value being printed is the value you expect.
{"password":"Abc134","companyId":"CM1","userName":"450012"}
Give it a try with:
Console.WriteLine($"{json}");
If you really, really want to get rid of of that "extra" curly braces just convert the result into string.
var jsonString = json.ToString();
The above should do the work.
I would just suggest you changing your method to this:
var json2 = NSJsonSerialization.Serialize(dictionary, NSJsonWritingOptions.PrettyPrinted, out error);
Using the PrettyPrinted option.
Hope this helps.-
Yes, you can try to create a custom object to serialize. Create a simple plain object to hold the data you want.
User user = new User() {
UserName = "JohnDoe",
Password = "xxx",
CompanyId = 01
};
request.Body = NSJsonSerialization.Serialize(user, 0, out error);
Then serialize it and you will see the proper json well formed.

How can use json data bind in datatable and grivdview in mvc

I am parsing JSON Data in custom gridview and I get the following error:
I am using the Newtonsoft.Json.NET dll.
Additional information: Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
I am using this code
var result = _profitGenDiagnosticsService.GetSQLQueryResult(profitGenQueryEditorModel.SqlQuery);
var o = JObject.Parse(result);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(o.ToString());
profitGenQueryEditorModel.SqlQueryResult = dt;
return PartialView("_ProfitGenQueryResult", profitGenQueryEditorModel);

Add row to Google Spreadhseet via API

I am building a Chrome extension which should write new rows into a Google Spreadsheet. I manage to read the sheet content but am not able to write an additional row. Currently my error is "400 (Bad Request)". Any idea what I am doing wrong here?
I have gone through the Google Sheets API documentation and other posted questions here but was not able to find any solution.
Here is the code which I use to GET the sheet content (this works):
function loadSpreadsheet(token) {
var y = new XMLHttpRequest();
y.open('GET', 'https://spreadsheets.google.com/feeds/list/spreadsheet_id/default/private/values?access_token=' + token);
y.onload = function() {
console.log(y.response);
};
y.send();
}
And this is the code I try to POST a new row (gives me "400 - Bad Request"):
function appendRow(token){
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">',//'--END_OF_PART\r\n',
'<gsx:name>',foo,'</gsx:name>',//'--END_OF_PART\r\n',
'</entry>'].join('');
return atom;
};
var params = {
'body': constructAtomXML("foo")
};
url = 'https://spreadsheets.google.com/feeds/list/spreadsheet_id/default/private/full?alt=json&access_token=' + token;
var z = new XMLHttpRequest();
z.open("POST", url, true);
z.setRequestHeader("Content-type", "application/atom+xml");
z.setRequestHeader("GData-Version", "3.0");
z.setRequestHeader("Authorization", 'Bearer '+ token);
z.onreadystatechange = function() {//Call a function when the state changes.
if(z.readyState == 4 && z.status == 200) {
alert(z.responseText);
}
}
z.send(params);
}
Note: spreadsheet_id is a placeholder for my actual sheet ID.
Follow the protocol and to make it work.
Assume spreadsheet ID is '1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8'
First use the spreadsheet ID to retrieve list of worksheets:
GET https://spreadsheets.google.com/feeds/worksheets/1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8/private/full?alt=json
There you can read list of worksheets and their IDs. Let use the first worksheet from the example. You'll find its id in feed > entry[0] > link array. Look for "rel" equal 'http://schemas.google.com/spreadsheets/2006#listfeed'.
In my example the URL for this worksheet is (Worksheet URL): https://spreadsheets.google.com/feeds/list/1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8/ofs6ake/private/full
Now, to read its content use:
GET [Worksheet URL]?alt=json
Besides list-row feed, you'll also find a "post" URL which should be used to alter spreadsheet using list-row feed. It's the one where "rel" equals "http://schemas.google.com/g/2005#post" under feed > link.
It happens that it is the same URL as for GET request. In my case: https://spreadsheets.google.com/feeds/list/1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8/ofs6ake/private/full. Just be sure to not append alt=json.
Now, to insert a new row using list-row feed you need to send POST with payload which is specified in docs. You need to send a column name prefixed with "gsx:" as a tag name. However it may not be the same as the column name in the spreadsheet. You need to remove any white-spaces, make it all lowercase and without any national characters. So to make your example work you need to replace <gsx:Name> with <gsx:name>.
Before the change you probably had the following payload message:
Blank rows cannot be written; use delete instead.
It's because the API didn't understand what the "Name" is and it just dropped this part of entry from the request. Without it there were no more items and the row was blank.
Alternatively you can read column names from the GET response. Keys from objects in feed > entry array that begins with gsk$ are columns definitions (everything after $ sign is a column name).
=================================================================
EDIT
To answer a question from the comments.
I've changed two things from your example:
function appendRow(token){
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">',
'<gsx:name>',foo,'</gsx:name>',
'</entry>'].join('');
return atom;
};
/*
var params = {
'body': constructAtomXML("foo")
};
*/
var params = constructAtomXML("foo");
url = 'https://spreadsheets.google.com/feeds/list/'+spredsheetId+'/default/private/full?alt=json&access_token=' + token;
var z = new XMLHttpRequest();
z.open("POST", url, true);
z.setRequestHeader("Content-type", "application/atom+xml");
z.setRequestHeader("GData-Version", "3.0");
z.setRequestHeader("Authorization", 'Bearer '+ token);
z.onreadystatechange = function() {//Call a function when the state changes.
if(z.readyState == 4 && z.status == 200) {
alert(z.responseText);
}
}
z.send(params);
}
1) <gsx:Name> to <gsx:name>. Without it you'll receive an error.
2) params object should be a String! Not an object with some 'body' key. You just need to pass a value you want to send to the server.

Resources