smallrye make foreach conditiont Multi - if-statement

I want to make a category tree,
here is the category structure
class category{
private String id;
private String parentId;
private List<CategoryDto> children;
}
children at the beginning is empty,
parentId if null is a parent otherwise it is children.
I want to return this result:
[
{
"id": "61eb379e6d797574df47cfc3",
"parentId": "",
"children": [
{
"id": "61ea7e5f1323dd3731dd304a",
"parentId": "61eb379e6d797574df47cfc3",
"children": null
},
{
"id": "61ea8f471323dd3731dd304c",
"status": "PUBLISHED",
"parentId": "61eb379e6d797574df47cfc3",
"children": null
}
]
}
]
I did with classic programming I want to migrate to reactive programming with mutiny smallrye here is my code:
#Blocking
public Uni<List<CategoryDto>> getAllCategories(Request doc) {
log.info("REST request to find Categories : {}", doc);
Map<String, Object> parent = new HashMap<>();
List<CategoryDto> all = categoryRepository
.streamAllAggregators(doc).subscribe().asStream().map(it -> aggregatorMapper.categoryToCategoryDto(it, doc.getLang())).collect(toList());
List<CategoryDto> listParent = categoryRepository
.findByParentId("").subscribe().asStream().map(it -> aggregatorMapper.categoryToCategoryDto(it, doc.getLang())).collect(toList());
List<CategoryDto> listChildren = all.stream()
.filter(n -> n.getParentId() != null)
.collect(Collectors.toList());
List<CategoryDto> categoryDtoList = new ArrayList<>();
for (int i = 0; i < listParent.size(); i++) {
categoryDtoList = new ArrayList<>();
for (int j = 0; j < listChildren.size(); j++) {
if (listChildren.get(j).getParentId().equals(listParent.get(i).getId().toString())) {
categoryDtoList.add(listChildren.get(j));
}
}
listParent.get(i).setChildren(categoryDtoList);
}
return Uni.createFrom().item(listParent);
}

Taking my reply from https://github.com/smallrye/smallrye-mutiny/issues/823:
Something like this will work:
public Uni<List<CategoryDto>> getAllCategories(Request doc) {
Map<String, Object> parent = new HashMap<>();
Multi<CategoryDto> all = categoryRepository.streamAllAggregators(doc).map(s -> aggregatorMapper.categoryToCategoryDto(s, doc.getLang()));
Uni<List<CategoryDto>> listParent = categoryRepository
.findByParentId("").map(it -> aggregatorMapper.categoryToCategoryDto(it, doc.getLang())).collect().asList();
Uni<List<CategoryDto>> listChildren = all.select().where(n -> n.getParentId() != null).collect().asList();
return Uni.combine().all().unis(listParent, listChildren).combinedWith((parents, children) -> {
// Or whatever you need to do.
List<CategoryDto> categoryDtoList;
for (int i = 0; i < parents.size(); i++) {
categoryDtoList = new ArrayList<>();
for (int j = 0; j < children.size(); j++) {
if (children.get(j).getParentId().equals(parents.get(i).getId().toString())) {
categoryDtoList.add(children.get(j));
}
}
parents.get(i).setChildren(categoryDtoList);
}
return parents;
});
}

Related

Simplify Syntax

This could be a basic question, however, I couldn't figure out how can I simplify this statement. I have a feeling that something's not right on this code.
Thank you.
var a = string.Empty;
if (File.Exists(a = Path.Combine(modelPath, "attributes", filename))) { }
else
{
if (File.Exists(a = GetSaveAsAttribute(firmPath))) { }
else
{
for (int i = 0; i < systemPaths.Count; i++)
{
if (File.Exists(a = GetSaveAsAttribute(systemPaths[i])))
break;
}
}
}
You can remove your **if** by directly checking for another condition.
var a = string.Empty;
if (!(File.Exists(a = Path.Combine(modelPath, "attributes", filename)))) {
if (!(File.Exists(a = GetSaveAsAttribute(firmPath))) ){
for (int i = 0; i < systemPaths.Count; i++)
{
if (File.Exists(a = GetSaveAsAttribute(systemPaths[i])))
break;
}
}
}

Trouble with nested data structure in C++

