Spring JPA - Page<Company> - append Page contents - spring

Inside a for loop I have my 'Page companies' object which stores the result of method called 'findByNameOrGroupIdOrTerritoryIdAndCompanyIdsInobject' 'n' number of times. If it was a List we could go with companies.addAll() method so that it would append to the same object.
Is there any way to append to companies object instead of assigning every time which only stores last iteration result?
Here is the code snippet:
Page<Company> companies = null;
int parametersLimit = 500;
int companyBatches = companyIds.size() / parametersLimit;
for (int companyBatchIndex = 0; companyBatchIndex <= companyBatches; companyBatchIndex++) {
int lowerIndex = companyBatchIndex * parametersLimit;
int upperIndex = Math.min((companyBatchIndex + 1) * parametersLimit, companyIds.size());
companies = companyRepository.findByNameOrGroupIdOrTerritoryIdAndCompanyIdsIn(nameOrGroupId, territoryId, companyIds.subList(lowerIndex, upperIndex), pageable);
}
Thank you!

Simply use a list you should not use page like this

Simply put, there is no such way to append to Page contents. So I modified the logic to return List of Companies and then using PageImpl I converted the List to Page.
Page<Company> companies = null;
List<Company> companiesList = new ArrayList<Company>();;
int parametersLimit = 500;
int companyBatches = companyIds.size() / parametersLimit;
for (int companyBatchIndex = 0; companyBatchIndex <= companyBatches; companyBatchIndex++) {
int lowerIndex = companyBatchIndex * parametersLimit;
int upperIndex = Math.min((companyBatchIndex + 1) * parametersLimit, companyIds.size());
companiesList.addAll(companyRepository.findByNameOrGroupIdOrTerritoryIdAndCompanyIdsIn(nameOrGroupId, territoryId, companyIds.subList(lowerIndex, upperIndex), pageable));
}
int fromIndex = pageable.getPageNumber() * pageable.getPageSize();
int toIndex = Math.min( (int) (pageable.getOffset() + pageable.getPageSize()), companiesList.size());
companies = new PageImpl<>(companiesList.subList(fromIndex, toIndex), pageable, companiesList.size());

Related

How to delete all rows which have value 1 in "status_pesanan" column

I want to delete all rows which have value of 1 in column "status_pesanan" before running create data Laravel
my controller
public function create()
{
$penjualan = DB::table('penjualan')
->groupBy('status_pesanan')
->havingRaw('COUNT(status_pesanan) = 1')
->delete();
$penjualan = new Penjualan();
$penjualan->nama_pemesan = 1;
$penjualan['no_nota'] = tambah_nol_didepan($penjualan->no_nota+1, 5);
$penjualan->alamat_pemesan = 1;
$penjualan->telepon_pemesan = 1;
$penjualan->acc_desain = 1;
$penjualan->total_item = 0;
$penjualan->total_harga = 0;
$penjualan->diskon = 0;
$penjualan->bayar = 0;
$penjualan->diterima = 0;
$penjualan->id_user = auth()->id();
$penjualan->save();
session(['id_penjualan' => $penjualan->id_penjualan]);
return redirect()->route('transaksi-baru.index');
}
If I run the code as above, the output I receive is that all old rows in the database are deleted
You are grouping by status_penasan having its count equal to 1 and call delete upon it. You wanted to remove the records whose status_penasan value is 1. This could be a fix:
$penjualan = DB::table('penjualan')
->where('status_pesanan', 1)
->delete();

How to add number of days to a custom Date captured from Correlation function?

I am looking for logic which can add couple of days to a custom date(not current date)
Below is Correlation function:
web_reg_save_param("Recommended_Date",
"LB=\"start\":\"",
"RB/DIG=T##:##:##\",",
"Ord=1",
"Search=Body",
LAST);
I want to add +21 days to Recommended_Date parameter. I tried doing below thing but no luck
lr_save_datetime("%Y-%M-%D", lr_eval_string("{Recommended_Date}") + (ONE_DAY*21), "New_Date");
Can anyone please assist me.
One of our engineers prepared this example for you:
int diff_days(char * dateString, char * dateFormat) {
int year, month, day;
struct tm info;
double delta;
double days=0;
time_t today;
time(&today);
sscanf(dateString, dateFormat, &year, &month, &day);
info.tm_year = year - 1900;
info.tm_mon = month - 1;
info.tm_mday = day;
// info.tm_hour = 0;
// info.tm_min = 0;
// info.tm_sec = 0;
info.tm_isdst = -1;
mktime(&info);
delta = difftime(mktime(&info),today);
if (delta >= 0) {
days = difftime(mktime(&info),today)/ 86400.0 +1;
} else {
days = difftime(mktime(&info),today)/ 86400.0;
}
return (int)days;
}
Action()
{
int plus;
lr_save_string("2020-09-01","D2");
plus = diff_days(lr_eval_string("{D2}"),"%d-%d-%d");
lr_save_datetime("%Y-%m-%d", DATE_NOW + ONE_DAY*(21+plus), "New_Date");
lr_save_string("2020/04/05","D2");
plus = diff_days(lr_eval_string("{D2}"),"%d/%d/%d");
lr_save_datetime("%Y/%m/%d", DATE_NOW + ONE_DAY*(21+plus), "New_Date");
return 0;
}

