text stringlengths 1 2.12k | source dict |
|---|---|
c#, winforms, pdf
}
else
{
if
(billsDGV.SelectedRows.Count > 0 && billsDGV.SelectedRows.Count < 16)
{
Gen1stTable();
GenLastPart();
pdoc.Close();
Process.Start(@"F:\test.pdf");
}
else{
MetroMessageBox.Show(this,"Please select minimum 1 item and/or maximum 15 items","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
Using the helper methods :
decimal total, _total, amt;
PdfWriter pwriter;
iTextSharp.text.Document pdoc;
iTextSharp.text.Font myfont=FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(),20,iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE);
iTextSharp.text.Font _myfont=FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(),14,iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE);
iTextSharp.text.Font myfont2=FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(),11,iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.RED);
iTextSharp.text.Font myfont3=FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(),9,iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font myfont4=FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(),12,iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
private iTextSharp.text.Font blankFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE, BaseColor.WHITE);
private iTextSharp.text.Font headerFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
private iTextSharp.text.Font standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
private iTextSharp.text.Font totalfont=new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12f, iTextSharp.text.Font.BOLD);
//Generates the header portion & the first table taking data from billsDGV
public iTextSharp.text.Document Gen1stTable()
{
total = billsDGV.SelectedRows.OfType<DataGridViewRow>()
.Sum(t => Convert.ToDecimal(t.Cells[2].Value));
_total = creditNotesDGV.SelectedRows.OfType<DataGridViewRow>()
.Sum(t => Convert.ToDecimal(t.Cells[2].Value));
amt=total-_total;
pdoc=new iTextSharp.text.Document(PageSize.A4,20f,20f,30f,30f);
pwriter=PdfWriter.GetInstance(pdoc,new FileStream(@"F:\test.pdf",FileMode.Create));
pdoc.Open();
iTextSharp.text.Paragraph pg=new iTextSharp.text.Paragraph("DREAMLAND",myfont);
pg.Alignment=Element.ALIGN_CENTER;
pdoc.Add(pg);
iTextSharp.text.Paragraph _pg=new iTextSharp.text.Paragraph("A Unit Of LA LA LAND",_myfont);
_pg.Alignment=Element.ALIGN_CENTER;
pdoc.Add(_pg); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
iTextSharp.text.Paragraph pg2=new iTextSharp.text.Paragraph("2/221, Tahira Road, Gr Floor, Rajouri Garden, New Delhi-110069",myfont2);
pg2.Alignment=Element.ALIGN_CENTER;
pdoc.Add(pg2);
iTextSharp.text.Paragraph lineSeparator = new iTextSharp.text.Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
lineSeparator.SetLeading(0.5F, 0.5F);
pdoc.Add(lineSeparator);
iTextSharp.text.Paragraph pg3=new iTextSharp.text.Paragraph("\nDate: "+ DateTime.Now.ToString("dd-MMM-yyyy")+"\n\n",myfont3);
pg3.Alignment=Element.ALIGN_RIGHT;
pdoc.Add(pg3);
iTextSharp.text.Paragraph pg4=new iTextSharp.text.Paragraph("To\nM/s "+ kryptonComboBox1.Text+"\n"+lblCity.Text+"\n\n\n\nDear Sir,\n\nPlease find enclosed herewith the payment for Rs. "+String.Format(new CultureInfo( "en-IN", false ), "{0:n}", Convert.ToDouble(amt))+" through paythru of your following bills\n\n",myfont4);
pg4.Alignment=Element.ALIGN_LEFT;
pdoc.Add(pg4); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
PdfPTable tab = new PdfPTable(billsDGV.ColumnCount);
tab.WidthPercentage = 75;
tab.DefaultCell.Padding = 3;
tab.HorizontalAlignment = Element.ALIGN_CENTER;
PdfPCell headcell = new PdfPCell(new Phrase(kryptonComboBox1.Text,headerFont));
headcell.BackgroundColor = new BaseColor(255, 255, 30);
headcell.Colspan=3;
headcell.HorizontalAlignment=Element.ALIGN_CENTER;
tab.AddCell(headcell);
PdfPTable pdfTable = new PdfPTable(billsDGV.ColumnCount);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 75;
pdfTable.HorizontalAlignment = Element.ALIGN_CENTER;
foreach (DataGridViewColumn column in billsDGV.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText,headerFont));
cell.BackgroundColor = new BaseColor(137, 220, 165);
pdfTable.AddCell(cell);
}
foreach (DataGridViewRow row in billsDGV.SelectedRows.OfType<DataGridViewRow>().OrderBy(s=>s.Index))
{
foreach (DataGridViewCell cell in row.Cells)
{
pdfTable.AddCell(new Phrase(cell.Value.ToString(),standardFont));
}
}
pdoc.Add(tab);
pdoc.Add(pdfTable);
return pdoc;
}
//Generates the second table taking data from billsDGV & creditNotesDGV when items from both the DGV's are selected
public iTextSharp.text.Document Gen2ndTable(iTextSharp.text.Document doc)
{
PdfPTable tabl = new PdfPTable(3);
tabl.WidthPercentage = 75;
tabl.DefaultCell.Padding = 3;
PdfPCell b2_cell = new PdfPCell(new Phrase("",blankFont));
b2_cell.HorizontalAlignment=Element.ALIGN_CENTER;
b2_cell.Colspan=2;
tabl.AddCell(b2_cell); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
PdfPCell b4_cell = new PdfPCell();
Chunk _c = new Chunk(total.ToString(),headerFont);
_c.SetUnderline(1,12);
b4_cell.AddElement(_c);
tabl.AddCell(b4_cell);
PdfPCell a_cell = new PdfPCell(new Phrase("Less Credit Note/Debit Note",headerFont));
a_cell.Colspan=3;
a_cell.HorizontalAlignment=Element.ALIGN_CENTER;
tabl.AddCell(a_cell);
PdfPTable tab2 = new PdfPTable(creditNotesDGV.ColumnCount);
tab2.WidthPercentage = 75;
tab2.DefaultCell.Padding = 3;
tab2.HorizontalAlignment = Element.ALIGN_CENTER;
int j = 0;
foreach (DataGridViewColumn column in creditNotesDGV.Columns)
{
j++;
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText,headerFont));
tab2.AddCell(cell);
}
foreach (DataGridViewRow row in creditNotesDGV.SelectedRows.OfType<DataGridViewRow>().OrderBy(s=>s.Index))
{
j = 0;
foreach (DataGridViewCell cell in row.Cells)
{
j++;
tab2.AddCell(new Phrase(cell.Value.ToString(),standardFont));
}
}
PdfPTable _tabl = new PdfPTable(3);
_tabl.WidthPercentage = 75;
_tabl.DefaultCell.Padding = 3;
_tabl.HorizontalAlignment = Element.ALIGN_CENTER;
PdfPCell x1_cell = new PdfPCell(new Phrase(total.ToString(),blankFont));
x1_cell.Colspan=2;
_tabl.AddCell(x1_cell); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
PdfPCell x4_cell = new PdfPCell();
Chunk c = new Chunk(_total.ToString(),headerFont);
c.SetUnderline(1,12);
x4_cell.AddElement(c);
_tabl.AddCell(x4_cell);
doc.Add(tabl);
doc.Add(tab2);
doc.Add(_tabl);
return doc;
}
//Generates the lower end part
public void GenLastPart()
{
iTextSharp.text.Paragraph tot = new iTextSharp.text.Paragraph();
Phrase phrase = new Phrase();
phrase.Add(new Chunk("Total: Rs. ", totalfont));
phrase.Add(new Chunk(String.Format(new CultureInfo( "en-IN", false ), "{0:n}", Convert.ToDouble(amt)), totalfont));
tot.Add(phrase);
PdfPTable totTbl = new PdfPTable(1);
totTbl.TotalWidth = 200;
PdfPCell tot_cell = new PdfPCell(tot);
tot_cell.Border = iTextSharp.text.Rectangle.TOP_BORDER| iTextSharp.text.Rectangle.BOTTOM_BORDER;
totTbl.AddCell(tot_cell);
totTbl.WriteSelectedRows(0, -1, 290, 190, pwriter.DirectContent);
iTextSharp.text.Paragraph copyright = new iTextSharp.text.Paragraph("Kindly acknowledge receipt of the same.\n\nThanking you,\n\nYours faithfully,\nfor DREAMLAND\n\n\n(Agatha Darkness)", myfont4);
PdfPTable footerTbl = new PdfPTable(1);
footerTbl.TotalWidth = 300;
PdfPCell _cell = new PdfPCell(copyright);
_cell.Border = 0;
footerTbl.AddCell(_cell);
footerTbl.WriteSelectedRows(0, -1, 10, 150, pwriter.DirectContent);
}
I've used iText5 for PDF creation & .Net 4.5. How can I make my code more organized & efficient ? | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
I've used iText5 for PDF creation & .Net 4.5. How can I make my code more organized & efficient ?
Answer: To have a more readable, and flexible code, you need to follow coding best practices. As the current code is not readable; because it lakes a good naming convention. Several names are either short or not clear and might have mixing between global and scoped variables naming conventions. This is my biggest concern. This is a great start of C# Coding Conventions.
for code redundancy, you could use extension methods to extend Document which you can create a simple fluent API that would make thigs much readable, and shorter. So, for insance, you can translate Gen1stTable code into something like this :
document
.AddParagraph("DREAMLAND", titleFont)
.AddParagraph("A Unit Of LA LA LAND", subtitleFont)
.AddParagraph("2/221, Tahira Road, Gr Floor, Rajouri Garden, New Delhi-110069", subtitle2Font)
.AddLineSeparator()
.AddParagraph($"\nDate: {DateTime.Now.ToDefaultStringFormat()}\n\n", smallFont, Alignment.Right);
.AddParagraph($"To\nM/s {customerName}\n{customerCity}\n\n\n\nDear Sir,\n\nPlease find enclosed herewith the payment for Rs. {totalAmount.ToDefaultStringFormat()} through paythru of your following bills\n\n", _timesRomanNormal)
.AddTable(billsDGV.ColumnCount, table =>
{
table.AddPhrase(customerName, _tableHeaderFont, 3, Alignment.Center);
})
.AddTable(billsDGV, _tableHeaderFont, new BaseColor(137, 220, 165), _standardFont);
To do this, you can extend Document using extension methods, and customize the methods as it fits your work.
public enum Alignment
{
Undefined = -1,
Left = 0,
Center = 1,
Right = 2,
Justified = 3,
Top = 4,
Middle = 5,
Bottom = 6,
Baseline = 7,
JustifiedAll = 8
} | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
public static class TextSharpHelper
{
public static readonly iTextSharp.text.Font TimesRomanNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
public static readonly iTextSharp.text.Font BlankFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE, BaseColor.WHITE);
public static iTextSharp.text.Document AddParagraph(this iTextSharp.text.Document document, string text, iTextSharp.text.Font font, Alignment alignment = Alignment.Center)
{
var paragraph = new iTextSharp.text.Paragraph(text, font)
{
Alignment = (int)alignment
};
document.Add(paragraph);
return document;
}
public static iTextSharp.text.Document AddLineSeparator(this iTextSharp.text.Document document)
{
var line = new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1);
var lineSeparator = new iTextSharp.text.Paragraph(new iTextSharp.text.Chunk(line));
lineSeparator.SetLeading(0.5F, 0.5F);
document.Add(lineSeparator);
return document;
}
public static iTextSharp.text.pdf.PdfWriter AddTable(this iTextSharp.text.pdf.PdfWriter writer, int columns, int rowStart, int rowEnd, float xPos, float yPos, Action<iTextSharp.text.pdf.PdfPTable> action)
{
var table = new iTextSharp.text.pdf.PdfPTable(columns);
action.Invoke(table);
table.WriteSelectedRows(rowStart, rowEnd, xPos, yPos, writer.DirectContent);
return writer;
}
public static iTextSharp.text.Document AddTable(this iTextSharp.text.Document document, int columns, Action<iTextSharp.text.pdf.PdfPTable> action)
{
var table = new iTextSharp.text.pdf.PdfPTable(columns)
{
WidthPercentage = 75
};
table.DefaultCell.Padding = 3; | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
table.DefaultCell.Padding = 3;
table.HorizontalAlignment = Element.ALIGN_CENTER;
action.Invoke(table);
document.Add(table);
return document;
}
public static iTextSharp.text.Document AddTable(this iTextSharp.text.Document document, DataGridView gridView, iTextSharp.text.Font headerFont, BaseColor headerBackgroundColor, iTextSharp.text.Font bodyFont)
{
var table = new iTextSharp.text.pdf.PdfPTable(gridView.ColumnCount)
{
WidthPercentage = 75
};
table.DefaultCell.Padding = 3;
table.HorizontalAlignment = Element.ALIGN_CENTER;
foreach (DataGridViewColumn column in gridView.Columns)
{
var cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(column.HeaderText, headerFont))
{
BackgroundColor = headerBackgroundColor
};
table.AddCell(cell);
}
foreach (DataGridViewRow row in gridView.SelectedRows.OfType<DataGridViewRow>().OrderBy(s => s.Index))
{
foreach (DataGridViewCell cell in row.Cells)
{
table.AddCell(new iTextSharp.text.Phrase(cell.Value.ToString(), bodyFont));
}
}
document.Add(table);
return document;
}
public static iTextSharp.text.pdf.PdfPTable AddEmptyCell(this iTextSharp.text.pdf.PdfPTable table, int colspan)
{
var cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(string.Empty, BlankFont))
{
HorizontalAlignment = Element.ALIGN_CENTER,
Colspan = colspan
};
table.AddCell(cell);
return table;
} | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
table.AddCell(cell);
return table;
}
public static iTextSharp.text.pdf.PdfPTable AddPhrase(this iTextSharp.text.pdf.PdfPTable table, string text, iTextSharp.text.Font font, int colspan, Alignment alignment = Alignment.Center)
{
var cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(text, font))
{
Colspan = colspan,
HorizontalAlignment = (int)alignment
};
table.AddCell(cell);
return table;
}
public static iTextSharp.text.pdf.PdfPTable AddPhrase(this iTextSharp.text.pdf.PdfPTable table, string text, iTextSharp.text.Font font, Action<iTextSharp.text.pdf.PdfPCell, iTextSharp.text.Phrase> action)
{
var phrase = new iTextSharp.text.Phrase(text, font);
var cell = new iTextSharp.text.pdf.PdfPCell();
action.Invoke(cell, phrase);
cell.Column.AddText(phrase);
table.AddCell(cell);
return table;
}
public static iTextSharp.text.pdf.PdfPTable AddStrongUnderlinedPhrase(this iTextSharp.text.pdf.PdfPTable table, string text, iTextSharp.text.Font font)
{
var cell = new iTextSharp.text.pdf.PdfPCell();
var chunck = new iTextSharp.text.Chunk(text, font);
chunck.SetUnderline(1, 12);
cell.AddElement(chunck);
table.AddCell(cell);
return table;
}
}
Element.ALIGN_xxx are just integers, so we can use enum as a replacement to increase the readability. That's why I did Alignment enum.
The other helpful extensions that you may need are Formatting and DataGridView extension methods.
public static class FormatExtensions
{
public static string ToDefaultStringFormat(this decimal number)
{
return number.ToString("N2", new CultureInfo("en-IN", false));
}
public static string ToDefaultStringFormat(this DateTime date)
{
return date.ToString("dd-MMM-yyyy");
}
} | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
}
public static class DataGridViewExtensions
{
public static decimal SumSelectedRows(this DataGridView gridView, int cellIndex)
{
return gridView.SelectedRows.OfType<DataGridViewRow>().Sum(t => Convert.ToDecimal(t.Cells[cellIndex].Value));
}
}
Now, the only thing left is just to try reduce code redundancy by following the same ideas, and if there are multiple places that you see there are some repeated strings or code, then it's time to unify them into one place and reuse them.
The other thing that I should not out, Document implements IDisposal so you should use using clause on it to dispose it correctly.
here is a revised sample of your code (not tested, but it should give you the boost you're looking for) :
/// <summary>
/// Description of TextSharpExample.
/// </summary>
public class TextSharpExample
{
private readonly iTextSharp.text.Font _timesRomanNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
private readonly iTextSharp.text.Font _tableHeaderFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
private readonly iTextSharp.text.Font _helveticaFontSamllStandard = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
/// <summary>
/// Generates the document's header
/// </summary>
/// <param name="document"></param>
private void GenerateHeader(iTextSharp.text.Document document)
{
var titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 20, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
var subtitleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 14, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
var subtitle2Font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 11, iTextSharp.text.Font.NORMAL, BaseColor.RED);
var smallFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
document
.AddParagraph("DREAMLAND", titleFont)
.AddParagraph("A Unit Of LA LA LAND", subtitleFont)
.AddParagraph("2/221, Tahira Road, Gr Floor, Rajouri Garden, New Delhi-110069", subtitle2Font)
.AddLineSeparator()
.AddParagraph(string.Format("\nDate:{0}\n\n", DateTime.Now.ToDefaultStringFormat()), smallFont, Alignment.Right);
}
/// <summary>
/// For generating the Bills and Credits tables
/// </summary>
/// <param name="document"></param>
/// <param name="gridView"></param>
/// <param name="total"></param>
/// <param name="headerText"></param>
/// <param name="primaryHeaderBackgroundColor"></param>
/// <param name="secondaryHeaderBackgroundColor"></param>
/// <returns></returns>
private iTextSharp.text.Document GenerateTable(iTextSharp.text.Document document, DataGridView gridView, decimal total, string headerText, BaseColor primaryHeaderBackgroundColor, BaseColor secondaryHeaderBackgroundColor)
{
if (gridView.SelectedRows.Count > 0)
{
var columnsCount = gridView.Columns.Count; | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
// Generate bills table
return document
.AddTable(columnsCount, table =>
{
table.AddPhrase(headerText, _tableHeaderFont, (cell, phrase) =>
{
cell.BackgroundColor = primaryHeaderBackgroundColor;
cell.Colspan = columnsCount;
cell.HorizontalAlignment = (int)Alignment.Center;
});
})
.AddTable(gridView, _tableHeaderFont, secondaryHeaderBackgroundColor, _helveticaFontSamllStandard)
.AddTable(columnsCount, table =>
{
table
.AddEmptyCell(columnsCount - 1)
.AddStrongUnderlinedPhrase(total.ToDefaultStringFormat(), _tableHeaderFont);
});
} | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
}
return document;
}
/// <summary>
/// Generates the document's body
/// </summary>
/// <param name="document"></param>
/// <param name="customerName"></param>
/// <param name="customerCity"></param>
/// <param name="totalAmount"></param>
private void GenerateBody(iTextSharp.text.Document document, PdfWriter writer, string customerName, string customerCity, DataGridView biilsDataGridView, DataGridView creditNotesDataGridView)
{
var totalBills = biilsDataGridView.SumSelectedRows(2);
var totalCreditNotes = creditNotesDataGridView.SumSelectedRows(2);
var totalAmount = totalBills - totalCreditNotes;
// since it's a long string, declaring it in a local variable will improve readibility.
var bodyStartParagraph = string.Format("To\nM/s {0}\n{1}\n\n\n\nDear Sir,\n\nPlease find enclosed herewith the payment for Rs. {2} through paythru of your following bills\n\n", customerName, customerCity, totalAmount.ToDefaultStringFormat());
// Generate body's paragraph
document.AddParagraph(bodyStartParagraph, _timesRomanNormal, Alignment.Left);
// Generate bills table
GenerateTable(document, biilsDataGridView, totalBills, customerName, new BaseColor(255, 255, 30), new BaseColor(137, 220, 165));
// Generate credits table
GenerateTable(document, creditNotesDataGridView, totalCreditNotes, "Less Credit Note/Debit Note", BaseColor.WHITE, BaseColor.WHITE);
// Generate the end of document
writer.AddTable(1, 0, -1, 290, 190, table =>
{
table.TotalWidth = 200;
var totalPhrase = string.Format("Total: Rs. {0}", totalAmount.ToDefaultStringFormat()); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
table.AddPhrase(totalPhrase, new Font(Font.FontFamily.TIMES_ROMAN, 12f, Font.BOLD), (cell, phrase) =>
{
cell.Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
});
})
.AddTable(1, 0, -1, 10, 150, table =>
{
table.TotalWidth = 300;
var appreciationPhrase = "Kindly acknowledge receipt of the same.\n\nThanking you,\n\nYours faithfully,\nfor DREAMLAND\n\n\n(Agatha Darkness)";
table.AddPhrase(appreciationPhrase, _timesRomanNormal, (cell, phrase) =>
{
cell.Border = 0;
});
});
}
public void GenerateDocument(string filePath, string customerName, string customerCity, DataGridView biilsDataGridView, DataGridView creditNotesDataGridView)
{
var document = new iTextSharp.text.Document(PageSize.A4, 20f, 20f, 30f, 30f);
var fileStream = new System.IO.FileStream(filePath, FileMode.Create);
var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fileStream);
try
{
// Open the document to enable you to write to the document
document.Open();
// Add a simple and wellknown phrase to the document in a flow layout manner
GenerateHeader(document);
GenerateBody(document, writer, customerName, customerCity, biilsDataGridView, creditNotesDataGridView);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
// .NET 4.5 support
if (document != null)
{
document.Dispose();
}
if (writer != null)
{
writer.Dispose();
}
if (fileStream != null)
{
fileStream.Dispose();
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
c#, winforms, pdf
}
}
Usage :
var invoice = new TextSharpExample();
var filePath = @"F:\test.pdf";
invoice.GenerateDocument(filePath, kryptonComboBox1.Text, lblCity.Text, billsDGV, creditNotesDGV);
Process.Start(filePath); | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
python, numpy, matplotlib
Title: Calculating quantiles of timeseries data and then create a "fanplot"
Question: My code is working properly, but I am looking for better approach in the calculation of quantiles and the finding of the data in the dataframe.
import datetime
import pandas
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import seaborn as sns
import matplotlib.pyplot as plt
colnames = ['Date', 'Energy']
df_1 = pd.read_csv('WTPV_Spring_2016.csv', names = colnames , encoding="utf8", delimiter=";")
start_date = datetime(2022, 9, 27, 1, 0)
end_date = datetime(2022, 9, 28, 1, 0)
def daterange(start_date, end_date):
delta = timedelta(hours = 1)
while start_date < end_date:
yield start_date
start_date += delta
df = pd.DataFrame(columns =
['Time','pct0.1','pct0.2','pct0.3','pct0.4','pct0.5','pct0.6','pct0.7','pct0.8','pct0.9'])
for single_date in daterange(start_date, end_date):
df.loc[single_date, ['Time']] = single_date.strftime("%H:%M:%S")
x = []
for index in df.index:
y = df_1.loc[df_1['Date'].str.contains(df['Time'][index])]
for i in np.arange(1, 10, 1)/10:
x.append(y.quantile(i))
pct = pd.DataFrame(x, columns = ['Energy'])
df['pct0.1'] = pct.loc[0.1].values
df['pct0.2'] = pct.loc[0.2].values
df['pct0.3'] = pct.loc[0.3].values
df['pct0.4'] = pct.loc[0.4].values
df['pct0.5'] = pct.loc[0.5].values
df['pct0.6'] = pct.loc[0.6].values
df['pct0.7'] = pct.loc[0.7].values
df['pct0.8'] = pct.loc[0.8].values
df['pct0.9'] = pct.loc[0.9].values
sns.set(font_scale = 1.5, style = "white")
fig, ax = plt.subplots(figsize = (8, 6))
xs = np.arange(len(df))
colors = plt.cm.Greens(np.linspace(0.1, 0.6, 5))
for lower, upper, color in zip([f'pct0.{i}' for i in range(1, 5)], [f'pct0.{i}' for i in range(9, 5, -1)], colors):
ax.fill_between(xs, df[lower], df[upper], color = color, label = lower + '-' + upper) | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
ax.plot(xs, df['pct0.5'], color = 'black' , lw = 1.5, label ='Median')
ax.set_xticks(xs)
ax.set_xticklabels(df['Time'], fontsize = 11)
ax.margins(x = 0)
ax.set_ylim(ymin = 0)
for sp in ['top', 'right']:
ax.spines[sp].set_visible(True)
plt.xticks(rotation = 90)
plt.yticks(fontsize = 11)
plt.title('WT & PV Spring 2016', fontsize = 15)
plt.ylabel('Energy MWh', fontsize = 12)
plt.xlabel('Time', fontsize = 12)
plt.ylim([0, 3200])
plt.show() | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
My data have a format like this:
2016/09/01 00:00:00;0
2016/09/01 01:00:00;0
2016/09/01 02:00:00;0
2016/09/01 03:00:00;0
2016/09/01 04:00:00;0
2016/09/01 05:00:00;0
2016/09/01 06:00:00;0
2016/09/01 07:00:00;0
2016/09/01 08:00:00;103
2016/09/01 09:00:00;420
2016/09/01 10:00:00;837
2016/09/01 11:00:00;1213
2016/09/01 12:00:00;1470
2016/09/01 13:00:00;1594
2016/09/01 14:00:00;1609
2016/09/01 15:00:00;1506
2016/09/01 16:00:00;1288
2016/09/01 17:00:00;994
2016/09/01 18:00:00;645
2016/09/01 19:00:00;309
2016/09/01 20:00:00;72
2016/09/01 21:00:00;0
2016/09/01 22:00:00;0
2016/09/01 23:00:00;0
2016/09/02 00:00:00;0
2016/09/02 01:00:00;0
2016/09/02 02:00:00;0
2016/09/02 03:00:00;0
2016/09/02 04:00:00;0
2016/09/02 05:00:00;0
2016/09/02 06:00:00;0
2016/09/02 07:00:00;0
2016/09/02 08:00:00;94
2016/09/02 09:00:00;376
2016/09/02 10:00:00;745
2016/09/02 11:00:00;1085
2016/09/02 12:00:00;1341
2016/09/02 13:00:00;1496
2016/09/02 14:00:00;1527
2016/09/02 15:00:00;1457
2016/09/02 16:00:00;1286
2016/09/02 17:00:00;1005
2016/09/02 18:00:00;659
2016/09/02 19:00:00;326
2016/09/02 20:00:00;76
2016/09/02 21:00:00;0
2016/09/02 22:00:00;0
2016/09/02 23:00:00;0
2016/09/03 00:00:00;0
2016/09/03 01:00:00;0
2016/09/03 02:00:00;0
2016/09/03 03:00:00;0
2016/09/03 04:00:00;0
2016/09/03 05:00:00;0
2016/09/03 06:00:00;0
2016/09/03 07:00:00;0
2016/09/03 08:00:00;100
2016/09/03 09:00:00;418
2016/09/03 10:00:00;840
2016/09/03 11:00:00;1220
2016/09/03 12:00:00;1483
2016/09/03 13:00:00;1622
2016/09/03 14:00:00;1648
2016/09/03 15:00:00;1568
2016/09/03 16:00:00;1374
2016/09/03 17:00:00;1086
2016/09/03 18:00:00;726
2016/09/03 19:00:00;355
2016/09/03 20:00:00;78
2016/09/03 21:00:00;0
2016/09/03 22:00:00;0
2016/09/03 23:00:00;0
2016/09/04 00:00:00;0
2016/09/04 01:00:00;0
2016/09/04 02:00:00;0
2016/09/04 03:00:00;0
2016/09/04 04:00:00;0
2016/09/04 05:00:00;0
2016/09/04 06:00:00;0
2016/09/04 07:00:00;0
2016/09/04 08:00:00;100
2016/09/04 09:00:00;430
2016/09/04 10:00:00;861
2016/09/04 11:00:00;1253 | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
2016/09/04 08:00:00;100
2016/09/04 09:00:00;430
2016/09/04 10:00:00;861
2016/09/04 11:00:00;1253
2016/09/04 12:00:00;1526
2016/09/04 13:00:00;1664
2016/09/04 14:00:00;1688
2016/09/04 15:00:00;1610
2016/09/04 16:00:00;1425
2016/09/04 17:00:00;1138
2016/09/04 18:00:00;762
2016/09/04 19:00:00;371
2016/09/04 20:00:00;79
2016/09/04 21:00:00;0
2016/09/04 22:00:00;0
2016/09/04 23:00:00;0
2016/09/05 00:00:00;0
2016/09/05 01:00:00;0
2016/09/05 02:00:00;0
2016/09/05 03:00:00;0
2016/09/05 04:00:00;0
2016/09/05 05:00:00;0
2016/09/05 06:00:00;0
2016/09/05 07:00:00;0
2016/09/05 08:00:00;98
2016/09/05 09:00:00;430
2016/09/05 10:00:00;865
2016/09/05 11:00:00;1263
2016/09/05 12:00:00;1539
2016/09/05 13:00:00;1673
2016/09/05 14:00:00;1697
2016/09/05 15:00:00;1603
2016/09/05 16:00:00;1384
2016/09/05 17:00:00;1078
2016/09/05 18:00:00;696
2016/09/05 19:00:00;320
2016/09/05 20:00:00;63
2016/09/05 21:00:00;0
2016/09/05 22:00:00;0
2016/09/05 23:00:00;0
2016/09/06 00:00:00;0
2016/09/06 01:00:00;0
2016/09/06 02:00:00;0
2016/09/06 03:00:00;0
2016/09/06 04:00:00;0
2016/09/06 05:00:00;0
2016/09/06 06:00:00;0
2016/09/06 07:00:00;0
2016/09/06 08:00:00;64
2016/09/06 09:00:00;252
2016/09/06 10:00:00;491
2016/09/06 11:00:00;718
2016/09/06 12:00:00;855
2016/09/06 13:00:00;920
2016/09/06 14:00:00;937
2016/09/06 15:00:00;831
2016/09/06 16:00:00;650
2016/09/06 17:00:00;478
2016/09/06 18:00:00;288
2016/09/06 19:00:00;128
2016/09/06 20:00:00;26
2016/09/06 21:00:00;0
2016/09/06 22:00:00;0
2016/09/06 23:00:00;0
2016/09/07 00:00:00;0
2016/09/07 01:00:00;0
2016/09/07 02:00:00;0
2016/09/07 03:00:00;0
2016/09/07 04:00:00;0
2016/09/07 05:00:00;0
2016/09/07 06:00:00;0
2016/09/07 07:00:00;0
2016/09/07 08:00:00;43
2016/09/07 09:00:00;172
2016/09/07 10:00:00;353
2016/09/07 11:00:00;537
2016/09/07 12:00:00;708
2016/09/07 13:00:00;913
2016/09/07 14:00:00;1011
2016/09/07 15:00:00;1002
2016/09/07 16:00:00;969
2016/09/07 17:00:00;797
2016/09/07 18:00:00;508
2016/09/07 19:00:00;238
2016/09/07 20:00:00;47 | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
2016/09/07 17:00:00;797
2016/09/07 18:00:00;508
2016/09/07 19:00:00;238
2016/09/07 20:00:00;47
2016/09/07 21:00:00;0
2016/09/07 22:00:00;0
2016/09/07 23:00:00;0
2016/09/08 00:00:00;0
2016/09/08 01:00:00;0
2016/09/08 02:00:00;0
2016/09/08 03:00:00;0
2016/09/08 04:00:00;0
2016/09/08 05:00:00;0
2016/09/08 06:00:00;0
2016/09/08 07:00:00;0
2016/09/08 08:00:00;60
2016/09/08 09:00:00;247
2016/09/08 10:00:00;477
2016/09/08 11:00:00;692
2016/09/08 12:00:00;870
2016/09/08 13:00:00;1040
2016/09/08 14:00:00;1105
2016/09/08 15:00:00;1033
2016/09/08 16:00:00;905
2016/09/08 17:00:00;701
2016/09/08 18:00:00;444
2016/09/08 19:00:00;215
2016/09/08 20:00:00;42
2016/09/08 21:00:00;0
2016/09/08 22:00:00;0
2016/09/08 23:00:00;0
2016/09/09 00:00:00;0
2016/09/09 01:00:00;0
2016/09/09 02:00:00;0
2016/09/09 03:00:00;0
2016/09/09 04:00:00;0
2016/09/09 05:00:00;0
2016/09/09 06:00:00;0
2016/09/09 07:00:00;0
2016/09/09 08:00:00;60
2016/09/09 09:00:00;276
2016/09/09 10:00:00;555
2016/09/09 11:00:00;809
2016/09/09 12:00:00;995
2016/09/09 13:00:00;1124
2016/09/09 14:00:00;1160
2016/09/09 15:00:00;1103
2016/09/09 16:00:00;979
2016/09/09 17:00:00;769
2016/09/09 18:00:00;487
2016/09/09 19:00:00;220
2016/09/09 20:00:00;39
2016/09/09 21:00:00;0
2016/09/09 22:00:00;0
2016/09/09 23:00:00;0
2016/09/10 00:00:00;0
2016/09/10 01:00:00;0
2016/09/10 02:00:00;0
2016/09/10 03:00:00;0
2016/09/10 04:00:00;0
2016/09/10 05:00:00;0
2016/09/10 06:00:00;0
2016/09/10 07:00:00;0
2016/09/10 08:00:00;65
2016/09/10 09:00:00;310
2016/09/10 10:00:00;629
2016/09/10 11:00:00;925
2016/09/10 12:00:00;1152
2016/09/10 13:00:00;1310
2016/09/10 14:00:00;1349
2016/09/10 15:00:00;1265
2016/09/10 16:00:00;1096
2016/09/10 17:00:00;845
2016/09/10 18:00:00;531
2016/09/10 19:00:00;240
2016/09/10 20:00:00;41
2016/09/10 21:00:00;0
2016/09/10 22:00:00;0
2016/09/10 23:00:00;0
2016/09/11 00:00:00;0
2016/09/11 01:00:00;0
2016/09/11 02:00:00;0
2016/09/11 03:00:00;0
2016/09/11 04:00:00;0
2016/09/11 05:00:00;0
2016/09/11 06:00:00;0 | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
2016/09/11 03:00:00;0
2016/09/11 04:00:00;0
2016/09/11 05:00:00;0
2016/09/11 06:00:00;0
2016/09/11 07:00:00;0
2016/09/11 08:00:00;73
2016/09/11 09:00:00;359
2016/09/11 10:00:00;726
2016/09/11 11:00:00;1066
2016/09/11 12:00:00;1305
2016/09/11 13:00:00;1443
2016/09/11 14:00:00;1472
2016/09/11 15:00:00;1386
2016/09/11 16:00:00;1197
2016/09/11 17:00:00;914
2016/09/11 18:00:00;569
2016/09/11 19:00:00;254
2016/09/11 20:00:00;41
2016/09/11 21:00:00;0
2016/09/11 22:00:00;0
2016/09/11 23:00:00;0
2016/09/12 00:00:00;0
2016/09/12 01:00:00;0
2016/09/12 02:00:00;0
2016/09/12 03:00:00;0
2016/09/12 04:00:00;0
2016/09/12 05:00:00;0
2016/09/12 06:00:00;0
2016/09/12 07:00:00;0
2016/09/12 08:00:00;66
2016/09/12 09:00:00;337
2016/09/12 10:00:00;695
2016/09/12 11:00:00;1041
2016/09/12 12:00:00;1310
2016/09/12 13:00:00;1478
2016/09/12 14:00:00;1510
2016/09/12 15:00:00;1426
2016/09/12 16:00:00;1241
2016/09/12 17:00:00;952
2016/09/12 18:00:00;595
2016/09/12 19:00:00;265
2016/09/12 20:00:00;42
2016/09/12 21:00:00;0
2016/09/12 22:00:00;0
2016/09/12 23:00:00;0
2016/09/13 00:00:00;0
2016/09/13 01:00:00;0 | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
Answer: You don't strictly need Seaborn for what you're doing.
Prefer to express your column names as an immutable tuple.
You should tell read_csv to do actual date parsing right off the hop. Your daterange method and your start_date and end_date should not be necessary. As much as possible, use "real" Numpy/Pandas/Matplotlib datetime support, rather than stringy manipulation (contains, etc.). There are some annoying gaps that have to be hacked around, but overall this can be dragged into a workable state.
Add PEP484 type hints.
You should not need to hard-code an entire list of percentiles (i.e. pct0.1, etc.) and this should be done in a loop. Once properly abstracted, you'll find that you aren't limited to ten quantiles - you could just as easily use 20 or more. This should be explained in your graph with a side colour bar.
Don't arange/10; use linspace instead.
Don't call quantile() once for each of your quantiles; instead call it once passing the entire array for this operation to vectorise.
I don't think it's appropriate to set xs, the horizontal axis of your plot, to be an arange over the entire dataframe: instead, you should apply grouping over the time.
Avoid calling plt.* functions when more direct and explicit ax.* and fig.* methods are available.
I find the automatic y-limits to fit somewhat better than your hard-coded 3200.
This may sound radical, but you should replace your Greens with a perceptually uniform colour map. I've shown a common one - viridis - but there are others. If you want to learn more, this is a fairly deep rabbit hole but fascinating reading material. Long story short, such a colour map is a higher-fidelity human-computer interface.
Suggested
import numpy as np
from datetime import datetime, date, time
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.cm import ScalarMappable, get_cmap
from matplotlib.dates import DateFormatter
from pandas.core.groupby import SeriesGroupBy | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
def load_data(
filename: str = 'WTPV_Spring_2016.csv',
) -> pd.DataFrame:
"""
Load the indicated CSV, parsing dates.
"""
return pd.read_csv(
filepath_or_buffer=filename,
names=('Date', 'Energy'), parse_dates=[0],
encoding='utf8', delimiter=';',
)
def make_quantiles(
df: pd.DataFrame,
quantiles: np.ndarray,
) -> pd.Series:
"""
Apply the given quantiles over time groups. The input quantiles are assumed
to include 0 and 1 but these are not included in the calculation.
The output is a series with a multi-level index: time, quantile. For plot
compatibility the time is represented as a time of day on Jan 1 1970.
"""
fake_date = date(1970, 1, 1)
def dt_to_time(t: time) -> datetime:
return datetime.combine(fake_date, t)
times = df.Date.dt.time.apply(dt_to_time)
df.set_index(times, inplace=True)
by_time: SeriesGroupBy = df.Energy.groupby(level=0)
bands = by_time.quantile(quantiles[1:-1])
bands.index.names = ('Time', 'Quantile')
return bands
def plot(quantiles: np.ndarray, bands: pd.Series) -> plt.Figure:
"""
Plot the given quantile bands as filled regions with an associated colour
bar. The colour bar shows only the first half of the quantile range; the
second half is symmetric and implied.
"""
fig, ax = plt.subplots()
ax.set_title('WT & PV Spring 2016')
ax.set_xlabel('Time')
ax.set_ylabel('Energy (MWh)')
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
map = ScalarMappable(
cmap=get_cmap('viridis'),
norm=plt.Normalize(vmin=0, vmax=0.5),
)
ax.set_facecolor(map.to_rgba(0))
fig.colorbar(map, label='quantile') | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
python, numpy, matplotlib
counterposed_quantiles = np.vstack((
quantiles[1: len(quantiles)//2],
quantiles[-2: len(quantiles)//2: -1],
)).T
for q0, q1 in counterposed_quantiles:
y0 = bands.loc[:, q0]
x = y0.index
y1 = bands.loc[x, q1]
ax.fill_between(x, y0, y1, color=map.to_rgba(q0))
q = 0.5
y = bands.loc[:, q]
x = y.index
ax.plot(x, y, color=map.to_rgba(q))
return fig
def main() -> None:
quantiles = np.linspace(0, 1, 41)
data = load_data()
bands = make_quantiles(data, quantiles)
plot(quantiles, bands)
plt.show()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 42898,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, matplotlib",
"url": null
} |
c#, logging, .net-core, entity-framework-core
Title: EFCore Monitor Interceptor with logging queries
Question: I created a SqlMonitorInterceptor that will check the execution time of queries and log errors. The main idea is to log queries in such a way that they can be easily copied into SQL Server Management Studio and executed.
SqlMonitorInterceptor:
using System;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
namespace WebApplication.Data
{
public class SqlMonitorInterceptor : DbCommandInterceptor
{
private readonly ILogger<SqlMonitorInterceptor> logger;
public SqlMonitorInterceptor(ILogger<SqlMonitorInterceptor> logger)
{
this.logger = logger;
}
public override void CommandFailed(DbCommand command, CommandErrorEventData eventData)
{
if (eventData.Exception is not null)
{
logger.LogError(eventData.Exception, "Command:\r\n{Command}\r\nfailed with Exception.", GetGeneratedQuery(command));
}
}
public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData, CancellationToken cancellationToken = default)
{
CommandFailed(command, eventData);
return Task.CompletedTask;
}
public override int NonQueryExecuted(DbCommand command, CommandExecutedEventData eventData, int result)
{
CommandExecuted(eventData);
return result;
}
public override ValueTask<int> NonQueryExecutedAsync(DbCommand command, CommandExecutedEventData eventData, int result, CancellationToken cancellationToken = default)
{
CommandExecuted(eventData);
return new ValueTask<int>(result);
} | {
"domain": "codereview.stackexchange",
"id": 42899,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, .net-core, entity-framework-core",
"url": null
} |
c#, logging, .net-core, entity-framework-core
return new ValueTask<int>(result);
}
public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
{
CommandExecuted(eventData);
return result;
}
public override ValueTask<DbDataReader> ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default)
{
CommandExecuted(eventData);
return new ValueTask<DbDataReader>(result);
}
public override object ScalarExecuted(DbCommand command, CommandExecutedEventData eventData, object result)
{
CommandExecuted(eventData);
return result;
}
public override ValueTask<object> ScalarExecutedAsync(DbCommand command, CommandExecutedEventData eventData, object result, CancellationToken cancellationToken = default)
{
CommandExecuted(eventData);
return new ValueTask<object>(result);
}
private void CommandExecuted(CommandExecutedEventData eventData)
{
// Log command if non-async.
if (!eventData.IsAsync)
{
logger.LogWarning("Non-async command used:\r\n{Command}", GetGeneratedQuery(eventData.Command));
}
// Log command if too slow.
if (eventData.Duration > AppConfiguration.SqlPerformance_WarningThreshold)
{
logger.LogDebug("Query time ({Duration}ms) exceeded the threshold of {Threshold}ms. Command:\r\n{Command}",
eventData.Duration.TotalMilliseconds,
AppConfiguration.SqlPerformance_WarningThreshold.TotalMilliseconds,
GetGeneratedQuery(eventData.Command));
}
} | {
"domain": "codereview.stackexchange",
"id": 42899,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, .net-core, entity-framework-core",
"url": null
} |
c#, logging, .net-core, entity-framework-core
private static string GetGeneratedQuery(DbCommand command)
{
var quotedParameterTypes = new DbType[] {
DbType.Date, DbType.DateTime, DbType.DateTime2, DbType.DateTimeOffset,
DbType.Guid, DbType.AnsiString, DbType.String,
DbType.AnsiStringFixedLength, DbType.StringFixedLength
};
var sb = new StringBuilder();
foreach (DbParameter p in command.Parameters)
{
sb.Append($"DECLARE {p.ParameterName}");
sb.Append(' ');
if (p is SqlParameter sqlParameter)
{
sb.Append(sqlParameter.SqlDbType.ToString().ToLower());
}
else
{
sb.Append(p.DbType.ToString().ToLower());
}
if (p.Size > 0)
{
sb.Append("(" + (p.Size > 4000 ? "max" : p.Size.ToString()) + ")");
}
else if (p.Precision > 0)
{
sb.Append("(" + p.Precision.ToString() + (p.Scale > 0 ? "," + p.Scale.ToString() : "") + ")");
}
sb.Append(' ');
string pValStr = quotedParameterTypes.Contains(p.DbType) ? $"'{p.Value}'" : p.Value.ToString();
sb.Append($"= {pValStr};");
sb.AppendLine();
}
sb.AppendLine();
sb.Append(command.CommandText);
return sb.ToString();
}
}
}
Example of generated log:
Query time (878.28ms) exceeded the threshold of 500ms. Command:
DECLARE @__8__locals1_entityDB_Id_0 int = 1094610;
DECLARE @__8__locals1_entityDB_CustomerId_1 uniqueidentifier = 'f47253a5-d660-4faf-408d-08d833e8e27b';
DECLARE @__phone_2 nvarchar(63) = '+79991111111'; | {
"domain": "codereview.stackexchange",
"id": 42899,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, .net-core, entity-framework-core",
"url": null
} |
c#, logging, .net-core, entity-framework-core
SELECT COUNT(*)
FROM [Leads] AS [l]
WHERE (([l].[Id] <> @__8__locals1_entityDB_Id_0) AND ([l].[CustomerId] = @__8__locals1_entityDB_CustomerId_1)) AND ((@__phone_2 LIKE N'') OR (CHARINDEX(@__phone_2, [l].[PhoneNumbers]) > 0))
Do you see any improvement / issue?
Answer: CommandFailed
I would suggest to check whether the eventData is not null as well, not just its Exception
Minor, but with the log severity (LogError) you have already indicated that the command has failed with an exception
So the log message might contain facts that are already part of the log itself
CommandFailedAsync
Always returning with Task.CompletedTask might not be the best solution for all scenarios
For example if the cancellationToken has been already requested for cancellation then it might make sense to return with a canceled task as well to bubble up the cancellation fact
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: Task.CompletedTask
CommandExecuted
It might make sense to have two separate versions of this method
One for the sync methods and another for the async ones
It might make sense to use >= whenever you check Duration against threshold
With that you would log those methods as well which are reached the limit not just those which are exceeded
GetGeneratedQuery
The quotedParameterTypes collection could be declared as a static class level member
Naming a stringBuilder to sb might seem really handy but adding more meaningful name like commandStringBuilder would increase legibility
Yet again naming an iteration variable to p might not be the best choice
The first if-else block could be simplified with a conditional operator
sb.Append(dbParam is SqlParameter sqlParameter
? sqlParameter.SqlDbType.ToString().ToLower()
: dbParam.DbType.ToString().ToLower()); | {
"domain": "codereview.stackexchange",
"id": 42899,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, .net-core, entity-framework-core",
"url": null
} |
c#, logging, .net-core, entity-framework-core
p.Size > 4000: It might make sense to introduce a class level constant for this magic number or make it configurable
Inside the second if-else if block you could also use string interpolation instead of concatenation
With that you could avoid to write the .ToString() everywhere
Based on its name I have no idea what is pValStr | {
"domain": "codereview.stackexchange",
"id": 42899,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, .net-core, entity-framework-core",
"url": null
} |
python, array, numpy, combinatorics
Title: Minimum re-labeling to make an array as close as possible to another one
Question: I have an array with integer labels in [0, n-1], say arr1=[1, 0, 3, 2] with n = 3. And then I have another array again with integer labels in [0, n-1], say arr2=[0, 0, 2, 3]. How can I find the minimum re-labeling of arr2 in order to make it as close as possible to arr1 in terms of number of nonzero elements of their difference? For example, here the new arr2 is arr2* = [0, 0, 3, 2].
Here is the code that I'm already using:
from itertools import permutations
import numpy as np
arr1 = np.array([1, 0, 3, 2])
n_labels = 4
perms = list(permutations(np.arange(n_labels)))
arr2 = np.array([0, 0, 2, 3])
best_perm = None
best_err = 1e8
for perm in perms:
arr2_new = [perm[el] for el in arr2]
err = np.linalg.norm(arr2_new - arr1, ord = 0)
if err < best_err:
best_err = err
best_perm = perm
if best_err == 0:
break
arr2_new = [best_perm[el] for el in arr2]
Is there any way to make it more efficient?
UPDATED: Some notes
I need the least number of nonzero elements of arr1-arr2*. That's why I use the l0-norm.
I want a re-labeling scheme: every 0 should become 1, for example, and so on and so forth.
I don't want the positions of the elements of arr2 to change.
I also care about best_perm. Because I have another array, say c = [0.1, 1.1, 2.1, 3.1] in which each element corresponds to a label in arr2. So when I change arr2 to arr2*, I also want to change c to c* = [c[best_perm[j]] for j in range(n_labels)]
The arrays arr1 and arr2 may contain repeating elements. But the elements of both are in [0, n-1].
The solution may not be unique. We are interested in just one of the possible solutions. | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
The solution may not be unique. We are interested in just one of the possible solutions.
Answer: Yes. First of all, your norm() call implies Frobenius: but any kind of least-squares is totally uncalled for in this problem since you just want integer comparison.
To put it lightly, the description of what this is actually supposed to do is troubled. For instance, rather than "labelling" I would call it "substitution". I hope the extended back-and-forth has prepared you for the kind of information reviewers need to know in future questions.
A better algorithm is definitely possible. First, frame the problem as a bipartite graph, where:
the left subset nodes are unique values from the original arr2
the right subset nodes are all possible destination values from 0 through n-1
the graph starts as being complete and unbalanced; the left cardinality will typically be smaller than the right cardinality
the edge weights are non-negative integers representing the number of mismatches between the source and destination
The problem becomes: how do you prune this graph such that
for every left-node, there remains exactly one edge (the left subset becomes 1-regular);
for every right-node, there remains at most one edge;
the graph becomes disconnected and acyclic; and
the edges are chosen such that the total remaining weight is minimised.
This is a known problem - a variant of bipartite maximum matching called Bipartite Min-Cost Perfect Matching, also called the assignment problem. Crucially, the insight from interpreting this as a bipartite matching problem is that it can be solved using mixed-integer linear programming (MIP).
MIP problems are well-understood and have excellent software that already exists to solve them. I recommend glpk and its Python SWIG bindings in swiglpk.
In this strategy, | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
c, the cost vector, will be non-negative integers capturing your edge weights
z, the objective, is the total distance
xs, the structural variables/columns, will be a flattened 2d matrix of boolean edge choices
xr, the auxiliary variables/rows, will be the node degree (sum of edge counts per node)
A, the constraint matrix, will be constructed to sum up the node degrees over both axes
xs, when interpreted as a 2D matrix, must be constrained to have exactly one nonzero per (source) row, and between 0 and 1 nonzeros per (dest) column. In glpk these are expressed with fixed and double bounds, respectively.
It takes a little bit of code to express all of this, but it's quite worth it: when I run a problem of n=500 on my machine it completes in about two seconds.
Suggested
import random
from collections import defaultdict
from timeit import timeit
from typing import Optional, Iterator
import swiglpk as lp
class OptError(Exception):
pass
def make_map() -> tuple[tuple[int, list[int]], ...]:
"""
From arr1 and arr2, produce an ordered map in tuple-of-pairs format
where the key is the unique source arr2 value, and the values are all
(potentially non-unique) arr1 values to which a match will be attempted.
"""
targets = defaultdict(list)
for source, dest in zip(arr2, arr1):
targets[source].append(dest)
return tuple(targets.items())
def fill_sources() -> None:
"""
For each of our unique arr2 source values,
- Fill some the GLPK problem's "auxiliary rows" of count n_source. These
rows correspond to constraints on the arr2 source values.
- Name those rows and apply fixed bounds: each source must get exactly one
match. | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
For each combination of source and candidate destination,
- Reinterpret the source/destination matrix as a flat, horizontal vector
- Fill all of the GLPK problem's "structural columns" of count
n_source*n_dest.
- Name those columns and set the structural variable type as binary-value.
- Set the corresponding objective coefficient to the mismatch cost of
choosing this pair.
- Populate the constraint matrix to enforce that each source gets one dest,
and every dest gets up to one source
"""
row_indices = lp.intArray(3)
row_values = lp.doubleArray(3)
row_values[1] = row_values[2] = 1
# For each source in the map
for y, (source, dests) in enumerate(target_map):
lp.glp_set_row_name(problem, y+1, f'{source}->')
# First n_source auxiliary rows are fixed-bounded at 1
lp.glp_set_row_bnds(
P=problem, i=y+1, type=lp.GLP_FX, lb=1, ub=1,
)
# For each possible destination (not just those in the map)
for candidate_dest in range(n_dest):
x = y*n_dest + candidate_dest + 1
# This structural variable is a Binary Variable
lp.glp_set_col_kind(problem, x, lp.GLP_BV)
lp.glp_set_col_name(problem, x, f"{source}->{candidate_dest}")
# Objective coefficient is the sum of mismatched elements
cost = sum(
candidate_dest != actual_dest
for actual_dest in dests
)
lp.glp_set_obj_coef(problem, x, cost)
# Set the constraint matrix elements (sparse)
row_indices[1] = 1 + y # sum the sources
row_indices[2] = 1 + n_source + candidate_dest # sum the destinations
lp.glp_set_mat_col(
P=problem, j=x, len=2, ind=row_indices, val=row_values,
) | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
def fill_dests() -> None:
"""
For each of our candidate destination values,
- Fill the rest of the GLPK problem's "auxiliary rows" of count n_dest.
These rows correspond to constraints on the arr1 dest values.
- Name those rows and apply double bounds: each dest must get up to one
match.
"""
# For each possible destination
for candidate_dest in range(n_dest):
y = 1 + n_source + candidate_dest
lp.glp_set_row_name(problem, y, f'->{candidate_dest}')
# Last n_dest auxiliary rows are double-bounded between 0 and 1
lp.glp_set_row_bnds(
P=problem, i=y, type=lp.GLP_DB, lb=0, ub=1,
)
def create() -> None:
"""
Set some problem parameters, including objective characteristics; set the
structural and auxiliary size; call into subroutines to fill all problem
constraints.
"""
lp.glp_set_prob_name(problem, 'proximal_substitution')
lp.glp_set_obj_name(problem, 'distance')
lp.glp_set_obj_dir(problem, lp.GLP_MIN)
lp.glp_add_cols(problem, n_source * n_dest)
lp.glp_add_rows(problem, n_source + n_dest)
fill_sources()
fill_dests()
def check_code(code: int) -> None:
"""
If an optimisation function returned a failure code, attempt to convert
that into a code name and raise an OptError
"""
if code != 0:
codes = {
getattr(lp, k): k
for k in dir(lp)
if k.startswith('GLP_E')
}
raise OptError(f'glpk returned {codes[code]}') | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
def check_status(expected: int, actual: int) -> None:
"""
If an optimisation status is not as expected, attempt to convert the status
into a status name and raise an OptError
"""
if expected != actual:
statuses = {
getattr(lp, f'GLP_{stat}'): stat
for stat in ('OPT', 'FEAS', 'INFEAS', 'NOFEAS', 'UNBND', 'UNDEF')
}
raise OptError(
f'Optimisation failed: status {statuses.get(actual)}'
)
def solve(log_level: int = lp.GLP_MSG_ON) -> None:
"""
Perform a two-pass linear programming solver, with a simplex basis and then
a mixed-integer programming (MIP) discretisation.
"""
# First pass to calculate the basis segment: do not use the default MIP
# pre-solver because we want to use the faster primal method instead of dual
parm = lp.glp_smcp()
lp.glp_init_smcp(parm)
parm.msg_lev = log_level
check_code(lp.glp_simplex(problem, parm))
check_status(lp.GLP_FEAS, lp.glp_get_prim_stat(problem))
check_status(lp.GLP_OPT, lp.glp_get_status(problem))
# Second (very fast) MIP pass
parm = lp.glp_iocp()
lp.glp_init_iocp(parm)
parm.msg_lev = log_level
check_code(lp.glp_intopt(problem, parm))
check_status(lp.GLP_OPT, lp.glp_mip_status(problem))
def construct_substitution() -> Iterator[tuple[int, int]]:
for x in range(n_source * n_dest):
matched = lp.glp_mip_col_val(problem, x+1)
if matched:
i_source, dest = divmod(x, n_dest)
source, _ = target_map[i_source]
yield source, dest
def output(substitution: dict[int, int], log_file: Optional[str] = None) -> None:
if log_file:
lp.glp_print_mip(problem, log_file)
print('arr2, arr1, arr2new:')
print(' '.join(f'{d:3}' for d in arr2))
print(' '.join(f'{d:3}' for d in arr1))
print(' '.join(
f'{substitution[d]:3}'
for d in arr2
)) | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
print(' '.join(
f'{substitution[d]:3}'
for d in arr2
))
def main():
create()
t = timeit(solve, number=1)
print(f'\nSolution in {t:.2}s')
substitution = dict(construct_substitution())
output(substitution)
if __name__ == '__main__':
N = 500
random.seed(0)
arr1 = [random.randrange(N) for _ in range(N)]
arr2 = [random.randrange(N) for _ in range(N)]
target_map = make_map()
n_dest = len(arr1)
n_source = len(target_map)
problem = lp.glp_create_prob()
main() | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
Output
Shown with GLP_MSG_ALL:
GLPK Integer Optimizer 5.0
319 rows, 23800 columns, 47600 non-zeros
23800 integer variables, all of which are binary
Preprocessing...
319 rows, 23800 columns, 47600 non-zeros
23800 integer variables, all of which are binary
Scaling...
A: min|aij| = 1.000e+00 max|aij| = 1.000e+00 ratio = 1.000e+00
Problem data seem to be well scaled
Constructing initial basis...
Size of triangular part is 319
Solving LP relaxation...
GLPK Simplex Optimizer 5.0
319 rows, 23800 columns, 47600 non-zeros
0: obj = 2.000000000e+02 inf = 1.180e+02 (1)
Perturbing LP to avoid stalling [299]...
352: obj = 1.990000000e+02 inf = 0.000e+00 (0)
Removing LP perturbation [796]...
* 796: obj = 1.020000000e+02 inf = 0.000e+00 (0) 2
OPTIMAL LP SOLUTION FOUND
Integer optimization begins...
Long-step dual simplex will be used
+ 796: mip = not found yet >= -inf (1; 0)
+ 796: >>>>> 1.020000000e+02 >= 1.020000000e+02 0.0% (1; 0)
+ 796: mip = 1.020000000e+02 >= tree is empty 0.0% (0; 1)
INTEGER OPTIMAL SOLUTION FOUND
Writing MIP solution to 'problem-log.txt'...
arr2, arr1, arr2new:
89 111 46 15 128 119 10 152 25 179 100 51 66 91 187 120 145 43 178 172 52 196 14 173 40 41 87 135 64 30 152 113 170 44 3 120 174 104 145 130 79 166 91 99 168 64 39 143 176 3 117 189 20 85 189 11 139 71 34 61 195 123 90 156 73 172 91 151 162 158 33 183 79 99 191 106 166 20 0 152 49 178 85 40 61 57 163 114 96 181 172 145 106 8 102 179 145 107 197 169 181 11 42 114 16 66 179 40 114 135 124 143 154 193 0 9 126 83 79 119 12 106 48 140 162 21 185 33 3 102 173 106 80 0 54 3 183 193 0 172 135 156 25 48 30 155 166 50 77 71 176 46 25 121 101 160 20 5 70 115 29 65 34 167 133 166 165 88 29 39 71 4 10 10 52 174 66 142 80 93 145 10 191 179 155 167 126 182 164 117 163 111 95 137 45 53 96 150 74 2 | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
98 194 107 10 66 130 124 103 77 122 91 149 55 129 35 72 35 193 24 158 64 136 180 154 37 79 25 186 18 175 84 120 143 25 90 111 80 156 163 52 141 122 113 133 66 15 140 3 23 184 102 181 171 160 0 156 126 85 62 186 83 180 16 48 145 56 61 36 139 114 23 20 81 130 125 27 77 141 74 180 31 140 85 138 52 154 140 150 73 113 23 152 98 81 147 61 74 47 48 47 8 156 168 66 121 17 22 173 193 33 38 9 20 179 138 174 100 180 134 70 133 60 55 173 150 107 148 70 115 126 169 164 179 91 21 83 156 29 124 150 161 85 48 62 4 187 69 29 180 56 95 43 85 109 15 25 37 178 56 11 146 162 136 154 174 18 6 31 162 48 155 147 30 100 23 94 29 9 155 5 49 47 183 31 122 53 186 15 173 5 139 108 158 25 66 17 56 18 165 77
98 108 43 10 4 70 30 84 48 61 91 149 12 129 35 111 49 193 24 150 64 136 22 169 138 79 26 33 18 175 84 120 143 32 90 111 94 105 49 52 134 69 129 130 40 18 140 3 95 90 102 181 37 160 181 156 126 56 62 186 83 54 16 85 145 150 129 36 139 114 23 20 134 130 125 60 69 37 74 84 46 24 160 138 186 154 68 66 73 113 150 49 60 81 8 61 49 72 75 47 113 156 168 66 121 12 61 138 66 33 38 3 80 179 74 82 100 180 134 70 133 60 55 87 139 107 148 23 90 8 169 60 155 74 21 90 20 179 74 150 33 85 48 55 175 122 69 29 27 56 95 43 48 109 96 25 37 178 99 11 146 162 62 53 174 69 6 31 146 140 56 147 30 30 64 94 12 9 155 5 49 30 125 61 122 53 100 15 173 102 68 108 158 112 199 17 73 116 165 77 | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
python, array, numpy, combinatorics
Abridged Log
Problem: proximal_substitution
Rows: 319
Columns: 23800 (23800 integer, 23800 binary)
Non-zeros: 47600
Status: INTEGER OPTIMAL
Objective: distance = 102 (MINimum)
No. Row name Activity Lower bound Upper bound
------ ------------ ------------- ------------- -------------
1 89-> 1 1 =
2 111-> 1 1 =
3 46-> 1 1 =
4 15-> 1 1 =
5 128-> 1 1 =
...
23796 2->195 * 0 0 1
23797 2->196 * 0 0 1
23798 2->197 * 0 0 1
23799 2->198 * 0 0 1
23800 2->199 * 0 0 1
Integer feasibility conditions:
KKT.PE: max.abs.err = 0.00e+00 on row 0
max.rel.err = 0.00e+00 on row 0
High quality
KKT.PB: max.abs.err = 0.00e+00 on row 0
max.rel.err = 0.00e+00 on row 0
High quality
End of output | {
"domain": "codereview.stackexchange",
"id": 42900,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, numpy, combinatorics",
"url": null
} |
sql
Title: Which one is faster and preferable when doing aggregate function to the data in sql? CASE WHEN or WHERE?
Question: I have following simple sql code to select the number of rows that meet a specific criteria:
SELECT COUNT(CASE WHEN /*condition*/ THEN 1 END) FROM table_name;
Verus
SELECT COUNT(*) FROM table_name WHERE /*condition*/;
Both of them seems to work the same when I only want to do some aggregate function to the data.
I have two questions:
Which one has faster performance speed?
Which one is commonly preferable by developers (when doing aggregate function)?
Thanks for any responds!
Answer: The usual answer to "which way is faster" usually depends on your DB. The way to find out is to use your DB's "explain" tool to see how it's providing the answer to your query.
As to your other question, I've never see COUNT(CASE WHEN /*condition*/ THEN 1 END) in the 30yrs I've been working with DBs.
I had to think about it, to even be sure it'd work. As it relies on an implicit else null and that the count function ignores NULL.
In your case, I'd expect them to be the same for most DB's. However, that's only because I'd expect most DB's to rewrite the query into the same form of
COUNT(*) FROM table_name WHERE /*condition*/
This form of the query can definitely take advantages of indexes, whereas the other form might not. | {
"domain": "codereview.stackexchange",
"id": 42901,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql",
"url": null
} |
java, algorithm, sorting
Title: Insertion Sorting Algorithm
Question: I am new to data structures and algorithms. I have just implemented an insertion sorting algorithm. I just want to make sure if my code is alright.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] test = {40, 1, 5, 0, 9};
for (int i = 0; i < test.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (test[i] < test[j]) {
//swap if i is smaller than j .
int temp = test[j];
test[j] = test[i];
test[i] = temp;
/*we swap the j's value with i.we also have to check the other left items
so we have to make i at the index where we just swapped.*/
i = j;
}
}
}
System.out.println(Arrays.toString(test));
}
} | {
"domain": "codereview.stackexchange",
"id": 42902,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting",
"url": null
} |
java, algorithm, sorting
}
}
Answer: Is it insertion sort
In short, no. But in longer, well it's clearly related to insertion sort, but still no.
This algorithm does the same sequence of swaps that a swap-based insertion sort would do (there is also a move-based version of insertion sort which is more efficient in practice). So that's it, case closed? Actually no, because this algorithm keeps resetting the loop variable of the outer loop, which is a behaviour that is normally not part of insertion sort, and it changes it in a fundamental way.
In terms of number of swaps, this algorithm (unnamed as far as I'm aware) still makes O(nΒ²) swaps in the worst case. But I think it makes O(nΒ³) comparisons, which is significantly worse than insertion sort.
Informally: let's assume the worst, that every next item is inserted all the way at the start of the sorted part of the array. Therefore, i is reset to zero after every insertion. Re-running the algorithm from zero up to the point where it just left off from takes O(nΒ²) comparisons (but zero swaps, because the elements it's running over are already sorted), and since this happens n times, it's O(nΒ³) comparisons in total. (to make that more proper I should say that the sum of iΒ² from i=0 to i=n is a function of n contained in O(nΒ³), but "informally"..)
Does it work though
Yes, but inefficiently.
What would make it insertion sort
If rather than changing i you instead compare and swap the positions j and j+1, the inner loop would do the same thing as it does now but without resetting i. That would make it an O(nΒ²) algorithm that uses insertion as its strategy, so IMO that would qualify as insertion sort. Usually insertion sort is described having the inner loop stop when the comparison is false, but I don't think that continuing would make it not-insertion-sort, that would just make an inefficient implementation of insertion sort. | {
"domain": "codereview.stackexchange",
"id": 42902,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting",
"url": null
} |
python, object-oriented, api, polymorphism
Title: Logistics project that implements several shipping APIs
Question: I have a Python logistic project that implements several shipping APIs using class inheritance. Each of those classes must do three things:
Fire requests to each endpoint with the proper parameters
Serialize and map the original input in order to store it
Finally, produce a document according to the specification of each company
I firstly thought it unmantainable to have all this things together in a single giantic file, despite dealing with so unrelated tasks such as sending HTTP requests and formatting a PDF file. Finally, I've came across this directory structure:
shipment/
shipment.py - primitive Shipment class (for mapping data)
printer.py - primitive Printer class (for producing documents)
controller.py - primitives for sending requests, inherits Shipment and has Printer instance as member
providers/
provider1/
shipment.py - implements shipment.Shipment
printer.py - implements shipment.Printer
controller.py - implements shipment.Controller
provider2/
shipment.py
printer.py
controller.py
As you can see, each shipping provider class has been splitted into 3 separate files. Printer is inherited by Controller, and provides the "summary_to_pdf" method.
shipment/controller.py:
import logging
from abc import ABCMeta, abstractmethod
from datetime import datetime
from os import environ
from bson.objectid import ObjectId
from lib.database import db, ReturnDocument
from lib.model import Shipment, IndividualShipment, Sale | {
"domain": "codereview.stackexchange",
"id": 42903,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, api, polymorphism",
"url": null
} |
python, object-oriented, api, polymorphism
def ProviderClass(mapping_name:str, shipment_class:type, printer_class:type, url:str, packets_limit:int=0, asynchronous:bool=False):
def decorator(cls):
cls.mapping_name = mapping_name
cls.Shipment = shipment_class
cls.Printer = printer_class
cls.url = url
cls.packets_limit = packets_limit
cls.asynchronous = asynchronous
class NewClass(cls, printer_class, ShipmentController):
__name__ = cls.__name__
pass
return NewClass
return decorator
def ProviderInit():
def decorator(init):
def new_init(self, **kwargs):
self.profile = kwargs
self.Printer.__init__(self, **kwargs)
ShipmentController.__init__(self, **kwargs)
init(self, **kwargs)
return new_init
return decorator
class ShipmentHealthException(metaclass=ABCMeta):
def __init__(self, message:str):
self.message = message
def __str__(self):
return f'Shipment health check failed: {message}'
class ShipmentController:
def __init__(self, **kwargs):
self.raw_posting_objects = []
self.logger = logging.getLogger('shipment')
def build_shipment(self, **kwargs):
self.raw_posting_objects = kwargs['posting_objects']
return self.Shipment(**{ **kwargs, **self.profile, 'sender': self.profile['business'] })
def insert(self, shipment, stamp:str, local_id:str, foreign_id:str):
payload = {
'shipment_profile': self.profile['_id'],
'created_at': datetime.now(),
'stamp': stamp,
'local_id': local_id,
'foreign_id': foreign_id,
'objects_count': len(shipment)
}
shipment_id = Shipment.insert(**payload).inserted_id
for s in shipment:
db['sales'].find_one_and_update({ '_id': s['_id'] }, { '$set': { 'shipment': shipment_id } })
return shipment_id | {
"domain": "codereview.stackexchange",
"id": 42903,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, api, polymorphism",
"url": null
} |
python, object-oriented, api, polymorphism
return shipment_id
@classmethod
def _get_id(cls):
return db['shipments'].count_documents({})
@classmethod
def _get_individual_id(cls):
_id = 100000 + db['sales'].count_documents({
'local_individual_shipment_id': {
'$ne': None
}
})
return str(_id)
@staticmethod
def instantiate(provider_mapping, **kwargs):
return provider_mapping[kwargs['provider']['controller']](**kwargs)
@classmethod
def _raise_not_implemented(cls):
raise NotImplementedError('Method not implemented for this provider ({})'.format(cls.__name__))
@abstractmethod
def check_health(self):
'''Checks whether provider is operational or not
Implemented in:
- Correios
'''
self._raise_not_implemented()
@abstractmethod
def get_id(self):
'''Client unique ID for shipment provider
Implemented in:
- Correios
- Jadlog
'''
self._raise_not_implemented()
@abstractmethod
def get_labels(self, **kwargs):
'''Requests provider for label (tracking code) numbers
Implemented in:
- Correios
'''
self._raise_not_implemented()
@abstractmethod
def append_verifier_digit(self, **kwargs):
'''Appends verifier digits in label numbers
Implemented in:
- Correios
'''
self._raise_not_implemented()
@abstractmethod
def get_services(self, save_to_db=False, **kwargs):
'''Asks provider for available shipment services
Implemented in:
- Correios
- Jadlog
'''
self._raise_not_implemented() | {
"domain": "codereview.stackexchange",
"id": 42903,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, api, polymorphism",
"url": null
} |
python, object-oriented, api, polymorphism
def request_already_sent_shipment(self, _list, local_shipment_id, service_id):
unsent = [ sale for sale in _list if not sale.get('individual_shipment') ]
for sale in unsent:
self.request_individual_shipment(sale, sale['_id'])
return local_shipment_id, self.build_shipment(posting_objects=_list)
@abstractmethod
def request_shipment(self, **kwargs):
'''Sends PLP to be acquited by provider
Implemented in:
- Correios
'''
return self.request_already_sent_shipment(**kwargs)
@abstractmethod
def _request_individual_shipment(self, **kwargs):
'''Requests a single object shipment (in case of asynchronous shipment)
Implemented in:
- Jadlog
'''
self._raise_not_implemented()
def request_individual_shipment(self, item:dict, item_id, **kwargs):
query = {
'_id': ObjectId(item_id),
'individual_shipment': None
}
sale = Sale.find_one(**query)
if not sale:
raise Exception('order already dispatched')
foreign_id, code = self._request_individual_shipment(item, **kwargs)
foreign_id = str(foreign_id)
local_id = self._get_individual_id()
individual_shipment = IndividualShipment.insert(local_id=local_id, foreign_id=foreign_id, code=code).inserted_id
item = db['sales'].find_one_and_update({ '_id': sale['_id'] }, { '$set': { 'individual_shipment': individual_shipment } }, return_document=ReturnDocument.AFTER)
return foreign_id, local_id, code
@abstractmethod
def request_updated_shipment(self, **kwargs):
'''Retrieves previous sent PLP
Implemented in:
- Correios
'''
self._raise_not_implemented()
Feel free to make comments overall comments as well. | {
"domain": "codereview.stackexchange",
"id": 42903,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, api, polymorphism",
"url": null
} |
python, object-oriented, api, polymorphism
Feel free to make comments overall comments as well.
Answer: Your code seems reasonable to me, basing your implementation on generic objects that are specialized for specific uses.
What I might do differently is the overall architecture. Is there a need for the functionality to be implemented as a single process? Given the disparate requirements I think I would have structured it as a system of micro-services speaking together over a queuing system (e.g. RabbitMQ). Each program then becomes a simple loop of read input, process the input, based on the process result send the result to the appropriate next processor. The last sub-step of choosing the next processor can be done in a switchboard processor which can additionally provide a view of how well the system is working.
A micro-service architecture will have code that is simplified but your deployment will become more complex since you have to successfully deploy all the micro-service processors to have the system "up". Bringing the system down will require that you first drain all the queues. However a controlled shutdown will require something similar in a unified program if you want to insure that all data read is processed before shutting down. | {
"domain": "codereview.stackexchange",
"id": 42903,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, api, polymorphism",
"url": null
} |
java, object-oriented, design-patterns
Title: How to design planet class so that it is open for changes?
Question: The task is to model a Solar system using OOP. The planets are orbiting and its needs to find distances between planets.
My approach is something like this.
public abstract class SolarSystem {
// TODO
}
public class Planet extends SolarSystem {
private final String name;
private final double x;
private final double y;
public Planet(String name, double x, double y) {
this.name = name;
this.x = x;
this.y = y;
}
public double distanceTo(Planet p) {
return Math.sqrt((p.x - this.x) * (p.x - this.x) + (p.y - this.y) * (p.y - this.y));
}
}
public class Main {
public static void main(String[] args) {
Planet earth = new Planet("Earth", 5.2, 8.3);
Planet mars = new Planet("Mars", 4.3, 2.7);
System.out.println(mars.distanceTo(earth));
}
}
I am stuck with the question of how to design Planet class in a way that it is open for changes?
For example, let's say that the requirements change a bit and two-dimensional space changes to three-dimensional space.
At the moment, my approach supports only one way to calculate distance.
What am I missing here? | {
"domain": "codereview.stackexchange",
"id": 42904,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, design-patterns",
"url": null
} |
java, object-oriented, design-patterns
Answer: I am sorry that you recieved so negative feedback in the comments.
It is true that your code isn't actually modelling any dynamic system which from your description seems to be your goal.
However, your code is working, and can be deemed as first stage prototype.
Maybe you are stuck or want to perfectionate your stage one before going to another stage. And I think it is fair to review your working code in this stage, even if it's not supposed to be final.
So to the review!
There really is no reason why a Planet should extend SolarSystem. If you cannot justify statement "A is B" then never model relation between A and B with inheritance.
I would much rather understand inheritance relation "Planet extends CelestialBody" because a planet is a celestial body.
But anyway in your current code that abstraction is useless. An abstract class or interface with no methods or properties is never of any use.
Now to your concern how to make your class open to be used with any kind of coordinates. You can achieve that with a generic type.
Let me show you how.
First let me first define a separate class for the coordinates x,y. Later you can create a new class for 3D coordinates.
public class Point2D {
public final double x;
public final double y;
public Point2D(double x, double y) {
this.x = x;
this.y = y;
}
public double getDistanceSquare(Point2D other) {
double dx = other.x - this.x;
double dy = other.y - this.y;
return dx * dx + dy * dy;
}
public double getDistance(Point2D other) {
return Math.sqrt(this.getDistanceSquare(other));
}
} | {
"domain": "codereview.stackexchange",
"id": 42904,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, design-patterns",
"url": null
} |
java, object-oriented, design-patterns
Notice that I extracted getDisanceSquare() method separately because it might come handy when you start dealing with for example Newton's law of gravity.
Gravitation force/potential is proportional to distance square and it would be ineffective to compute the square root only to then square the result.
I will rename the Planet class to Pin to just stand for a position with a name, to not imply that it is anything more than that at this point.
public class Pin<TCoordinate> {
public final String name;
public final TCoordinate position;
public Pin(String name, TCoordinate position) {
this.name = name;
this.position = position;
}
}
public class Main {
public static void main(String[] args) {
Pin<Point2D> earth = new Pin<Point2D>("Earth", new Point2D(5.2, 8.3));
Pin<Point2D> mars = new Pin<Point2D>("Mars", new Point2D(4.3, 2.7));
System.out.println(mars.position.getDistance(earth.position));
}
}
Notice that the Pin now does not have it's own distance method. Just use disantce of the positions.
Now when you create a 3D coordinate class. You can just instantiate Pin to create a 3D model of similar kind. And all your code will still work as long as Point3D also has a double getDistance(Point3D other) method.
But remember Pin<Point2D> is not compatible with Pin<Point3D>. They live in separate universes. One lives in a 2 dimensional universe and the other in 3 dimensional one.
One last note, your use of final is good. It makes your classes immutable which is good. But notice, in my implementation i made them public, because eventually you may want to access those values maybe for serialization or for display purpose. Normally you would add getters, but with final props, making them public is just as fine.
PS: The code is not tested and I'm not even a Javist. I hope it's ok but sorry if I messed up somewhere. | {
"domain": "codereview.stackexchange",
"id": 42904,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, design-patterns",
"url": null
} |
c, strings
Title: simple string comparison program in c
Question: I wrote this simple program to compare two strings ,I think it's working properly I just need to confirm that and also have few advices if possible
#include<stdio.h>
// #include<string.h>
int main(){
int value, lenght=0, i=0;
char passwd[11], pass[11]="comptiatar";
printf("enter ur passwd: ");
scanf("%s", passwd);
//value = strcmp(passwd,pass);
while (passwd[i]!=0){
lenght++;
i++;
}
for (i=0;i<=lenght;i++){
if (passwd[i]==pass[i])
value=0;
else {
value=passwd[i]-pass[i];
break;
}
}
if (value)
printf("\nwrong password\n\n");
else
printf("\nlogin successfully\n\n");
printf("%d\n", value);
return 0;}
Answer: Is it really necesary to "reinvent the wheel"? Instead of this:
while (passwd[i]!=0){
lenght++;
i++;
}
could just use:
lenght=strlen(passwd);
And what the problem with just using strcmp? Also you can exit the for loop as soon passwd[i]!=pass[i].
Also what hapens if somebody type password longer then 10 characters? You should make passwd biger or check the return value of scanf. | {
"domain": "codereview.stackexchange",
"id": 42905,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
python, python-3.x, template, pdf
Title: Resume Builder using Jinja Templates and HTML
Question: I have attempted to hack together a CV/Resume builder and I would like a review. The aim is to output a styled PDF containing dynamic fields. I have taken a simple HTML file, an arguably bloated CSS file and the below test dataframe data from online.
Here is the code:
from __future__ import annotations
from typing import ClassVar, Any
import jinja2
import pandas as pd
from random import getrandbits, randint
import pdfkit
from jinja2 import Template
# Just random data
def random_hex(length=10):
return '%0x' % getrandbits(length * 4)
COLS = ['number', 'name', 'data1', 'data2', 'data3']
df = pd.DataFrame(
[
{
"number": randint(0, 100),
"name": random_hex(15),
"data1": random_hex(5),
"data2": random_hex(5),
"data3": random_hex(5)
}
for i in range(10)
]
)[COLS]
class CVBuilder:
TEMPLATE_DIR: ClassVar[str] = "templates"
TEMPLATE_NAME: ClassVar[str] = "cv_template.html"
OUTPUT_DIR: ClassVar[str] = "output.pdf"
CSS_FILE: ClassVar[str] = "cv_template.css"
def __init__(self, cv_content: Any): # TODO
self.content = cv_content
@classmethod
def cv_template(cls) -> Template:
environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(cls.TEMPLATE_DIR)
)
template = environment.get_template(cls.TEMPLATE_NAME)
return template
@classmethod
def build_cv(cls, **kwargs) -> CVBuilder:
cv_template = cls.cv_template()
return cls(cv_template.render(**kwargs))
def to_pdf(self) -> None:
pdfkit.from_string(
input=self.content,
output_path=self.OUTPUT_DIR,
css=self.CSS_FILE
) | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
python, python-3.x, template, pdf
if __name__ == "__main__":
content = df.to_html(index=False, classes="table-title", border=False)
cv = CVBuilder.build_cv(
df=content,
title="Example",
message="This is an example text input"
)
cv.to_pdf()
I think I could probably nuke the ClassVar stuff
I think I could probably use a dataclass
Do I even need a class?
Here is the HTML and CSS:
<link rel="stylesheet" type="text/css" href="cv_template.css"/>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>{{title}}</title>
<meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; width=device-width;">
</head>
<body>
<div class="table-title" align="center">
<h4>{{ title }}</h4>
<p style="font-weight: bold">templating example.</p>
</div>
<div align="center">
{{ df }}
</div>
<p align="center">{{ message }}</p>
</body>
</html>
/*** Most of this CSS is unused in the exaple **/
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100);
body {
background-color: #ffffff;
font-family: "Roboto", helvetica, arial, sans-serif;
font-size: 22px;
font-weight: 400;
text-rendering: optimizeLegibility;
}
h4 {
margin-bottom: 0px;
margin-top: 5px;
}
hr {
height:2px;
visibility:hidden;
line-spacing:0px;
}
div.table-title {
display: block;
margin: auto;
max-width: 600px;
padding:5px;
width: 100%;
}
.table-title h3 {
color: #000000;
font-size: 30px;
font-weight: 400;
font-style:normal;
font-family: "Roboto", helvetica, arial, sans-serif;
text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);
text-transform:uppercase;
}
/*** Table Styles **/ | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
python, python-3.x, template, pdf
/*** Table Styles **/
.table-fill {
background: white;
border-radius:3px;
border-collapse: collapse;
border-bottom:2px solid #C1C3D1;
border-right:2px solid #C1C3D1;
border-left:2px solid #C1C3D1;
height: 320px;
margin: auto;
max-width: 600px;
padding:5px;
width: 100%;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
animation: float 5s infinite;
}
th {
color:#D5DDE5;
background:#1b1e24;
border-bottom:2px solid #1b1e24;
border-top:2px solid #1b1e24;
border-right: 1px solid #343a45;
font-size:23px;
font-weight: 300;
padding:12px;
text-align:left;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
vertical-align:middle;
white-space: pre;
}
th:first-child {
border-top-left-radius:3px;
border-left: 2px solid #1b1e24;
}
th:last-child {
border-top-right-radius:3px;
border-right: 2px solid #1b1e24;
}
tr {
border-top: 1px solid #C1C3D1;
border-bottom-: 1px solid #C1C3D1;
color:#000000; /*#666B85*/
font-size:16px;
font-weight: normal;
text-shadow: 0 1px 1px rgba(256, 256, 256, 0.1);
white-space: pre;
}
tr:hover td {
background:#4E5066;
color:#FFFFFF;
border-top: 1px solid #22262e;
border-bottom: 1px solid #22262e;
}
tr:first-child {
border-top:none;
}
tr:last-child {
border-bottom:none;
}
tr:nth-child(odd) td {
background:#EBEBEB;
}
tr:nth-child(odd):hover td {
background:#4E5066;
}
tr:last-child td:first-child {
border-bottom-left-radius:3px;
}
tr:last-child td:last-child {
border-bottom-right-radius:3px;
}
td {
background:#FFFFFF;
padding:20px;
text-align:left;
vertical-align:middle;
font-weight:450;
font-size:20px;
text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);
border-right: 1px solid #C1C3D1;
white-space: nowrap;
}
td:last-child {
border-right: 0px;
}
th.text-left {
text-align: left;
}
th.text-center {
text-align: center;
}
th.text-right {
text-align: right;
}
td.text-left {
text-align: left;
} | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
python, python-3.x, template, pdf
th.text-right {
text-align: right;
}
td.text-left {
text-align: left;
}
td.text-left-top {
vertical-align: top;
text-align: left;
}
td.text-center {
text-align: center;
}
td.text-right {
text-align: right;
}
footer {
page-break-after: always;
}
Answer: I agree that the CSS may be a bit bloated. That may be unavoidable when you want very specific settings but the CSS is bigger than your HTML template and that is a sign isn't it.
I would normally define a font family and a default font size at the BODY level, so that contained elements inherit from it. Then, only override when needed.
Your body section contains:
font-family: "Roboto", helvetica, arial, sans-serif;
font-size: 22px;
font-weight: 400;
Then, it should not be necessary to repeat the font for style .table-title h3.
Omit default settings
font-weight: 400; is the same as: font-weight: normal; and should be the default setting applied by the browser anyway, so it seems to me that it can be safely omitted.
Remove unused styles
Some styles seem not be used at present, for example:
td.text-left-top {
vertical-align: top;
text-align: left;
}
And perhaps this could be merged with your TH definition ?
But you already know that very well, since you've actually written that in comments.
Your current template is very minimalistic. But you still have a lot of inline styles for a small template, which defeats the purpose of using a CSS file. Examples:
<p style="font-weight: bold">templating example.</p>
or:
<div align="center"> | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
python, python-3.x, template, pdf
or:
<div align="center">
Add CSS styles for those, and get rid of what you don't need. You can always put the styles back in place as you need them, but one by one.
Fixed vs relative size
I would discourage using fixed pixel size for text, because some screens have a higher resolution and different DPI values. The rendering will vary from one screen to another. Prefer relative size for responsive layout. It doesn't hurt to set a minimum value though.
I am not even certain that the contents will always fit inside your tables if you increase the amount of text. Either the browser constrains the content, and part of it shall remain invisible, or the browser stretches the layout as necessary and then your height specification is neutered. Test extensively. Use your desktop computer, a mobile phone, a tablet, reduce window size and see what happens. Try zooming too.
Suggested reading: Pixels vs. Relative Units in CSS: why itβs still a big deal
Shorthand notation
You can reduce the number of lines slightly by using shorthand notation. For example:
.table-fill {
background: white;
border-radius:3px;
border-collapse: collapse;
border-bottom:2px solid #C1C3D1;
border-right:2px solid #C1C3D1;
border-left:2px solid #C1C3D1;
height: 320px;
margin: auto;
max-width: 600px;
padding:5px;
width: 100%;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
animation: float 5s infinite;
}
Since 3 of the 4 borders have the same style and only the top border is different you could write:
border: 2px solid #C1C3D1;
border-top: 0;
This is effectively an override.
Typo
In TR definition (a trailing hyphen)
border-bottom-: 1px solid #C1C3D1;
Spacing
In the very next lines you have:
color:#000000; /*#666B85*/
font-size:16px; | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
python, python-3.x, template, pdf
Spacing
In the very next lines you have:
color:#000000; /*#666B85*/
font-size:16px;
Add some spacing to have a consistent property: value coding style throughout your CSS definition (at least I find that slightly more readable).
HTML
The HTML is broken - the <link rel="stylesheet" should be within the HEAD section:
<link rel="stylesheet" type="text/css" href="cv_template.css"/>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>{{title}}</title>
<meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; width=device-width;">
</head>
Since broken HTML (and CSS) code has always been very common, browsers tend to be very forgiving but may not all react the same way. Rendering may be inconsistent from one browser to another. So you test against as many browsers as possible and in different resolutions.
Accessibility
OK, I am not the expert and I am guilty of reusing old code without giving it much thought too. But from time to time reviewing code compels me to check the relevant documentation. Your HTML page has the following viewport definition:
<meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; width=device-width;">
This may be bad in line of what's been said already but so that you understand the possible implications (emphasis is mine) :
Maximum-scale is designed to prevent the user from zooming too far in
on a page, and is not intrinsically bad, however it is relatively easy
to accidentally set up the viewport so that the maximum-scale disables
using from zooming at all, so it is generally not recommended. For
this reason, Apple decided to ignore the declarations of
user-scalable, minimum-scale, and maximum-scale, as of iOS 10.
The recommended, 'safe' viewport setting is:
<meta name="viewport" content="width=device-width, initial-scale=1"> | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
python, python-3.x, template, pdf
Source
Test, test, test, torture your layout until it behaves well in every condition :)
Final notes
I have not yet reviewed the Python and the Jinja proper, which are probably more important to you. Should you use a dataclass ? You could, but the benefit would be inconsequential I think. Do you even need a class ? At this point I tend to say no because you have just 3 methods and the class does not perform a lot of abstraction.
If on the other hand you added the possibility to embed a picture, which is common in rΓ©sumΓ©s, this could get interesting. If you wanted to export to different formats like MS Word, then the case for a class becomes stronger. If this is something you would be interested in, read up about Python interfaces, and this article may be a good introduction: The Factory Method Pattern and Its Implementation in Python | {
"domain": "codereview.stackexchange",
"id": 42906,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, template, pdf",
"url": null
} |
java, recursion, binary-search
Title: size() method for a binary search tree
Question: This is my size method for my binary search tree, that is meant to implement recursion to calculate the tree's size.
public int size() {
if (left != null && right != null) {
return left.size() + 1 + right.size();
}
else if (left != null && right == null) {
return left.size() + 1;
}
else if (right != null && left == null) {
return right.size() + 1;
}
else {
return 0;
}
}
First I'm wondering if this looks all right. I also got some feedback on this function that I can calculate the size of the tree with fewer if statements but I don't see how I can do that.
Answer: Can be made much simpler:
public int size() {
int size=1;
if(left != null) size+=left.size();
if(right != null) size+=right.size();
return size;
} | {
"domain": "codereview.stackexchange",
"id": 42907,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, recursion, binary-search",
"url": null
} |
validation, swift, ios, gui, uikit
Title: Best way to do Input Validation on Swift/iOS/UIKit
Question: I have the following form that creates a new "activity":
For which I want to enforce the following requirements:
Name => minimum # of chars: 1; maximum # of chars: 50
Description => maximum # of chars: 200
I have written the following code:
// ActivityDetailViewController.swift
import UIKit
private struct Constants {
static let activityNameMaxCharacters = 50
static let activityDescriptionMaxCharacters = 200
}
final class ActivityDetailViewController: NiblessViewController {
/* ... */
// This method is called when user taps on the "Add" bar button item
// from the navigation bar.
@objc
func save(_ sender: UIBarButtonItem) {
do {
try validateInputs()
activity.name = nameField.text ?? ""
activity.activityDescription = descriptionTextView.text
presentingViewController?.dismiss(animated: true, completion: onDismiss)
} catch let error as ErrorMessage {
present(errorMessage: error)
} catch {
// NO-OP
}
}
/* ... */
// This methods applies the input validation rules.
private func validateInputs() throws {
guard let activityName = nameField.text else {
let errorMessage = ErrorMessage(
title: "Activity Creation Error",
message: "Activity name can't be empty."
)
throw errorMessage
}
let activityDescription = descriptionTextView.text ?? ""
if activityName.count > Constants.activityNameMaxCharacters {
let errorMessage = ErrorMessage(
title: "Activity Creation Error",
message: "Activity name exceeds max characters (50)."
)
throw errorMessage | {
"domain": "codereview.stackexchange",
"id": 42908,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, swift, ios, gui, uikit",
"url": null
} |
validation, swift, ios, gui, uikit
} else if activityDescription.count > Constants.activityDescriptionMaxCharacters {
let errorMessage = ErrorMessage(
title: "Activity Creation Error",
message: "Activity description exceeds max characters (200)."
)
throw errorMessage
}
}
}
Some supporting code:
// ErrorMessage.swift
import Foundation
public struct ErrorMessage: Error {
// MARK: - Properties
public let id: UUID
public let title: String
public let message: String
// MARK: - Methods
public init(title: String, message: String) {
self.id = UUID()
self.title = title
self.message = message
}
}
extension ErrorMessage: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
}
// UIViewController+ErrorPresentation.swift
import UIKit
extension UIViewController {
public func present(errorMessage: ErrorMessage) {
let errorAlertController = UIAlertController(
title: errorMessage.title,
message: errorMessage.message,
preferredStyle: .alert
)
let okAction = UIAlertAction(title: "OK", style: .default)
errorAlertController.addAction(okAction)
present(errorAlertController, animated: true, completion: nil)
}
}
I'd appreciate any feedback on how to improve the current solution.
Things I don't like:
Having to add an empty catch at the end of the try-catch clause located in the save(_:) method. Otherwise the compiler complains with: "Errors thrown from here are not handled because the enclosing catch is not exhaustive."
Answer: One can make the error conform to LocalizedError:
// MARK: - ActivityCreationError
enum ActivityCreationError: Error {
case empty
case nameTooLong
case descriptionTooLong
}
// MARK: LocalizedError conformance | {
"domain": "codereview.stackexchange",
"id": 42908,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, swift, ios, gui, uikit",
"url": null
} |
validation, swift, ios, gui, uikit
// MARK: LocalizedError conformance
extension ActivityCreationError: LocalizedError {
var errorDescription: String? {
switch self {
case .empty:
return NSLocalizedString("The name cannot be empty.", comment: "MyError.empty")
case .nameTooLong:
return String.localizedStringWithFormat(
NSLocalizedString("The name is too long (max %d characters).", comment: "MyError.nameTooLong"),
Constants.activityNameMaxCharacters
)
case .descriptionTooLong:
return String.localizedStringWithFormat(
NSLocalizedString("The description is too long (max %d characters).", comment: "MyError.descriptionTooLong"),
Constants.activityDescriptionMaxCharacters
)
}
}
}
// MARK: Public interface
extension ActivityCreationError {
static let title = NSLocalizedString("Activity Creation Error", comment: "MyError.title")
}
Notice that in my error messages, in the spirit of keeping it DRY, I avoided hardcoding the max string lengths again in the error message, but instead used localizedStringWithFormat to pull the same constant that was used during the validation process.
Then you can just catch it and use its localizedDescription:
do {
try validateInputs()
...
} catch {
presentAlert(title: ActivityCreationError.title, message: error.localizedDescription)
}
Where:
extension UIViewController {
public func presentAlert(title: String?, message: String?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let string = NSLocalizedString("OK", comment: "Alert Button")
let action = UIAlertAction(title: string, style: .default)
alert.addAction(action)
present(alert, animated: true)
}
} | {
"domain": "codereview.stackexchange",
"id": 42908,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, swift, ios, gui, uikit",
"url": null
} |
validation, swift, ios, gui, uikit
present(alert, animated: true)
}
}
By the way, before confirming validating the input and confirming string lengths, I would suggest sanitizing the input to trim whitespace. You do not want, for example, a user saying βoh, the name is required? ... well, I'll get around that by just entering a single space in that field.β You probably want the whitespace removed, anyway, as you do not want, for example, input with leading or trailing spaces.
E.g., rather than:
let activityDescription = descriptionTextView.text ?? ""
Use:
let activityDescription = descriptionTextView.text.?trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
If you are looking for more advanced counsel, one might adopt a better separation of responsibilities and pull the validation logic out of the view controller altogether. You might put it in what some people call the βview modelβ or the βpresenterβ or simply the βcontrollerβ (not to be confused with the βview controllerβ), a UIKit independent object in which you place your business logic (e.g. validation rules, initiate interactions with data stores or network managers, etc.).
For more information, see:
See Dave Delongβs A Better MVC for a perspective of embracing MVC but employing techniques to keep them small and manageable.
See Mediumβs iOS Architecture Patterns for a review of other approaches ranging from MVP, MVVM, Viper, etc.
See Krzysztof ZabΕockiβs iOS Application Architecture for another good discussion on the topic.
The common theme in all of these discussions is to avoid conflating the βviewβ (the configuration of and interaction with UIKit controls) and the business business rules. | {
"domain": "codereview.stackexchange",
"id": 42908,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, swift, ios, gui, uikit",
"url": null
} |
python, lazy
Title: Writing a lazy-evaluation dataclass
Question: I have a dataclass which is frequently used but is slow because as it processes multiple large datasets. I have tried to speed it up by making it lazily-evaluate, where the data is only read when requested and subsequent calls are cached.
Below is a (simplified) implementation for the variables x, y and z
import time, timeit
from functools import cache
class LazyDataStore:
def __init__(self): pass
@property
def x(self): return self.load_xy()["x"]
@property
def y(self): return self.load_xy()["y"]
@property
def z(self): return self.load_z()
@cache
def load_xy(self):
time.sleep(1) # simulate slow loading data
return {"x":1,"y":2} # simulate data
@cache
def load_z(self):
time.sleep(2) # simulate slow loading data
return 3 # simulate data
if __name__ == "__main__":
print(f'Time taken to access x, y and z once {timeit.timeit("my_data.x; my_data.y; my_data.z", setup="from __main__ import LazyDataStore; my_data = LazyDataStore()", number=1)}')
print(f'Time taken to access x 5 times {timeit.timeit("my_data.x", setup="from __main__ import LazyDataStore; my_data = LazyDataStore()", number=5)}')
print(f'Time taken to access x and z 100 times {timeit.timeit("my_data.x; my_data.z", setup="from __main__ import LazyDataStore; my_data = LazyDataStore()", number=100)}')
With the results printed below:
Time taken to access x, y and z once 3.0019894000142813
Time taken to access x 5 times 1.0117400998715311
Time taken to access x and z 100 times 3.0195651999674737
Is there a better/neater/cleaner way to do this? Any comments welcomed.
Some thoughts: | {
"domain": "codereview.stackexchange",
"id": 42909,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, lazy",
"url": null
} |
python, lazy
Is there a better/neater/cleaner way to do this? Any comments welcomed.
Some thoughts:
I think self.load_xy()["x"] isn't ideal, however it is concise, which helps as more variables are added the class starts to fill with boilerplate code - making it less readable.
Should I be using the @dataclass decorator in some way?
I do use this same format in several files, so is there a clear/clean/useful way to make a Superclass/Subclass?
Answer: Did you consider functools.cached_property? Seems like it was designed for this use case. It doesn't appear to be any faster, but maybe the intent of the code is clearer.
from functools import cached_property
class LazyDataStore:
def __init__(self): pass
@cached_property
def x(self):
self.load_xy()
return self.x
@cached_property
def y(self):
self.load_xy()
return self.y
@cached_property
def z(self):
self.load_z()
return self.z
def load_xy(self):
time.sleep(1) # simulate slow loading data
self.x = 1 # simulate data
self.y = 2
def load_z(self):
time.sleep(2) # simulate slow loading data
self.z = 3 # simulate data | {
"domain": "codereview.stackexchange",
"id": 42909,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, lazy",
"url": null
} |
performance, c, assembly, collatz-sequence, x86
Title: Beating the compiler with a simple program finding the longest collatz sequence
Question: I found this question in Stackoverflow asking why his/her assembly program isn't faster than the C++ program. In his/her assembly program I saw the lines mov rbx, 2; xor rdx, rdx; div rbx, and I didn't even read further. Anyway the question was interesting enough for me to write an assembly program to see how much I can beat the compiler.
The program is a simple bruteforce solution to problem 14 of Project Euler.
The algorithm used in both the C and assembly version is the same; no algorithmic optimization was done.
This is the result in rdtscp cycles, which has a constant tick on my CPU. The first output number is the result of the function with input 10,000,000.
/* gcc */
8400511 c 1,710,915,921
8400511 asm 1,656,971,166
8400511 c 1,707,514,184
8400511 asm 1,653,252,527
8400511 c 1,702,896,033
8400511 asm 1,652,814,196
/* clang */
8400511 c 2,011,935,915
8400511 asm 1,655,126,396
8400511 c 2,009,606,165
8400511 asm 1,649,501,254
8400511 c 2,016,743,666
8400511 asm 1,653,020,407
My assembly version has a marginal win against gcc and quite a visible gap with clang. The assembly output by each compiler can be seen here.
lcs_c.c
#include <inttypes.h>
static unsigned bsfq(uint64_t a) {
#if LONG_MAX == UINT64_MAX
return __builtin_ctzl(a);
#else
return __builtin_ctzll(a);
#endif
}
uint64_t lcs_c(uint64_t n) {
uint64_t Mn;
unsigned Mc = 1;
do {
unsigned c = 1;
uint64_t n_ = n;
for (;;) {
unsigned c_ = bsfq(n_);
n_ >>= c_;
c += c_;
if (n_ == 1) {
break;
}
n_ = n_ * 3 + 1;
++c;
}
if (c > Mc) {
Mc = c;
Mn = n;
}
} while (--n > 0);
return Mn;
}
lcs_asm.s
%define n rdi
%define n_ rsi
%define Mc r8d
%define c edx | {
"domain": "codereview.stackexchange",
"id": 42910,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, assembly, collatz-sequence, x86",
"url": null
} |
performance, c, assembly, collatz-sequence, x86
lcs_asm.s
%define n rdi
%define n_ rsi
%define Mc r8d
%define c edx
align 16
global lcs_asm
lcs_asm:
mov Mc, 1
jmp L0
align 16
L0:
mov c, 1
mov n_, n
jmp L1
align 16
L1:
bsf rcx, n_
shr n_, cl
cmp n_, 1
je next
lea n_, [n_ + n_ * 2 + 1]
lea c, [c + ecx + 1]
jmp L1
align 16
next:
add c, ecx
cmp c, Mc
ja L2
dec n
jz end
jmp L0
align 16
L2:
mov Mc, c
mov rax, n
dec n
jz end
jmp L0
align 16
end:
ret
main.c
#include <stdio.h>
#include <locale.h>
#include <inttypes.h>
extern uint64_t lcs_c(uint64_t);
extern __attribute__((sysv_abi)) uint64_t lcs_asm(uint64_t);
static uint64_t rdtscp() {
unsigned _;
return __builtin_ia32_rdtscp(&_);
}
static void test(const char *id, uint64_t (*lcs)(uint64_t), uint64_t lim) {
uint64_t c = rdtscp();
uint64_t Mn = lcs(lim);
c = rdtscp() - c;
printf("%"PRIu64"%4s %'"PRIu64"\n", Mn, id, c);
}
int main() {
setlocale(LC_NUMERIC, "");
uint64_t lim = 1e7;
for (int i = 0; i < 3; ++i) {
test("c", lcs_c, lim);
test("asm", lcs_asm, lim);
}
}
build.sh
#!/bin/sh -x
C="gcc"
O="-O3 -march=tigerlake"
$C -c $O lcs_c.c
nasm -felf64 lcs_asm.s
$C $O -or main.c lcs_c.o lcs_asm.o
rm *.o
Answer: I rewrote your assembly code a bit. I leave it to you if this results in any better performance.
I reduced the number of branches. You had 2 in your inner loop, my code uses 1.
I also inverted the conditional branch near the bottom and removed some code that was repeating itself. Again reducing branches.
The few remaining branch targets are still paragraph aligned but I replaced the 'jump-over the nops' by the recommended sequence of multi-byte nop. | {
"domain": "codereview.stackexchange",
"id": 42910,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, assembly, collatz-sequence, x86",
"url": null
} |
performance, c, assembly, collatz-sequence, x86
align 16
lcs_asm:
mov r8d, 1 ; 6
mov edx, 1 ; 5
mov rsi, rdi ; 3
jmp L2 ; 2
L1: lea rsi, [rsi + rsi * 2 + 1] ; 5
lea edx, [edx + ecx + 1] ; 5
db 66h, 0Fh, 1Fh, 44h, 00h, 00h ; jmp L2 : align 16 -> 66 nop word ptr [rax + rax * 1 + 0]
L2: bsf rcx, rsi
shr rsi, cl
cmp rsi, 1
jne L1
add edx, ecx
cmp edx, r8d
jna L3
mov r8d, edx
mov rax, rdi
db 66h, 0Fh, 1Fh, 44h, 00h, 00h ; jmp L3 : align 16 -> 66 nop word ptr [rax + rax * 1 + 0]
L3: dec rdi
mov edx, 1
mov rsi, rdi
jnz L2
ret
The entire code fits in 78 bytes. | {
"domain": "codereview.stackexchange",
"id": 42910,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, assembly, collatz-sequence, x86",
"url": null
} |
multithreading, swift, thread-safety, concurrency
Title: Bank account concurrency problem Swift
Question: I tried to implement a simple BankAccount class to practice providing a solution to the common Bank Account transaction data race problem. Reference to a description of such a problem can be found here.
The public API of the class:
func deposit(amount: Double)
func withdraw(amount: Double)
func currentBalance() -> Double
func sendMoney(to other: BankAccount, amount: Double)
I was thinking that we can prevent any data race from happening by using a serial queue for depositing and withdrawing money, and I went ahead and made the implementation as following (sendMoney method is excluded for now)
class BankAccount {
private var balance = 0.0
private let accountQueue = DispatchQueue(label: "bank.account.queue")
func deposit(amount: Double) {
accountQueue.sync(flags: .barrier) {
balance += amount
}
}
func withdraw(amount: Double) {
accountQueue.sync(flags: .barrier) {
guard balance >= amount else {
return
}
balance -= amount
}
}
func currentBalance() -> Double {
accountQueue.sync {
return balance
}
}
}
My first question is, are .barrier flags are unnecessary because the queue is serial anyways, and are the implementations are correct?
The second question is specifically about the correctness of the sendMoney method. I defined the method as following:
func sendMoney(to other: BankAccount, amount: Double) {
accountQueue.sync(flags: .barrier) {
guard balance >= amount else {
return
}
other.deposit(amount: amount)
withdrawWhileTransfering(amount: amount)
}
}
private func withdrawWhileTransfering(amount: Double) {
balance -= amount
} | {
"domain": "codereview.stackexchange",
"id": 42911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "multithreading, swift, thread-safety, concurrency",
"url": null
} |
multithreading, swift, thread-safety, concurrency
private func withdrawWhileTransfering(amount: Double) {
balance -= amount
}
I had to implement withdrawWhileTransfering method to call from sendMoney method, to avoid deadlock by calling regular withdraw method.
The class is like following including all the methods implemented:
class BankAccount {
private var balance = 0.0
private let accountQueue = DispatchQueue(label: "bank.account.queue")
func deposit(amount: Double) {
accountQueue.sync(flags: .barrier) {
balance += amount
}
}
func withdraw(amount: Double) {
accountQueue.sync(flags: .barrier) {
guard balance >= amount else {
return
}
balance -= amount
}
}
func currentBalance() -> Double {
accountQueue.sync {
return balance
}
}
func sendMoney(to other: BankAccount, amount: Double) {
accountQueue.sync(flags: .barrier) {
guard balance >= amount else {
return
}
other.deposit(amount: amount)
withdrawWhileTransferring(amount: amount)
}
}
private func withdrawWhileTransferring(amount: Double) {
balance -= amount
}
} | {
"domain": "codereview.stackexchange",
"id": 42911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "multithreading, swift, thread-safety, concurrency",
"url": null
} |
multithreading, swift, thread-safety, concurrency
In sendMoney method, first we make sure that the current balance is greater than or equal to the amount we want to send to the other account, and then we go ahead and call deposit on the other account already. Then we withdraw the amount from the account where we send the money from. Since all this is inside a synchronous block, and the deposit method for the other will also execute serially, it feels like this would work fine, but I am not hundred percent sure.
Do you think this class would work data race free? Could we make some changes so we get rid of the private withdrawWhileTransferring method? Also do you see any performance problems with such an implementation?
PS: The API does not have to be like this by the way, if it will make the implementation better, we can introduce additional fields, such as accountID
Answer: You asked:
My first question is, are .barrier flags are unnecessary because the queue is serial anyways, β¦
Yes, if it is a serial queue, the barriers are not needed. But you can make it a concurrent queue, if you wanted, at which point the barriers would be essential.
β¦ and are the implementations are correct?
Yes, from a synchronization perspective, itβs pretty close. You should make the writes async as thereβs no reason for the caller to wait and you want to avoid deadlock risks.
From a business perspective, I suspect you want withdrawal method to return a Boolean or throw an error if there were insufficient funds. Itβs not good to just silently fail. And you probably want tests to make sure that your deposits are non-negative.
Also, when dealing with currencies, make sure to use Decimal rather than Double. E.g., if your account had $1 and you remove 10 cents ten times, the final total will not quite equal 0 with Double, but will with Decimal (if youβre careful).
I had to implement withdrawWhileTransfering method to call from sendMoney method, to avoid deadlock by calling regular withdraw method. | {
"domain": "codereview.stackexchange",
"id": 42911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "multithreading, swift, thread-safety, concurrency",
"url": null
} |
multithreading, swift, thread-safety, concurrency
Yeah, I get it. I might add the following to that method to make your assumptions explicit:
dispatchPrecondition(condition: .onQueue(accountQueue))
Do you think this class would work data race free?
The only problem that jumps out at me is a deadlock risk. If you simultaneously have account A send B money at the exact same time as B is sending A money, it will deadlock if all of these are synchronous. But if you make your writes asynchronous, then you should be OK. | {
"domain": "codereview.stackexchange",
"id": 42911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "multithreading, swift, thread-safety, concurrency",
"url": null
} |
c#, async-await
Title: Cleanup Async WhenAll
Question: I have a sequence, retrieve data from a vendor API, cleanup our stage tables, and write the retrieve data into the database. What I have:
public static async Task Main()
{
try
{
IDataRetrievalService api = services.GetService<IDataRetrievalService>();
AuthenticationModel authenticated = await api.GetToken();
authenticated.Decorate(Log.Logger);
#region Web Request:
var budget = api.GetBudgetReport(authenticated);
var site = api.GetSiteReport(authenticated);
var project = api.GetProjectReport(authenticated);
var task = api.GetTaskReport(authenticated);
var workEffort = api.GetWorkEffortReport(authenticated);
var invoiceMaterial = api.GetInvoiceMaterialReport(authenticated);
var pickup = api .GetPickupSummary(authenticated);
var pickupMaterial = api.GetPickupMaterialReport(authenticated);
var dropship = api.GetDropshipReport(authenticated);
var dropshipMaterial = api.GetDropshipMaterialReport(authenticated);
var materialType = api.GetMaterialTypeReport(authenticated);
#endregion
IDatabaseCleanupService cleanup = services.GetService<IDatabaseCleanupService>();
await Task.WhenAll(
budget,
cleanup.PurgeBudget(),
site,
cleanup.PurgeSite(),
project,
cleanup.PurgeProject(),
task,
cleanup.PurgeTask(),
workEffort,
cleanup.PurgeWorkEffort(),
invoiceMaterial,
cleanup.PurgeInvoiceMaterial(),
pickup,
cleanup.PurgePickupSummary(),
pickupMaterial,
cleanup.PurgePickupMaterial(),
dropship,
cleanup.PurgeDropship(), | {
"domain": "codereview.stackexchange",
"id": 42912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c#, async-await
dropship,
cleanup.PurgeDropship(),
dropshipMaterial,
cleanup.PurgeDropshipMaterial(),
materialType,
cleanup.PurgeMaterialType()
);
IDatabaseImporterService importer = services.GetService<IDatabaseImporterService>();
await Task.WhenAll(
importer.InsertBudget(await budget),
importer.InsertSite(await site),
importer.InsertProject(await project),
importer.InsertTask(await task),
importer.InsertWorkEffort(await workEffort),
importer.InsertInvoiceMaterial(await invoiceMaterial),
importer.InsertPickupSummary(await pickup),
importer.InsertPickupMaterial(await pickupMaterial),
importer.InsertDropship(await dropship),
importer.InsertDropshipMaterial(await dropshipMaterial),
importer.InsertMaterialType(await materialType)
);
}
catch (Exception exception)
{
exception.Decorate(Log.Logger);
throw;
}
}
I feel though that the second WhenAll should not need to wait for a batch of task that should of been completed above, the syntax feels weird to me.
Answer: As you have said you are executing the following operations against each entity:
Retrieve from vendor
Purge local datastore (in parallel with the previous)
Insert retrieved data
So, we look at the problem from a single entity perspective then we can say:
(TRetrieve, TPurge) -> TInsert(TRetrieve.Result)
TRetrieve represents the vendor call
TPurge represents the database cleanup
() represents parallel execution
-> represents continuation
TInsert represents the database population
TRetrieve.Result represents the retrieved data | {
"domain": "codereview.stackexchange",
"id": 42912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c#, async-await
If we could create a structure that bundles these tasks together then we can express our intent on the entity level:
class CoherentTasks<T>
{
public Func<Task<T>> RetrieveTask { get; init; }
public Func<Task> PurgeTask { get; init; }
public Func<T, Task> InsertTask { get; init; }
public CoherentTasks(Func<Task<T>> retrieve, Func<Task> purge, Func<T, Task> insert)
=> (RetrieveTask, PurgeTask, InsertTask) = (retrieve, purge, insert);
}
Each property here is init only (so can be set only via the constructor or the object initializer)
Each property is defined as a Func<...> so we will not run the Tasks during property assignment
The constructor is taking advantage of ValueTuple and deconstruction
With this approach only a single assignment is needed to set all three properties
In C# we can't create a List<CoherentTasks<object>> to be able to store CoherentTasks<int> and CoherentTasks<string> objects in it
In order to overcome on this we need to get rid of the generic parameter and use boxing + unboxing
class CoherentTasks
{
public Func<Task<object>> RetrieveTask { get; set; }
public Func<Task> PurgeTask { get; set; }
public Func<object, Task> InsertTask { get; set; }
public CoherentTasks(Func<Task<object>> retrieve, Func<Task> purge, Func<object, Task> insert)
=> (RetrieveTask, PurgeTask, InsertTask) = (retrieve, purge, insert);
}
For the sake of simplicity let me introduce a couple dummy retrieve, purge and insert methods in order to demonstrate the the proposed solution works with different entity types
async Task<object> GetId()
{
await Task.Delay(300);
return 1;
}
async Task PurgeId() => await Task.Delay(700);
Task InsertId(int id)
{
Console.WriteLine(id);
return Task.CompletedTask;
}
async Task<object> GetDescription()
{
await Task.Delay(200);
return "desc";
}
async Task PurgeDesciption() => await Task.Delay(1000); | {
"domain": "codereview.stackexchange",
"id": 42912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c#, async-await
async Task PurgeDesciption() => await Task.Delay(1000);
Task InsertDescription(string description)
{
Console.WriteLine(description);
return Task.CompletedTask;
}
Now we can define a collection of CoherentTasks, which represents the operations on different entities
List<CoherentTasks> operationsOnEntities = new ()
{
new CoherentTasks(() => GetId(), () => PurgeId(), (id) => InsertId((int)id)),
new CoherentTasks(() => GetDescription(), () => PurgeDesciption(), (desc) => InsertDescription((string)desc)),
...
};
I've used here new () which is the target-typed new expression feature of C# 9 if you haven't encountered with that before
I've used here explicit casting ((int), (string)) to unbox data
Finally lets implement the syncronization functionality:
var retrieveTasks = operationsOnEntities.Select(tasks => tasks.RetrieveTask());
var purgeTasks = operationsOnEntities.Select(tasks => tasks.PurgeTask());
await Task.WhenAll(retrieveTasks.Union(purgeTasks));
var insertionTasks = retrieveTasks.Zip(operationsOnEntities.Select(tasks => tasks.InsertTask),
(retrievedTask, insertTask) => insertTask(retrievedTask.Result));
await Task.WhenAny(insertionTasks);
Step 1 - Issue retrieve and purge
First we kick off the data retrieval jobs (retrieveTasks)
Then we kick off the clean-up jobs (purgeTasks)
We await to finish (Task.WhenAll) both kinds of jobs (Union)
Step 2 - Issue insertion by using retrieved data
First we retrieve all insertion tasks operationsOnEntities.Select(tasks => tasks.InsertTask)
Then we combine this list with the retrieval jobs (Zip)
The second argument of the Zip method is a function which receives one item from each enumerable and we tell how to combine these (insertTask(retrievedTask.Result) | {
"domain": "codereview.stackexchange",
"id": 42912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c#, async-await
So, as you can see the core functionality can be implemented with 6 lines of code if you separate data and operation from each other.
For the sake of completeness here is the full demo code:
class Program
{
static async Task Main(string[] args)
{
List<CoherentTasks> operationsOnEntities = new ()
{
new CoherentTasks(() => GetId(), () => PurgeId(), (id) => InsertId((int)id)),
new CoherentTasks(() => GetDescription(), () => PurgeDesciption(), (desc) => InsertDescription((string)desc)),
};
var retrieveTasks = operationsOnEntities.Select(tasks => tasks.RetrieveTask());
var purgeTasks = operationsOnEntities.Select(tasks => tasks.PurgeTask());
await Task.WhenAll(retrieveTasks.Union(purgeTasks));
var insertionTasks = retrieveTasks.Zip(operationsOnEntities.Select(tasks => tasks.InsertTask),
(retrievedTask, insertTask) => insertTask(retrievedTask.Result));
await Task.WhenAny(insertionTasks);
}
static async Task<object> GetId() { await Task.Delay(300); return 1; }
static async Task PurgeId() => await Task.Delay(700);
static Task InsertId(int id) { Console.WriteLine(id); return Task.CompletedTask; }
static async Task<object> GetDescription() { await Task.Delay(200); return "desc"; }
static async Task PurgeDesciption() => await Task.Delay(1000);
static Task InsertDescription(string description) { Console.WriteLine(description); return Task.CompletedTask; }
}
class CoherentTasks
{
public Func<Task<object>> RetrieveTask { get; set; }
public Func<Task> PurgeTask { get; set; }
public Func<object, Task> InsertTask { get; set; }
public CoherentTasks(Func<Task<object>> retrieve, Func<Task> purge, Func<object, Task> insert)
=> (RetrieveTask, PurgeTask, InsertTask) = (retrieve, purge, insert);
} | {
"domain": "codereview.stackexchange",
"id": 42912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c++, generics, c++20, median
Title: generic implementation of median
Question: Below is a generic implementation of the summary statistics function Median.
Discussion of efficient use of std::nth_element and std::max_element (for even number of elements only) is from here.
We want the median algorithm to work for ranges of primitive builtin types, as well as complex types. This may require passing in an ordering comparator and an "extraction" functor as lambdas.
Yet we want the algorithm to remain simple to use for simple types.
As a complex type we include a simple vector2 implementation. This is not the focus here.
C++20 has been used for concept constraints and "lambdas in non-evaluated contexts".
Comments, particularly on the API choices for the median(...) appreciated.
Is there a better way specify the default Extract Lambda type?
#include <cmath>
#include <cstdlib>
#include <exception>
#include <functional>
#include <iostream>
#include <ostream>
#include <stdexcept>
#include <utility>
template <typename Numeric>
requires std::is_floating_point_v<Numeric> || std::is_integral_v<Numeric>
class vector2 {
public:
Numeric x{};
Numeric y{};
constexpr vector2(Numeric x_, Numeric y_) : x(x_), y(y_) {}
constexpr vector2() = default;
[[nodiscard]] Numeric mag() const { return std::hypot(x, y); }
[[nodiscard]] vector2 norm() const { return *this / this->mag(); }
[[nodiscard]] Numeric dot(const vector2& rhs) const { return x * rhs.x + y * rhs.y; }
// clang-format off
vector2& operator+=(const vector2& obj) { x += obj.x; y += obj.y; return *this; }
vector2& operator-=(const vector2& obj) { x -= obj.x; y -= obj.y; return *this; }
vector2& operator*=(const double& scale) { x *= scale; y *= scale; return *this; }
vector2& operator/=(const double& scale) { x /= scale; y /= scale; return *this; }
// clang-format on | {
"domain": "codereview.stackexchange",
"id": 42913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, generics, c++20, median",
"url": null
} |
c++, generics, c++20, median
friend vector2 operator+(vector2 lhs, const vector2& rhs) { return lhs += rhs; }
friend vector2 operator-(vector2 lhs, const vector2& rhs) { return lhs -= rhs; }
friend vector2 operator*(vector2 lhs, const double& scale) { return lhs *= scale; }
friend vector2 operator*(const double& scale, vector2 rhs) { return rhs *= scale; }
friend vector2 operator/(vector2 lhs, const double& scale) { return lhs /= scale; }
friend std::ostream& operator<<(std::ostream& os, const vector2& v) {
return os << '[' << v.x << ", " << v.y << "] mag = " << v.mag();
}
};
using vec2 = vector2<double>;
template <typename RandAccessIter, typename Comp = std::less<>,
typename Extract = decltype([](const typename RandAccessIter::value_type& e) { return e; })>
auto median(RandAccessIter first, RandAccessIter last, Comp comp = std::less<>(),
Extract extr = Extract()) {
auto s = last - first;
if (s == 0) throw std::domain_error("Can't find median of an empty range");
auto n = s / 2;
auto middle = first + n;
std::nth_element(first, middle, last, comp);
#if !defined(NDEBUG)
std::cerr << "After nth_element with n= " << n << ":\n";
std::for_each(first, last, [](const auto& e) { std::cerr << e << "\n"; });
#endif
if (s % 2 == 1) {
return extr(*middle);
}
auto below_middle = std::max_element(first, middle, comp);
#if !defined(NDEBUG)
std::cerr << "below_middle:" << *below_middle << "\n";
#endif
return (extr(*middle) + extr(*below_middle)) / 2.0;
}
// wrap the generic median algorithm for particular type and container
double median(std::vector<vec2> modes) { // intentional copy to protect caller
return median(
modes.begin(), modes.end(), [](const auto& a, const auto& b) { return a.mag() < b.mag(); },
[](const auto& v) { return v.mag(); });
} | {
"domain": "codereview.stackexchange",
"id": 42913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, generics, c++20, median",
"url": null
} |
c++, generics, c++20, median
int main() {
try {
std::cout << "mutable vector of builtin types\n";
auto vector_of_doubles = std::vector<std::vector<double>>{
{1.0, 2.0, 3.0, 4.0, 5.0},
{1.0, 2.0, 3.0, 4.0},
{1.0, 2.0, 3.0},
{1.0, 2.0},
{1.0},
};
for (auto& doubles: vector_of_doubles) {
auto med = median(doubles.begin(), doubles.end()); // call generic algorithm
std::cout << "median mag = " << med << "\n";
}
std::cout << "immutable vector of complex types\n";
const auto vector_of_vecs = std::vector<std::vector<vec2>>{
{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}},
{{1, 2}, {3, 4}, {5, 6}, {7, 8}},
{{1, 2}, {3, 4}, {5, 6}},
{{1, 2}, {3, 4}},
{{1, 2}},
{},
};
for (const auto& vecs: vector_of_vecs) {
auto med = median(vecs); //call via simplifying wrapper
std::cout << "median mag = " << med << "\n";
}
} catch (const std::exception& e) {
std::cerr << "Exception thrown: " << e.what() << " Terminating\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 42913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, generics, c++20, median",
"url": null
} |
c++, generics, c++20, median
Answer: It modifies the input
I think it is surprising that an operation that is intended to just give you some statistics back is going to modify the input. In the test code you also test it on const vectors, but there you use the helper function that makes a copy. Maybe make copying part of the real median() function? It might be tempting to use std::partial_sort_copy(), but as you benchmarked, that is always less efficient that just copying the whole input and then using std::nth_element() + std::max_element().
Making a copy here does not increase the algorithmic complexity in any way, but of course there is an overhead. If the caller really wants to avoid that, perhaps provide an in_place_median() or a sorting_median() function?
Provide a version with a ranges interface
Since you target C++20, consider providing an overload that takes a std::ranges::random_access_range as an argument.
Simplify template default parameters
Just like you used std::less<>, you can use std::identity to provide a default value for Extract. Furthermore, when providing default values for the function parameters, you can avoid repeating things by just using {}:
template <typename RandAccessIter, typename Comp = std::less<>,
typename Extract = std::identity>
auto median(RandAccessIter first, RandAccessIter last,
Comp comp = {}, Extract extr = {}) {
...
} | {
"domain": "codereview.stackexchange",
"id": 42913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, generics, c++20, median",
"url": null
} |
c++, generics, c++20, median
Use std::midpoint()
If you have an even number of elements, then the line of code that averages two values is problematic. Consider that the sum of two values might be outside the range of the value type. There's std::midpoint() which will calculate the average for you while also avoiding all the pitfalls that come with it. (See this presentation from Marshall Clow for the problems one encounters while trying to average two numbers.)
Use std::invoke() instead of calling extr() directly
To make the code even more generic and to allow member function pointers to be passed for extr, make sure you use std::invoke() to invoke the callable:
if (s % 2 == 1) {
return std::invoke(extr, *middle);
}
...
return std::midpoint(std::invoke(extr, *middle), std::invoke(extr, *below_middle));
Consider adding a projection parameter
You'll notice that std::ranges::nth_element() has a template parameter Proj that is similar to your Extract, except that it is applied before comparing two elements. It would simplify your helper function std::vector<vec2>, and would allow you to write:
template <typename RandAccessIter, typename Comp = std::less<>,
typename Proj = std::identity, typename Extract = std::identity>
auto median(RandAccessIter first, RandAccessIter last, Comp comp = {},
Proj proj = {}, Extract extr = {}) {
...
std::ranges::nth_element(first, middle, last, comp, proj);
...
auto below = std::ranges::max_element(first, middle, comp, proj);
...
}
auto median(std::vector<vec2> modes) {
return median(modes.begin(), modes.end(), {}, &vec::mag, &vec::mag);
} | {
"domain": "codereview.stackexchange",
"id": 42913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, generics, c++20, median",
"url": null
} |
c++, generics, c++20, median
Use concepts to restrict the allowed template parameter types
In C++20 we can use concepts to restrict template parameters, so type errors are detected early with helpful error messages. If you want to keep using std::nth_element(), then the easiest would be to use std::sortable for RandAccessIter, Comp and Proj, and use std::invocable for Extract:
template <typename RandAccessIter, typename Comp = std::less<>,
typename Proj = std::identity, typename Extract = std::identity>
requires std::sortable<RandAccessIter, Comp, Proj> &&
std::invocable<Extract, std::iter_reference_t<RandAccessIter>>
auto median(RandAccessIter first, RandAccessIter last, Comp comp = {},
Proj proj = {}, Extract extr = {}) {
...
} | {
"domain": "codereview.stackexchange",
"id": 42913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, generics, c++20, median",
"url": null
} |
c#, .net, playing-cards, shuffle
Title: Card Shuffle without using any help C#
Question: I'm new to C# but not 100% new to development. I wanted to try writing a Card Shuffle + Card Dealing algorithm using as least as possible inbuilt functions or any libraries and no internet use to practice my C# skills.
Here is my code:
class cardShuffle
{
private string[] deck = new string[] {"Ace-of-Clubs", "Ace-of-Hearts", "Ace-of-Spades", "Ace-of-Diamonds",
"King-of-Clubs", "King-of-Hearts", "King-of-Spades", "King-of-Diamonds",
"Quenn-of-Clubs", "Quenn-of-Hearts", "Quenn-of-Spades", "Quenn-of-Diamonds","Jack-of-Clubs", "Jack-of-Hearts", "Jack-of-Spades", "Jack-of-Diamonds",
"10-of-Clubs", "10-of-Hearts", "10-of-Spades", "10-of-Diamonds",
"9-of-Clubs", "9-of-Hearts", "9-of-Spades", "9-of-Diamonds",
"8-of-Clubs", "8-of-Hearts", "8-of-Spades", "8-of-Diamonds",
"7-of-Clubs", "7-of-Hearts", "7-of-Spades", "7-of-Diamonds",
"6-of-Clubs", "6-of-Hearts", "6-of-Spades", "6-of-Diamonds",
"5-of-Clubs", "5-of-Hearts", "5-of-Spades", "5-of-Diamonds",
"4-of-Clubs", "4-of-Hearts", "4-of-Spades", "4-of-Diamonds",
"3-of-Clubs", "3-of-Hearts", "3-of-Spades", "3-of-Diamonds",
"2-of-Clubs", "2-of-Hearts", "2-of-Spades", "2-of-Diamonds",};
public void Start(int numberOfShuffles)
{
var shuffledDeck = new string[52];
for(int i = 1; i <= numberOfShuffles; i++)
{
shuffledDeck = Shuffle(deck);
}
DealCards(shuffledDeck);
}
private string[] Shuffle(string[] deck)
{
Random randomNum = new Random();
for (int i = deck.Length - 1; i > 0; --i)
{
int j = randomNum.Next(i + 1);
string temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
} | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
c#, .net, playing-cards, shuffle
private void DealCards(string[] shuffledDeck)
{
string[] player1 = new string[13];
string[] player2 = new string[13];
string[] player3 = new string[13];
string[] player4 = new string[13];
const int maxCardsInHand = 13;
int currentCardsP1 = 0;
int currentCardsP2 = 0;
int currentCardsP3 = 0;
int currentCardsP4 = 0;
int indexP1 = 0;
int indexP2 = 0;
int indexP3 = 0;
int indexP4 = 0;
for(int i = 0; i < deck.Length; i++)
{
if(currentCardsP1 < maxCardsInHand)
{
player1[indexP1] = shuffledDeck[i];
currentCardsP1++;
indexP1++;
}else if(currentCardsP2 < maxCardsInHand)
{
player2[indexP2] = shuffledDeck[i];
currentCardsP2++;
indexP2++;
}else if(currentCardsP3 < maxCardsInHand)
{
player3[indexP3] = shuffledDeck[i];
currentCardsP3++;
indexP3++;
}else if(currentCardsP4 < maxCardsInHand)
{
player4[indexP4] = shuffledDeck[i];
currentCardsP4++;
indexP4++;
}
}
Console.WriteLine("--------------------------------------------------------------------------------------");
Console.WriteLine(string.Format("{0, -20} | {1, -20} | {2, -20} | {3, -20}", "Player1 - Cards", "Player2 - Cards", "Player3 - Cards", "Player4 - Cards"));
Console.WriteLine("--------------------------------------------------------------------------------------");
for (int j = 0; j < 13; j++)
{
Console.WriteLine(string.Format("{0, -20} | {1, -20} | {2, -20} | {3, -20}", player1[j], player2[j], player3[j], player4[j]));
}
}
}
I'm using net6.0
cardShuffle shuffle = new cardShuffle();
shuffle.Start(1);
With the start Method, it takes an integer of how many times you want to shuffle the deck. If you put in 0 the output will be nothing. Please keep that in mind it's not a bug, that's intended. | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
c#, .net, playing-cards, shuffle
Answer: Modeling the real world
You've clearly drawn inspiration from the real world. That's a good thing. A lot of programming and the design that goes into it can be modeled based off of real life.
However, sometimes there are better ways to algorithmically approach something that doesn't quite work in real life. It's okay to not see this on the first pass when you write your code, but you should re-evaluate your code a second time to look for improvements.
Most if not all of the below review points are things you could have found on a second pass of your code. With experience, you'll learn to spot these yourself.
Defining your cards and deck
private string[] deck = new string[] {"Ace-of-Clubs", "Ace-of-Hearts", ...
Programming is all about finding reusable repeating patterns. While there are 52 unique cards in a deck, they can more easily be defined by their value (ace, king, ...) and their suit (hearts, clubs, ...)
Given that we are using a closed set of options, enums are the way to go here.
public enum CardValue { Ace, King, ... } // Complete this yourself
public enum CardSuit { Hearts, Clubs, Spades, Diamonds }
A card can then be defined as a combination of these values
public struct Card
{
public CardValue Value { get; }
public CardSuit Suit { get; }
public Card(CardValue value, CardSuit suit)
{
Value = value;
Suit = suit;
}
}
I've intentionally designed it so that a card cannot be changed after it has been created, to avoid mistakes where you magically change one card into another.
I'm skipping over the struct vs class explanation here because it's not the main focus of the answer; Google this for yourself to learn when to use what.
You can then create cards like so:
var kingOfClubs = new Card(CardValue.King, CardSuit.Clubs);
And to generate a full deck, you can just iterate over the available values in the enums:
public IEnumerable<Card> CreateDeck()
{
var deck = new List<Card>(); | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
c#, .net, playing-cards, shuffle
foreach (var value in Enum.GetValues<CardValue>())
foreach (var suit in Enum.GetValues<CardSuit>())
deck.Add(new Card(value, suit));
return deck;
}
Note that because we are now using a Card type, a lot of your string[] code will have to change to using a Card-based collection type. It could be Card[] but I would advise moving towards IEnumerable<Card> where possible. It's a more generalized approach that can account for both lists and arrays.
Shuffling multiple times
for(int i = 1; i <= numberOfShuffles; i++)
{
shuffledDeck = Shuffle(deck);
}
Shuffling multiple times makes sense in the real world, because when we shuffle, we only move the cards around somewhat. For example, in a riffle shuffle the cards are interleaved, but the order of the cards (in either half of the deck) remains the same. This is an imperfect random, and experienced dealers are able to keep track of the new card order; which is why we shuffle several times to make it impossible for humans to keep track of the card order.
The computer, however, does not cheat (unless you tell it to). It can randomly shuffle all cards around on the first go; so there is no need to shuffle more than once.
Shuffling multiple times is the equivalent of rolling a die several times and only using the last roll. The previous rolls were simply irrelevant and could have been skipped.
Dealing cards
private void DealCards(string[] shuffledDeck)
{
// long code omitted
} | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
c#, .net, playing-cards, shuffle
Dealing cards
private void DealCards(string[] shuffledDeck)
{
// long code omitted
}
1
There is a lot of repetition in your code here, which can be reduced drastically. Because you're using arrays, you're having to keep track of the "next empty" index where you want to add the next card. Had you been using a list, you could've simply called the .Add() method without needing to bother specifying where to add it (it automatically gets added at the end of the list).
Similary, because you are using arrays instead of lists, it's hard to keep track of how "full" your players' hands are. Had you been using lists, you wouldn't have needed to keep track of these separate integers, because you could just use the .Count property of a list.
Short example of how a list would be much easier to use here:
var myHand = new List<Card>();
myHand.Add(new Card(...));
myHand.Add(new Card(...));
myHand.Add(new Card(...));
Console.WriteLine($"You are holding {myHand.Count} cards");
This alone would reduce your method's size by 75% (this is my personal guesstimate) by cutting out all the index tracking and array juggling logic. I'm skipping the rewrite of your logic here as there are other optimizations I want to discuss.
2
Initially, I suspected you were dealing your cards round-robin style (P1, P2, P3, P4, P1, P2, P3, P4, P1, ...), but this is not the case. When you step through your code, you'll see that the first 13 cards are dealt to P1, then the next 13 are dealt to P2, and so on.
If this is the intended approach, then this can be simplified using LINQ. The simplest solution would be:
IEnumerable<Card> P1 = deck.Take(13);
IEnumerable<Card> P2 = deck.Skip(13).Take(13);
IEnumerable<Card> P3 = deck.Skip(2 * 13).Take(13);
IEnumerable<Card> P4 = deck.Skip(3 * 13).Take(13); | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
c#, .net, playing-cards, shuffle
This could be made better by iteratively creating your decks, but this would require you to create a list of player hands, instead of having separate variables for each player hand. Depending on your logic, that may or may not be desirable, which is why I'm skipping it here.
If you intend to deal your cards round-robin style; I suggest you reconsider. This kind of dealing in the real world is another form of random shuffling to ensure that players cannot reliably track which card goes to which player. However, given that we trust our own shuffling logic to be truly random (let's sidestep a discussion on "true" random here), there's no need to further obfuscate the card order.
I would omit round robin dealing because it has no real benefit here. However, if you prefer to model real world dealing strategies (whatever your reason may be), round robin dealing can be done easier using LINQ and modulo operations.
In essence, if we calculate index % 4 for each card's index in the list, we get a value from 0 to 3 which indicates which player should receive the card. Note that the 4 is the number of players. If you have 2 players, you would use % 2, and so on.
int playerCount = 4;
var playerHands = deck
// Select each card with its index attached)
.Select((card, index) => new { Index = index, Card = card })
// Sort them into sublists based on the index modulo calculation
.GroupBy(x => x.Index % playerCount)
// Reconvert back to only cards without indexes
.Select(g => g.Select(x => x.Card));
var P1 = playerHands[0];
var P2 = playerHands[1];
var P3 = playerHands[2];
var P4 = playerHands[3]; | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
c#, .net, playing-cards, shuffle
var P1 = playerHands[0];
var P2 = playerHands[1];
var P3 = playerHands[2];
var P4 = playerHands[3];
I suggest reading up on the modulo operator for more details. There's some interesting math here that is very commonly used in card games and similar cyclic data structures.
I suggest reading up on the GroupBy LINQ method for more details. There's more to say on this topic than I can cover in this answer.
Printing the result
First and foremost, you should be separating this logic into a method of its own. Whether you deal your cards and whether you print the player hands are two very different actions and you want to be able to take one without taking the other. As a simple example, you wouldn't want to immediately report all the player hands because then every player knows what the other player is holding.
I'm not going to go deep into how you should display your data, because it is so very contextual and prone to change. I suspect your intention here was only to verify the results of your logic, and the code you wrote suffices for that purpose.
One tip though, since I've changed your code to use a Card type, you can print the values as a string there:
public struct Card
{
public CardValue Value { get; }
public CardSuit Suit { get; }
public Card(CardValue value, CardSuit suit)
{
Value = value;
Suit = suit;
}
public override string ToString()
{
return $"{Value} of {Suit}";
}
}
$"{Value} of {Suit}" will yield results like Seven of Clubs, Ace of Spades, ... which nicely matches the names we give to playing cards. | {
"domain": "codereview.stackexchange",
"id": 42914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, playing-cards, shuffle",
"url": null
} |
java, algorithm, graph, depth-first-search
Title: DFS search that returns "not found" or distance
Question: Assuming I've the following code:
public static int dfsDistance(List<List<Integer>> graph, int current, int searchValue, int steps, BitSet visited) {
if (current == searchValue) {
return steps;
}
for (int neighbor : graph.get(current)) {
if (visited.get(neighbor)) {
continue;
}
visited.set(neighbor);
int cStep = dfs(graph, neighbor, searchValue, steps + 1, visited);
if (cStep > -1) {
return cStep;
}
}
return -1;
}
Is this the common approach? The only other way I could see is replacing it with Optional<Integer>. How should I properly return "not found" or distance?
Answer: One problem with your version is this:
visited.set(neighbor);
Above, if neighbor is a large integer (say 100_000_000), the BitSet will have to create a huge array under the hood to accommodate 100_000_000+ bits. One workaround is to use a simple java.util.HashSet<Integer>.
Also, the steps can be renamed to depth. (Actually, you could give the data more specific names, see below.)
Alternative implementation
I had this in mind:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 42915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, depth-first-search",
"url": null
} |
java, algorithm, graph, depth-first-search
public class DFS {
public static final int NOT_FOUND = -1;
public static int getDistance(List<List<Integer>> graph,
Integer currentNode,
Integer goalNode) {
return getDistanceImpl(
graph,
new HashSet<>(),
currentNode,
goalNode,
0);
}
private static int getDistanceImpl(List<List<Integer>> graph,
Set<Integer> visitedSet,
Integer currentNode,
Integer goalNode,
int depth) {
if (Objects.equals(currentNode, goalNode)) {
return depth;
}
for (Integer neighborNode : graph.get(currentNode)) {
if (visitedSet.add(neighborNode)) {
int tentativeDepth =
getDistanceImpl(
graph,
visitedSet,
neighborNode,
goalNode,
depth + 1);
if (tentativeDepth != NOT_FOUND) {
return tentativeDepth;
}
}
}
return NOT_FOUND;
}
public static void main(String[] args) {
// A 4-node cycle:
List<List<Integer>> graph = new ArrayList<>();
graph.add(new ArrayList<>());
graph.add(new ArrayList<>());
graph.add(new ArrayList<>());
graph.add(new ArrayList<>());
graph.get(0).add(1);
graph.get(1).add(2);
graph.get(2).add(3);
graph.get(3).add(0);
System.out.println(getDistance(graph, 0, 3));
}
}
for (int neighbor : graph.get(current)) {
} | {
"domain": "codereview.stackexchange",
"id": 42915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, depth-first-search",
"url": null
} |
java, algorithm, graph, depth-first-search
for (int neighbor : graph.get(current)) {
}
Above, graph.get(x) will return an Integer; thus, you spend some CPU cycles in autounboxing that Integer to an int.
Finally, your version does not allow negative graph nodes since visited.set(-1) will throw. | {
"domain": "codereview.stackexchange",
"id": 42915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, depth-first-search",
"url": null
} |
python, pandas
Title: Construct Pandas DataFrame whose (i,j)th entry is the probability that a person aged i+100 will still be alive after j years
Question: The following function takes the probability of a person aged 100+i dying in the next year (conditional on them being alive at the start of the year) and returns the probability that they will be alive after j years (for 0 < j < 21):
import pandas as pd
def prob_in_force():
# i-th entry of qx_curve gives the probability that a life aged i+100 (for 1 < i < 21) will die in the next year
# (conditional on being alive at the start of the year)
qx_curve = pd.Series([0.378702, 0.402588, 0.42709, 0.452127, 0.477608, 0.503432, 0.529493, 0.555674, 0.581857,
0.607918, 0.633731, 0.659171, 0.684114, 0.708442, 0.732042, 0.754809, 0.776648, 0.797477,
0.817225, 1], index=range(101, 121))
# i-th entry of px_curve gives the probability that a life aged i+100 (for 1 < i < 21) will NOT die in the next year
# (conditional on being alive at the start of the year)
px_curve = (1 - qx_curve).to_list()
# Construct a DataFrame whose (i, j)th entry is the probability that a life aged i+j+100 (for 1 < i < 21) will NOT
# die in the next year (conditional on being alive at the start of the year)
df_px_arr = pd.DataFrame([px_curve[i:] + [0] * i for i in range(1, 21)], index=[x for x in range(101, 121)])
# Calculate the cumulative product of the px values in each row of the DataFrame constructed above. The (i, j)th
# entry of this DataFrame is the probability that a life aged i+100 (for 1 < i < 21) will still be alive after j
# years
return df_px_arr.cumprod(axis=1)
if __name__ == '__main__':
print(prob_in_force()) | {
"domain": "codereview.stackexchange",
"id": 42916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, pandas
if __name__ == '__main__':
print(prob_in_force())
In practice, the qx curve is read from a csv file, so the instantiation of this variable can be ignored for the purpose of improving this code. The line that I suspect leaves most room for improvement is
df_px_arr = pd.DataFrame([px_curve[i:] + [0] * i for i in range(1, 21)], index=[x for x in range(101, 121)])
I suspect that both the speed and readability of this line leave room for improvement.
Any advice appreciated.
Answer: As in the comments, I don't trust that it's correct for you to skip the first element of your input; but for now I'll assume that this is intentional.
You don't need Pandas for any of this, and cutting straight to Numpy is possible (though you'll later see that this isn't always beneficial). The input and output can be trivially converted from and to Pandas if needed.
You're correct in thinking that there are speed concerns in this code. List comprehensions are often the death of performance in Pandas/Numpy. A fully-vectorised version is possible. The strided version I've demonstrated takes some spooky shortcuts in constructing a triangularised two-dimensional matrix with low overhead.
Numerically what I show here is equivalent, verified with regression tests and inspection. Functionally, it doesn't produce a dataframe. About the only thing you were using in Pandas that would be worth reintroducing after the fact is an age index, though you haven't shown any information on its use.
Of course, as with anything performance: measuring the results is critical, and - very interestingly - Numpy's cumprod implementation, whereas it has very low startup cost, scales poorly at O(n^2) whereas the original method and @tdy's method scale linearly. If you have fewer than ~1000 elements, one of the Numpy methods is best; otherwise, use one of the Pandas methods.
Suggested
from timeit import timeit | {
"domain": "codereview.stackexchange",
"id": 42916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, pandas
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from numpy.random import default_rng
def prob_in_force_old(qx_curve: np.ndarray) -> np.ndarray:
# i-th entry of px_curve gives the probability that a life aged i+100 (for 1 < i < 21) will NOT die in the next year
# (conditional on being alive at the start of the year)
px_curve = (1 - qx_curve).to_list()
# Construct a DataFrame whose (i, j)th entry is the probability that a life aged i+j+100 (for 1 < i < 21) will NOT
# die in the next year (conditional on being alive at the start of the year)
df_px_arr = pd.DataFrame([px_curve[i:] + [0] * i for i in range(1, 21)], index=[x for x in range(101, 121)])
# Calculate the cumulative product of the px values in each row of the DataFrame constructed above. The (i, j)th
# entry of this DataFrame is the probability that a life aged i+100 (for 1 < i < 21) will still be alive after j
# years
return df_px_arr.cumprod(axis=1)
def prob_in_force_rowwise(qx_curve: np.ndarray) -> np.ndarray:
n = len(qx_curve)
prod = np.zeros((n, n), dtype=qx_curve.dtype)
px_curve: np.ndarray = 1 - qx_curve[1:]
for y in range(0, n-1):
px_curve[y:].cumprod(out=prod[y, :n-y-1])
return prod
def prob_in_force_strided(qx_curve: np.ndarray) -> np.ndarray:
n = len(qx_curve)
# Tricky: make an array of double the width, so that when we broadcast-triangularise,
# the lower right fills with zeros.
px_curve = np.zeros(2*n, dtype=qx_curve.dtype)
px_curve[:n-1] = 1 - qx_curve[1:]
# Broadcast-triangularise. This is an efficient view construction that
# should not take up any additional memory.
broadcasted = np.broadcast_to(px_curve, (n, 2*n))
bytes = broadcasted.dtype.itemsize
slid = np.lib.stride_tricks.as_strided(px_curve, shape=(n, n), strides=(bytes, bytes))
return slid.cumprod(axis=1) | {
"domain": "codereview.stackexchange",
"id": 42916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, pandas
return slid.cumprod(axis=1)
def prob_in_force_tdy(qx_curve):
return pd.DataFrame({
i - 1: qx_curve.rsub(1).shift(-i, fill_value=0)
for i in range(1, 21)
}).cumprod(axis=1)
def test_regression() -> None:
def isclose(a, b):
assert np.allclose(a, b, rtol=0, atol=1e-9)
# i-th entry of qx_curve gives the probability that a life aged i+100 (for 1 < i < 21) will die in the next year
# (conditional on being alive at the start of the year)
as_array = np.array((0.378702, 0.402588, 0.42709, 0.452127, 0.477608, 0.503432, 0.529493, 0.555674, 0.581857,
0.607918, 0.633731, 0.659171, 0.684114, 0.708442, 0.732042, 0.754809, 0.776648, 0.797477,
0.817225, 1))
as_series = pd.Series(as_array)
for method in (prob_in_force_old, prob_in_force_strided, prob_in_force_rowwise, prob_in_force_tdy):
qx_curve = (
as_array if method in (prob_in_force_strided, prob_in_force_rowwise) else as_series
)
result = method(qx_curve)
if isinstance(result, pd.DataFrame):
result = result.values
assert result.shape == (20, 20)
isclose(0, result.min())
isclose(0.597412, result.max())
isclose(0.02894936687892334, result.mean())
isclose(11.579746751569337, result.sum())
def test_performance() -> None:
times = []
rand = default_rng(seed=0)
n_values = np.round(10**np.linspace(0.5, 5, 50))
methods = {
prob_in_force_old, prob_in_force_strided, prob_in_force_rowwise, prob_in_force_tdy,
}
for n in n_values:
n = int(n)
times.append(('ideal_n', n, (n/1000) * 5e-3))
if 1e2 <= n <= 1e4:
times.append(('ideal_n2', n, (n/1000)**2 * 5e-3))
as_array = rand.random(n)
as_series = pd.Series(as_array) | {
"domain": "codereview.stackexchange",
"id": 42916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, pandas
as_array = rand.random(n)
as_series = pd.Series(as_array)
slow = set()
for method in methods:
qx_curve = (
as_array if method in (prob_in_force_strided, prob_in_force_rowwise)
else as_series
)
def run():
method(qx_curve)
t = timeit(run, number=1)
times.append((method.__name__, n, t))
if t > 0.2:
slow.add(method)
methods -= slow
df = pd.DataFrame(times, columns=('method', 'n', 't'))
fig, ax = plt.subplots()
sns.lineplot(data=df, x='n', y='t', hue='method', ax=ax)
ax.set(xscale='log', yscale='log')
plt.show()
if __name__ == '__main__':
test_regression()
test_performance() | {
"domain": "codereview.stackexchange",
"id": 42916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, beginner, object-oriented, hangman
Title: Hangman game in Python with OOP
Question: I made the hangman game using OOP. It is the first "big" project I do using OOP. I would like to know if there is something to improve in the program I made.
This is the code:
#!/usr/bin/env python3
# Hangman game
import random
class Hangman:
HANGMAN_PICS = (r'''
βββββ
β β
β
β
β
β
βββββββββ''', r'''
βββββ
β β
O β
β
β
β
βββββββββ''', r'''
βββββ
β β
O β
| β
β
β
βββββββββ''', r'''
βββββ
β β
O β
/β β
β
β
βββββββββ''', r'''
βββββ
β β
O β
/β\ β
β
β
βββββββββ''', r'''
βββββ
β β
O β
/β\ β
/ β
β
βββββββββ''', r'''
βββββ
β β
O β
/β\ β
/ \ β
β
βββββββββ''')
def __init__(self, word):
"""
Our constructor class that instantiates the game.
"""
self.max_trials = len(self.HANGMAN_PICS) - 1
self.trials = self.max_trials
self.secret_word = word
self.secret_word_low = word.lower()
self.blanks = list('_' * len(self.secret_word))
self.found_letters = set()
def _spacer(self, length=50):
"""
Returns a dash string to be used as a separator.
"""
return '-' * length
@property
def _blanks_string(self):
"""
Returns a string with blanks.
"""
return ''.join(self.blanks)
def _draw_hangman(self):
"""
Returns a string with the current position of the hangman.
"""
return f'{self.HANGMAN_PICS[self.max_trials-self.trials]}\n' | {
"domain": "codereview.stackexchange",
"id": 42917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, hangman",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.