Using https://github.com/nlohmann/json, I am trying to assign values to a recursive data structure (json_node_t):
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
struct json_node_t {
int id;
std::vector<json_node_t> children;
};
void to_json(json& j, const json_node_t& node) {
j = {{"ID", node.id}};
if (!node.children.empty())
j.push_back({"children", node.children});
}
int main() {
json_node_t node_0;
std::vector<int> values = {1,2,3};
std::vector<json_node_t> parents;
parents.resize(20);
for(int i = 0; i < values.size(); i++) {
if ( i == 0 )
{
node_0.id = values[0];
std::vector<json_node_t> node_children_;
node_0.children = node_children_;
parents[0] = node_0;
} else {
json_node_t node_i;
node_i.id = values[i];
std::vector<json_node_t> node_i_children_;
parents[i] = node_i;
parents[i-1].children.push_back(node_i);
}
}
json j = node_0;
cout << j.dump(2) << endl;
return 0;
}
My purpose is to create a JSON representation like the following:
{
"ID": 1,
"children": [
{
"ID": 2
},
{
"ID": 3,
"children": []
}
]
}
However, the nested children are not getting printed. I only get this output:
{
"ID": 1
}
What is wrong? I cannot connect the child to his parent correct. How can I fix the problem?
You output node_0;, but you never append any children to it. The reason for that, is parents[0] = node_0; copies node_0. So when you parents[0].children.push_back(node_i); you append node_i as a child to the copy of node_0 - the original one remains unchanged. That is why it contains no children in the end.
EDIT:
My code.
#include "json.hpp"
#include <memory>
#include <vector>
#include <iostream>
struct json_node;
using json_node_ptr = std::shared_ptr<json_node>;
struct json_node
{
int id;
std::vector<json_node_ptr> children;
json_node(int _id)
: id{ _id }
{
}
};
void to_json(nlohmann::json& j, const json_node_ptr& node)
{
j = {{"ID", node->id}};
if (!node->children.empty()) {
j.push_back({"children", node->children});
}
}
int main()
{
std::vector<int> values = {1,2,3};
std::vector<json_node_ptr> parents;
for(int i = 0; i < values.size(); i++)
{
if ( i == 0 ) {
auto root = std::make_shared<json_node>(values[0]);
parents.push_back(root);
} else {
parents.push_back(std::make_shared<json_node>(values[i]));
parents[i-1]->children.push_back(parents[i]);
}
}
nlohmann::json j = parents[0];
std::cout << j.dump(2) << std::endl;
return 0;
}
Output:
{
"ID": 1,
"children": [
{
"ID": 2,
"children": [
{
"ID": 3
}
]
}
]
}

C# How to filter <list> data into dataGridView using datetimepicker

I have a List that contains Student objects. When the form loads, data was displayed in a Datagridview control.
Do not use a button to filtered data with date range base on my 2 datetimepicker (datefrom and dateto)
Below is my code. Can you help me what is the problem? Thank you!
Source code
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace formStudent
{
public partial class formStudent : Form
{
List<Student> listStudent = new List<Student>();
class Student
{
public string name { get; set; }
public string gender { get; set; }
public string birthday { get; set; }
public Student(string inName, string inGender, string inBirthday)
{
name = inName;
gender = inGender;
birthday = inBirthday;
}
}
public formStudent()
{
InitializeComponent();
string[,] arrData = new string[10, 3] {
{ "Jane","Female","2016/08/11" },
{ "Peter","Female","2016/08/12" },
{ "John","Female","2016/08/13" },
{ "Ronaldo","Male","2016/08/14" },
{ "Jerry","Female","2016/08/15" },
{ "David","Female","2016/08/16" },
{ "Rooney","Male","2016/08/17" },
{ "Ozil","Male","2016/08/18" },
{ "Torres","Male","2016/08/19" },
{ "Messi","Male","2016/08/20" },
};
//Data row
List<string> dataRow = new List<string>();
//Data array
List<List<string>> listData = new List<List<string>>();
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 3; col++)
dataRow.Add(arrData[row, col]);
listData.Add(dataRow);
dataRow = new List<string>();
}
Student student = null;
foreach (List<string> data in listData)
{
student = new Student(data[0], data[1], data[2]);
//Get data student
listStudent.Add(student);
}
}
private void formStudent_Load(object sender, EventArgs e)
{
//Show data
foreach (Student item in listStudent)
{
int ii = this.dataGridView.Rows.Add();
this.dataGridView.Rows[ii].Cells[0].Value = item.name;
//Gender
string strGender = string.Empty;
if ("Male".Equals(item.gender))
strGender = "Male";
else
strGender = "Female";
this.dataGridView.Rows[ii].Cells[1].Value = strGender;
this.dataGridView.Rows[ii].Cells[2].Value = item.birthday;
}
}
}
}

