Form a JSON request using previous response value in JMETER - jmeter

On my request I am getting the following response,
{
"studyDTO": {
"studyId": 191,
"studyCode": "test_ispptest2"
},
"sites": [],
"subjects": [],
"visits": [],
"sftpLocations": [],
"dicomLocations": [],
"fileSystemLocations": [],
"rawFileSystemLocations": [],
"states": null,
"modalities": [
{
"studyId": 191,
"submitValue": "ct",
"displayValue": "Conventional CT",
"orderOfDisplay": 30
},
{
"studyId": 191,
"submitValue": "multi_slice_spiral_ct",
"displayValue": "Multi-Slice Spiral CT",
"orderOfDisplay": 50
},
{
"studyId": 191,
"submitValue": "dxa",
"displayValue": "DXA",
"orderOfDisplay": 60
},
{
"studyId": 191,
"submitValue": "mri",
"displayValue": "MRI",
"orderOfDisplay": 100
},
{
"studyId": 191,
"submitValue": "unknown",
"displayValue": "Unknown",
"orderOfDisplay": 240
}
],
"examDates": [],
"series": null,
"transferType": null,
"customFolder": false,
"customFile": false,
"folderStructure": null,
"fileStructure": null,
"allSites": true,
"allSubjects": true,
"allVisits": true,
"allStates": false,
"allExamDates": true,
"allModalities": false,
"allSeries": false,
"softEditOverride": false,
"includePS": false,
"includeSR": false,
"includeRTStruct": false,
"dicomTemplate": null,
"errorMessage": null,
"successMessage": null
}
in the response I received 5 modality value this can be more and in my next request body in the JSON type I want to add all the modalities, how I can do this using JSR223 Post-Processer,
Request Sample:
{
"studyDTO": {
"studyId": 191,
"studyCode": "test_ispptest2"
},
"allVisits": true,
"modalities": [
{
"studyId": 191,
"submitValue": "ct",
"displayValue": "Conventional CT",
"orderOfDisplay": 30
},
{
"studyId": 191,
"submitValue": "multi_slice_spiral_ct",
"displayValue": "Multi-Slice Spiral CT",
"orderOfDisplay": 50
},
{
"studyId": 191,
"submitValue": "dxa",
"displayValue": "DXA",
"orderOfDisplay": 60
},
{
"studyId": 191,
"submitValue": "mri",
"displayValue": "MRI",
"orderOfDisplay": 100
},
{
"studyId": 191,
"submitValue": "unknown",
"displayValue": "Unknown",
"orderOfDisplay": 240
}
],
"includePS": null
}
I have developed so far, but don't have a clue to form the request JSON
import groovy.json.JsonSlurper
def jsonString = prev.getResponseDataAsString();
def jsonConvert = new JsonSlurper();
def object = jsonConvert.parseText(jsonString);
def modalityS = object.modalities.size().toString();
def modalitySize = modalityS?.isInteger() ? modalityS.toInteger() : null
for (int i = 0; i < modalitySize ; i++) {
def modalityOrderOfDisplay = object.modalities[i].orderOfDisplay;
def modalSubmitValue = object.modalities[i].submitValue;
def modalDisplayValue = object.modalities[i].displayValue;
log.info('----------------------->'+modalityOrderOfDisplay);
log.info('----------------------->'+modalSubmitValue);
log.info('----------------------->'+modalDisplayValue);
}

Take a look at JsonBuilder class
Something like:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def request = [:]
request.put('studyDTO', response.studyDTO)
request.put('allVisits', response.allVisits)
request.put('modalities', response.modalities)
request.put('includePS', null)
vars.put('request', new groovy.json.JsonBuilder(request).toPrettyString())
should do the trick for you.
You will be able to refer the generated request body as ${request} where required.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

Related

How to return consistent data types in laravel pagination

