need to remove the array in json - node.js

var meds= [
{
"sno": 1,
"brandName": "EPIDOSIN 8 MG INJECTION",
"companyName": "TTK Healthcare Ltd",
"price": "Rs. 17",
"packagingOfProduct": "1 vial(s) (1 ML injection each)"
}
]

As per your comment above you want 17 from Rs. 17 from your array.
var value = meds["price"].split(""); // split Rs. 17 with space
var price = value[1]; // at index 1 you will get value 17
now you can do whatever you want to do with the price
if you want to set it back to the array, do this
meds["price"] = price;
Hope this will help!

Related

Tabulator - Sorting groups by group calcResults

Is it possible to order results of grouped items by the calculation results for each group? It seems that when I set the initialSort (or when I don't)it sorts by the order of the items within each group, rather than by the total calculation of each group.
For example, if I have data that looks something like this:
[
{id:1, company:"company 1", quantity:"10"},
{id:2, company:"company 1", quantity:"10"},
{id:3, company:"company 1", quantity:"10"},
{id:4, company:"company 2", quantity:"20"},
{id:5, company:"company 2", quantity:"1"},
{id:6, company:"company 2", quantity:"1"},
{id:7, company:"company 3", quantity:"9"},
{id:8, company:"company 3", quantity:"9"},
{id:9, company:"company 3", quantity:"9"},
]
I would end up with groups ordered:
Company 2: 22 // Highest qty 20
company 1: 30 // Highest qty 10
company 3: 27 // Highest qty 9
What I am trying to get is:
company 1: 30
company 3: 27
Company 2: 22
I can see the calculation results, but I'm not sure how to resort the groups, assuming it's possible. If anyone can point me in the right direction I will be quite grateful.
Rows can only be sorted according to a field stored in the row data.
Rows are sorted individually and then grouped, with groups appearing in the order of the sorted data.
In order to sort your table in this way, you would need to analyse your row data first before ingesting it into the table, and then set a field on each row with the desired order for the group that contains it.
The other option is to manually specify the groups you want using the groupValues option, with this approach you specify the exact groups you want and the order they should appear:
groupValues:[["male", "female", "smizmar"]]
Thanks Oli for pointing me in the direction of 'groupValues'. I ended up writing a function that uses the calcResults to get the sort order I want and then push them into groupValues to get the ordering I'm looking for.
const sortByGroupCalc = ( thisTable, thisSortField, thisSortDirection ) => {
// Temp arrays
let tempCalcArray = [];
let tempSortArray = [];
// Get calculation results
const calcResults = thisTable.getCalcResults();
// Populate Array with key:value pairs from the caculation results
for( const [key, value] of Object.entries(calcResults)) {
tempCalcArray.push([key, value.top[thisSortField]])
};
// Sort the object by value and direction and then create an array of the keys
tempCalcArray
.sort(function(a, b) {
if( thisSortDirection === 'asc' ) {
return a[1] - b[1];
} else {
return b[1] - a[1];
}})
.map(
x => tempSortArray.push(x[0])
);
// Set group order according to sort order
thisTable.setGroupValues([tempSortArray]);
}
I'm calling it in the dataSorted function. It's not perfect for all occasions, I imagine. But it seems to do what I need.
Thanks again.

Google Slides API update table background color

basically I have table (8 rows x 3 columns) within the Google slides presentation, that I want to change background color to via the API.
First item of my list of rgb color values:
cons_data_lst[0][1][-1]
>>> [0.5882353, 0.7764706, 0.4862745]
My function to produce a request body:
def update_table_cell_colors(color_list):
req = [{
'updateTableCellProperties':{
'objectId': 'obj_id',
'tableRange': {
'location': {
'rowIndex': 1,
'columnIndex': 2,
},
'rowSpan': 1,
'columnSpan': 1,
},
'tableCellProperties':{
'tableCellBackgrounFill':{
'solidFill':{
'color':{
'rgbColor':{
'red': color_list[0],
'green': color_list[1],
'blue': color_list[2],
}
}
}}
}}} ]
return req
When I send batch update to presentation I receive the following error:
HttpError: https://slides.googleapis.com/v1/presentations/1dzxYYPuqTM3VhwaR93Ep2jj_9Y2NCkSBsVBnmN6lcOs:batchUpdate?alt=json
returned "Invalid JSON payload received. Unknown name
"table_cell_backgroun_fill" at
'requests[0].update_table_cell_properties.table_cell_properties':
Cannot find field.". Details: "[{'#type':
'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations':
[{'field':
'requests[0].update_table_cell_properties.table_cell_properties',
'description': 'Invalid JSON payload received. Unknown name
"table_cell_backgroun_fill" at
\'requests[0].update_table_cell_properties.table_cell_properties\':
Cannot find field.'}]}]">
Given a list of different rgb color values, how can I create a request body to update all columns (1 to 2) row (there are 8) text background color ?
Thank you.
How about this answer?
A1:
In this section, it explains about the reason of the error.
Modification points:
From the error message of Unknown name "table_cell_backgroun_fill" at 'requests[0].update_table_cell_properties.table_cell_properties', it is found that the property name of tableCellBackgrounFill is a spelling mistake. Please modify to tableCellBackgroundFill.
At updateTableCellProperties, the property of fields is required to be used. In your case, how about adding "fields": "tableCellBackgroundFill"? You can also use 'fields': '*'.
When these modifications are reflected to your request body, it becomes as follows.
Modified request body:
req = [
{
'updateTableCellProperties': {
'objectId': 'obj_id',
'tableRange': {
'location': {
'rowIndex': 1,
'columnIndex': 2
},
'rowSpan': 1,
'columnSpan': 1
},
'tableCellProperties': {
'tableCellBackgroundFill': { # Modified
'solidFill': {
'color': {
'rgbColor': {
'red': color_list[0],
'green': color_list[1],
'blue': color_list[2],
}
}
}
}
},
'fields': 'tableCellBackgroundFill' # Added
}
}
]
Before you use this script, please check the variables of color_list and 'obj_id',
A2:
In this section, it explains about the question 2 of Given a list of different rgb color values, how can I create a request body to update all columns (1 to 2) row (there are 8) text background color ?.
In your question, you say I have table (8 rows x 3 columns) at the top of your question. But at Given a list of different rgb color values, how can I create a request body to update all columns (1 to 2) row (there are 8) text background color ?, you say columns (1 to 2). I'm confused about this. So I would like to suppose as follows.
Your table has 8 rows and 2 columns.
You want to change the background color of all columns and rows with one color.
The sample request body is as follows.
Sample request body:
req = [
{
"updateTableCellProperties":
{
"objectId": "obj_id",
"tableRange":
{
"location":
{
"rowIndex": 0,
"columnIndex": 0
},
"rowSpan": 8,
"columnSpan": 2
},
"tableCellProperties":
{
"tableCellBackgroundFill":
{
"solidFill":
{
"color":
{
"rgbColor":
{
"red": color_list[0],
"green": color_list[1],
"blue": color_list[2]
}
}
}
}
},
"fields": "tableCellBackgroundFill"
}
}
]
rowIndex and columnIndex are the start cell.
"rowIndex": 0 and "columnIndex": 0 means the cell "A1".
rowSpan and columnSpan are the number of rows and columns.
"rowSpan": 8 and "columnSpan": 2 means 8 rows and 2 columns. By this, the background colors of cells "A1:B8" are changed.
If your table is 8 rows and 3 columns, and you want to change all cells, please set them as follows.
"rowIndex": 0, "columnIndex": 0 and "rowSpan": 8, "columnSpan": 3
If you want to change the special background color every cell, it is required to create the array of request body for each cell. Please be careful this.
Note:
This answer supposes that you have already been able to put and get values for Google Slides using Slides API.
References:
UpdateTableCellPropertiesRequest
TableCellProperties
If I misunderstood your question and this didn't resolve your issue, I apologize.

Updating excel with values from rest assured json response using apache-poi

I am a newbie with Rest Assured and seek help. I have written code to read values from an excel sheet and pass them as a path params in my Rest Assured tests. And this works as expected. However after I get the json response from the post request I make, I want to update the same excel with values from the response.
The excel has columns called Train number, date of journey and various class codes as other columns like first class code, business class code, standard class code that should show the availabality in them and so on something like this:
Initially:
ServiceName | Date | A0 | A1 | A2 | ...... 45 columns
9008 |2019-07-28| 0 | 0 | 0 |....... 45 columns
After test:
ServiceName | Date | A0 | A1 | A2 | ...... 45 columns
9008 |2019-07-28| 45 | 23 | 64 |....... 45 columns
I have followed apache-poi documentation to read values from excel with supporting methods to read rows, columns and getting cell value. However could not find anything that suggests how to update the same excel with the values from Json response.
These are the test and data provider methods I have come up for reading values from excel
#DataProvider(name="logicalAvProvider")
String [][] getLogicalAv() throws IOException
{
String path = "C:\\Misc\\LogAv.xlsx";
int rownum = XLUtils.getRowCount(path, "LogAv");
int colcount=XLUtils.getCellCount(path, "LogAv",rownum );
String LogAvData[][] = new String[rownum-1][colcount];
for (int i=1; i <rownum; i++ ) {
for (int j=0; j<colcount; j++) {
LogAvData[i-1][j] = XLUtils.getCellData(path, "LogAv", i, j);
//System.out.println("Data is " +LogAvData[i-1][j]);
}
}
return(LogAvData);
}
#Test(dataProvider="logicalAvProvider")
public void LogicalAvailablity(String ServiceName, String Date) throws IOException {
Response res=
given()
//.log().all()
.spec(reqSpec)
.pathParams("service_name", ServiceName, "travel_date", Date)
.when()
.get(EndPoints.LOGICAL_AVAILABILTY)
.then()
.spec(resSpec)
.extract().response();
//.log().body();
}
This is the sort of response we see after doing the post request. I need the number available to be updated under the respective columns in the excel.
[
{
"od_pair": "7015400:8727100",
"buckets": [
{
"bucket": "C00",
"original": 2,
"available": 2
},
{
"bucket": "A01",
"original": 76,
"available": 0
},
{
"bucket": "B01",
"original": 672,
"available": 477
},
{
"bucket": "B03",
"original": 578,
"available": 383
}
]
}
]
An advice on the approach to update the excel sheet with the values. I am not expecting anyone to give me the exact solution of my problem but any advice on the approach or any reference that I can refer to achieve this would be highly appreciated.
Extract the required data from response and then write it to excel sheet.
Using restAssured/JsonPath you can extract data from API response.
Using apachePOI you should be able to write into Excel, refer below link for more details:
https://www.codejava.net/coding/how-to-write-excel-files-in-java-using-apache-poi
Let us know if you run into any issues

Which method ideal to query Cloudant for latest doc having same value for a field and again filter on that result?

I am very new to NoSQL. My usecase is related to this.... Many users post messages and we store it in cloudant as different documents
{
id:random,
userid:xxx,
timestamp: 1449216912282,
msg: "Hi..."
}
I want to find out users who have not posted anything for last 5 days - Additionally I want to know if they have posted anything between last five and 10 days. If they have, then send a reminder mail to user to be active.
Which option would be better - views, search, cloudant query? Assume we will be having 1000s of posts per hour
I though of creating view - map(userid,timestamp) reduce as _stats and get max timestamp of each user. Then iterating through this list - we get users who did not post in last 5 days.
Other option was to use search index, get all userids between required timestamps. Compare both lists in application.
Is there any way to do it in a single query without overloading the application? Would Changing data format or creating appropriate index or view help?
If your data looked like this:
{
"_id": "abcdefghijklmon1234",
"userid" : "user1",
"timestamp": 1449739485035,
"msg": "Hi"
}
You could create a MapReduce view that created an index with a key consisting of [ 2015, 50, "user1" ], where "2015" is the year, "50" is the week number and "user1" is the document's userid. This can be achieved with a Map function like this:
function (doc) {
var getWeek = function(t) {
var date = new Date(t);
date.setHours(0, 0, 0, 0);
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
var week1 = new Date(date.getFullYear(), 0, 4);
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
};
if (typeof doc.timestamp == "number") {
var d = new Date(doc.timestamp);
var weeknum = getWeek(d.getTime());
var year = d.getFullYear();
emit( [ year, weeknum, doc.userid], null);
}
}
with a reduce of "_count". This allows queries such as ?startkey=[2015,49]&endkey=[2015,50]&group_level=3 to get a list of users who DID post last week. The list of users who didn't are the users who don't appear in the above list.
This isn't a solution to your problem in terms of "in the last 5 days", but uses week numbers instead.

ArangoDB - how find element in collection by substring of element of array?

There is a collection with this structure:
{
   "user": 1,
   "timestamp": 216354113151,
   "message": "asddsaasddsaa",
   "data": [
     "name = Jack & hash = s5w464t35w145df13s5df4sdg & id = 2"
     "name = Mansonack & hash = xga5fd7h68745v46ed2 & id = 18"
   ]
}
I need to find an element of this collection, in the key data has a value that contains a string that contains the substring xga5fd7h68745v46ed2
Can I write this query? How will it look like?
You can loop over the array items like over any other list:
FOR d IN collection_name
FILTER IS_LIST(d.data)
FOR data IN d.data
FILTER CONTAINS(data, "xga5fd7h68745v46ed2")
RETURN d
If your data array has multiple occurances of substring you are searching for and want to return only the unique documents that contains search value, then use query like this:
// what you are looking for in string
LET searchValue = 'xga5fd7h68745v46ed2'
// go through items of your collection
FOR item IN collection_name
// store result of subquery in temporary variable
LET wasItemFound = FIRST((
// go through elements of your data array
FOR str IN item.data
// search for desired value within the element
FILTER CONTAINS(str, searchValue)
// we need to find only single occurance of searchValue
LIMIT 1
// return true if it was found
RETURN true
))
// give me only items which contained value you searched for
FILTER wasItemFound == true
RETURN item
Query which pluma suggested might do the job for your usecase if values you are looking for are all unique for all data array elements. If there are multiple occurances of substrings you search for within data array elements then the query will return duplicate documents. For example consider this example dataset:
[
{
"user": 1,
"data": [
"name = Jack & hash = abc & id = 2",
"name = Mansonack & hash = abcd & id = 18"
]
},
{
"user": 2,
"data": [
"name = Jack & hash = abb & id = 2",
"name = Mansonack & hash = abc & id = 18",
"name = xxx& hash = aaa & id = 18"
]
}
]
If you use this query
FOR d IN collection_name
FILTER IS_LIST(d.data)
FOR data IN d.data
FILTER CONTAINS(data, "ab")
RETURN d
It will return 4 documents even when the collection contains only 2. However the very first query in this post will return only 2. To be clear I'm not saying that pluma's solution is wrong it just depends what do you expect to be returned.

Resources