How to iterate through a QStandardItemModel completely?

I have a QStandardItemModel, which I display in q QTreeView. Works fine.
To highlight relevant rows I want to highlight some of them: Therefore I have a QStringList with the names of the QStandItem* s to be highlighted.
QStringList namesToBeHighlighted = getNames();
QModelIndex in = myModel->index(0, 0);
if ( in.isValid() ) {
for (int curIndex = 0; curIndex < myModel->rowCount(in); ++curIndex) {
QModelIndex si = myModel->index(curIndex, 0, in);
QStandardItem *curItem = myModel->itemFromIndex(si);
if (curItem) {
QString curItemName = curItem->text();
if ( namesToBeHighlighted.contains(curItem->text()) ) {
curItem->setFont(highlightFont);
}
else curItem->setFont(unHighlightFont);
}
}
}
My Model has following structure:
Level_1
+--> Level_11
+--> Level_12
+--> Level_13
Level_2
+--> Level_21
+--> Level_22
+--> Level_23
...
Here, it iterates trough Levels 11, 12 and 13 then it stops.
I hope it helps you:
void forEach(QAbstractItemModel* model, QModelIndex parent = QModelIndex()) {
for(int r = 0; r < model->rowCount(parent); ++r) {
QModelIndex index = model->index(r, 0, parent);
QVariant name = model->data(index);
qDebug() << name;
// here is your applicable code
if( model->hasChildren(index) ) {
forEach(model, index);
}
}
}
QStandardItemModel model;
QStandardItem* parentItem = model.invisibleRootItem();
for (int i = 0; i < 4; ++i) {
QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
for (int j = 0; j < 5; ++j) {
item->appendRow(new QStandardItem(QString("item %0%1").arg(i).arg(j)));
}
parentItem->appendRow(item);
parentItem = item;
}
forEach(&model);

Build tree from flat QStandardItemModel

i have problem with QStandardItemModel. I want to get values from one model (id, name, parent) and build tree in another model.
First i'm getting all childrens of any parent to QMultiMap<int,QStandardItem*> childrenIndexes:
getChildrens()
{
for(int i = 0 ; i < tableModel->rowCount() ; i++ )
{
QStandardItem* item_ptr = tableModel->item(i,1);
int parent;
if(tableModel->item(i,2)->text() == "null")
{
parent = -1;
}
else
{
parent = tableModel->item(i,2)->text().toInt();
}
childrenIndexes.insert(parent, item_ptr);
}
}
Multimap builds fine, in next step i recursively call building function. Starting from root (Item 1):
void addChildrens(QStandardItem* item)
{
int id = tableModel->item(tableModel->indexFromItem(item).row(),0)->text().toInt();
QString name = tableModel->item(tableModel->indexFromItem(item).row(),1)->text();
qDebug() << "Parsing item: " << name;
int parent;
if(tableModel->item(tableModel->indexFromItem(item).row(),2)->text() == "null")
{
qDebug() << "Got root!";
item = new QStandardItem(name);
treeModel->appendRow(item);
parent = -1;
}
else
{
parent = tableModel->item(tableModel->indexFromItem(item).row(),2)->text().toInt();
}
qDebug("Got %d childrens!",childrenIndexes.values(id).count());
for(int i = 0 ; i < childrenIndexes.values(id).count() ; i++)
{
QStandardItem* newItem = childrenIndexes.values(id).at(i);
qDebug() << newItem->text();
item->appendRow(newItem->clone());
addChildrens(newItem);
}
}
Unfortunately my tree got only childrens of root. Where is problem?