text
stringlengths
1
2.12k
source
dict
java, algorithm, linked-list, interview-questions com.quora.algo.list.TestUtils.java: package com.quora.algo.list; import static com.quora.algo.list.TestUtils.createList; import static com.quora.algo.list.TestUtils.eq; import static com.quora.algo.list.TestUtils.getList; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class SafeReverseLinkedListTest { private Node list1; private Node list2; private Node list3; private Node list4; private Node list5; @Before public void before() { list1 = getList(1); list2 = getList(2); list3 = getList(3); list4 = getList(4); list5 = getList(5); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooSmallFromIndex() { ReverseLinkedList.safeReverse(list1, 0, 1); } @Test(expected = IllegalArgumentException.class) public void throwsOnIndicesBackwards() { ReverseLinkedList.safeReverse(list2, 2, 1); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooLargeToIndex() { ReverseLinkedList.safeReverse(list5, 2, 6); } @Test public void list1TrivialReverse() { ReverseLinkedList.safeReverse(list1, 1, 1); } @Test public void listAll2() { Node result = ReverseLinkedList.safeReverse(list2, 1, 2); Node expected = createList(2, 1); assertTrue(eq(result, expected)); } @Test public void listAll3() { Node result = ReverseLinkedList.safeReverse(list3, 1, 3); Node expected = createList(3, 2, 1); assertTrue(eq(result, expected)); } } (pom.xml is here.). Critique request Please, tell me anything that comes to mind. PS: safeReverse is there for comparing the actual method to something that can be easily deemed correct.
{ "domain": "codereview.stackexchange", "id": 42781, "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, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions Answer: With a class containing static methods, only (like ReverseLinkedList), I can see final as a hint to keep it that way. (Make it abstract to block instantiation and support the notion.) But why make Node a class? A final one, at that? • Program to interfaces/specifications, not implementations.   Especially given multiple inheritance with interfaces, but not classes. (public static void checkContainsNoCycles(Node head) lacks a doc comment. Appreciating the presence of tests, focusing ReverseLinkedList() from here.) (Late) Idea how Node reverse(head, fromIndex, toInclusive) got to its present(ed) state: specification top-down design (&implementation?) of Node safeReverse(head, fromIndex, toInclusive) coding I find the naming helpful, I think you were explicitly trying to have it document your code. Consider making some of the variables final. Handling off-the-end indices in two places lead to a copy&paste error: The message about toIndex is true only when fromIndex == 1. Somehow, all those variable seem to have complicated things. Not copying the doc comment to highlight a problem I see with Java's doc comments avoided in Python docstrings: /** @throws <code>IllegalArgumentException}</code> * if {@code fromIndex} < 1 or {@code toInclusive < fromIndex} * @return {@code fromIndex == toInclusive} (reverse idempotent) */ private static boolean nonMutating(int fromIndex, int toInclusive) { if (0 < fromIndex && fromIndex <= toInclusive) { return fromIndex == toInclusive; } throw new IllegalArgumentException( "fromIndex(" + fromIndex + "), toIndex(" + toInclusive + ")"); }
{ "domain": "codereview.stackexchange", "id": 42781, "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, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions public static Node reverse(Node head, int fromIndex, final int toInclusive) { if (head == null || nonMutating(fromIndex, toInclusive)) { return head; } final Node preHead = new Node(-42, head), prefixTail, // known to stay unreversed headTurnsTail; // sublist head before, tail after reversal Node node = head, // iterating the list reversed = null;// already reversed int i = 1; // like node outside try for message in catch try { // Go to the fromIndex'th node: while (++i < fromIndex) { node = node.next; } prefixTail = node; node = headTurnsTail = prefixTail.next; // may throw NPE // March through the nodes comprising the sublist to reverse. for (/*i = fromIndex*/ ; i <= toInclusive ; i++) { Node nextNode = node.next; node.next = reversed; reversed = node; node = nextNode; } } catch (NullPointerException npe) { throw new IllegalArgumentException( (i < fromIndex ? ("fromIndex(" + fromIndex): "toIndex(" + toInclusive) + ") is too large: Must be at most " + i + ".", npe); } prefixTail.next = reversed; headTurnsTail.next = node; return preHead.next; }
{ "domain": "codereview.stackexchange", "id": 42781, "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, linked-list, interview-questions", "url": null }
python, performance, pandas Title: How do you efficiently calculate YTD values in a pandas dataframe? Question: I implemented the following code to calculate the YTD sum in Pandas: def calculateYTDSum(df:pd.DataFrame)->pd.DataFrame: '''Calculates the YTD sum of numeric values in a dataframe. This assumes the input dataframe contains a "quarter" column of type "Quarter" ''' ans = (df .sort_values(by='quarter', ascending=True) .assign(_year = lambda x: x['quarter'].apply(lambda x: x.year)) .groupby('_year') .apply(lambda x: x .set_index('quarter') .cumsum() ) .drop(columns=['_year']) .reset_index() .drop(columns=['_year']) .sort_values(by='quarter', ascending=False) ) return ans To see it in action consider the following: @dataclass class Quarter: # This class is used elsewhere in the codebase year:int quarter:int def __repr__(self): return f'{self.year} Q{self.quarter}' def __hash__(self) -> int: return self.year*4 + self.quarter def __lt__(self, other): return hash(self) < hash(other) df = pd.DataFrame({ 'quarter': [Quarter(2020, 4), Quarter(2020, 3), Quarter(2020, 2), Quarter(2020, 1), Quarter(2019, 4), Quarter(2019, 3), Quarter(2019, 2), Quarter(2019, 1)], 'quantity1' : [1,1,1,1,1,1,1,1], 'quantity2' : [2,2,2,2,3,3,3,3] }) Then you have: df = quarter quantity1 quantity2 0 2020 Q4 1 2 1 2020 Q3 1 2 2 2020 Q2 1 2 3 2020 Q1 1 2 4 2019 Q4 1 3 5 2019 Q3 1 3 6 2019 Q2 1 3 7 2019 Q1 1 3 and df.pipe(calculateYTDSum) = quarter quantity1 quantity2 4 2020 Q4 4 8 5 2020 Q3 3 6 6 2020 Q2 2 4 7 2020 Q1 1 2 0 2019 Q4 4 12 1 2019 Q3 3 9 2 2019 Q2 2 6 3 2019 Q1 1 3
{ "domain": "codereview.stackexchange", "id": 42782, "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, performance, pandas", "url": null }
python, performance, pandas 6 2020 Q2 2 4 7 2020 Q1 1 2 0 2019 Q4 4 12 1 2019 Q3 3 9 2 2019 Q2 2 6 3 2019 Q1 1 3 However, even for a small sample like the above, the calculation takes ~4ms - and tbh it looks unmaintainable. I welcome any recommendations on Python tooling, libraries, Pandas extensions, or code changes that would improve the performance and/or simplicity of the code. Answer: TL;DR The current groupby.apply code computes an extra cumsum (_year) and requires a lot of extra index manipulation (set + drop + reset + drop). Instead use groupby.cumsum, which is more idiomatic and ~20x faster for larger dataframes. Issues This groupby.apply adds a lot of overhead: ...groupby('_year').apply(lambda x: x.set_index('quarter').cumsum()) Sets an index Computes an extra cumsum over _year Later requires dropping the _year index and _year column We can see this intermediate state by stopping the chain early: (df.sort_values(by='quarter', ascending=True) .assign(_year=lambda x: x['quarter'].apply(lambda q: q.year)) .groupby('_year').apply(lambda g: g.set_index('quarter').cumsum()) ) # quantity1 quantity2 _year # _year quarter # 2019 2019 Q1 1 3 2019 # 2019 Q2 2 6 4038 # 2019 Q3 3 9 6057 # 2019 Q4 4 12 8076 # 2020 2020 Q1 1 2 2020 # 2020 Q2 2 4 4040 # 2020 Q3 3 6 6060 # 2020 Q4 4 8 8080 Suggestions groupby.cumsum is fast and idiomatic, but we lose the quarter column: (df.sort_values(by='quarter', ascending=True) .assign(_year=lambda x: x['quarter'].apply(lambda q: q.year)) .groupby('_year').cumsum() ) # quantity1 quantity2 # 7 1 3 # 6 2 6 # 5 3 9 # 4 4 12 # 3 1 2 # 2 2 4 # 1 3 6 # 0 4 8
{ "domain": "codereview.stackexchange", "id": 42782, "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, performance, pandas", "url": null }
python, performance, pandas So we can just join this groupby.cumsum result back to df[['quarter']]: df[['quarter']].join( df.sort_values(by='quarter', ascending=True) .assign(_year=lambda x: x['quarter'].apply(lambda q: q.year)) .groupby('_year').cumsum() ) # quarter quantity1 quantity2 # 0 2020 Q4 4 8 # 1 2020 Q3 3 6 # 2 2020 Q2 2 4 # 3 2020 Q1 1 2 # 4 2019 Q4 4 12 # 5 2019 Q3 3 9 # 6 2019 Q2 2 6 # 7 2019 Q1 1 3 Timings At 10K rows, the groupby.cumsum approach is ~21x faster than groupby.apply: %%timeit df[['quarter']].join( df.sort_values(by='quarter', ascending=True) .assign(_year=lambda x: x['quarter'].apply(lambda q: q.year)) .groupby('_year').cumsum() ) # 74 ms ± 1.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %%timeit (df.sort_values(by='quarter', ascending=True) .assign(_year=lambda x: x['quarter'].apply(lambda q: q.year)) .groupby('_year').apply(lambda g: g.set_index('quarter').cumsum()) .drop(columns=['_year']) .reset_index() .drop(columns=['_year']) .sort_values(by='quarter', ascending=False) ) # 1.58 s ± 16.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Testing data for reference: rng = np.random.default_rng(123) n = 2500 df = pd.DataFrame({ 'quarter': [Quarter(y, q) for y in range(1000, 1000 + n) for q in (4, 3, 2, 1)], 'quantity1': rng.integers(5, size=n * 4), 'quantity2': rng.integers(10, size=n * 4), }) # quarter quantity1 quantity2 # 0 1000 Q4 0 8 # 1 1000 Q3 3 5 # ... ... ... ... # 9998 3499 Q2 1 7 # 9999 3499 Q1 0 4 # # [10000 rows x 3 columns]
{ "domain": "codereview.stackexchange", "id": 42782, "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, performance, pandas", "url": null }
python Title: Check for matching symbols Question: The following code is a working solution for the balanced parentheses problem. I'm really just wondering about coding style here when it comes to separating out related if-statements. When there are two related if-statements, and where the second is run if the first is run, should I merge all checks into one complete if-statement, as in, if char in open_close_parens and stack and stack[-1] == open_close_parens[char]: or separate out the two if-statements as I've done here, with the check for an empty stack (list) then being more prominent in the second follow-up if-statement? def is_valid(stri: str) -> bool: stack = [] open_close_parens = { ')':'(', ']':'[', '}':'{' } for char in stri: if char in open_close_parens: # if stack is not empty and there is a match, pop it if stack and stack[-1] == open_close_parens[char]: stack.pop() else: return False else: stack.append(char) return not stack print(is_valid(']')) print(is_valid('()')) Answer: I would not combine those terms, but there are a few minor improvements. Naming: Naming things is hard, but you have some improvements. You should try to use accurate terminology when writing code. You are not checking for parenthesis. You are checking for brackets, where parenthesis () is a special case of brackets. Similarly stri is a bad name. Something like brackets is better and because of the typing hint we know it is a string. pen_close_parens can be named bracket_pairs and should be a global constant. So BRACKET_PAIRS. Early exits and continue: A way to clean up the logic is early exits and continue. Tests are nicely placed inside of docstrings. Code: BRACKET_PAIRS = {")": "(", "]": "[", "}": "{"}
{ "domain": "codereview.stackexchange", "id": 42783, "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", "url": null }
python Tests are nicely placed inside of docstrings. Code: BRACKET_PAIRS = {")": "(", "]": "[", "}": "{"} def balanced_brackets(brackets: str) -> bool: """Returns true if the number of brackets are balanced >>> balanced_brackets("]") False >>> balanced_brackets("()") True """ stack = [] for bracket in brackets: if bracket not in BRACKET_PAIRS: stack.append(bracket) continue # if stack is not empty and there is a match, pop it if not (stack and stack[-1] == BRACKET_PAIRS[bracket]): return False stack.pop() return not stack if __name__ == "__main__": import doctest doctest.testmod()
{ "domain": "codereview.stackexchange", "id": 42783, "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", "url": null }
c#, beginner, winforms, ms-word Title: Export DGV data as a table to a word file using Xceed's DocX library Question: my winform app contains a combo box, a button and two datagridview among other controls. Both DGV's have 3 columns. When I select an item/items from one or both of the DGV's and hit the button the app would create/open a word file(*.docx) and first add a header and a date on the top,then add a table with the selected DGV rows with a sum of the 3rd DGV column in a new page. Example 1 (only 1st DGV items are selected) The resulting word file should look like this Example 2 (both DGV items are selected) Then the resulting word file should look like The code I've done, the rough idea behind it is like this (its messy, badly organized and redundant and needs refinement): Check if any row/rows from the 2nd DGV is chosen or not, if yes, you cannot select more than 3 in the 2nd DGV & also you cannot select more than 8 rows in the 1st DGV when any item from the 2nd DGV is chosen. If the word file exists open it or create a new file Calculate the sum of the 3 rd columns of the selected rows of both the DGV's and Calculate their difference (DGV1-DGV2) Add the selected rows in the word file in table format (see image below) If no row/rows from the 2nd DGV is chosen, Check how many rows from the 1st DGV are selected. Minimum 1 item and/or maximum 15 items can be chosen. Then follow the steps from 2-4, only calculate sum of the 3rd columns of selected rows of DGV1 in this case. string fileName=@"G:\forwarding.docx"; if (kryptonDataGridView2.SelectedRows.Count > 0) { if (kryptonDataGridView2.SelectedRows.Count > 3) { MessageBox.Show(this,"Please select 3 or less Credit/Debit notes","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); return; } if (kryptonDataGridView1.SelectedRows.Count > 0 && kryptonDataGridView1.SelectedRows.Count > 8)
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word { MessageBox.Show(this,"Please select atleast 1 bill and/or maximum 8 bills","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); } else { decimal total = kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>() .Sum(tt => Convert.ToDecimal(tt.Cells[2].Value)); decimal _total = kryptonDataGridView2.SelectedRows.OfType<DataGridViewRow>() .Sum(tt => Convert.ToDecimal(tt.Cells[2].Value)); if (_total > total) { MessageBox.Show(this,"Credit/Debit note total value cannot be higher than total bill value","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); return; } decimal adj_total=total - _total; if (File.Exists(fileName)) { using( var document = DocX.Load( fileName ) ) { document.AddHeaders(); Xceed.Document.NET.Paragraph para=document.InsertParagraph(); para.InsertPageBreakBeforeSelf(); Xceed.Document.NET.Header header_default = document.Headers.Odd; Xceed.Document.NET.Paragraph p1 = header_default.InsertParagraph(); p1.FontSize(20).Append("W").Bold().Font("Arial").Color(Color.Red); p1.FontSize(20).Append("I").Bold().Font("Arial").Color(Color.Brown); p1.FontSize(20).Append("Z").Bold().Font("Arial").Color(Color.Gold); p1.FontSize(20).Append("D").Bold().Font("Arial").Color(Color.Chocolate); p1.FontSize(20).Append("E").Bold().Font("Arial").Color(Color.Teal); p1.FontSize(20).Append("R").Bold().Font("Arial").Color(Color.Violet); p1.FontSize(20).Append("M").Bold().Font("Arial").Color(Color.Orange);
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word p1.Alignment=Alignment.center; p1.FontSize(20); Xceed.Document.NET.Paragraph fdate=document.InsertParagraph(); fdate.Append(" Date: "+DateTime.Today.ToString("dd-MMM-yyyy")); fdate.Alignment=Alignment.right; Xceed.Document.NET.Paragraph blank=document.InsertParagraph(); var tab = document.AddTable( 1, 3 ); tab.Design = TableDesign.TableGrid; tab.Alignment=Alignment.center; tab.Rows[0].MergeCells(0,2); tab.AutoFit=AutoFit.Contents; tab.Rows[0].Cells[0].Paragraphs.First().Append(kryptonComboBox1.Text).Bold().Alignment=Alignment.center; document.InsertTable( tab ); var table = document.AddTable( kryptonDataGridView1.SelectedRows.Count+3, kryptonDataGridView1.Columns.Count ); table.Design = TableDesign.TableGrid; table.Alignment=Alignment.center; table.AutoFit = AutoFit.Contents; int rowNumber = 0; int columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); columnNumber++; } rowNumber++;
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>().OrderBy(c=>c.Index)) { columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(row.Cells[columnNumber].Value.ToString()); columnNumber++; } rowNumber++; } table.Rows[kryptonDataGridView1.SelectedRows.Count+1].Cells[2].Paragraphs.First().Append(total.ToString()).Bold(true); table.Rows[kryptonDataGridView1.SelectedRows.Count+1].MergeCells(0,1); table.Rows[kryptonDataGridView1.SelectedRows.Count+2].Cells[0].Paragraphs.First().Append("Credit/Debit Note").Bold(true).Alignment=Alignment.center; table.Rows[kryptonDataGridView1.SelectedRows.Count+2].MergeCells(0,2); document.InsertTable(table); var cndn_table = document.AddTable( kryptonDataGridView2.SelectedRows.Count+3, kryptonDataGridView2.Columns.Count ); cndn_table.Design = TableDesign.TableGrid; cndn_table.Alignment=Alignment.center; cndn_table.AutoFit = AutoFit.Contents; int _rowNumber = 0; int _columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView2.Columns) { cndn_table.Rows[_rowNumber].Cells[_columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); _columnNumber++; } _rowNumber++;
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word _rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView2.SelectedRows.OfType<DataGridViewRow>().OrderBy(c=>c.Index)) { _columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView2.Columns) { cndn_table.Rows[_rowNumber].Cells[_columnNumber].Paragraphs.First().Append(row.Cells[_columnNumber].Value.ToString()); _columnNumber++; } _rowNumber++; } cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+1].Cells[2].Paragraphs.First().Append(_total.ToString()).Bold(true); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+1].MergeCells(0,1); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+2].Cells[0].Paragraphs.First().Append("Total after adjustment :").Bold(true).Alignment=Alignment.right; cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+2].Cells[2].Paragraphs.First().Append(adj_total.ToString()).Bold(true); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+2].MergeCells(0,1); document.InsertTable(cndn_table); document.Save(); } } else { using( var document = DocX.Create( fileName ) ) { document.AddHeaders(); Xceed.Document.NET.Paragraph para=document.InsertParagraph();
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word Xceed.Document.NET.Paragraph para=document.InsertParagraph(); Xceed.Document.NET.Header header_default = document.Headers.Odd; Xceed.Document.NET.Paragraph p1 = header_default.InsertParagraph(); p1.FontSize(20).Append("W").Bold().Font("Arial").Color(Color.Red); p1.FontSize(20).Append("I").Bold().Font("Arial").Color(Color.Brown); p1.FontSize(20).Append("Z").Bold().Font("Arial").Color(Color.Gold); p1.FontSize(20).Append("D").Bold().Font("Arial").Color(Color.Chocolate); p1.FontSize(20).Append("E").Bold().Font("Arial").Color(Color.Teal); p1.FontSize(20).Append("R").Bold().Font("Arial").Color(Color.Violet); p1.FontSize(20).Append("M").Bold().Font("Arial").Color(Color.Orange); p1.Alignment=Alignment.center; p1.FontSize(20); Xceed.Document.NET.Paragraph fdate=document.InsertParagraph(); fdate.Append(" Date: "+DateTime.Today.ToString("dd-MMM-yyyy")); fdate.Alignment=Alignment.right; Xceed.Document.NET.Paragraph blank=document.InsertParagraph(); var tab = document.AddTable( 1, 3 ); tab.Design = TableDesign.TableGrid; tab.Alignment=Alignment.center; tab.Rows[0].MergeCells(0,2); tab.AutoFit=AutoFit.Contents; tab.Rows[0].Cells[0].Paragraphs.First().Append(kryptonComboBox1.Text).Bold().Alignment=Alignment.center; document.InsertTable( tab );
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word document.InsertTable( tab ); var table = document.AddTable( kryptonDataGridView1.SelectedRows.Count+3, kryptonDataGridView1.Columns.Count ); table.Design = TableDesign.TableGrid; table.Alignment=Alignment.center; table.AutoFit = AutoFit.Contents; int rowNumber = 0; int columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); columnNumber++; } rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>().OrderBy(c=>c.Index)) { columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(row.Cells[columnNumber].Value.ToString()); columnNumber++; } rowNumber++; } table.Rows[kryptonDataGridView1.SelectedRows.Count+1].Cells[2].Paragraphs.First().Append(total.ToString()).Bold(true); table.Rows[kryptonDataGridView1.SelectedRows.Count+1].MergeCells(0,1); table.Rows[kryptonDataGridView1.SelectedRows.Count+2].Cells[0].Paragraphs.First().Append("Credit/Debit Note").Bold(true).Alignment=Alignment.center; table.Rows[kryptonDataGridView1.SelectedRows.Count+2].MergeCells(0,2); document.InsertTable(table);
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word document.InsertTable(table); var cndn_table = document.AddTable( kryptonDataGridView2.SelectedRows.Count+3, kryptonDataGridView2.Columns.Count ); cndn_table.Design = TableDesign.TableGrid; cndn_table.Alignment=Alignment.center; cndn_table.AutoFit = AutoFit.Contents; int _rowNumber = 0; int _columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView2.Columns) { cndn_table.Rows[_rowNumber].Cells[_columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); _columnNumber++; } _rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView2.SelectedRows.OfType<DataGridViewRow>().OrderBy(c=>c.Index)) { _columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView2.Columns) { cndn_table.Rows[_rowNumber].Cells[_columnNumber].Paragraphs.First().Append(row.Cells[_columnNumber].Value.ToString()); _columnNumber++; } _rowNumber++; } cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+1].Cells[2].Paragraphs.First().Append(_total.ToString()).Bold(true); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+1].MergeCells(0,1);
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+2].Cells[0].Paragraphs.First().Append("Total after adjustment :").Bold(true).Alignment=Alignment.right; cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+2].Cells[2].Paragraphs.First().Append(adj_total.ToString()).Bold(true); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count+2].MergeCells(0,1); document.InsertTable(cndn_table); document.Save(); } } MessageBox.Show(this,"Done","Info",MessageBoxButtons.OK,MessageBoxIcon.Information); kryptonDataGridView1.Rows.Clear(); kryptonDataGridView2.Rows.Clear(); } } else { if (kryptonDataGridView1.SelectedRows.Count < 1 || kryptonDataGridView1.SelectedRows.Count > 15) { MessageBox.Show(this,"Please select minimum 1 item and/or maximum 15 items","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); } else { if (File.Exists(fileName)) { using( var document = DocX.Load( fileName ) ) { document.AddHeaders(); Xceed.Document.NET.Paragraph para=document.InsertParagraph(); para.InsertPageBreakBeforeSelf();
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word Xceed.Document.NET.Header header_default = document.Headers.Odd; Xceed.Document.NET.Paragraph p1 = header_default.InsertParagraph(); p1.FontSize(20).Append("W").Bold().Font("Arial").Color(Color.Red); p1.FontSize(20).Append("I").Bold().Font("Arial").Color(Color.Brown); p1.FontSize(20).Append("Z").Bold().Font("Arial").Color(Color.Gold); p1.FontSize(20).Append("D").Bold().Font("Arial").Color(Color.Chocolate); p1.FontSize(20).Append("E").Bold().Font("Arial").Color(Color.Teal); p1.FontSize(20).Append("R").Bold().Font("Arial").Color(Color.Violet); p1.FontSize(20).Append("M").Bold().Font("Arial").Color(Color.Orange); p1.Alignment=Alignment.center; p1.FontSize(20); Xceed.Document.NET.Paragraph fdate=document.InsertParagraph(); fdate.Append(" Date: "+DateTime.Today.ToString("dd-MMM-yyyy")); fdate.Alignment=Alignment.right; Xceed.Document.NET.Paragraph blank=document.InsertParagraph(); var tab = document.AddTable( 1, 3 ); tab.Design = TableDesign.TableGrid; tab.Alignment=Alignment.center; tab.Rows[0].MergeCells(0,2); tab.AutoFit=AutoFit.Contents; tab.Rows[0].Cells[0].Paragraphs.First().Append(kryptonComboBox1.Text).Bold().Alignment=Alignment.center; document.InsertTable( tab ); var table = document.AddTable( kryptonDataGridView1.SelectedRows.Count+2, kryptonDataGridView1.Columns.Count ); table.Design = TableDesign.TableGrid; table.Alignment=Alignment.center; table.AutoFit = AutoFit.Contents;
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word int rowNumber = 0; int columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); columnNumber++; } rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>().OrderBy(c=>c.Index)) { columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(row.Cells[columnNumber].Value.ToString()); columnNumber++; } rowNumber++; } decimal total = kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>() .Sum(tt => Convert.ToDecimal(tt.Cells[2].Value)); table.Rows[kryptonDataGridView1.SelectedRows.Count+1].Cells[0].Paragraphs.First().Append("Total :").Bold(true).Alignment=Alignment.right; table.Rows[kryptonDataGridView1.SelectedRows.Count+1].Cells[2].Paragraphs.First().Append(total.ToString()).Bold(true); table.Rows[kryptonDataGridView1.SelectedRows.Count+1].MergeCells(0,1); document.InsertTable(table); document.Save(); } } else { using( var document = DocX.Create( fileName ) ) { document.AddHeaders(); Xceed.Document.NET.Paragraph para=document.InsertParagraph();
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word Xceed.Document.NET.Paragraph para=document.InsertParagraph(); Xceed.Document.NET.Header header_default = document.Headers.Odd; Xceed.Document.NET.Paragraph p1 = header_default.InsertParagraph(); p1.FontSize(20).Append("W").Bold().Font("Arial").Color(Color.Red); p1.FontSize(20).Append("I").Bold().Font("Arial").Color(Color.Brown); p1.FontSize(20).Append("Z").Bold().Font("Arial").Color(Color.Gold); p1.FontSize(20).Append("D").Bold().Font("Arial").Color(Color.Chocolate); p1.FontSize(20).Append("E").Bold().Font("Arial").Color(Color.Teal); p1.FontSize(20).Append("R").Bold().Font("Arial").Color(Color.Violet); p1.FontSize(20).Append("M").Bold().Font("Arial").Color(Color.Orange); p1.Alignment=Alignment.center; p1.FontSize(20); Xceed.Document.NET.Paragraph fdate=document.InsertParagraph(); fdate.Append(" Date: "+DateTime.Today.ToString("dd-MMM-yyyy")); fdate.Alignment=Alignment.right; Xceed.Document.NET.Paragraph blank=document.InsertParagraph(); var tab = document.AddTable( 1, 3 ); tab.Design = TableDesign.TableGrid; tab.Alignment=Alignment.center; tab.Rows[0].MergeCells(0,2); tab.AutoFit=AutoFit.Contents; tab.Rows[0].Cells[0].Paragraphs.First().Append(kryptonComboBox1.Text).Bold().Alignment=Alignment.center; document.InsertTable( tab );
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word document.InsertTable( tab ); var table = document.AddTable( kryptonDataGridView1.SelectedRows.Count+2, kryptonDataGridView1.Columns.Count ); table.Design = TableDesign.TableGrid; table.Alignment=Alignment.center; table.AutoFit = AutoFit.Contents; int rowNumber = 0; int columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); columnNumber++; } rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>().OrderBy(c=>c.Index)) { columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView1.Columns) { table.Rows[rowNumber].Cells[columnNumber].Paragraphs.First().Append(row.Cells[columnNumber].Value.ToString()); columnNumber++; } rowNumber++; } decimal total = kryptonDataGridView1.SelectedRows.OfType<DataGridViewRow>() .Sum(tt => Convert.ToDecimal(tt.Cells[2].Value)); table.Rows[kryptonDataGridView1.SelectedRows.Count+1].Cells[0].Paragraphs.First().Append("Total :").Bold(true).Alignment=Alignment.right; table.Rows[kryptonDataGridView1.SelectedRows.Count+1].Cells[2].Paragraphs.First().Append(total.ToString()).Bold(true); table.Rows[kryptonDataGridView1.SelectedRows.Count+1].MergeCells(0,1); document.InsertTable(table);
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word document.InsertTable(table); document.Save(); } } MessageBox.Show(this,"Done","Info",MessageBoxButtons.OK,MessageBoxIcon.Information); } }
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word Answer: Review I have gone through all the code, this is a part of a single function that seems to be handling an event in the user interface, possibly a selection event on a data grid. There are 450 lines of code and that is way too much for a single function. A general rule in current programming is that any function larger than one screen in an editor is too large and needs to be broken down into smaller functions because it is too hard to follow the logic in the function. Visual Studio is kind enough to allow you to hide portions of the code, but I feel this is a bug in Visual Studio rather than a feature. Programmers that are just starting out using Visual Studio, C# and Windows Forms quite often make the mistake of tying the display together with the data and the logic. The problem with this is that it creates monolithic blocks of code that are impossible to debug and maintain. I've had to professionally fix bugs in similar code that was in production. Generally I broke the code into smaller functions. Move the data into a separate module (C# class) that performs all necessary logic. You can bind a DataTable from System.Data to a DataGridView. Perform all necessary actions on the DataTable rather than on the DataGridView. The DataGridView should be purely for presenting tabular data in the user interface, I have found it difficult to perform calculations and modifications to the data when trying to manipulate the data in the DataGridView. Move the code to generate the word document into another C# class that is only concerned with generating the word document, pass the DataTable into that class as input. The code that generates the word document should have nothing to do with the user interface. If you follow some or all of my suggestions your code will look something like this, please note that this code identifies possible bugs in the code where return is not called.
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word string fileName = @"G:\forwarding.docx"; // This assignment belong in the function that generates the word document
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word if (kryptonDataGridView2.SelectedRows.Count > 0) { if (kryptonDataGridView2.SelectedRows.Count > 3) { MessageBox.Show(this, "Please select 3 or less Credit/Debit notes", "Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (kryptonDataGridView1.SelectedRows.Count > 0 && kryptonDataGridView1.SelectedRows.Count > 8) { MessageBox.Show(this, "Please select atleast 1 bill and/or maximum 8 bills", "Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // missing return statement here. } else { if ()// Call function here to calculate the totals here and return a boolean value { MessageBox.Show(this, "Credit/Debit note total value cannot be higher than total bill value", "Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } decimal adj_total = total - _total; // call function to generate word document here. The if below belongs in the function that generates the document if (File.Exists(fileName)) else MessageBox.Show(this, "Done", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); kryptonDataGridView1.Rows.Clear(); kryptonDataGridView2.Rows.Clear(); } } else { if (kryptonDataGridView1.SelectedRows.Count < 1 || kryptonDataGridView1.SelectedRows.Count > 15) { MessageBox.Show(this, "Please select minimum 1 item and/or maximum 15 items", "Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // missing return here } else { // Call function to generate word document here MessageBox.Show(this, "Done", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word Don't Repeat Yourself This is in response to your comment/question at the end of your answer. The art/science of software design is to keep breaking the problem into smaller and smaller pieces until each problem problem is very simple to resolve. I don't specifically know if you can merge those functions into one, but you will know if you keep breaking the functions into smaller pieces that can be reused. Each one of the functions to generate repeats code that can be moved into functions, some examples are: Formatting the First Paragraph private void FormatFirstPara(ref Xceed.Document.NET.Paragraph p1) { p1.FontSize(20).Append("W").Bold().Font("Arial").Color(Color.Red); p1.FontSize(20).Append("I").Bold().Font("Arial").Color(Color.Brown); p1.FontSize(20).Append("Z").Bold().Font("Arial").Color(Color.Gold); p1.FontSize(20).Append("D").Bold().Font("Arial").Color(Color.Chocolate); p1.FontSize(20).Append("E").Bold().Font("Arial").Color(Color.Teal); p1.FontSize(20).Append("R").Bold().Font("Arial").Color(Color.Violet); p1.FontSize(20).Append("M").Bold().Font("Arial").Color(Color.Orange); p1.Alignment = Alignment.center; p1.FontSize(20); } Adding the cndn Table private void Cndn_table1() { cndn_table.Design = TableDesign.TableGrid; cndn_table.Alignment = Alignment.center; cndn_table.AutoFit = AutoFit.Contents; int _rowNumber = 0; int _columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView2.Columns) { cndn_table.Rows[_rowNumber].Cells[_columnNumber].Paragraphs.First().Append(column.HeaderText).Bold(); _columnNumber++; } _rowNumber++;
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word _rowNumber++; foreach (DataGridViewRow row in kryptonDataGridView2.SelectedRows.OfType<DataGridViewRow>().OrderBy(c => c.Index)) { _columnNumber = 0; foreach (DataGridViewColumn column in kryptonDataGridView2.Columns) { cndn_table.Rows[_rowNumber].Cells[_columnNumber].Paragraphs.First().Append(row.Cells[_columnNumber].Value.ToString()); _columnNumber++; } _rowNumber++; } cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count + 1].Cells[2].Paragraphs.First().Append(_total.ToString()).Bold(true); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count + 1].MergeCells(0, 1); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count + 2].Cells[0].Paragraphs.First().Append("Total after adjustment :").Bold(true).Alignment = Alignment.right; cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count + 2].Cells[2].Paragraphs.First().Append(adj_total.ToString()).Bold(true); cndn_table.Rows[kryptonDataGridView2.SelectedRows.Count + 2].MergeCells(0, 1); } Suggestions and Suggested Reading Here are basic software engineering guidelines that universities teach and generally applied in the industry. Design Patterns Use design patterns. Many design patterns apply across multiple programming languages. Some well know design patterns that might apply to your projects are: The Model View Controller Pattern sometimes known as MVC. The View Model ModelView Pattern sometimes known as MVVM.
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word Both of these design patterns are used in C# with Windows Forms, they are also common web development design patterns. DRY Code There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. Complexity I disagree a bit with a previous review, this code is too complex, which means it does too much. This is only part of a function, not a complete function and it does not begin to fit on one screen in an editor or IDE. A common programming practice is that any function that is larger than a single screen is too complex and should be broken into smaller functions. There is a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states: that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. SOLID Programming SOLID is 5 object oriented design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, beginner, winforms, ms-word The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. The Interface segregation principle - states that no client should be forced to depend on methods it does not use. The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. Example You also might want to look at this code review question that takes data from an excel spreadsheet and generates word documents as an example, the data and logic have been separated out in this question.
{ "domain": "codereview.stackexchange", "id": 42784, "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#, beginner, winforms, ms-word", "url": null }
c#, serialization, unity3d, byte Title: Multiplayer game byte array serializer with unity Question: I I'm trying to make an multiplayer game using golang and unity. Golang server side checking units on scene(like a character move). It also sends the information (position, health) of the units on the scene to the Unity 20 times per second. a unit contains 15 bytes of information. there is an average of 10 units in a scene. So golang sends Unity a byte array of size 150(10*15) 20 times per second. my question is to make this byte array meaningful on unity side with the best performance. private void UdpFrameHandle() { // _recieveData -> packet head(2 byte) + units data(150 byte) var pureData = _recieveData.packet.Skip(2).Take(_recieveData.packet.Count()).ToList(); // find unit count var unitCount = pureData.Count() / 15; // parse units for (int i = 0; i < unitCount; i++) { var unitInfo = ByteToUnitNetwork(pureData.Skip(15 * i).Take(15).ToList()); FrameManager.SendDataToView(unitInfo.ViewId, unitInfo); } } protected UnitNetworkDto ByteToUnitNetwork(List<byte> arr) { var viewId = BitConverter.ToInt16(arr.Take(2).ToArray(), 0); float x = BitConverter.ToSingle(arr.Skip(2).Take(4).ToArray(),0); float z = BitConverter.ToSingle(arr.Skip(6).Take(4).ToArray(),0); int health = BitConverter.ToInt16(arr.Skip(10).Take(2).ToArray(), 0); int teamType = arr.Skip(12).Take(1).First(); int targetViewId = BitConverter.ToInt16(arr.Skip(13).Take(2).ToArray(), 0); return new UnitNetworkDto { ViewId = viewId, X = x, Z = z, Health = health, TeamType = teamType, TargetViewId = targetViewId }; } this is my code. do you think there is a better way. Or do you have any suggestions?
{ "domain": "codereview.stackexchange", "id": 42785, "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#, serialization, unity3d, byte", "url": null }
c#, serialization, unity3d, byte this is my code. do you think there is a better way. Or do you have any suggestions? Answer: First of all, use array instead of list. Every time you know the data size, use array instead of list. Stop instantiating lot of new arrays, it's very slow. Use offset instead. This one arr.Skip(12).Take(1).First() looks really killing. Why not arr[13]? Also Int16 is short not int. Use matching types. Let's assume that _recieveData.packet is byte[]. private void UdpFrameHandle() { int unitCount = (_recieveData.packet.Length - 2) / 15; for (int i = 0; i < unitCount; i++) { var unitInfo = ByteToUnitNetwork(_recieveData.packet, i * 15 + 2); FrameManager.SendDataToView(unitInfo.ViewId, unitInfo); } } protected UnitNetworkDto ByteToUnitNetwork(byte[] arr, int offset) { short viewId = BitConverter.ToInt16(arr, offset); float x = BitConverter.ToSingle(arr, offset + 2); float z = BitConverter.ToSingle(arr, offset + 6); short health = BitConverter.ToInt16(arr, offset + 10); byte teamType = arr[13]; short targetViewId = BitConverter.ToInt16(arr, offset + 14); return new UnitNetworkDto { ViewId = viewId, X = x, Z = z, Health = health, TeamType = teamType, TargetViewId = targetViewId }; } Also BitConverter isn't safe to use because its numbers format depends on CPU architecture. Check BitConverter.IsLittleEndian before use. If available, use BinaryPrimitives instead. Also always keep in mind when you're thinking of performance: "Linq is slow".
{ "domain": "codereview.stackexchange", "id": 42785, "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#, serialization, unity3d, byte", "url": null }
c#, excel, error-handling, winforms Title: Follow Up: Refactored C# Tool to Generate MS Word Document Mailbox List From MS Excel Question: Background Some very good observations were made about my original code in the 2 answers to this question. In this version I have attempted to reduce cyclic complexity and class coupling even more as well as improve maintainability. The worst offenders of maintainability are now Visual Studio generated modules for the dialogs. Hopefully this is a much more SOLID implementation, please let me know where I violate any of the SOLID principles. If you wrote one of the 2 answers to the previous question and do not see where I addressed your concerns please let me know, I may have overlooked it, or I will explain why I didn't implement it. I did base the ExcelInterface class on the IDisposable interface, it still didn't clear up all the orphan processes, but I have addressed that in the protected virtual void Dispose(bool disposing) function. One bad habit I do acknowledge is there is currently no unit testing, only testing of the application itself. The code behind the forms for this question are in The User Interface Code since I can't fit all the code into a single question. The entire source for the project can be found in my GitHub Repository. It also contains a CSV version of the test data. All issues from this review and the user interface review can be found recorded in the issues list on the GitHub repository. The differences from the original implementation:
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms The global static variable declared in Program have been migrated to a public static class called Globals. Most MessageBox instances have been moved into the UI portion of the program. Each access of the data in the Excel Workbook is a stand alone task and the workbook is closed and the excel process is killed to prevent orphan excel processes from being left behind. Two Exception classes have been added to improve error handling. The class CExcelInteropMethods that interfaces with excel has been broken into multiple classes and is no longer monolithic, unfortunately it is still 390 lines of code, the new classes are ExcelInterface, ExcelFileData, CheckExcelWorkBookOpen, ExcelFileException, AlreadyOpenInExcelException and TenantDataTable. Some portions of the original CExcelInteropMethods have been moved into the Globals class or added as variables to the Globals class. The class CRenter has been replaced by Tenant. The bad C++ programming habit of classes starting with C has been removed, however, the code is now in 2 subdirectories, one called Classes and one called Forms. It helps me to find the code I need to work on. Questions/Concerns I am still interested in: Maintainability Cyclic Complexity Class/Object Coupling Anything I am doing in C# that is considered a bad habit. Anything where I can decrease the amount of code by using LINQ.
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms First 20 lines of Analysis Here is the first 20 lines of the code analysis as a CSV file. The CVS file is posted on GitHub if you want to see all of it. It has been sorted first by Maintainability, then by Complexity and then by Class Coupling. Scope,Project,Namespace,Type,Member,Maintainability Index,Cyclomatic Complexity,Depth of Inheritance,Class Coupling,Lines of Source code,Lines of Executable code Assembly,TenantRosterAutomation (Release), , , ,76,435,7,130,3806,1548 Namespace,TenantRosterAutomation (Release),TenantRosterAutomation, , ,76,429,7,119,3707,1531 Member,TenantRosterAutomation (Release),TenantRosterAutomation,EditPreferencesDlg,InitializeComponent() : void,25,1,,13,217,156 Member,TenantRosterAutomation (Release),TenantRosterAutomation,AddOrEditResidentDlg,InitializeComponent() : void,25,1,,10,238,162 Member,TenantRosterAutomation (Release),TenantRosterAutomation,PrintMailboxListsDlg,InitializeComponent() : void,32,1,,12,128,91 Member,TenantRosterAutomation (Release),TenantRosterAutomation,DeleteRenterDlg,InitializeComponent() : void,34,1,,12,118,81 Member,TenantRosterAutomation (Release),TenantRosterAutomation,RentRosterApp,InitializeComponent() : void,37,1,,9,94,63 Member,TenantRosterAutomation (Release),TenantRosterAutomation,ApartmentNumberVerifier,InitializeComponent() : void,45,1,,10,55,33 Type,TenantRosterAutomation (Release),TenantRosterAutomation,AddOrEditResidentDlg, ,51,15,7,20,349,199 Member,TenantRosterAutomation (Release),TenantRosterAutomation,TenantDataTable,"UdateTenantDataTable(int, Tenant) : bool",52,1,,4,31,20 Member,TenantRosterAutomation (Release),TenantRosterAutomation,PrintMailboxListsDlg,printAndOrSaveMailList(int) : void,53,10,,7,30,17 Member,TenantRosterAutomation (Release),TenantRosterAutomation,ExcelInterface,SaveEdits(List<Apartment>) : void,53,3,,10,39,20
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms Member,TenantRosterAutomation (Release),TenantRosterAutomation,MSWordInterface,"CreateMailistPrintAndOrSave(string, MailboxData, bool, bool, bool, bool) : bool",53,2,,8,38,19 Member,TenantRosterAutomation (Release),TenantRosterAutomation,MSWordInterface,"AddTitleToMailBoxList(Document, int, bool) : void",54,2,,8,23,17 Member,TenantRosterAutomation (Release),TenantRosterAutomation,ReportCurrentStatusWindow,InitializeComponent() : void,55,1,,8,33,17 Member,TenantRosterAutomation (Release),TenantRosterAutomation,UserPreferences,GetPreferenceValues(string[]) : bool,56,10,,5,54,12 Member,TenantRosterAutomation (Release),TenantRosterAutomation,PropertyComplex,CreateBuildingList(List<BuildingAndApartment>) : void,56,5,,4,32,15 Member,TenantRosterAutomation (Release),TenantRosterAutomation,PropertyComplex,"VerifyApartmentNumber(string, int) : PropertyComplex.ApartmentNumberValid",56,5,,3,34,16 Member,TenantRosterAutomation (Release),TenantRosterAutomation,UserPreferences,SavePreferencesToFile(string) : bool,57,4,,3,30,15 Member,TenantRosterAutomation (Release),TenantRosterAutomation,ExcelFileData,GetActiveWorkSheetContents(bool) : DataTable,57,3,,5,36,15 Member,TenantRosterAutomation (Release),TenantRosterAutomation,AddOrEditResidentDlg,"AddNewResident_Form_Load(object, EventArgs) : void",57,2,,5,18,13 Type,TenantRosterAutomation (Release),TenantRosterAutomation,EditPreferencesDlg, ,59,30,7,25,412,213 Member,TenantRosterAutomation (Release),TenantRosterAutomation,MSWordInterface,"FillFloor1Stand2Nd(MailboxData, int, Table) : void",59,4,,5,24,12
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms The Code To allow for some comparison with the original code I will do my best to present the modules in the same order as before, modules that haven't changed will not be presented here. ExcelInterface.cs using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using Excel = Microsoft.Office.Interop.Excel; namespace TenantRosterAutomation { // Provides the interface between the rest of the program and Microsoft excel. // This class is constructed on an as needed basis and should not persist // during execution. The distruction of this class releases the excel process // of this class creates and prevents orphan excel processes from being // created. class ExcelInterface : IDisposable { private Excel.Application xlApp; private Excel.Workbook xlWorkbook; private Excel.Worksheet tenantRoster; private bool disposed; private string tenantRosterName; private string WorkbookName; public int ExcelProcessId { get; private set; } public ExcelInterface(string workBookName, string workSheetName) { if (string.IsNullOrEmpty(workBookName)) { ExcelFileException efe = new ExcelFileException("Attempted to create ExcelInterface " + "Object without Excel Data File Name."); throw efe; } WorkbookName = workBookName; tenantRosterName = workSheetName; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms public void SaveEdits(List<Apartment> tenantUpdates) { ReportCurrentStatusWindow SaveStatus = new ReportCurrentStatusWindow(); string eSaveMsg = "Can't save edits to " + WorkbookName; try { SaveStatus.MessageText = "Saving updated tenants and apartments to Excel."; SaveStatus.Show(); StartExcelOpenWorkbook(); OpenTenantRosterWorkSheet(); xlApp.Visible = false; xlApp.DisplayAlerts = false; if (tenantRoster == null) { MessageBox.Show(eSaveMsg + " can't open the excel worksheet " + tenantRosterName + " to save changes"); return; } List<string> columnNames = GetColumnNames(); foreach (Apartment edit in tenantUpdates) { UpdateColumnData(edit, columnNames); } xlWorkbook.Save(); SaveStatus.Close(); } catch (AlreadyOpenInExcelException) { SaveStatus.Close(); throw; } catch (Exception ex) { SaveStatus.Close(); ExcelFileException efe = new ExcelFileException(eSaveMsg, ex); throw efe; } } public List<string> GetWorkSheetNames() { List<string> sheetNames = null; StartExcelOpenWorkbook(); if (xlWorkbook != null) { sheetNames = new List<string>(); int SheetCount = xlWorkbook.Sheets.Count; for (int i = 1; i <= SheetCount; ++i) { string sheetname = xlWorkbook.Sheets[i].Name; sheetNames.Add(sheetname); } }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return sheetNames; } public DataTable GetWorkSheetContents() { StartExcelOpenWorkbook(); int headerRow = 1; int firstColumn = 1; DataTable workSheetContents = ReadExcelIntoDatatble(headerRow, firstColumn); return workSheetContents; } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (xlWorkbook != null) { xlWorkbook.Close(); xlWorkbook = null; } if (xlApp != null) { xlApp.Quit(); xlApp = null; // Ensure that Excel exits after this class is disposed. // In some cases orphaned Excel proceses remain. Process xlProcess = Process.GetProcessById(ExcelProcessId); if (xlProcess != null) { xlProcess.Kill(); } } } disposed = true; } } [DllImport("user32.dll")] static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId); private int GetExcelProcessID(Excel.Application excelApp) { int processId; GetWindowThreadProcessId(excelApp.Hwnd, out processId); return processId; } private void StartExcelOpenWorkbook() { if (xlApp != null) { return; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms CheckExcelWorkBookOpen testOpen = new CheckExcelWorkBookOpen(); testOpen.TestAndThrowIfOpen(WorkbookName, false); xlApp = new Excel.Application(); xlApp.Visible = false; xlApp.DisplayAlerts = false; xlWorkbook = xlApp.Workbooks.Open(WorkbookName); // Retain the process ID so that the process can be killed later ExcelProcessId = GetExcelProcessID(xlApp); } // Updates a row of data in the excel file private void UpdateColumnData(Apartment rowEdit, List<string> columnNames) { Tenant tenant = rowEdit.Tenant; Excel.Range currentRow = FindRowInWorkSheetForUpdate(rowEdit.ApartmentNumber); UpdateColumn(currentRow, "Last", tenant.LastName, columnNames); UpdateColumn(currentRow, "First", tenant.FirstName, columnNames); UpdateColumn(currentRow, "Add OCC First", tenant.CoTenantFirstName, columnNames); UpdateColumn(currentRow, "Add OCC Last", tenant.CoTenantLastName, columnNames); UpdateColumn(currentRow, "Ph #", tenant.HomePhone, columnNames); UpdateColumn(currentRow, "Renters Ins", tenant.RentersInsurancePolicy, columnNames); UpdateColumn(currentRow, "Lease Start", tenant.LeaseStart, columnNames); UpdateColumn(currentRow, "Lease End", tenant.LeaseEnd, columnNames); UpdateColumn(currentRow, "Email", tenant.Email, columnNames); }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms private void OpenTenantRosterWorkSheet() { try { if (!string.IsNullOrEmpty(tenantRosterName)) { List<string> sheetNames = GetWorkSheetNames(); bool exists = sheetNames.Any(x => x.Contains(tenantRosterName)); if (!exists) { MessageBox.Show("The workbook " + WorkbookName + " does not contain the worksheet " + tenantRosterName); tenantRoster = null; } else { tenantRoster = xlWorkbook.Worksheets[tenantRosterName]; } } } catch (Exception ex) { string eMsg = "Function ExcelInterface.OpenTenantRosterWorkSheet() failed! "; ExcelFileException efe = new ExcelFileException(eMsg, ex); throw efe; } } // To enhance performance the excel worksheet is read once into a local // DataTable. private DataTable ReadExcelIntoDatatble(int HeaderLine, int ColumnStart) { try { OpenTenantRosterWorkSheet(); if (tenantRoster == null) { return null; } Excel.Range TenantDataRange = tenantRoster.UsedRange; DataTable tenantTable = CreateDataTableAddColumns(TenantDataRange, HeaderLine, ColumnStart); AddTenantDataToTenantTable(TenantDataRange, ref tenantTable, HeaderLine, ColumnStart);
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return tenantTable; } catch (Exception ex) { string eMsg = "In ExcelInterface::ReadExcelToDatatble error! "; ExcelFileException efe = new ExcelFileException(eMsg, ex); throw efe; } } private DataTable CreateDataTableAddColumns(Excel.Range TenantDataRange, int headerLine, int firstColumn) { DataTable tenantTable = new DataTable(); int columnCount = TenantDataRange.Columns.Count; for (int column = firstColumn; column <= columnCount; column++) { tenantTable.Columns.Add(Convert.ToString (TenantDataRange.Cells[headerLine, column].Value2), typeof(string)); } return tenantTable; } private void AddTenantDataToTenantTable(Excel.Range TenantDataRange, ref DataTable tenantTable, int headerLine, int firstColumn) { int columnCount = TenantDataRange.Columns.Count; int rowcount = TenantDataRange.Rows.Count; var values = TenantDataRange.Value2; for (int row = headerLine + 1; row <= rowcount; row++) { DataRow tenantData = tenantTable.NewRow(); for (int column = firstColumn; column <= columnCount; column++) { tenantData[column - firstColumn] = Convert.ToString(values[row, column]); } tenantTable.Rows.Add(tenantData); } } private Excel.Range FindRowInWorkSheetForUpdate(int apartmentNumber) { Excel.Range currentRow = null; object oMissing = Missing.Value;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms try { Excel.Range UnitNoColumn = GetUnitColumn(); if (UnitNoColumn != null) { currentRow = UnitNoColumn.Find(apartmentNumber.ToString(), oMissing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, oMissing, oMissing); } } catch (Exception ex) { ExcelFileException efe = new ExcelFileException( "Exception in ExcelInterface::getRowNumberForSave(): ", ex); throw efe; } return currentRow; } void UpdateColumn(Excel.Range currentRow, string columnName, string newValue, List<string> columnNames) { int columnNumber = GetColumnNumber(columnName, columnNames); currentRow.Cells[1, columnNumber] = newValue; } // Get the apartment unit column for searching. private Excel.Range GetUnitColumn() { Excel.Range UnitColumn = null; try { string headerName = "UnitNo"; Excel.Range headerRow = tenantRoster.UsedRange.Rows[1]; foreach (Excel.Range cel in headerRow.Cells) { if (cel.Text.ToString().Equals(headerName)) { UnitColumn = tenantRoster.Range[cel.Address, cel.End[Excel.XlDirection.xlDown]]; return UnitColumn; } } } catch (Exception ex) { ExcelFileException efe = new ExcelFileException( "Exception in ExcelInterface::GetUnitColumn()!", ex); throw efe; } return UnitColumn; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return UnitColumn; } private int GetColumnNumber(string columnName, List<string> columnNames) { int columnNumber = 1; foreach (string name in columnNames) { if (name.Equals(columnName)) { return columnNumber; } columnNumber++; } return columnNumber; } private List<string> GetColumnNames() { List<string> columnNames = new List<string>(); try { Excel.Range headerRow = tenantRoster.UsedRange.Rows[1]; foreach (Excel.Range cell in headerRow.Cells) { columnNames.Add(cell.Text); } } catch (Exception ex) { ExcelFileException efe = new ExcelFileException( "Exception in ExcelInterface::GetColumnNames()!", ex); throw efe; } return columnNames; } } } ExcelFileData.cs using System; using System.Collections.Generic; using System.Data; namespace TenantRosterAutomation { public class ExcelFileData { private DataTable worksheetContents; private List<string> WorkSheets; public string ActiveWorkbookFullFileSpec { get; private set; } public string ActiveWorkSheet { get; private set; } public bool WorkbookRead { get; private set; } public bool WorkbookOpen { get; private set; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms public ExcelFileData(string fullFileSpec, string activeWorkSheet) { if (string.IsNullOrEmpty(fullFileSpec)) { ExcelFileException efe = new ExcelFileException("Attempted to create ExcelFileData " + "Object without Excel Data File Name."); throw efe; } ActiveWorkbookFullFileSpec = fullFileSpec; ActiveWorkSheet = activeWorkSheet; WorkSheets = null; worksheetContents = null; WorkbookOpen = false; WorkbookRead = false; } public void AddOrChangeWorkSheets(List<string> workSheets) { if (WorkSheets != null) { WorkSheets = null; } WorkSheets = workSheets; } public void ChangeActiveWorkbook(string fullFileSpec) { ActiveWorkbookFullFileSpec = null; ActiveWorkbookFullFileSpec = fullFileSpec; } public void ChangeActiveWorksheet(string newActiveWorkSheet) { ActiveWorkSheet = null; ActiveWorkSheet = newActiveWorkSheet; } public List<string> GetWorkSheetCollection() { if (WorkSheets == null) { using (ExcelInterface excelInterface = new ExcelInterface( ActiveWorkbookFullFileSpec, ActiveWorkSheet)) { try { WorkSheets = excelInterface.GetWorkSheetNames(); excelInterface.Dispose(); } catch (Exception) { excelInterface.Dispose(); throw; } } } return WorkSheets; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return WorkSheets; } public void SaveChanges(List<Apartment> tenantEdits) { if (tenantEdits.Count > 0) { if (string.IsNullOrEmpty(ActiveWorkSheet)) { ExcelFileException efe = new ExcelFileException("Attempted to Save Excel changes " + "without Excel worksheet name."); throw efe; } using (ExcelInterface excelInterface = new ExcelInterface( ActiveWorkbookFullFileSpec, ActiveWorkSheet)) { try { excelInterface.SaveEdits(tenantEdits); excelInterface.Dispose(); } catch (Exception) { excelInterface.Dispose(); throw; } } } }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms public DataTable GetActiveWorkSheetContents(bool checkIfOPen) { if (worksheetContents == null) { if (string.IsNullOrEmpty(ActiveWorkSheet)) { ExcelFileException efe = new ExcelFileException("Attempted to get Excel worksheet " + "data without Excel worksheet name."); throw efe; } using (ExcelInterface excelInterface = new ExcelInterface( ActiveWorkbookFullFileSpec, ActiveWorkSheet)) { ReportCurrentStatusWindow statusReport = new ReportCurrentStatusWindow(); statusReport.MessageText = "Starting Excel and Loading Tenant Data From Excel."; statusReport.Show(); try { worksheetContents = excelInterface.GetWorkSheetContents(); excelInterface.Dispose(); } catch (Exception) { statusReport.Close(); excelInterface.Dispose(); throw; } statusReport.Close(); } } return worksheetContents; } } } TenantDataTable.cs using System; using System.Collections.Generic; using System.Data;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms TenantDataTable.cs using System; using System.Collections.Generic; using System.Data; namespace TenantRosterAutomation { public class TenantDataTable { private bool dataChanged; private DataTable tenantData; // Updates are stored to a list to be written to back to the excel // file when the user clicks the save button in the UI or when the // user exits the program. Writing the entire DataTable back is // undesirable for 2 reasons, one is performance and the other is // to prevent corruption of the excel file. private List<Apartment> tenantUpdates; private ExcelFileData ExcelFile; public bool DataChanged { get { return dataChanged; } } public DataTable TenantRoster { get { return tenantData; } } public TenantDataTable(ExcelFileData excelFile) { ExcelFile = excelFile; if (string.IsNullOrEmpty(ExcelFile.ActiveWorkSheet)) { } tenantData = excelFile.GetActiveWorkSheetContents(false); dataChanged = false; tenantUpdates = new List<Apartment>(); } public Tenant GetTenant(int apartmentNumber) { Tenant tenant = null; try { if (tenantData != null) { string searchString = "UnitNo = '" + apartmentNumber.ToString() + "'"; DataRow[] aptTenantData = tenantData.Select(searchString); tenant = FillTenantFromDataRow(aptTenantData); } } catch (Exception e) { Exception Tdt = new Exception("Exception in TenantDataTable::GetTenant(): ", e); throw Tdt; } return tenant; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return tenant; } public bool SaveChanges() { bool successChange = true; if (dataChanged) { ExcelFile.SaveChanges(tenantUpdates); dataChanged = false; tenantUpdates.Clear(); } return successChange; } public void DeleteTenant(int apartmentNumber) { Tenant tenant = new Tenant(); tenantUpdates.Add(new Apartment(apartmentNumber, tenant)); dataChanged = UdateTenantDataTable(apartmentNumber, tenant); } public void AddEditTenant(int apartmentNumber, Tenant tenant) { tenantUpdates.Add(new Apartment(apartmentNumber, tenant)); dataChanged = UdateTenantDataTable(apartmentNumber, tenant); } // Creates data for a single tenant that can be edited from // the local data table. private Tenant FillTenantFromDataRow(DataRow[] aptTenantData) { Tenant tenant = new Tenant(); tenant.LastName = aptTenantData[0].Field<string>("Last"); tenant.FirstName = aptTenantData[0].Field<string>("First"); tenant.CoTenantLastName = aptTenantData[0].Field<string>("Add OCC Last"); tenant.HomePhone = aptTenantData[0].Field<string>("Ph #"); tenant.CoTenantFirstName = aptTenantData[0].Field<string>("Add OCC First"); tenant.RentersInsurancePolicy = aptTenantData[0].Field<string>("Renters Ins"); tenant.LeaseStart = aptTenantData[0].Field<string>("Lease Start"); tenant.LeaseEnd = aptTenantData[0].Field<string>("Lease End"); tenant.Email = aptTenantData[0].Field<string>("Email"); return tenant; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return tenant; } // Updates the local version of the data in the application. private bool UdateTenantDataTable(int apartmentNumber, Tenant tenant) { bool updated = false; try { string searchString = "UnitNo = '" + apartmentNumber.ToString() + "'"; DataRow[] aptTenantData = tenantData.Select(searchString); DataRow currentApartment = aptTenantData[0]; currentApartment.BeginEdit(); currentApartment["First"] = tenant.FirstName; currentApartment["Last"] = tenant.LastName; currentApartment["Add OCC Last"] = tenant.CoTenantLastName; currentApartment["Add OCC First"] = tenant.CoTenantFirstName; currentApartment["Ph #"] = tenant.HomePhone; currentApartment["Renters Ins"] = tenant.RentersInsurancePolicy; currentApartment["Lease Start"] = tenant.LeaseStart; currentApartment["Lease End"] = tenant.LeaseEnd; currentApartment["Email"] = tenant.Email; currentApartment.EndEdit(); updated = true; } catch (Exception e) { Exception Tdt = new Exception( "Exception in TenantDataTable::updateDataTable(): ", e); throw Tdt; } return updated; } } } CheckExcelWorkBookOpen.cs using System; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms namespace TenantRosterAutomation { public class CheckExcelWorkBookOpen { // Check if there is any instance of excel open using the workbook. public static bool IsOpen(string workBook) { Excel.Application TestOnly = null; bool isOpened = true; // There are 2 possible exceptions here, GetActiveObject will throw // an exception if no instance of excel is running, and // workbooks.get_Item throws an exception if the sheetname isn't found. // Both of these exceptions indicate that the workbook isn't open. try { TestOnly = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); int lastSlash = workBook.LastIndexOf('\\'); string fileNameOnly = workBook.Substring(lastSlash + 1); TestOnly.Workbooks.get_Item(fileNameOnly); TestOnly = null; } catch (Exception) { isOpened = false; if (TestOnly != null) { TestOnly = null; } } return isOpened; } // Common error message to use when the excel file is op in another app. public string ReportOpen(bool atStartUp) { string alreadyOpen = "The excel workbook " + Globals.Preferences.ExcelWorkBookFullFileSpec + " is alread open in another application. \n" + "Please save your changes in the other application and close the " + "workbook and then" + (atStartUp ? " try this operation again." : " restart this application."); return alreadyOpen; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return alreadyOpen; } public void TestAndThrowIfOpen(string workBook, bool atStartUp) { if (IsOpen(workBook)) { AlreadyOpenInExcelException alreadOpen = new AlreadyOpenInExcelException(ReportOpen(atStartUp)); throw alreadOpen; } } } } AlreadyOpenInExcelException.cs using System; namespace TenantRosterAutomation { [Serializable] public class AlreadyOpenInExcelException : Exception { public AlreadyOpenInExcelException(string message) : base(message) { } } } ExcelFileException.cs using System; namespace TenantRosterAutomation { [Serializable] class ExcelFileException : Exception { public ExcelFileException(string message, Exception innerException = null) : base(message, innerException) { } } } Globals.cs namespace TenantRosterAutomation { // Perhaps this class and file should be renamed to GlobalModels // or just Modles. For performance reasons the classes provided // by this static class are created once at the beginning of the // program execution and deleted at the end of program execution. public static class Globals { private static string preferencesFileName = "./MyPersonalRentRosterPreferences.txt"; public static TenantDataTable TenantRoster; public static PropertyComplex Complex; public static UserPreferences Preferences; public static ExcelFileData ExcelFile; public static bool InitializeAllModels() { bool everthingInitialized = false; ReleaseAllModels(); Preferences = new UserPreferences(preferencesFileName); everthingInitialized = AdvancedInitialization(); return everthingInitialized; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return everthingInitialized; } // Restart with new preferences public static bool ReInitizeAllModels(UserPreferences preferences) { bool everthingInitialized = false; ReleaseAllModels(false); Preferences.CopyValues(preferences); everthingInitialized = AdvancedInitialization(); return everthingInitialized; } public static void ReleaseAllModels(bool releasePrefernces = true) { Complex = null; ExcelFile = null; TenantRoster = null; if (releasePrefernces) { Preferences = null; } } public static void Save() { SavePreferences(); SaveTenantData(); } public static void SavePreferences() { if (Preferences != null) { Preferences.SavePreferencesToFile(); } } public static void SaveTenantData() { if (TenantRoster != null && TenantRoster.DataChanged) { TenantRoster.SaveChanges(); } } private static bool AdvancedInitialization() { bool everthingInitialized = false; if (!string.IsNullOrEmpty(Preferences.ExcelWorkBookFullFileSpec) && !string.IsNullOrEmpty(Preferences.ExcelWorkSheetName)) { ExcelFile = CreateExcelDataFile(); if (ExcelFile != null) { TenantRoster = new TenantDataTable(ExcelFile); if (TenantRoster != null && TenantRoster.TenantRoster != null) { ConstructComplexAndReport(TenantRoster); } everthingInitialized = true; } } return everthingInitialized; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms return everthingInitialized; } private static void ConstructComplexAndReport(TenantDataTable TenantRoster) { ReportCurrentStatusWindow statusReport = new ReportCurrentStatusWindow(); statusReport.MessageText = "Constructing Apartment Complex Data."; statusReport.Show(); Complex = new PropertyComplex("Anza Victoria Apartments, LLC", TenantRoster.TenantRoster); statusReport.Close(); } private static ExcelFileData CreateExcelDataFile() { ExcelFileData excelFile = null; if (!string.IsNullOrEmpty(Preferences.ExcelWorkBookFullFileSpec)) { CheckExcelWorkBookOpen testOpen = new CheckExcelWorkBookOpen(); testOpen.TestAndThrowIfOpen(Preferences.ExcelWorkBookFullFileSpec, true); testOpen = null; excelFile = new ExcelFileData(Preferences.ExcelWorkBookFullFileSpec, Preferences.ExcelWorkSheetName); } return excelFile; } } } PropertyComplex.cs using System; using System.Collections.Generic; using System.Data; using System.Windows; namespace TenantRosterAutomation { // Models the entire apartment complex (5 buildings 177 apartmens) public class PropertyComplex { private string propertyName; private List<int> allApartmentNumbers; private List<Building> buildingList = new List<Building>(); public string PropertyName { get { return propertyName; } } public List<Building> Buildings { get; private set; } public List<string> BuildingAddressList { get; private set; } public List<int> StreetNumbers { get; private set; } public List<int> AllApartmentNumbers { get { return allApartmentNumbers; } } public int MinApartmentNumber { get; private set; } public int MaxApartmentNumber { get; private set; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms public enum ApartmentNumberValid { APARTMENT_NUMBER_OUT_OF_RANGE, APARTMENT_NUMBER_NONNUMERIC, APARTMENT_NUMBER_NOT_FOUND, APARTMENT_NUMBER_VALID } public PropertyComplex(string PropertyName, DataTable tenantRoster) { propertyName = PropertyName; BuildingAddressList = new List<string>(); allApartmentNumbers = new List<int>(); StreetNumbers = new List<int>(); List<BuildingAndApartment> bldsAntApts = CreateBuildingAndApartmentsList(tenantRoster); CreateBuildingList(bldsAntApts); foreach (Building building in Buildings) { BuildingAddressList.Add(building.FullStreetAddress); allApartmentNumbers.AddRange(building.ApartmentNumbers); } allApartmentNumbers.Sort(); MinApartmentNumber = allApartmentNumbers[0]; MaxApartmentNumber = allApartmentNumbers[allApartmentNumbers.Count - 1]; } public Building GetBuilding(int streetNumber) { Building building; building = buildingList.Find(x => x.AddressStreetNumber == streetNumber); return building; } public Building GetBuilding(string streetNumber) { int iStreetNumber = 0; try { if (Int32.TryParse(streetNumber, out iStreetNumber)) { return GetBuilding(iStreetNumber); } else { MessageBox.Show("Non Numeric string passed into Building::GetBuilding()."); return null; } } catch (Exception) { return null; } }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms public string FindBuildingByApartment(int apartmentNumber) { string buildingAddress = null; foreach (Building building in Buildings) { buildingAddress = building.BuildingFromApartment(apartmentNumber); if (!string.IsNullOrEmpty(buildingAddress)) { return buildingAddress; } } return buildingAddress; } public ApartmentNumberValid VerifyApartmentNumber(string aptNumberString, out int apartmentNumber) { ApartmentNumberValid exitStatus = ApartmentNumberValid.APARTMENT_NUMBER_VALID; int aptNumber = 0; apartmentNumber = aptNumber; if (string.IsNullOrEmpty(aptNumberString)) { return ApartmentNumberValid.APARTMENT_NUMBER_NONNUMERIC; } bool IsNumeric = int.TryParse(aptNumberString, out aptNumber); if (!IsNumeric) { return ApartmentNumberValid.APARTMENT_NUMBER_NONNUMERIC; } // 1/9/2022 Bugfix, some error messages contained the wrong value // for the apartment number. apartmentNumber = aptNumber; if (aptNumber < MinApartmentNumber || aptNumber > MaxApartmentNumber) { return ApartmentNumberValid.APARTMENT_NUMBER_OUT_OF_RANGE; } int found = 0; found = AllApartmentNumbers.Find(x => x == aptNumber); if (found == 0) { return ApartmentNumberValid.APARTMENT_NUMBER_NOT_FOUND; } apartmentNumber = aptNumber; return exitStatus; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms apartmentNumber = aptNumber; return exitStatus; } public MailboxData GetMailBoxList(Building building) { MailboxData mailboxData = new MailboxData(building); List<int> apartmentNumbers = building.ApartmentNumbers; foreach (int aptNo in apartmentNumbers) { mailboxData.addApartmentData(new Apartment(aptNo)); } return mailboxData; } private void CreateBuildingList(List<BuildingAndApartment> buildingAptList) { buildingList = new List<Building>(); string streetName = "Anza Avenue"; foreach (BuildingAndApartment entry in buildingAptList) { Building found = buildingList.Find(x => x.AddressStreetNumber == entry.building); if (found != null) { found.AddApartmentNumber(entry.apartment); } else { Building newBuilding = new Building(entry.building, streetName); newBuilding.AddApartmentNumber(entry.apartment); buildingList.Add(newBuilding); } } foreach (Building building in buildingList) { building.SortApartMentNumbers(); } foreach (Building building in buildingList) { StreetNumbers.Add(building.AddressStreetNumber); } Buildings = buildingList; } private List<BuildingAndApartment> CreateBuildingAndApartmentsList(DataTable tenantRoster) { if (tenantRoster == null) { return null; } List<BuildingAndApartment> buildingAndApartments = new List<BuildingAndApartment>(); int LastDataRow = tenantRoster.Rows.Count;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms for (int row = 0; row < LastDataRow; row++) { DataRow dataRow = tenantRoster.Rows[row]; buildingAndApartments.Add(CreateBuildAndApartmentFromDataRow(dataRow)); } return buildingAndApartments; } private BuildingAndApartment CreateBuildAndApartmentFromDataRow(DataRow dataRow) { string streetAddress = dataRow.Field<string>("Street 1").ToString(); string apartmentNumString = dataRow.Field<string>("UnitNo").ToString(); int apartmentNumber; Int32.TryParse(apartmentNumString, out apartmentNumber); int firstSpace = streetAddress.IndexOf(' '); string streetNumber = streetAddress.Substring(0, firstSpace); int buildingNumber; Int32.TryParse(streetNumber, out buildingNumber); BuildingAndApartment currentApt = new BuildingAndApartment(buildingNumber, apartmentNumber, streetAddress); return currentApt; } } } UserPreferences.cs using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; namespace TenantRosterAutomation { // Reads and writes the user preferences file. Stores the user // preferences for access to the excel spreadsheet as well as // storing print options. public class UserPreferences { private PrintSavePreference.PrintSave printSaveValue; private PrintSavePreference printSavePreference; private Dictionary<int, string> FieldNameByIndex; private Dictionary<string, int> IndexFromFieldName; private const int fileVersion = 1; private bool preferenceFileExists; private bool preferenceFileRead; private string preferencesFileName; private string workBookFullFileSpec; private string workSheetName; private string defaultSaveFolder;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms public bool HavePreferenceData { get { return preferenceFileRead; } } public PrintSavePreference.PrintSave PrintSaveOptions { get => printSaveValue; set { SetPrintSave(value); } } public string ExcelWorkBookFullFileSpec { get => workBookFullFileSpec; set { SetExcelWorkBookFullFileSpec(value); } } public string ExcelWorkSheetName { get => workSheetName; set { SetExcelWorkSheetName(value); } } public string DefaultSaveDirectory { get => defaultSaveFolder; set { SetDefaultSaveDirectory(value); } } public bool PreferenceValuesChanged { get; private set; } public UserPreferences() { CommonInitialization(); } public UserPreferences(string PreferencesFileName) { CommonInitialization(); preferencesFileName = PreferencesFileName; if (!string.IsNullOrEmpty(preferencesFileName)) { preferenceFileExists = File.Exists(preferencesFileName); if (preferenceFileExists) { preferenceFileRead = ReadPreferenceFile(preferencesFileName); } } } public UserPreferences(UserPreferences original) { CommonInitialization(); CopyValues(original, true); } public bool SavePreferencesToFile(string PreferencesFileName = null) { if (!PreferenceValuesChanged && !string.IsNullOrEmpty(PreferencesFileName)) { return true; } if (!string.IsNullOrEmpty(PreferencesFileName)) { preferencesFileName = PreferencesFileName; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms StreamWriter Preferencesfile = new StreamWriter(preferencesFileName); try { WritePreferencesToDisc(Preferencesfile); Preferencesfile.Flush(); Preferencesfile.Close(); preferenceFileExists = true; preferenceFileRead = true; return true; } catch (IOException) { MessageBox.Show("Unable to write to preferences file: " + preferencesFileName); return false; } } public void CopyValues(UserPreferences newPreferences, bool copyPreferenceFileName = false) { PrintSaveOptions = newPreferences.PrintSaveOptions; ExcelWorkBookFullFileSpec = newPreferences.ExcelWorkBookFullFileSpec; ExcelWorkSheetName = newPreferences.ExcelWorkSheetName; DefaultSaveDirectory = newPreferences.DefaultSaveDirectory; if (copyPreferenceFileName) { preferencesFileName = newPreferences.preferencesFileName; } } private void SetExcelWorkBookFullFileSpec(string newName) { workBookFullFileSpec = newName; PreferenceValuesChanged = true; } private void SetExcelWorkSheetName(string newName) { workSheetName = newName; PreferenceValuesChanged = true; } private void SetDefaultSaveDirectory(string newName) { defaultSaveFolder = newName; PreferenceValuesChanged = true; } private void SetPrintSave(PrintSavePreference.PrintSave PrintSave) { printSaveValue = PrintSave; PreferenceValuesChanged = true; }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms private void CommonInitialization() { preferencesFileName = null; preferenceFileExists = false; preferenceFileRead = false; printSavePreference = new PrintSavePreference(); InitDictionaries(); SetValuesToUndefinedState(); } private void InitDictionaries() { FieldNameByIndex = new Dictionary<int, string>(); int fieldNameCount = fileValueIds.Length; for (int i = 0; i < fieldNameCount; ++i) { FieldNameByIndex.Add(i, fileValueIds[i]); } IndexFromFieldName = new Dictionary<string, int>(); for (int i = 0; i < fieldNameCount; ++i) { IndexFromFieldName.Add(fileValueIds[i], i); } } private void SetValuesToUndefinedState() { PrintSaveOptions = PrintSavePreference.PrintSave.PrintOnly; } // These constants and variables are used when reading and writing // the preferences to and from the preference file. private const int fileVersionId = 0; private const int printSaveOptionId = 1; private const int defaultSaveDirId = 2; private const int rentRosterFileId = 3; private const int rentRosterSheetNameId = 4; private string[] fileValueIds = { "FileVersion:", "PrintSaveValue:", "DefaultSaveDirectory:", "RentRosterFile:", "RentRosterSheet:" };
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms private void WritePreferencesToDisc(StreamWriter preferenceFile) { preferenceFile.WriteLine(fileValueIds[fileVersionId] + " " + fileVersion.ToString()); preferenceFile.WriteLine(fileValueIds[printSaveOptionId] + " " + printSavePreference.ConvertPrintSaveToString(printSaveValue)); preferenceFile.WriteLine(fileValueIds[defaultSaveDirId] + " " + DefaultSaveDirectory); preferenceFile.WriteLine(fileValueIds[rentRosterFileId] + " " + ExcelWorkBookFullFileSpec); preferenceFile.WriteLine(fileValueIds[rentRosterSheetNameId] + " " + ExcelWorkSheetName); } private void ConvertandTestFileVersion(string fileInput) { try { int testFileVersion = Int32.Parse(fileInput); if (testFileVersion != fileVersion) { if (testFileVersion < fileVersion) { MessageBox.Show("Preference file version " + fileInput + " out of date, please edit preferences to add new field values."); } else { MessageBox.Show("This version of the Tenant Roster tool does not support all the features of the tool that generated the file."); } } } catch (FormatException e) { string eMsg = "Reading preferences File Version failed: " + e.Message; MessageBox.Show(eMsg); } } private bool ReadPreferenceFile(string fileName) { bool fileReadSucceeded = true; string[] lines;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms if (File.Exists(fileName)) { try { lines = File.ReadAllLines(fileName); fileReadSucceeded = GetPreferenceValues(lines); } catch (IOException) { fileReadSucceeded = false; } } return fileReadSucceeded; } private bool GetPreferenceValues(string[] lines) { bool hasAllFields = false; int requiredFieldCount = 0; int lineCount = lines.Length; for (int i = 0; i < lineCount; ++i) { string[] nameAndValue = lines[i].Split(' '); // The first value in the line is the field index, if there // is no second value then the preference is not specified if (nameAndValue.Length < 2) { return false; } int fieldIndex; IndexFromFieldName.TryGetValue(nameAndValue[0], out fieldIndex); switch (fieldIndex) { case fileVersionId: ConvertandTestFileVersion(nameAndValue[1]); requiredFieldCount++; break; case printSaveOptionId: printSaveValue = printSavePreference.ConvertStringToPrintSave(nameAndValue[1]); requiredFieldCount++; break; case defaultSaveDirId: DefaultSaveDirectory = CorrectForMuliWordNames(nameAndValue); requiredFieldCount++; break; case rentRosterFileId: ExcelWorkBookFullFileSpec = CorrectForMuliWordNames(nameAndValue); requiredFieldCount++; break;
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms case rentRosterSheetNameId: ExcelWorkSheetName = CorrectForMuliWordNames(nameAndValue); requiredFieldCount++; break; default: MessageBox.Show("Reading preference file: Unknown field identity"); return false; } } if (requiredFieldCount == fileValueIds.Length) { hasAllFields = true; if (string.IsNullOrEmpty(ExcelWorkSheetName)) { hasAllFields = false; } } return hasAllFields; } private string CorrectForMuliWordNames(string[] lineValues) { // The first value in the line is the field index, if there // is no second value then the preference is not specified if (lineValues.Length < 2) { return ""; } string wholeName = lineValues[1]; for (int i = 2; i < lineValues.Length; i++) { wholeName += " " + lineValues[i]; } return wholeName; } } } Program.cs using System; using System.Windows.Forms; namespace TenantRosterAutomation { static class Program { #if DEBUG [DllImport("kernel32.dll")] static extern bool AttachConsole(int dwProcessId); private const int ATTACH_PARENT_PROCESS = -1; #endif
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { #if DEBUG AttachConsole(ATTACH_PARENT_PROCESS); Console.WriteLine("\nStarting TenantRosterAutomation Application"); #endif try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new RentRosterApp()); } catch (AlreadyOpenInExcelException e) { MessageBox.Show(e.Message); } catch (Exception e) { MessageBox.Show("An unexpected error occurred: " + e.ToString()); } } } } Answer: I'm happy to see that we were able to convince you to use the C# naming convension :-] Here are my other thoughs... ExcelInterface To my taste the ExcelInterface.SaveEdits method either does too much for a Save method or it shouldn't be called like that. Internally it calls UpdateColumnData and this is the part that bothers me. A clean Save shouldn't be doing things like that. I would not expect it to change my workseet. I don't think you should call StartExcelOpenWorkbook everywhere. I my opinion the instance of ExcelInterface should be fully initialized at creation time. Otherwise it's too easy to implement something new and to forget that it's necessary to call this method first. Throwing exceptions that use the class and method names as a message like Function ExcelInterface.OpenTenantRosterWorkSheet() failed! doesn't have much value as the stack-strace already provides the same information. It'd be much more helpful to the user if you gave them other details like the name of the excel-file or the worksheet or the row or some other data that is relevant to an exception and provides more context.
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms Try to write pure functions where possible. One such candidate is the OpenTenantRosterWorkSheet method. Currently it does something and sets the tenantRoster field. This side-effect is unexpected and you need to know its implementation in order understand its purpose. I'd start with something like this. Where you explicitly pass the necessary parameters and explictly get a result. It might look like an overkill at first but when you keep writing code like this it might quickly turn out that a method is actually so gneric that it could be extracted into a utility method like an extension. The next step would be to rewrite GetWorkSheetNames. It's almost there, it just needs to take some more parameters and you can turn it into static. This way you'd greatly reduce the complexity and made the code more intuitive to use. private Excel.Worksheet? OpenWorksheetOrDefault(Excel.Workbook xlWorkbook, string tenantRosterName) { try { if (!string.IsNullOrEmpty(tenantRosterName)) { List<string> sheetNames = GetWorkSheetNames(); bool exists = sheetNames.Any(x => x.Contains(tenantRosterName)); if (!exists) { MessageBox.Show("The workbook " + WorkbookName + " does not contain the worksheet " + tenantRosterName); return default; } else { return xlWorkbook.Worksheets[tenantRosterName]; } } } catch (Exception ex) { string eMsg = "Function ExcelInterface.OpenTenantRosterWorkSheet() failed! "; ExcelFileException efe = new ExcelFileException(eMsg, ex); throw efe; } }
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, excel, error-handling, winforms GetUnitColumn could use some more forgiving string conditions. Currently it's case sensitive and doesn't trim strings. From my experience I know this easily goes sideways. I even use my own custom SoftString class to avoid the case and white-space trap. Dispose(bool disposing) could be simplified with the null propagation operator like this. No ifs requried: xlWorkbook?.Close(); xlWorkbook = null; xlApp?.Quit(); xlApp = null; // Ensure that Excel exits after this class is disposed. // In some cases orphaned Excel proceses remain. Process.GetProcessById(ExcelProcessId)?.Kill(); ExcelFileData public void AddOrChangeWorkSheets(List<string> workSheets) { if (WorkSheets != null) { WorkSheets = null; } WorkSheets = workSheets; } This, ChangeActiveWorkbook, and ChangeActiveWorksheet could be properties. TenantDataTable public TenantDataTable(ExcelFileData excelFile) { ExcelFile = excelFile; if (string.IsNullOrEmpty(ExcelFile.ActiveWorkSheet)) { } tenantData = excelFile.GetActiveWorkSheetContents(false); dataChanged = false; tenantUpdates = new List<Apartment>(); } I like that if condition. It looks really useful ;-P string searchString = "UnitNo = '" + apartmentNumber.ToString() + "'"; This could be replaced with string interpolation: var searchString = $"UnitNo = '{apartmentNumber}'"; UdateTenantDataTable can either return bool or throws an exception if it fails. It should be either or. Both mechanisms at the same time are redundant as it can never return false. CheckExcelWorkBookOpen IsOpen works with the workbook name and extracts the file-name: int lastSlash = workBook.LastIndexOf('\\'); string fileNameOnly = workBook.Substring(lastSlash + 1); This can be done easier with the Path class that provides a couple of handy methods to work with paths and file names.
{ "domain": "codereview.stackexchange", "id": 42786, "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#, excel, error-handling, winforms", "url": null }
c#, image, memory-optimization, .net-core Title: Memory leak I can't identify using Bitmap and Graphics classes Question: I have some parallel.for one inside another. the last parallel.for have a normal for that should Create images by combining other images. the images are generated but the memory consumed by the process slowly increases. I'm using net core 6, and as you can see I have dispatched all the Bitmaps and the Graphics objects. also I'm forcing garbage collection so the memory stop growing (I ran the code for 4 hours without forcing collection and the dispatched objects were not collected) here is the code: using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; Console.WriteLine("Generando!"); var count = 0; Parallel.For(1, 11, (a) => { Parallel.For(1, 11, (b) => { Parallel.For(1, 11, (c) => { Parallel.For(1, 11, (d) => { Parallel.For(1, 11, (e) => { for (int f = 1; f <= 10; f++) { Bitmap source1 = new Bitmap($"1/{a}.png"); Bitmap source2 = new Bitmap($"2/{b}.png"); Bitmap source3 = new Bitmap($"3/{c}.png"); Bitmap source4 = new Bitmap($"4/{d}.png"); Bitmap source5 = new Bitmap($"5/{e}.png");
{ "domain": "codereview.stackexchange", "id": 42787, "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#, image, memory-optimization, .net-core", "url": null }
c#, image, memory-optimization, .net-core Bitmap sourceBase = new Bitmap($"Rostro Base.png"); Bitmap source6 = new Bitmap($"6/{f}.png"); var target = new Bitmap(source1.Width, source1.Height, PixelFormat.Format32bppArgb); var graphics = Graphics.FromImage(target); graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear graphics.DrawImage(sourceBase, 0, 0); graphics.DrawImage(source6, 0, 0); graphics.DrawImage(source5, 0, 0); graphics.DrawImage(source4, 0, 0); graphics.DrawImage(source3, 0, 0); graphics.DrawImage(source2, 0, 0); graphics.DrawImage(source1, 0, 0); count++; var nombre = $"{count}_{a}-{b}-{c}-{d}-{e}-{f}"; var target2 = Cropimage(target); target2.Save($"rostros/{nombre}.png", ImageFormat.Png); source1.Dispose(); source2.Dispose(); source3.Dispose(); source4.Dispose(); source5.Dispose(); source6.Dispose(); sourceBase.Dispose(); target.Dispose(); target2.Dispose(); graphics.Dispose(); GC.Collect(); } }); Console.Write($"\r{count} imagenes generadas "); }); }); }); }); Bitmap Cropimage(Bitmap input) { // Find the min/max non-white/transparent pixels Point min = new Point(int.MaxValue, int.MaxValue); Point max = new Point(int.MinValue, int.MinValue);
{ "domain": "codereview.stackexchange", "id": 42787, "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#, image, memory-optimization, .net-core", "url": null }
c#, image, memory-optimization, .net-core for (int x = 0; x < input.Width; ++x) { for (int y = 0; y < input.Height; ++y) { Color pixelColor = input.GetPixel(x, y); if (pixelColor.A > 0) { if (x < min.X) min.X = x; if (y < min.Y) min.Y = y; if (x > max.X) max.X = x; if (y > max.Y) max.Y = y; } } } // Create a new bitmap from the crop rectangle Rectangle cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y); Bitmap newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height); using (Graphics g = Graphics.FromImage(newBitmap)) { g.DrawImage(input, 0, 0, cropRectangle, GraphicsUnit.Pixel); } return newBitmap; } Answer: Just few tips Prefer using over manual calling Dispose(). Consumed memory isn't always busy memory, GC can free the memory anytime it want. That is OK, trust GC. Just assume that there's no leaks in managed code possible unless you manually allocated unmanaged memory. manual calling GC.Collect() is almost never effective but makes the app slower. The above code isn't an exception NEVER use GetPixel/SetPixel if you don't want to die before the app ends working, it's superslow way to deal with Bitmap count is shared counter, increment it thread-safely. No need to read the same image from disk for each Thread, lock here is more efficient.
{ "domain": "codereview.stackexchange", "id": 42787, "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#, image, memory-optimization, .net-core", "url": null }
c#, image, memory-optimization, .net-core int count = 0; using Bitmap sourceBase = new Bitmap($"Rostro Base.png"); Parallel.For(1, 11, (a) => { using Bitmap source1 = new Bitmap($"1/{a}.png"); Parallel.For(1, 11, (b) => { using Bitmap source2 = new Bitmap($"2/{b}.png"); Parallel.For(1, 11, (c) => { using Bitmap source3 = new Bitmap($"3/{c}.png"); Parallel.For(1, 11, (d) => { using Bitmap source4 = new Bitmap($"4/{d}.png"); Parallel.For(1, 11, (e) => { using Bitmap source5 = new Bitmap($"5/{e}.png"); for (int f = 1; f <= 10; f++) { using Bitmap source6 = new Bitmap($"6/{f}.png"); using Bitmap target = new Bitmap(source1.Width, source1.Height, PixelFormat.Format32bppArgb); using Graphics graphics = Graphics.FromImage(target); graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear lock(sourceBase) graphics.DrawImage(sourceBase, 0, 0); graphics.DrawImage(source6, 0, 0); graphics.DrawImage(source5, 0, 0); lock(source4) graphics.DrawImage(source4, 0, 0); lock(source3) graphics.DrawImage(source3, 0, 0); lock(source2) graphics.DrawImage(source2, 0, 0); lock(source1) graphics.DrawImage(source1, 0, 0);
{ "domain": "codereview.stackexchange", "id": 42787, "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#, image, memory-optimization, .net-core", "url": null }
c#, image, memory-optimization, .net-core int localCount = Interlocked.Increment(ref count); string nombre = $"{localCount}_{a}-{b}-{c}-{d}-{e}-{f}"; using Bitmap target2 = Cropimage(target); target2.Save($"rostros/{nombre}.png", ImageFormat.Png); } }); Console.Write($"\r{count} imagenes generadas "); }); }); }); }); Bitmap Cropimage(Bitmap input) { // Find the min/max non-white/transparent pixels Point min = new Point(int.MaxValue, int.MaxValue); Point max = new Point(int.MinValue, int.MinValue); // Retreiving bitmap data to array BitmapData data = input.LockBits(new Rectangle(Point.Empty, input.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte[] bytes = new byte[input.Height * input.Width * 4]; // 32bpp Marshal.Copy(data.Scan0, bytes, 0, input.Height * data.Stride); // Stride can be negative in some bitmaps but Marshal supports that. // In short: (Math.Abs(data.Stride) == input.Width * 4) for 32bpp is always 'true'. input.UnlockBits(data); // bytes array contains sequence of 4-byte pixels like B G R A B G R A for (int y = 0; y < input.Height; ++y) { int rowOffset = y * input.Width * 4; for (int x = 0; x < input.Width; ++x) { int colOffset = x * 4; if (bytes[rowOffset + colOffset + 3] > 0) { if (x < min.X) min.X = x; if (y < min.Y) min.Y = y; if (x > max.X) max.X = x; if (y > max.Y) max.Y = y; } } } // Create a new bitmap from the crop rectangle Rectangle cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
{ "domain": "codereview.stackexchange", "id": 42787, "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#, image, memory-optimization, .net-core", "url": null }
c#, image, memory-optimization, .net-core Bitmap newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height); using Graphics g = Graphics.FromImage(newBitmap); g.DrawImage(input, 0, 0, cropRectangle, GraphicsUnit.Pixel); return newBitmap; } This might work ~100x times faster than the initial code. It also may work without locks but I'm not sure if DrawImage uses LockBits internally and didn't try accessing single Bitmap from multiple threads. But you may try. Anyway there will be no any sensitive difference in performance. Reading same images thousands times from disk is significantly slower in comparison to reading it from memory even locked for single-threaded access.
{ "domain": "codereview.stackexchange", "id": 42787, "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#, image, memory-optimization, .net-core", "url": null }
python, python-3.x Title: Python: select n of each type from ordered dict Question: I have a for loop that contains multiple if -conditions. The speed of this function is not critical for my application at the moment but I'd like to learn and have a few tips how to optimize my code to make it run faster. In my loop, I get first 5 A's, 5 B's and first 2 C's of each type C_1 and C_2. The code is working correctly, I get a wanted output but I'd like to make it as efficient as possible as I'm not sure how big amount of data it will be given at some point later. Here's the code: from collections import OrderedDict odl = [OrderedDict([('id', '1'), ('date', '2022-01-08'), ('time', '15:59:00'), ('type', 'A')]), OrderedDict([('id', '8'), ('date', '2022-01-08'), ('time', '14:59:00'), ('type', 'A')]), OrderedDict([('id', '2'), ('date', '2022-01-09'), ('time', '11:59:00'), ('type', 'A')]), OrderedDict([('id', '3'), ('date', '2022-01-08'), ('time', '12:59:00'), ('type', 'B')]), OrderedDict([('id', '9'), ('date', '2022-01-09'), ('time', '17:59:00'), ('type', 'B')]), OrderedDict([('id', '4'), ('date', '2022-01-09'), ('time', '18:59:00'), ('type', 'B')]), OrderedDict([('id', '5'), ('date', '2022-01-08'), ('time', '09:59:00'), ('type', 'C'), ('C_TYPE', 'C_1')]), OrderedDict([('id', '6'), ('date', '2022-01-09'), ('time', '10:59:00'), ('type', 'C'), ('C_TYPE', 'C_2')]), OrderedDict([('id', '7'), ('date', '2022-01-07'), ('time', '16:59:00'), ('type', 'A')])]
{ "domain": "codereview.stackexchange", "id": 42788, "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", "url": null }
python, python-3.x sorted_list = sorted(odl, key=lambda item: (item['date'], item['time'])) sl_list = [] type_a = 0 type_b = 0 type_c_1 = 0 type_c_2 = 0 for s in sorted_list: if s['type'] == 'A': if type_a < 5: sl_list.append(s) type_a += 1 if s['type'] == 'B': if type_b < 5: sl_list.append(s) type_b += 1 if s['type'] == 'C': if s['C_TYPE'] == 'C_1': if type_c_1 < 2: sl_list.append(s) type_c_1 += 1 if s['C_TYPE'] == 'C_2': if type_c_2 < 2: sl_list.append(s) type_c_2 += 1 Example output: [OrderedDict([('id', '7'), ('date', '2022-01-07'), ('time', '16:59:00'), ('type', 'A')]), ...] Are there some obvious performance issues I could face with bigger amounts of data? I'd appreciate every tip to make this more efficient! Answer: Use a collection rather than spawning lots of similarly named variables. Anytime you find yourself creating a bunch of numbered/lettered variables, stop and figure out a way to put that information in a collection. If your data is smart, your code can often be simple. Applying limits when collecting data by type. You appear to want to control the number of dicts of each type that you collect. Rather than weaving those limits into your algorithm, define a data structure holding the maximums. And then while collecting the data, use a copy of that collection to keep track of how many of each type are still available to be selected. Start putting your code in functions. Even for small programs. from collections import OrderedDict ODL = [...] MAXES = { ('A', None): 5, ('B', None): 5, ('C', 'C_1'): 2, ('C', 'C_2'): 2, } def main(): for d in select_dicts(ODL): print(d)
{ "domain": "codereview.stackexchange", "id": 42788, "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", "url": null }
python, python-3.x def main(): for d in select_dicts(ODL): print(d) def select_dicts(ods): sort_key = lambda od: (od['date'], od['time']) type_key = lambda od: (od['type'], od.get('C_TYPE')) available = dict(MAXES) selected = [] for od in sorted(ods, key=sort_key): k = type_key(od) if available[k] > 0: selected.append(od) available[k] -= 1 return selected if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 42788, "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", "url": null }
swift, concurrency Title: Debounce and throttle tasks using Swift Concurrency Question: There are many debouncer and throttle implementations created using Grand Central Dispatch, and even one built into Combine. I wanted to create one using the new Swift Concurrency feature in Swift 5.5+. Below is what I put together with help from others: actor Limiter { enum Policy { case throttle case debounce } private let policy: Policy private let duration: TimeInterval private var task: Task<Void, Never>? init(policy: Policy, duration: TimeInterval) { self.policy = policy self.duration = duration } nonisolated func callAsFunction(task: @escaping () async -> Void) { Task { switch policy { case .throttle: await throttle(task: task) case .debounce: await debounce(task: task) } } } private func throttle(task: @escaping () async -> Void) { guard self.task?.isCancelled ?? true else { return } Task { await task() } self.task = Task { try? await sleep() self.task?.cancel() self.task = nil } } private func debounce(task: @escaping () async -> Void) { self.task?.cancel() self.task = Task { do { try await sleep() guard !Task.isCancelled else { return } await task() } catch { return } } } private func sleep() async throws { try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000)) } }
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency I created tests to go with it, but testThrottler and testDebouncer are failing randomly which means there's some race condition somewhere or my assumptions in the tests are incorrect: final class LimiterTests: XCTestCase { func testThrottler() async throws { // Given let promise = expectation(description: "Ensure first task fired") let throttler = Limiter(policy: .throttle, duration: 1) var value = "" var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 func sendToServer(_ input: String) { throttler { value += input // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, "h") case 1: XCTAssertEqual(value, "hwor") default: XCTFail() } promise.fulfill() fulfillmentCount += 1 } } // When sendToServer("h") sendToServer("e") sendToServer("l") sendToServer("l") sendToServer("o") await sleep(2) sendToServer("wor") sendToServer("ld") wait(for: [promise], timeout: 10) } func testDebouncer() async throws { // Given let promise = expectation(description: "Ensure last task fired") let limiter = Limiter(policy: .debounce, duration: 1) var value = "" var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 func sendToServer(_ input: String) { limiter { value += input // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, "o") case 1: XCTAssertEqual(value, "old") default: XCTFail() }
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency promise.fulfill() fulfillmentCount += 1 } } // When sendToServer("h") sendToServer("e") sendToServer("l") sendToServer("l") sendToServer("o") await sleep(2) sendToServer("wor") sendToServer("ld") wait(for: [promise], timeout: 10) } func testThrottler2() async throws { // Given let promise = expectation(description: "Ensure throttle before duration") let throttler = Limiter(policy: .throttle, duration: 1) var end = Date.now + 1 promise.expectedFulfillmentCount = 2 func test() { // Then XCTAssertLessThan(.now, end) promise.fulfill() } // When throttler(task: test) throttler(task: test) throttler(task: test) throttler(task: test) throttler(task: test) await sleep(2) end = .now + 1 throttler(task: test) throttler(task: test) throttler(task: test) await sleep(2) wait(for: [promise], timeout: 10) } func testDebouncer2() async throws { // Given let promise = expectation(description: "Ensure debounce after duration") let debouncer = Limiter(policy: .debounce, duration: 1) var end = Date.now + 1 promise.expectedFulfillmentCount = 2 func test() { // Then XCTAssertGreaterThan(.now, end) promise.fulfill() } // When debouncer(task: test) debouncer(task: test) debouncer(task: test) debouncer(task: test) debouncer(task: test) await sleep(2) end = .now + 1 debouncer(task: test) debouncer(task: test) debouncer(task: test) await sleep(2) wait(for: [promise], timeout: 10) }
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency await sleep(2) wait(for: [promise], timeout: 10) } private func sleep(_ duration: TimeInterval) async { await Task.sleep(UInt64(duration * 1_000_000_000)) } } I'm hoping for help in seeing anything I missed in the Limiter implementation, or maybe if there's a better way to do debounce and throttle with Swift Concurrency. Answer: The problem is the use of a nonisolated function to initiate an asynchronous update of an actor-isolated property. (I'm surprised the compiler even permits that.) Not only is it misleading, but actors also feature reentrancy, and you introduce all sorts of unintended races. In the latter part of this answer, below, I offer my suggestions on what I would change in your implementation. But, nowadays, the right solution is to use the debounce and throttle from Apple’s Swift Async Algorithms library. For example: import AsyncAlgorithms final class AsyncAlgorithmsTests: XCTestCase { // a stream of individual keystrokes with a pause after the first five characters func keystrokes() -> AsyncStream<String> { AsyncStream<String> { continuation in Task { continuation.yield("h") continuation.yield("e") continuation.yield("l") continuation.yield("l") continuation.yield("o") try await Task.sleep(seconds: 2) continuation.yield(",") continuation.yield(" ") continuation.yield("w") continuation.yield("o") continuation.yield("r") continuation.yield("l") continuation.yield("d") continuation.finish() } } }
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency // A stream of the individual keystrokes aggregated together as strings (as we // want to search the whole string, not for individual characters) // // e.g. // h // he // hel // hell // hello // ... // // As the `keystrokes` sequence has a pause after the fifth character, this will // also pause after “hello” and before “hello,”. We can use that pause to test // debouncing and throttling func strings() -> AsyncStream<String> { AsyncStream<String> { continuation in Task { var string = "" for await keystroke in keystrokes() { string += keystroke continuation.yield(string) } continuation.finish() } } } func testDebounce() async throws { let debouncedSequence = strings().debounce(for: .seconds(1)) // usually you'd just loop through the sequence with something like // // for await string in debouncedSequence { // sendToServer(string) // } // but I'm just going to directly await the yielded values and test the resulting array let result: [String] = await debouncedSequence.reduce(into: []) { $0.append($1) } XCTAssertEqual(result, ["hello", "hello, world"]) } func testThrottle() async throws { let throttledSequence = strings().throttle(for: .seconds(1)) let result: [String] = await throttledSequence.reduce(into: []) { $0.append($1) } XCTAssertEqual(result, ["h", "hello,"]) } } // MARK: - Task.sleep(seconds:) extension Task where Success == Never, Failure == Never {
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency // MARK: - Task.sleep(seconds:) extension Task where Success == Never, Failure == Never { /// Suspends the current task for at least the given duration /// in seconds. /// /// If the task is canceled before the time ends, /// this function throws `CancellationError`. /// /// This function doesn't block the underlying thread. public static func sleep(seconds duration: TimeInterval) async throws { try await Task.sleep(nanoseconds: UInt64(duration * .nanosecondsPerSecond)) } } // MARK: - TimeInterval extension TimeInterval { static let nanosecondsPerSecond = TimeInterval(NSEC_PER_SEC) } Given that you were soliciting a “code review”, if you really wanted to write your own “debounce” and “throttle” and did not want to use Async Algorithms for some reason, my previous answer, below, addresses some observations on your implementation: You can add an actor-isolated function to Limiter: func submit(task: @escaping () async -> Void) { switch policy { case .throttle: throttle(task: task) case .debounce: debounce(task: task) } } Note, I am not using callAsFunction as an actor-isolated function as it looks like (in Xcode 13.2.1, for me, at least) that this causes a segmentation fault in the compiler. Anyway, you can then modify your tests to use the submit actor-isolated function, e.g.: // test throttling as user enters “hello, world” into a text field func testThrottler() async throws { // Given let promise = expectation(description: "Ensure first task fired") let throttler = Limiter(policy: .throttle, duration: 1) var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 var value = "" func accumulateAndSendToServer(_ input: String) async { value += input
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency func accumulateAndSendToServer(_ input: String) async { value += input await throttler.submit { [value] in // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, "h") case 1: XCTAssertEqual(value, "hello,") default: XCTFail() } promise.fulfill() fulfillmentCount += 1 } } // When await accumulateAndSendToServer("h") await accumulateAndSendToServer("e") await accumulateAndSendToServer("l") await accumulateAndSendToServer("l") await accumulateAndSendToServer("o") try await Task.sleep(seconds: 2) await accumulateAndSendToServer(",") await accumulateAndSendToServer(" ") await accumulateAndSendToServer("w") await accumulateAndSendToServer("o") await accumulateAndSendToServer("r") await accumulateAndSendToServer("l") await accumulateAndSendToServer("d") wait(for: [promise], timeout: 10) } As an aside: In debounce, the test for isCancelled is redundant. The Task.sleep will throw an error if the task was canceled. As a matter of convention, Apple uses operation for the name of the closure parameters, presumably to avoid confusion with Task instances. I would change the Task to be a Task<Void, Error>?. Then you can simplify debounce to: func debounce(operation: @escaping () async -> Void) { task?.cancel() task = Task { defer { task = nil } try await Task.sleep(seconds: duration) await operation() } } When throttling network requests for user input, you generally want to throttle the network requests, but not the accumulation of the user input. So I have pulled the value += input out of the throttler/debouncer. I also use a capture list of [value] to make sure that we avoid race conditions between the accumulation of user input and the network requests.
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency FWIW, this is my rendition of Limiter: actor Limiter { private let policy: Policy private let duration: TimeInterval private var task: Task<Void, Error>? init(policy: Policy, duration: TimeInterval) { self.policy = policy self.duration = duration } func submit(operation: @escaping () async -> Void) { switch policy { case .throttle: throttle(operation: operation) case .debounce: debounce(operation: operation) } } } // MARK: - Limiter.Policy extension Limiter { enum Policy { case throttle case debounce } } // MARK: - Private utility methods private extension Limiter { func throttle(operation: @escaping () async -> Void) { guard task == nil else { return } task = Task { defer { task = nil } try await Task.sleep(seconds: duration) } Task { await operation() } } func debounce(operation: @escaping () async -> Void) { task?.cancel() task = Task { defer { task = nil } try await Task.sleep(seconds: duration) await operation() } } } Which uses these extensions // MARK: - Task.sleep(seconds:) extension Task where Success == Never, Failure == Never { /// Suspends the current task for at least the given duration /// in seconds. /// /// If the task is canceled before the time ends, /// this function throws `CancellationError`. /// /// This function doesn't block the underlying thread. public static func sleep(seconds duration: TimeInterval) async throws { try await Task.sleep(nanoseconds: UInt64(duration * .nanosecondsPerSecond)) } } // MARK: - TimeInterval extension TimeInterval { static let nanosecondsPerSecond = TimeInterval(NSEC_PER_SEC) } And the following tests: final class LimiterTests: XCTestCase {
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency And the following tests: final class LimiterTests: XCTestCase { // test throttling as user enters “hello, world” into a text field func testThrottler() async throws { // Given let promise = expectation(description: "Ensure first task fired") let throttler = Limiter(policy: .throttle, duration: 1) var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 var value = "" func accumulateAndSendToServer(_ input: String) async { value += input await throttler.submit { [value] in // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, "h") case 1: XCTAssertEqual(value, "hello,") default: XCTFail() } promise.fulfill() fulfillmentCount += 1 } } // When await accumulateAndSendToServer("h") await accumulateAndSendToServer("e") await accumulateAndSendToServer("l") await accumulateAndSendToServer("l") await accumulateAndSendToServer("o") try await Task.sleep(seconds: 2) await accumulateAndSendToServer(",") await accumulateAndSendToServer(" ") await accumulateAndSendToServer("w") await accumulateAndSendToServer("o") await accumulateAndSendToServer("r") await accumulateAndSendToServer("l") await accumulateAndSendToServer("d") wait(for: [promise], timeout: 10) } // test debouncing as user enters “hello, world” into a text field func testDebouncer() async throws { // Given let promise = expectation(description: "Ensure last task fired") let debouncer = Limiter(policy: .debounce, duration: 1) var value = "" var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 func accumulateAndSendToServer(_ input: String) async { value += input await debouncer.submit { [value] in // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, "hello") case 1: XCTAssertEqual(value, "hello, world") default: XCTFail() } promise.fulfill() fulfillmentCount += 1 } } // When await accumulateAndSendToServer("h") await accumulateAndSendToServer("e") await accumulateAndSendToServer("l") await accumulateAndSendToServer("l") await accumulateAndSendToServer("o") try await Task.sleep(seconds: 2) await accumulateAndSendToServer(",") await accumulateAndSendToServer(" ") await accumulateAndSendToServer("w") await accumulateAndSendToServer("o") await accumulateAndSendToServer("r") await accumulateAndSendToServer("l") await accumulateAndSendToServer("d") wait(for: [promise], timeout: 10) } func testThrottler2() async throws { // Given let promise = expectation(description: "Ensure throttle before duration") let throttler = Limiter(policy: .throttle, duration: 1) var end = Date.now + 1 promise.expectedFulfillmentCount = 2 func test() { // Then XCTAssertLessThanOrEqual(.now, end) promise.fulfill() } // When await throttler.submit(operation: test) await throttler.submit(operation: test) await throttler.submit(operation: test) await throttler.submit(operation: test) await throttler.submit(operation: test) try await Task.sleep(seconds: 2) end = .now + 1
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
swift, concurrency try await Task.sleep(seconds: 2) end = .now + 1 await throttler.submit(operation: test) await throttler.submit(operation: test) await throttler.submit(operation: test) try await Task.sleep(seconds: 2) wait(for: [promise], timeout: 10) } func testDebouncer2() async throws { // Given let promise = expectation(description: "Ensure debounce after duration") let debouncer = Limiter(policy: .debounce, duration: 1) var end = Date.now + 1 promise.expectedFulfillmentCount = 2 func test() { // Then XCTAssertGreaterThanOrEqual(.now, end) promise.fulfill() } // When await debouncer.submit(operation: test) await debouncer.submit(operation: test) await debouncer.submit(operation: test) await debouncer.submit(operation: test) await debouncer.submit(operation: test) try await Task.sleep(seconds: 2) end = .now + 1 await debouncer.submit(operation: test) await debouncer.submit(operation: test) await debouncer.submit(operation: test) try await Task.sleep(seconds: 2) wait(for: [promise], timeout: 10) } }
{ "domain": "codereview.stackexchange", "id": 42789, "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": "swift, concurrency", "url": null }
c#, algorithm, binary-search Title: Binary Search of Array in C# Question: I am an algo-newbie and this is my first attempt at writing binary search and it worked on the first try. But something about it tells me that its far from perfect. Please tell me how I can improve. using System; class Program { public static void Main() { int[] arr = { 40, 67, 34, 25, 65, 87, 23 }; //insertion sort for (int i = 0; i < arr.Length; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; arr[j + 1] = key; } } //printing Console.WriteLine("Sorted Array"); for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + " "); } void BinarySearch(int[] arr, int lowerIndex, int upperIndex, int v) { if (lowerIndex <= upperIndex) { int middleIndex = (lowerIndex + upperIndex) / 2; if (v == arr[middleIndex]) { Console.WriteLine("Found at " + middleIndex); } else if (v < arr[middleIndex]) { BinarySearch(arr, lowerIndex, middleIndex - 1, v); } else if (v > arr[middleIndex]) { BinarySearch(arr, middleIndex + 1, upperIndex, v); } else Console.WriteLine("Not found"); } } //Searching for 87 BinarySearch(arr, 0, arr.Length - 1, 87); } } Answer: Your code tackles 2 problems, which is suboptimal when learning/asking for review: sort an array perform binary search
{ "domain": "codereview.stackexchange", "id": 42790, "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#, algorithm, binary-search", "url": null }
c#, algorithm, binary-search sort an array perform binary search Since you are interested in binary search, you can always assume, that your input array is sorted and take it from there. Your code for binary search looks alright apart for a little bug if an element isn't on the array. You should move your last else to the outer if: void BinarySearchRec(int[] arr, int lowerIndex, int upperIndex, int v) { if (lowerIndex <= upperIndex) { int middleIndex = (lowerIndex + upperIndex) / 2; if (v == arr[middleIndex]) { Console.WriteLine("Found at " + middleIndex); } else if (v < arr[middleIndex]) { BinarySearchRec(arr, lowerIndex, middleIndex - 1, v); } else if (v > arr[middleIndex]) { BinarySearchRec(arr, middleIndex + 1, upperIndex, v); } } else { Console.WriteLine("Not found"); } } There are however a couple of points where you might improve your code: If you are using recursion, you might want to create a public method that exposes the minimal amount of parameters and the recursive method with your full parameter list private: public void BinarySearch(int[] arr, int v) { BinarySearchRec(arr, 0, arr.Length - 1, v); } private void BinarySearchRec(int[] arr, int lowerIndex, int upperIndex, int v) { //TODO: Implement } Also you are returning nothing and writing to console your result. You might want to return the index of the item whenever it is present or -1 otherwise. This way you can use your method wherever you want; also this way your method does just one thing, search for an element in an array, instead of two: search and protocol the result. Lastly you might want to avoid recursion, since it creates an unnecessary overhead, and specially since the iterative code for this problem is almost the same: int BinarySearch<T>(T[] arr, T val) where T : IComparable { var lowerIndex = 0; var upperIndex = arr.Length - 1;
{ "domain": "codereview.stackexchange", "id": 42790, "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#, algorithm, binary-search", "url": null }
c#, algorithm, binary-search while(lowerIndex <= upperIndex) { var middleIndex = lowerIndex + (upperIndex - lowerIndex) / 2; var compareResult = arr[middleIndex].CompareTo(val); if(compareResult == 0) { return middleIndex; } if(compareResult > 0) { upperIndex = middleIndex - 1; } else { lowerIndex = middleIndex + 1; } } return -1; } Notice the use of IComparable Generic Types. Now if you want to test this method, you should always test the edge cases (first element, last element, element not found) aside from any random element. This way you are sure, that your code works in both directions and yields a correct result if the element is not present: int[] arr = { 23, 25, 34, 40, 65, 67, 87}; Console.WriteLine(BinarySearch(arr, 40)); //3 Console.WriteLine(BinarySearch(arr, 25)); //1 Console.WriteLine(BinarySearch(arr, 87)); //6 Console.WriteLine(BinarySearch(arr, 23)); //0 Console.WriteLine(BinarySearch(arr, 42)); //-1 As a last step you should use the previous Console.WriteLines and make actual test cases for your function. If anything to get used to test your code.
{ "domain": "codereview.stackexchange", "id": 42790, "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#, algorithm, binary-search", "url": null }
c, stream, signal-handling Title: Basic Client/Server model using Unix signals Question: I've created a basic client/server model using user defined signals (SIGUSR1 representing bit 1 and SIGUSR2 for bit 0). At a high level the algorithm looks something like: The server reveals its PID and starts listening. The client takes a string from standard input, encodes it to binary and starts streaming it to the server byte by byte. The server receives the signals and decodes them. The server prints the received string. server.c #include <signal.h> void handler(int signal) { //handler is called at each signal so my storage variables need to persist their values. static int i; char c; static int sequence[8]; if (signal == SIGUSR1) sequence[i++] = 1; else if (signal == SIGUSR2) sequence[i++] = 0; if (i == 8) { //we have a byte: decode, write and restart c = decoder(sequence); write(1, &c, 1); i = 0; } } int main(void) { pid_t pid; pid = getpid(); //put str to fd 1. putstr_fd("pid: ", 1); //put number as str to fd 1. putnbr_fd(pid, 1); putstr_fd("\n", 1); while (1) { signal(SIGUSR1, handler); signal(SIGUSR2, handler); pause(); } } client.c #include <unistd.h> #include <signal.h> #include <stdlib.h>
{ "domain": "codereview.stackexchange", "id": 42791, "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, stream, signal-handling", "url": null }
c, stream, signal-handling client.c #include <unistd.h> #include <signal.h> #include <stdlib.h> //for the sake of not missing up my signals i used only and only write(). void sender(int *sequence, pid_t pid) { int i = 0; while (i < 8) { if (sequence[i] == 1) if (kill(pid, SIGUSR1) == -1) { write(1, "Oh the package didn't arrive. you're obligated for a refund.\n", 50); exit(EXIT_FAILURE); } else if (sequence[i] == 0) if (kill(pid, SIGUSR2) == -1) { write(1, "Oh the package didn't arrive. you're obligated for a refund.\n", 50); exit(EXIT_FAILURE); }; i++; //Road traffic control for signals. usleep(500); } free(sequence); } int main(int argc, char **argv) { pid_t pid; int *sequence; int i = 0; //invalid number of args. if (argc != 3) { write(1, "WTF... I'm not executing that.\n", 31); exit(EXIT_FAILURE); } pid = atoi(argv[1]); while (argv[2][i]) { sequence = encoder(argv[2][i]); sender(sequence, pid); i++; } return 0; } encoder.c #include <stdlib.h> int *encoder(char c) { int *sequence = malloc(sizeof(*sequence) * 8); if (!sequence) { ft_putstr_fd("couldn't malloc... Give some space greedy\n", 1); exit(EXIT_FAILURE); } int i = 7; int decimal = (int)c; while (decimal) { sequence[i--] = decimal % 2; decimal /= 2; } //ok that's a glue code, i encoded and i filled what's left with zeros from MSB side​ some ascii's are 7 bits some are 6. i didn't want to guess. so i glued. ​while (i > -1) ​sequence[i--] = 0; ​return sequence; ​} decoder.c #include <math.h>
{ "domain": "codereview.stackexchange", "id": 42791, "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, stream, signal-handling", "url": null }
c, stream, signal-handling decoder.c #include <math.h> char decoder(int *sequence) { ​int i = 0; ​int n = 7; ​int result = 0; ​while (i < 8) ​{ ​result += (sequence[i] * pow(2, n)); ​i++; ​n--; ​} ​return (char)result; } The program is built using Make, and it functions as it supposed to. I'm interested in judgments regarding my style (if there's one, probably not...) and error handling and performance or just anything you think should be or shouldn't be there. Answer: The major flaw in the approach is that there's no guaranteed delivery of signals. If the server doesn't consume a signal quickly enough, it can miss a subsequent delivery of the same signal. Since the protocol provides no means of error detection/correction or resynchronisation, that will result in corrupt data. This situation is most likely to occur on heavily loaded systems, so may easily be missed in testing. Both sides write their error messages to standard output (stream 1) but should use standard error (stream 2). We don't need the decoder() function, as we can accumulate bits directly into an unsigned char rather than an int[8]: void handler(int signal) { static int i = 0; static unsigned char c = 0; c <<= 1; c += signal == SIGUSR1; if (++i == 8) { write(1, &c, 1); i = 0; c = 0; } } (c needs to be unsigned, so that <<= has defined semantics.) We really should check the return value from that write(), and reattempt if it wrote nothing (perhaps because it was interrupted by another signal?) Strictly speaking, in a signal handler, we should be using sig_atomic_t.
{ "domain": "codereview.stackexchange", "id": 42791, "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, stream, signal-handling", "url": null }
c, stream, signal-handling Similarly, we don't need to encoder() int a byte array: void sender(char c, pid_t pid) { for (int i = 0x80; i; i >>= 1) { if (kill(pid, c & i ? SIGUSR1 : SIGUSR2) == -1) { write(2, "Oh the package didn't arrive. you're obligated for a refund.\n", 50); exit(EXIT_FAILURE); } // Hope this sleep is long enough for receiver to handle signal! usleep(500); } } Even if we did, we could pass in a suitable array int[8] rather than allocating storage using malloc() and requiring the caller to free() it. Instead of using fixed value 8 everywhere, portable code should use CHAR_BIT.
{ "domain": "codereview.stackexchange", "id": 42791, "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, stream, signal-handling", "url": null }
python, performance, wikipedia Title: Count the frequency of n-grams in a random Wikipedia corpus Question: This code counts the frequency of n-grams in a random Wikipedia corpus, as of now, it downloads everything, than performs all the counting. In your opinion is there a way to perform downloading and counting simultaneously while keeping the code reasonably simple to improve the performance? import wikipedia as wk import time from itertools import combinations import string def get_random_wikipedia_corpus(articles_number, verbose=False): contents = [] i = 0 while i < articles_number: try: page = wk.random() content = wk.page(page).content contents.append(content) i += 1 except (wk.DisambiguationError, wk.PageError): pass time.sleep(1) # Avoid DDOSing Wikipedia :) if verbose: print(f"Iteration {i}, adding {page.title}") return ''.join(contents) def all_ngrams(n): return (''.join(t) for t in combinations(string.ascii_lowercase, n)) def count_all(text, fragments, forbidden_counts=[]): return [(t, c/len(text)) for t in fragments if (c := text.count(t)) not in forbidden_counts]
{ "domain": "codereview.stackexchange", "id": 42792, "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, performance, wikipedia", "url": null }
python, performance, wikipedia if __name__ == "__main__": s = time.time() CORPUS_ARTICLES = 10 corpus = get_random_wikipedia_corpus(CORPUS_ARTICLES).lower() corpus = ''.join(char for char in corpus if char in string.ascii_lowercase) print(time.time() - s, len(corpus)) onegrams = all_ngrams(1) bigrams = all_ngrams(2) trigrams = all_ngrams(3) quadrigrams = all_ngrams(4) onegrams_counts = count_all(corpus, onegrams, (0, 1)) bigrams_counts = count_all(corpus, bigrams, (0, 1)) trigrams_counts = count_all(corpus, trigrams, (0, 1)) quadrigrams_counts = count_all(corpus, quadrigrams, (0, 1)) onegrams_counts.sort(key=lambda pair: pair[1], reverse=True) bigrams_counts.sort(key=lambda pair: pair[1], reverse=True) trigrams_counts.sort(key=lambda pair: pair[1], reverse=True) quadrigrams_counts.sort(key=lambda pair: pair[1], reverse=True) print(onegrams_counts) print(bigrams_counts) print(trigrams_counts) print(quadrigrams_counts) Answer: I propose an optimization based on the multiprocessing module, to parallelize the requests. Unfortunately, if you want to get the results as soon as possible, you will have to "DDOS" Wikipedia at some point, and the sleep needs to be removed. Some notes and suggestions In the following piece of code, the page variable might not be defined in the print, the pass statement should probably be replaced by a continue: try: page = wk.random() ... except (wk.DisambiguationError, wk.PageError): pass # <- continue? time.sleep(1) # Avoid DDOSing Wikipedia :) if verbose: print(f"Iteration {i}, adding {page.title}") (It seems that page.title is a method and not a property or an attribute in the version of the wikipedia package I use (1.4.0), so it needs to be called in order to display it correctly)
{ "domain": "codereview.stackexchange", "id": 42792, "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, performance, wikipedia", "url": null }
python, performance, wikipedia The default value of the forbidden_counts argument of the count_all function should be an empty tuple instead of an empty list, as it is immutable, and it would be more consistent with the parameters you send when using this function. You could add a main function To handle the different sizes of "n-grams" and to avoid code duplication, a for loop wouldn't be more appropriate? Optimization part In this proposed solution, a new function has been extracted from the get_random_wikipedia_corpus function. This new function requests exactly one valid article. The get_random_wikipedia_corpus only calls it multiple times by using a multithreading.Pool object. Here is the solution with the suggestions: import multiprocessing import string import time from itertools import combinations, repeat import wikipedia as wk CORPUS_ARTICLES = 10 def get_random_wikipedia_article(iteration: int, verbose: False) -> str: while True: page = wk.random() try: content = wk.page(page).content except (wk.DisambiguationError, wk.PageError): continue if verbose: print(f"Request {iteration}, adding '{page.title()}'") return content def get_random_wikipedia_corpus(articles_number, verbose=False): pool = multiprocessing.Pool() return ''.join(pool.starmap(get_random_wikipedia_article, zip(range(articles_number), repeat(verbose)))) def all_ngrams(n): return (''.join(t) for t in combinations(string.ascii_lowercase, n)) def count_all(text, fragments, forbidden_counts=()): return [(t, c / len(text)) for t in fragments if (c := text.count(t)) not in forbidden_counts] def main(): s = time.time() corpus = get_random_wikipedia_corpus(CORPUS_ARTICLES, verbose=True).lower() corpus = ''.join(char for char in corpus if char in string.ascii_lowercase) print(time.time() - s, len(corpus))
{ "domain": "codereview.stackexchange", "id": 42792, "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, performance, wikipedia", "url": null }
python, performance, wikipedia print(time.time() - s, len(corpus)) for letter_count in (1, 2, 3, 4): ngrams = all_ngrams(letter_count) ngrams_counts = count_all(corpus, ngrams, (0, 1)) ngrams_counts.sort(key=lambda pair: pair[1], reverse=True) print(ngrams_counts) if __name__ == "__main__": main() Displayed metrics before optimization: 31.928 seconds for 30287 characters Displayed metrics after optimization: 2.154 seconds for 11948 characters It would be more meaningful to compare those durations for the same requested pages.
{ "domain": "codereview.stackexchange", "id": 42792, "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, performance, wikipedia", "url": null }
c++, design-patterns, c++14, type-safety Title: Nop class which can get optimized away Question: I designed a class for debug builds which does not incur any overhead in release mode. A usecase is for example: I have a function and I want to count how often it is called. For this I could write the following function void f() { #ifndef NDEBUG static int i = 0; ++i; std::cout << "Counter: " << i << "\n"; #endif // do something } But that clobbers up my source code with preprocessor directives. Thus I had the idea for a class such that the example above becomes: function void f() { static Nop_t<int> i = 0; std::cout << "Counter: "_nop << i << "\n"_nop; ++i; // do something } By default, in Debug Mode Nop_t< T > is the same as T, otherwise it is a type which does nothing and accepts all possible code constructs. Now the real implementation and a test file (I wrote the tests in Google Test and adapted them for posting here). The class uses some utilities (mostly taken from Stackoverflow) /// /// Utilities /// /* T_NDEBUG * Macro which is always defined. * It has the value true if NDEBUG is defined, and false otherwise */ #ifndef NDEBUG #define T_NDEBUG true #else #define T_NDEBUG false #endif /** Standard preprocessor string concatenation macro which expands also macro arguments * Example: T_JOIN( abc123, __LINE__ ) * Yields: abc123116 // or something else if the line of this macro changes */ #define T_JOIN( x, y ) T_JOIN_AGAIN( x, y ) #define T_JOIN_AGAIN( x, y ) x ## y
{ "domain": "codereview.stackexchange", "id": 42793, "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++, design-patterns, c++14, type-safety", "url": null }
c++, design-patterns, c++14, type-safety /** * Stuff for macro with variable number of arguments * @Link stackoverflow.com/questions/11761703 * * @Example: We want to have macros SUM(a), SUM(a,b), SUM(a,b,c). * * ``` * #define SUM( ... ) OVERLOADED_MACRO( SUM, __VA_ARGS__ ) * * #define SUM1( a ) (a) * #define SUM2( a, b ) (a)+(b) * #define SUM3( a, b, c ) (a)+(b)+(c) * ``` * Note: Macros without arguments are not possible in a portable way */ #define OVERLOADED_MACRO( M, ... ) _OVR( M, _COUNT_ARGS(__VA_ARGS__) ) ( __VA_ARGS__ ) #define _OVR( macroName, number_of_args ) _OVR_EXPAND(macroName, number_of_args) #define _OVR_EXPAND( macroName, number_of_args ) macroName##number_of_args #define _COUNT_ARGS( ... ) _ARG_PATTERN_MATCH( __VA_ARGS__, 9,8,7,6,5,4,3,2,1 ) #define _ARG_PATTERN_MATCH( _1,_2,_3,_4,_5,_6,_7,_8,_9, N, ... ) N /** Macro removing "unused" warning in Debug Mode * Macro does not work reliable * * @example * function f( int a ) { * MAYBE_UNUSED( a ); * } */ #ifndef MAYBE_UNUSED //macro for disabling "unused function warning" #define MAYBE_UNUSED(expr) do{ (void)(expr); } while (0) #endif Nop class /// /// Nop class /// #include <iosfwd> #include <utility>
{ "domain": "codereview.stackexchange", "id": 42793, "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++, design-patterns, c++14, type-safety", "url": null }
c++, design-patterns, c++14, type-safety Nop class /// /// Nop class /// #include <iosfwd> #include <utility> /** * # Nop.hpp * * ## General description * This is a class which is either * - a typedef for a type, or * - a type which takes everything and does nothing (i.e. every use of a variable of this type is optimized away by the compiler) * ``` * Nop_t< T, true > // is a typedef for T * Nop_t< T, false > // is the do-nothing type * Nop_t< T > // is a typedef in Debug Mode, and the do-nothing type in Release mode * ``` * * ## Usage example * static Nop_t< std::atomic<int> > counter; * void func() { * counter++; // count how often this function is called, but only in Debug mode * std::cout << (Nop_t<std::string>)"counter: " << counter; // text is only printed in Debug Mode * // do something * } * * ## User defined literals * By using the macro NOP_LITERAL a user defined literal can be generated. * NOP_LITERAL( name, condition ) * NOP_LITERAL( name ) // name defaults to "nop" * If condition is true, then the literal will become the usual literal, otherwise it will become a Nop_t * Example: * NOP_LITERAL( nop ) * void f() { * Nop_t< int > value; * std::cout << "Value: "_nop << value; // Does nothing in Release mode * } * Notes: * This macro shall only be used in cpp files, otherwise the global namespace may get polluted.* * * ## Adding supported functions * If a function / member function / typedef is missing, there are several ways to add it to the class * 1) Add it inside the class using the macros NOP_MEMBER_FUNCTION, NOP_FRIEND_FUNCTION, NOP_UNARY, NOP_BINARY_OPERATOR, NOP_TYPEDEF * 2) Add it inside the class handwritten. Such functions should be made as generic as possible * 3) Add it outside of the class using the macros NOP_FUNCTION, NOP_LAMBDA */ namespace detail {
{ "domain": "codereview.stackexchange", "id": 42793, "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++, design-patterns, c++14, type-safety", "url": null }