I have a function that returns staff and there associated attributes as below
foreach ($merchant_user_ac->staffs->sortByDesc('id') as $staff) {
$wage = Staff::find($staff->id)->totalCommissions($start_date, $end_date);
$payments = StaffPayment::where('merchant_id', AH::cMiD())
->where('user_id', $staff->id)
->when(!empty($start_date) && !empty($end_date), function ($q) use (
$start_date,
$end_date
) {
$q->whereBetween(\DB::raw('date(payment_date)'), [
$start_date,
$end_date,
]);
})
->sum('amount');
$balance_owed = $wage - $payments;
$transactions->add([
'id' => $staff->id,
'name' => $staff->name,
'profilephoto' => $staff->profilephoto,
'wage' => $wage,
'payments' => $payments,
'salary' => $staff->salary,
'rent' => $staff->rent,
'balance_owed' => $balance_owed + $staff->salary - $staff->rent,
]);
}
$merchant_staffs = collect(json_decode(json_encode($transactions), false));
$merchant_staffs = $merchant_staffs->paginate(10);
return response()->json($merchant_staffs);
In the results, the first page is OK but the subsequent pages are having a different data type from the first page and displaying the data becomes an issue.
The data key has different data types.
I have tried paginating before the foreach loop but the response did not have the pagination links.
I have tried adding ->toArray() method when collecting the data but has the same issue of different types.
How can I return the same data in all pagination links?
The data returned is as below
{
"current_page": 1,
"data": [
{
"id": 532,
"name": "George2",
"profilephoto": "photos/GwSIKoIXUk1GdL7boD7Ht9mSp1loxM1nGcZ5l5Gd.jpg",
"wage": 0,
"payments": 10000,
"salary": "90000.00",
"rent": "1000.00",
"balance_owed": 79000
},
{
"id": 528,
"name": "david",
"profilephoto": null,
"wage": 100,
"payments": 0,
"salary": "67000.00",
"rent": "67000.00",
"balance_owed": 100
},
{
"id": 524,
"name": "Naggie",
"profilephoto": null,
"wage": 0,
"payments": 0,
"salary": null,
"rent": null,
"balance_owed": 0
},
{
"id": 503,
"name": "Khaki ",
"profilephoto": null,
"wage": 0,
"payments": 0,
"salary": null,
"rent": null,
"balance_owed": 0
},
{
"id": 502,
"name": "Susan",
"profilephoto": null,
"wage": 0,
"payments": 0,
"salary": null,
"rent": null,
"balance_owed": 0
},
{
"id": 476,
"name": "Maggie",
"profilephoto": null,
"wage": 0,
"payments": 17000,
"salary": null,
"rent": "15000.00",
"balance_owed": -32000
},
{
"id": 475,
"name": "Aggy",
"profilephoto": null,
"wage": 0,
"payments": 15000,
"salary": "15000.00",
"rent": null,
"balance_owed": 0
},
{
"id": 465,
"name": "Rhoda",
"profilephoto": null,
"wage": 0,
"payments": 0,
"salary": null,
"rent": null,
"balance_owed": 0
},
{
"id": 464,
"name": "Very New Staff",
"profilephoto": null,
"wage": 500,
"payments": 0,
"salary": "10000.00",
"rent": null,
"balance_owed": 10500
},
{
"id": 422,
"name": "jane",
"profilephoto": null,
"wage": 0,
"payments": 0,
"salary": "15000.00",
"rent": null,
"balance_owed": 15000
}
],
"first_page_url": "http://127.0.0.1:8000/api/v1/staff/list?page=1",
"from": 1,
"last_page": 3,
"last_page_url": "http://127.0.0.1:8000/api/v1/staff/list?page=3",
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
{
"url": "http://127.0.0.1:8000/api/v1/staff/list?page=1",
"label": "1",
"active": true
},
{
"url": "http://127.0.0.1:8000/api/v1/staff/list?page=2",
"label": "2",
"active": false
},
{
"url": "http://127.0.0.1:8000/api/v1/staff/list?page=3",
"label": "3",
"active": false
},
{
"url": "http://127.0.0.1:8000/api/v1/staff/list?page=2",
"label": "Next »",
"active": false
}
],
"next_page_url": "http://127.0.0.1:8000/api/v1/staff/list?page=2",
"path": "http://127.0.0.1:8000/api/v1/staff/list",
"per_page": 10,
"prev_page_url": null,
"to": 10,
"total": 25
}
Try
$pagination = $merchant_user_ac->staffs()->latest()->paginate(10);
$data = $pagination->getCollection()->map(function ($staff) {
$wage = Staff::find($staff->id)->totalCommissions($start_date, $end_date);
$payments = StaffPayment::where('merchant_id', AH::cMiD())
->where('user_id', $staff->id)
->when(!empty($start_date) && !empty($end_date), function ($q) use (
$start_date,
$end_date
) {
$q->whereBetween(\DB::raw('date(payment_date)'), [
$start_date,
$end_date,
]);
})
->sum('amount');
$balance_owed = $wage - $payments;
return [
'id' => $staff->id,
'name' => $staff->name,
'profilephoto' => $staff->profilephoto,
'wage' => $wage,
'payments' => $payments,
'salary' => $staff->salary,
'rent' => $staff->rent,
'balance_owed' => $balance_owed + $staff->salary - $staff->rent,
];
});
return response()->json($pagination->setCollection($data));
}