Where clause using Expression tree builder

I have to fetch data from database and filter data using the linq where clause.
My filter is an integer column and it contains value more than 1000.
What i am doing in the code is, breaking this huge array into chunk of 1000's of each and putting it in the where clause of a base query
int j = 0;
int batchsize = 1000;
while ((j * batchsize) < items.Count())
{
List<long> batch = items.Skip(j * batchsize)
.Take(batchsize).ToList();
prequery = prequery.Where(x => batch.Contains(x.Id));
j++;
}
the query which is getting generated in sql is below,
SELECT
x.name,
x.email
FROM
table x
WHERE
x.Id IN (1,2,3,...,1000) AND
x.Id IN (1001,1002,1003....,2000)
i want the query to be generated as below,
SELECT
x.name,
x.email
FROM
table x
WHERE
x.Id IN (1,2,3,...,1000) OR
x.Id IN (1001,1002,1003....,2000)
can i achieve this using expression tree builder and generate the query dynamically, if so please help in doing
you could use the "Concat" API:
int j = 0;
int batchsize = 1000;
IQueryable<YourType> finalQuery = null;
while ((j * batchsize) < items.Count())
{
List<long> batch = items.Skip(j * batchsize)
.Take(batchsize).ToList();
if (finalQuery == null) {
finalQuery = prequery.Where(x => batch.Contains(x.Id));
}
else
finalQuery = finalQuery.Concat (prequery.Where(x => batch.Contains(x.Id)));
j++;
}
This will logically get you what you want: basically you want an "OR" operation between batches. Concat is translated into an "UNION ALL" database call.
BUT ... I don't understand why are you doing this, after all you are grabbing all your data, chunks are not helping you because in the end there will be only one statement executed.

How do you get the iteration / line number from TestContext in data driven tests?

I've implemented a data driven test using MsTest framework.
I was wondering if there was a way to get the iteration / line number of the current test code from the TestContext object?
As far as I can see, the only property relevant to DDT is DataRow that enables getting info for the current iteration from the data source, but I don't see any property that gives me what I need.
Try this:
int currentIteration = TestContext.DataRow.Table.Rows.IndexOf(TestContext.DataRow);
private readonly PropertyInfo _rowIdProp = typeof(System.Data.DataRow).GetProperty("rowID", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance);
..
// No datarow means only one iteraton
var currentIteration = DataRow == null ? 1 : (Int64)_rowIdProp.GetValue(DataRow, null);
this is without the DataSource attribute but i can tell you that it iterate by it self without the for loop
for (int i = 0; i < x; i++)
{
int currentIteration = TestContext.DataRow.Table.Rows.IndexOf(TestContext.DataRow);
DataTable dt = TestContext.DataRow.Table;
int rowCount = dt.Rows.Count;
DataRow secondRow = dt.Rows[i];
string name = secondRow["name"].ToString();
int Balance = Convert.ToInt32(secondRow["Balance"]);
int Amount = Convert.ToInt32(secondRow["Amount"]);
int Count = Convert.ToInt32(secondRow["Count"]);
Assert.AreEqual(Balance, Amount);
}

Exporting ListView content to Excel?

I've been trying to export the content data of my ListView control into an Excel application using C#. I've already done this before using VB.NET and I tried to convert my code to C# but it failed but I made a modification on it and seems everything is fine on code below except for the last part which to save the data as an excel file. I need an assistance to modify this code correctly. I would greatly appreciate your helpful response.
The code below that got an error is:
oBook.SaveAs(SaveFileDialog1.InitialDirectory.ToString() + SaveFileDialog1.FileName);
Error 5 No overload for method 'SaveAs' takes '1' arguments
private void Button4_Click(object sender, System.EventArgs e)
{
int row = 0;
int col = 0;
int row2 = 0;
int col2 = 0;
int ch = 0;
int ctr = 0;
ctr = 0;
row2 = 1;
col2 = 3;
row = 3;
col = 3;
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
oExcel.Visible = false;
Microsoft.Office.Interop.Excel.Workbook oBook = oExcel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oExcel.ActiveSheet;
SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
SaveFileDialog1.Filter = "Excel File|*.xlsx|Word File|*.doc|Text File|*.txt";
SaveFileDialog1.Title = "Save As";
if (SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
switch (SaveFileDialog1.FilterIndex)
{
case 1:
{
for (ch = 1; ch <= ListView1.Columns.Count; ch++)
{
oSheet.Cells[row2, col2] = ListView1.Columns[ctr].Text;
col2 = col2 + 1;
ctr = ctr + 1;
}
foreach (ListViewItem lview in ListView1.Items)
{
foreach (ListViewItem.ListViewSubItem lview2 in lview.SubItems)
{
oSheet.Cells[row, col] = lview2.Text;
col = col + 1;
}
col = 3;
row = row + 1;
}
oBook.SaveAs(SaveFileDialog1.InitialDirectory.ToString() + SaveFileDialog1.FileName);
oExcel.Quit();
SaveFileDialog1.Dispose();
MessageBox.Show("Data has been successfully saved", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
}
}
The workbook SaveAs method takes 11 parameters. In C# you have to pass something for these optional parameters even if you do not care about them. The easiest thing to do here is pass System.Reflection.Missing.Value for those you do not care about. It is a pain though.

Resources