Want to retrieve random value from the response

I have the following response payload and there are 4 siteId and I want to select any random siteId from it. This value of 4 can be change it will random, irrespective of it i want to select any random siteId.
Response Value
{
"studyDTO": {
"studyId": 191,
"studyCode": null
},
"sites": [
{
"studyId": 191,
"siteRecid": 1,
"siteId": "10000"
},
{
"studyId": 191,
"siteRecid": 16521,
"siteId": "11001"
},
{
"studyId": 191,
"siteRecid": 16632,
"siteId": "11011"
},
{
"studyId": 191,
"siteRecid": 201,
"siteId": "20000"
}
],
"subjects": [],
"visits": [],
"sftpLocations": [],
"dicomLocations": [],
"fileSystemLocations": [],
"rawFileSystemLocations": [],
"states": [],
"modalities": [],
"examDates": [],
"series": [],
"transferType": null,
"customFolder": false,
"customFile": false,
"folderStructure": null,
"fileStructure": null,
"allSites": false,
"allSubjects": false,
"allVisits": false,
"allStates": false,
"allExamDates": false,
"allModalities": false,
"allSeries": false,
"softEditOverride": false,
"includePS": false,
"includeSR": false,
"includeRTStruct": false,
"dicomTemplate": null,
"errorMessage": null,
"successMessage": null
}
Add JMESPath Extractor to your sampler and configure it:
JMESPath expressions: sites[*].studyId
Match No.: 0
Default Values: STUDYID_NOT_FOUND
JMESPath Extractor will collect all the studyId values and return one selected randomly.

JSGRID - Excel-like keyboard navigation

I have a jsgrid gride and I want to activate edit mode in next line after hit enter key (or arrow down key) in "inline edition" and focus on the same column but next line, as Excel -like keyboard navigation.
The only achievement is to fire update with enter key but how to activate edition in the next line in the same column?
var clients = [
{ "Name": "Otto Clay", "Age": 25, "Country": 1, "Address": "Ap #897-1459 Quam Avenue", "Married": false },
{ "Name": "Connor Johnston", "Age": 45, "Country": 2, "Address": "Ap #370-4647 Dis Av.", "Married": true },
{ "Name": "Lacey Hess", "Age": 29, "Country": 3, "Address": "Ap #365-8835 Integer St.", "Married": false },
{ "Name": "Timothy Henson", "Age": 56, "Country": 1, "Address": "911-5143 Luctus Ave", "Married": true },
{ "Name": "Ramona Benton", "Age": 32, "Country": 3, "Address": "Ap #614-689 Vehicula Street", "Married": false }
];
var countries = [
{ Name: "", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 }
];
$("#jsGrid").jsGrid({
width: "100%",
height: "400px",
inserting: false,
editing: true,
sorting: true,
paging: true,
data: clients,
fields: [
{ name: "Name", type: "text", width: 150, validate: "required" },
{ name: "Age", type: "number", width: 50 },
{ name: "Address", type: "text", width: 200 },
{ name: "Country", type: "select", items: countries, valueField: "Id", textField: "Name" },
{ name: "Married", type: "checkbox", title: "Is Married", sorting: false },
{ type: "control" }
],
onError: function (args) {
console.log("ERR");
console.log(args);
},
});
$('#jsGrid').off().on('keydown', 'input[type=text], input[type=number]', (event) => {
if (event.which === 13) { // Detect enter keypress
$('#jsGrid').jsGrid("updateItem"); // Update the row
}
});
UPDATE: I developed an alternative that use Enter (or arrow down key) con updateitem, activate the edit mode in the next row and focus on the same previous column control. But I think there is an easy way.
var LastIndexInputs = -1;
var LastIndexSelect = -1;
function ActivateEditNextLine(NewIndex) {
var gridBody = $("#jsGrid").find('.jsgrid-grid-body');
gridBody.find('.jsgrid-table tr').each(function (index, tr) {
if (index == NewIndex) {
$(tr).trigger('click');
RowTarget = gridBody.find(".jsgrid-edit-row");
if (LastIndexInputs != -1) {
RowTarget.find('.Campo')[LastIndexInputs].focus();
RowTarget.find('.Campo')[LastIndexInputs].select();
}
else {
if (LastIndexSelect != -1) {
RowTarget.find('select')[LastIndexSelect].focus();
}
}
}
});
};
var clients = [
{ "Name": "Otto Clay", "Age": 25, "Country": 1, "Address": "Ap #897-1459 Quam Avenue", "Married": false },
{ "Name": "Connor Johnston", "Age": 45, "Country": 2, "Address": "Ap #370-4647 Dis Av.", "Married": true },
{ "Name": "Lacey Hess", "Age": 29, "Country": 3, "Address": "Ap #365-8835 Integer St.", "Married": false },
{ "Name": "Timothy Henson", "Age": 56, "Country": 1, "Address": "911-5143 Luctus Ave", "Married": true },
{ "Name": "Ramona Benton", "Age": 32, "Country": 3, "Address": "Ap #614-689 Vehicula Street", "Married": false }
];
var countries = [
{ Name: "", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 }
];
$("#jsGrid").jsGrid({
width: "100%",
height: "400px",
inserting: false,
editing: true,
sorting: true,
paging: true,
data: clients,
fields: [
{ name: "Name", type: "text", width: 150, validate: "required" },
{ name: "Address", type: "text", width: 200 },
{ name: "Country", type: "select", items: countries, valueField: "Id", textField: "Name" },
{ name: "Age", type: "text", width: 50 },
{ name: "Married", type: "checkbox", title: "Is Married", sorting: false },
{ type: "control" },
],
onItemUpdating: function (args) {
console.log("confirm edition");
// pointer to last control index for jump to the same colum
var gridBody = $("#jsGrid").find('.jsgrid-grid-body');
Registro = gridBody.find(".jsgrid-edit-row");
var inputs = Registro.find('.Campo');
LastIndexInputs = inputs.index(inputs.filter(':focus'))
var selects = Registro.find('select');
LastIndexSelect = selects.index(selects.filter(':focus'))
},
onItemUpdated: function (args) {
if (args.grid.data.length != (args.itemIndex + 1)) {
ActivateEditNextLine(args.itemIndex + 1);
}
},
editItem: function (item) {
console.log("Enter in edition mode")
var $row = this.rowByItem(item);
if ($row.length) {
//console.log('$row: ' + JSON.stringify($row));
this._editRow($row);
}
},
onError: function (args) {
console.log("ERR");
console.log(args);
},
});
$('#jsGrid').off().on('keydown', 'input[type!=hidden], select', (event) => {
if (event.which === 13) { // Detect enter keypress
$('#jsGrid').jsGrid("updateItem"); // Update the row
}
if (event.which === 40) { // arrow down keypress
$('#jsGrid').jsGrid("updateItem"); // Update the row
}
});

Plotly: Slider animation don't move in applicaion with animated word cloud

I was trying to plot animated word cloud using plotly. When the output is plot (html) I can see all the word cloud in animated way (one by one using play botton). The problem is with the slider, which doesn't move at all.
The input data are 2 lists of 4 elements: the first list are 4 diferents wikipedia texts storaged in my_test = [text1, text2, text3, text4], and the second list is year = ["1952", "1962", "1967", "1972"].
The code is:
from wordcloud import WordCloud, STOPWORDS
import plotly.graph_objs as go
from plotly.offline import plot
import plotly.offline as py
py.init_notebook_mode()
def plotly_wordcloud(text):
wc = WordCloud(width = 500,
height = 300,
margin=0,
stopwords = set(STOPWORDS),
max_words = 2000,
max_font_size = 100,
min_font_size = 10)
wc.generate(text)
word_list=[]
freq_list=[]
fontsize_list=[]
position_list=[]
orientation_list=[]
color_list=[]
for (word, freq), fontsize, position, orientation, color in wc.layout_:
word_list.append(word)
freq_list.append(freq)
fontsize_list.append(fontsize)
position_list.append(position)
orientation_list.append(orientation)
color_list.append(color)
# get the positions
x=[]
y=[]
for i in position_list:
x.append(i[0])
y.append(i[1])
# get the relative occurence frequencies
new_freq_list = []
for i in freq_list:
new_freq_list.append(i*100)
new_freq_list
return x,y,word_list,freq_list,fontsize_list,color_list,new_freq_list
my_text = [text1,text2,text3,text4]
years = ["1952", "1962", "1967", "1972"]
fig_dict = {
"data": [],
"layout": {},
"layout.update": {},
"frames": []
}
sliders_dict = {
"active": 0,
"yanchor": "top",
"xanchor": "left",
"currentvalue": {
"font": {"size": 20},
"prefix": "Year:",
"visible": True,
"xanchor": "right"
},
"transition": {"duration": 300, "easing": "cubic-in-out"},
"pad": {"b": 10, "t": 50},
"len": 0.9,
"x": 0.1,
"y": 0,
"steps": []
}
fig_dict["layout"] = {"width":1000, "height":600}
fig_dict["layout"]["xaxis"] = {"showgrid":False, "showticklabels":False, "zeroline":False}
fig_dict["layout"]["yaxis"] = {"showgrid":False, "showticklabels":False, "zeroline":False}
fig_dict["layout"]["hovermode"] = "closest"
fig_dict["layout"]["title"] = "Issues by Month"
fig_dict["layout"]["sliders"] = {
"args": ["transition", {"duration": 300,
"easing": "cubic-in-out"}],
"initialValue": "1952",
"plotlycommand": "animate",
"values": years,
"visible": True
}
fig_dict["layout"]["updatemenus"] = [
{"buttons": [
{"args": [None, {"frame": {"duration": 500, "redraw": False},
"fromcurrent": True, "transition": {"duration": 300,
"easing": "quadratic-in-out"}}],
"label": "Play",
"method": "animate"
},
{
"args": [[None], {"frame": {"duration": 0, "redraw": False},
"mode": "immediate",
"transition": {"duration": 0}}],
"label": "Pause",
"method": "animate"
}
],
"direction": "left",
"pad": {"r": 10, "t": 87},
"showactive": False,
"type": "buttons",
"x": 0.1,
"xanchor": "right",
"y": 0,
"yanchor": "top"
}]
first_time = True
for texto,year in zip(my_text,years):
x,y,word_list,freq_list,fontsize_list,color_list,new_freq_list = plotly_wordcloud(str(texto))
if first_time == True:
first_time = False
data = go.Scatter(x=x,
y=x,
textfont = dict(size=new_freq_list,
color=color_list),
name=year,
mode='text',
text=word_list
)
fig_dict["data"].append(data)
fig_dict["frames"].append(go.Frame(data=[go.Scatter(
x=x,
y=y,
textfont = dict(size=new_freq_list,
color=color_list),
name=year,
mode='text',
text=word_list
)]))
slider_step = {"args": [[year],
{"frame": {"duration": 300, "redraw": False},
"mode": "immediate",
"transition": {"duration": 300}}
],
"label": year,
"method": "animate"}
sliders_dict["steps"].append(slider_step)
fig_dict["layout"]["sliders"] = [sliders_dict]
fig = go.Figure(fig_dict)
plot(fig)

Datatables with laravel how to render hasMany relationship

i have the following response from my controller
[
{
"id": 1,
"place_id": 1,
"name": "Test",
"type": 5,
"created_at": "2018-06-04 15:29:02",
"updated_at": "2018-06-04 15:29:02",
"time": [
{
"id": 1,
"stadium_id": 1,
"day": "Saturday",
"from_hour": 7,
"to_hour": 12,
"created_at": "2018-06-04 15:29:42",
"updated_at": "2018-06-04 15:29:42"
},
{
"id": 2,
"stadium_id": 1,
"day": "Sunday",
"from_hour": 7,
"to_hour": 12,
"created_at": "2018-06-04 15:54:03",
"updated_at": "2018-06-04 15:54:03"
}
]
}
]
i want to access the day attribute in each time object
i tried the code below but of course it just loads the first result
is there a solution
columns: [
{ data: 'name' },
{ data: 'type' },
{ data: 'time.0.day' },
{ data: 'time.0.from_hour' },
{ data: 'time.0.to_hour' },
],
You can actually access time array by using the render property:
columns: [{
data: 'name'
},
{
data: 'type'
},
{
data: 'time',
render: function(data, type, row) {
var txt = '';
data.forEach(function(item) {
if (txt.length > 0) {
txt += '</br> '
}
txt += item.day;
});
return txt;
}
},
...
This would just add a line break for every objects in time. Here's a Fiddle for you to examine.

Resources