text
stringlengths
1
2.12k
source
dict
java, algorithm, comparative-review, tree, trie com.github.coderodde.text.autocomplete.Demo: package com.github.coderodde.text.autocomplete; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; public class Demo { private static final int NUMBER_OF_STRINGS_TO_GENERATE = 500_000; private static final int MAXIMUM_STRING_LENGTH = 5; private static final String AUTOCOMPLETE_STRING = "5";
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie public static void main(String[] args) { if (args.length > 0 && args[0].trim().equals("benchmark")) { benchmark(); } else { runDemo(); } } private static void runDemo() { Scanner scanner = new Scanner(System.in); Application application = new Application(); while (true) { System.out.print(">>> "); String commandString = scanner.nextLine().trim().toLowerCase(); if (commandString.equals("quit")) { break; } try { application.processCommand(commandString.split("\\s+")); } catch (Throwable t) { System.out.println("ERROR: " + t.getMessage()); } } System.out.println("Bye!"); } private static void benchmark() { benchmarkImpl(false); benchmarkImpl(true); } private static void benchmarkImpl(boolean printStatistics) { if (printStatistics) { System.out.println("<<< Benchmarking... >>>"); } Random random = new Random(1255L); String[] strings = getStrings(NUMBER_OF_STRINGS_TO_GENERATE, random); String[] queryStrings = getQueryStrings(strings, 4, random); shuffle(queryStrings, random); PrefixTree prefixTree = new PrefixTree(); AutocompleteSystem autocompleteSystem = new AutocompleteSystem(); long prefixTreeDuration = 0L; long autocompletionSystemDuration = 0L; long start = System.currentTimeMillis(); for (String s : strings) { prefixTree.add(s); } long end = System.currentTimeMillis(); prefixTreeDuration += end - start; if (printStatistics) { System.out.println("PrefixTree.add() in " + (end - start) + " ms.");
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie System.out.println("PrefixTree.add() in " + (end - start) + " ms."); System.out.println("PrefixTree.size() = " + prefixTree.size()); } start = System.currentTimeMillis(); for (String s : prefixTree) { } end = System.currentTimeMillis(); prefixTreeDuration += end - start; if (printStatistics) { System.out.println("PrefixTree.iterator() in " + (end - start) + " ms."); } start = System.currentTimeMillis(); for (String s : queryStrings) { prefixTree.contains(s); } end = System.currentTimeMillis(); prefixTreeDuration += end - start; if (printStatistics) { System.out.println("PrefixTree.contains() in " + (end - start) + " ms."); } start = System.currentTimeMillis(); for (int i = 0; i < queryStrings.length / 2; i += 2) { prefixTree.remove(queryStrings[i]); } end = System.currentTimeMillis(); prefixTreeDuration += end - start; if (printStatistics) { System.out.println("PrefixTree.remove() in " + (end - start) + " ms."); System.out.println("PrefixTree.size() = " + prefixTree.size()); } start = System.currentTimeMillis(); List<String> prefixTreeCompletionStrings = prefixTree.autocomplete(AUTOCOMPLETE_STRING); end = System.currentTimeMillis(); prefixTreeDuration += end - start; Collections.sort(prefixTreeCompletionStrings); if (printStatistics) { System.out.println("PrefixTree.autocomplete() in " + (end - start) + " ms.");
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie " ms."); System.out.println("PrefixTree total duration: " + prefixTreeDuration + " ms."); } //////////////////////////////////////////////////////////////////////// System.out.println(); start = System.currentTimeMillis(); for (String s : strings) { autocompleteSystem.add(s); } end = System.currentTimeMillis(); autocompletionSystemDuration += end - start; if (printStatistics) { System.out.println("AutocompleteSystem.add() in " + (end - start) + " ms."); System.out.println("AutocompleteSystem.size() = " + autocompleteSystem.size()); } start = System.currentTimeMillis(); for (String s : autocompleteSystem) { } end = System.currentTimeMillis(); autocompletionSystemDuration += end - start; if (printStatistics) { System.out.println("AutocompleteSystem.iterator() in " + (end - start) + " ms."); } start = System.currentTimeMillis(); for (String s : queryStrings) { autocompleteSystem.contains(s); } end = System.currentTimeMillis(); autocompletionSystemDuration += end - start; if (printStatistics) { System.out.println("AutocompleteSystem.contains() in " + (end - start) + " ms."); } start = System.currentTimeMillis(); for (int i = 0; i < queryStrings.length / 2; i += 2) { autocompleteSystem.remove(queryStrings[i]); } end = System.currentTimeMillis(); autocompletionSystemDuration += end - start; if (printStatistics) {
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie autocompletionSystemDuration += end - start; if (printStatistics) { System.out.println("AutocompleteSystem.remove() in " + (end - start) + " ms."); System.out.println("AutocompleteSystem.size() = " + autocompleteSystem.size()); } start = System.currentTimeMillis(); List<String> autocompleteSystemCompletionStrings = autocompleteSystem.autocomplete(AUTOCOMPLETE_STRING); end = System.currentTimeMillis(); autocompletionSystemDuration += end - start; Collections.sort(autocompleteSystemCompletionStrings); if (printStatistics) { System.out.println("AutocompleteSystem.autocomplete() in " + (end - start) + " ms."); System.out.println("AutocompleteSystem total duration: " + autocompletionSystemDuration + " ms."); System.out.println(); System.out.println("Data structures agree: " + prefixTreeCompletionStrings .equals(autocompleteSystemCompletionStrings)); System.out.println("PrefixTree returned " + prefixTreeCompletionStrings.size() + " strings."); System.out.println("AutocompleteSystem returned " + autocompleteSystemCompletionStrings.size() + " strings."); } } private static String[] getQueryStrings(String[] strings, Random random) { return getQueryStrings(strings, MAXIMUM_STRING_LENGTH, random); } private static String[] getQueryStrings(String[] strings, int maximumStringLength, Random random) {
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie Random random) { String[] queryStrings = new String[strings.length]; int index = 0; for (; index < strings.length / 2; ++index) { queryStrings[index] = strings[index]; } for (; index < strings.length; ++index) { queryStrings[index] = generateString(maximumStringLength, random); } return queryStrings; } private static String[] getStrings(int numberOfStringsRandom, Random random) { return getStrings(numberOfStringsRandom, MAXIMUM_STRING_LENGTH, random); } private static String[] getStrings(int numberOfStringsRandom, int maximumStringLength, Random random) { String[] strings = new String[numberOfStringsRandom]; for (int i = 0; i < strings.length; ++i) { strings[i] = generateString(maximumStringLength, random); } return strings; } private static String generateString(int maximumStringLength, Random random) { int stringLength = random.nextInt(maximumStringLength + 1); StringBuilder sb = new StringBuilder(stringLength); for (int i = 0; i < stringLength; ++i) { sb.append('0' + (char)(random.nextInt(10))); } return sb.toString(); } private static void shuffle(String[] arr, Random random) { for (int i = arr.length - 1; i > 0; --i) { int j = random.nextInt(i); String s = arr[i]; arr[i] = arr[j]; arr[j] = s; } } }
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie The output on my PC is: <<< Benchmarking... >>> PrefixTree.add() in 62 ms. PrefixTree.size() = 67741 PrefixTree.iterator() in 52 ms. PrefixTree.contains() in 92 ms. PrefixTree.remove() in 18 ms. PrefixTree.size() = 47652 PrefixTree.autocomplete() in 15 ms. PrefixTree total duration: 239 ms. AutocompleteSystem.add() in 37 ms. AutocompleteSystem.size() = 67741 AutocompleteSystem.iterator() in 4 ms. AutocompleteSystem.contains() in 52 ms. AutocompleteSystem.remove() in 7 ms. AutocompleteSystem.size() = 47652 AutocompleteSystem.autocomplete() in 4 ms. AutocompleteSystem total duration: 104 ms. Data structures agree: true PrefixTree returned 38122 strings. AutocompleteSystem returned 38122 strings. So, no, prefix tree can't beat the HashSet<String>. Critique request I am eager to hear all the improvement comments that might come to mind.
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
java, algorithm, comparative-review, tree, trie Answer: Taking a single sample and calculating it's duration from the wall clock is an extremely error prone method to compere execution speed. A single OS interrupt and the measured time no longer means anything. to improve the accuracy, you can run the code several times and generate statistics to reduce possibility of outside effects causing errors. You need to change the AutocompleteSystem into an interface and create PrefixTreeAutocomplete and HashMapAutoComplete and a single test suite without copy-paste code, that can run the same test against any AutocompleteSystem implementation it receives. Performance wise, hash table's advantages are pretty obvious. This is a well known fact and it's documented in the side bar of the wikipedia article you linked. :) Prefix trees have a storage space advantage when you have a lot of identical string prefixes, but you're giving a bit of that advantage away by using regular HashMaps internally. Each character now consumes a 32bit integer as the array index, a 32bit pointer to the Character-key within Map.Entry and whatever the Map.Entry and Character objects themselves take. I assume the operation that is most important for the regular use case is the autocomplete(String) method. The prefix tree has an awful hadicap because it has to recreate the strings every time it is needed. To get an advantage over a HashMap, you could trade some of the storage space advantage into performance by adding the completed string into the Node as completeString and removing the now redundant representsString field. Then you can just return the existing string instead of building it character by character with a StringBuilder (clone the String before storing it so you don't leak memory by holding on to substrings from longer documents).
{ "domain": "codereview.stackexchange", "id": 42856, "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, comparative-review, tree, trie", "url": null }
javascript, random Title: Generate random characters from ranges 0–9 and a–Z Question: I’m trying to generate 5 characters from the ranges 0–9 and a–Z. Is my solution optimal or did I overthink it a little? Would hardcoding a character list be more optimal? const numbers = [ ...Math.random() .toString(36) .substr(2, 5), ].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join(''); Answer: Small Bias First a nit pick, Math.random() generates a number from 0 to < 1. It will never generate 1. Thus to get a statistical odds of 1/2 you must test either Math.random() < 0.5 or Math.random() >= 0.5. Testing Math.random() > 0.5 ? char : char.toUpperCase() will give a very (VERY) small bias in favor of upper case characters. Dramatic Bias Also there is a very strong bias towards numerals in your function with a 0-9 being 2 times more likely than a-z or A-Z The following snippet counts the occurrence of each character generated by your function and plots them (normalized) on a graph. I animated it slowly for dramatic effect.
{ "domain": "codereview.stackexchange", "id": 42857, "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": "javascript, random", "url": null }
javascript, random canvas.width = innerWidth - 10; const ctx = canvas.getContext("2d"); const w = canvas.width; const h = canvas.height; const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var testCount = 2; const val = new Array(chars.length) val.fill(0); const func = randString; function randString() { return [ ...Math.random() .toString(36) .substr(2, 5), ].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join(''); } function testRandomness() { var i = testCount; while (i--) { const a = func(); for (const c of a) { val[chars.indexOf(c)] += 1 } } const max = Math.max(...val); ctx.clearRect(0, 0, w, h); const ww = w / val.length; i = val.length; ctx.fillStyle = "blue"; while (i--) { if (chars[i] === "z") { ctx.fillStyle = "green" } if (chars[i] === "9") { ctx.fillStyle = "red" } const v = val[i] / max * h; ctx.fillRect(i * ww, h - v, ww- 2, v) } setTimeout(testRandomness, 1000 / 30); } testRandomness(); canvas.addEventListener("click",()=> (testCount = 10000,d.textContent = "Sample rate ~300,000per sec") ,{once:true}); body { font-family: arial black; } canvas { padding: 0px; } #a { color:red; } #b { color:green; } #c { color:blue; } #d { font-family: arial; } <canvas id="canvas"></canvas> <span id="a">Red</span> 0-9 <span id="b">Green</span> a-z <span id="c">Blue</span> A-Z <span id="d">Click graph to increase sample rate to 10000</span>
{ "domain": "codereview.stackexchange", "id": 42857, "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": "javascript, random", "url": null }
javascript, random Click the graph to increase the tests per sample to 10000 per 30th second (approx) and you will see that apart from the numeral bias the graph quickly becomes very flat showing no other major bias (the uppercase bias is way to small to see) The reason for the bias is that you split the characters a-z in two when you convert half to uppercase. Also note as pointed out in the other answer, there is a small chance that the returned string is less than 5 characters long. Performance In terms of performance using a lookup table is around 3 times faster ie calculate 1.5million strings in the time yours calculates 0.5million. const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; function randString(size = 5) { var str = ""; while (size--) { str += chars[Math.random() * chars.length | 0] } return str; } As a function it is much more flexible, and can easily be adapted to include extra characters, or reduced character sets. If all that matters is performance you can get around 10% faster by avoiding some of the readability introduce overhead with function randString() { return chars[Math.random() * 62 | 0] + chars[Math.random() * 62 | 0] + chars[Math.random() * 62 | 0] + chars[Math.random() * 62 | 0] + chars[Math.random() * 62 | 0]; } Or (on chrome) the following is on average 2% faster than the one above but only after it has been run many time so that the optimizer knows what it does. If run only a few time it is slower than above function randString3() { return `${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}`; }
{ "domain": "codereview.stackexchange", "id": 42857, "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": "javascript, random", "url": null }
performance, python-3.x Title: Knuth up-arrow notation Question: I have implemented Knuth up-arrow notation in Python: from functools import lru_cache @lru_cache def kuan(a, b, arrows): if arrows == 1: return a ** b res = a for i in range(b): res = kuan(a, res, arrows - 1) return res This can calculate kuan(3, 3, 1) pretty quickly. But it slows down for kuan(3, 3, 2). Any suggestions for improving the performance? Answer: There is not much code to review here, but some titbits can be mentioned Style The modern way is to use cache over lru_cache unless you need a cache of a very specific size. For one-off imports I always include the package, however I've seen different opinions on this. Especially for standard libraries Include typing hints Include a docstring explaining what your code does. Include a if __name__ == "__main__" guard if you want to run more examples. Better name. It took me far to long to understand that kuan = Knuth's up arrow notation. You are not paid by the number of characters you write; feel free to be a bit verbose. Implementation I have no idea what implementation you are using? Looking at Wikipedia it gives me this $$ a\uparrow^n b= \begin{cases} a^b, & \text{if }n=1; \\ 1, & \text{if }n>1\text{ and }b=0; \\ a\uparrow^{n-1}(a\uparrow^{n}(b-1)), & \text{otherwise } \end{cases} $$ Which, when implemented correctly runs in milliseconds. import functools @functools.cache def arrow(a: int, b: int, arrows: int) -> int: """Evaluates numbers using Knuth's up-arrow notation Source: http://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) arrow(2, 3, 1) = 2 * 2 * 2 = 8 arrow(2, 3, 2) = arrow(2, arrow(2, 2, 1), 1) = arrow(2, 4, 1) = 2 * 2 * 2 * 2 = 2 ^ 4 = 16
{ "domain": "codereview.stackexchange", "id": 42858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, python-3.x", "url": null }
performance, python-3.x arrow(2, 3, 3) = arrow(2, arrow(2, 2, 2), 2) = arrow(2, arrow(2, arrow(2, 1, 1), 1), 2) = arrow(2, arrow(2, 2, 1), 2) = arrow(2, 2 * 2, 2) = arrow(2, 4, 2) = arrow(2, arrow(2, arrow(2, 2, 1), 1), 1) = arrow(2, arrow(2, 4, 1), 1) = arrow(2, 2 * 2 * 2 * 2, 1) = arrow(2, 16, 1) = 2 * ... * 2 (16 times) = 2 ^ 16 = 65536 Example: >>> arrow_notation(2, 3, 1) 8 >>> arrow_notation(2, 3, 2) 16 >>> arrow_notation(2, 3, 3) 65536 >>> arrow_notation(3, 2, 3) 7625597484987 """ if arrows == 1 or b == 0: return a ** b return arrow( a=a, b=arrow(a, b - 1, arrows), arrows=arrows - 1, ) if __name__ == "__main__": import doctest doctest.testmod() # print(arrow_notation(3, 2, 3))
{ "domain": "codereview.stackexchange", "id": 42858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, python-3.x", "url": null }
c#, calculator, winforms Title: Windows standard calulator replica in WinForms C# Question: I tried my best to replicate, in style and functionality, the Windows standard calculator: I would like to get some feedback on the efficiency and readability of my code as well as the approach i chose (for example the one of using the evaluate function on the expression textbox): Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _2022_01_27 { public partial class Form1 : Form { bool equals_last_pressed; double last_number_entry = 0; public Form1() { InitializeComponent(); } private void Add_to_entry(string digit) { if (tbox_entry.Text.Length <= 18) { tbox_entry.Text += digit; tbox_entry.Text = Convert.ToString(double.Parse(tbox_entry.Text)); } equals_last_pressed = false; } static Double Evaluate(String expression) { System.Data.DataTable table = new System.Data.DataTable(); return Convert.ToDouble(table.Compute(expression, String.Empty)); } private void btn_0_Click(object sender, EventArgs e) { Add_to_entry("0"); } private void btn_1_Click(object sender, EventArgs e) { Add_to_entry("1"); } private void btn_2_Click(object sender, EventArgs e) { Add_to_entry("2"); } private void btn_3_Click(object sender, EventArgs e) { Add_to_entry("3"); } private void btn_4_Click(object sender, EventArgs e) { Add_to_entry("4"); } private void btn_5_Click(object sender, EventArgs e) { Add_to_entry("5"); }
{ "domain": "codereview.stackexchange", "id": 42859, "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#, calculator, winforms", "url": null }
c#, calculator, winforms private void btn_6_Click(object sender, EventArgs e) { Add_to_entry("6"); } private void btn_7_Click(object sender, EventArgs e) { Add_to_entry("7"); } private void btn_8_Click(object sender, EventArgs e) { Add_to_entry("8"); } private void btn_9_Click(object sender, EventArgs e) { Add_to_entry("9"); } private void btn_c_Click(object sender, EventArgs e) { tbox_entry.Text = "0"; tbox_expression.Text = ""; last_number_entry = 0; } private void btn_ce_Click(object sender, EventArgs e) { tbox_entry.Text = "0"; } private void btn_backspace_Click(object sender, EventArgs e) { tbox_entry.Text = tbox_entry.Text.Remove(tbox_entry.Text.Length - 1); if (tbox_entry.Text.Length == 0) tbox_entry.Text = "0"; } private void btn_addition_Click(object sender, EventArgs e) { last_number_entry = double.Parse(tbox_entry.Text); if (equals_last_pressed == false) tbox_expression.Text += tbox_entry.Text; tbox_expression.Text = $"{Evaluate(tbox_expression.Text)} + "; tbox_entry.Text = "0"; equals_last_pressed = false; } private void btn_subtraction_Click(object sender, EventArgs e) { last_number_entry = double.Parse(tbox_entry.Text); if (equals_last_pressed == false) tbox_expression.Text += tbox_entry.Text; tbox_expression.Text = $"{Evaluate(tbox_expression.Text)} - "; tbox_entry.Text = "0"; equals_last_pressed = false; }
{ "domain": "codereview.stackexchange", "id": 42859, "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#, calculator, winforms", "url": null }
c#, calculator, winforms private void btn_multiplication_Click(object sender, EventArgs e) { last_number_entry = double.Parse(tbox_entry.Text); if (equals_last_pressed == false) tbox_expression.Text += tbox_entry.Text; tbox_expression.Text = $"{Evaluate(tbox_expression.Text)} * "; tbox_entry.Text = "0"; equals_last_pressed = false; } private void btn_division_Click(object sender, EventArgs e) { last_number_entry = double.Parse(tbox_entry.Text); if (equals_last_pressed == false) tbox_expression.Text += tbox_entry.Text; tbox_expression.Text = $"{Evaluate(tbox_expression.Text)} / "; tbox_entry.Text = "0"; equals_last_pressed = false; } private void btn_sqrtx_Click(object sender, EventArgs e) { tbox_entry.Text = $"{Math.Sqrt(double.Parse(tbox_entry.Text))}"; } private void btn_x2_Click(object sender, EventArgs e) { tbox_entry.Text = $"{Math.Pow(double.Parse(tbox_entry.Text), 2)}"; } private void btn_1dividex_Click(object sender, EventArgs e) { if (tbox_entry.Text == "0") return; tbox_entry.Text = $"{1 / double.Parse(tbox_entry.Text)}"; } private void btn_equals_Click(object sender, EventArgs e) { last_number_entry = double.Parse(tbox_entry.Text); if (equals_last_pressed == true) return; equals_last_pressed = true; tbox_expression.Text += $"{tbox_entry.Text}"; tbox_entry.Text = Convert.ToString(Evaluate(tbox_expression.Text)); } private void btn_period_Click(object sender, EventArgs e) { foreach(char digit in tbox_entry.Text) if (digit == '.') return; tbox_entry.Text += "."; }
{ "domain": "codereview.stackexchange", "id": 42859, "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#, calculator, winforms", "url": null }
c#, calculator, winforms private void btn_changesign_Click(object sender, EventArgs e) { if (tbox_entry.Text.Contains("-")) tbox_entry.Text = tbox_entry.Text.Remove(0,1); else tbox_entry.Text = "-" + tbox_entry.Text; } private void btn_percentage_Click(object sender, EventArgs e) { tbox_entry.Text = Convert.ToString(last_number_entry / 100 * double.Parse(tbox_entry.Text)); } } } Answer: Since aepot has already mentioned a way how can you reduce the code of the btn_{n}_Click event handlers so, I will not address that problem here. Add_to_entry I think the second tbox_entry.Text assignment is pointless This piece of code double.Parse(tbox_entry.Text) is being used in several places I suggest to introduce a helper method for that private double GetEntryAsNumber() => double.Parse(tbox_entry.Text); Evaluate According to my understanding you don't need to create a new Table each and every time when you call this method So, you can convert the table to a static member of the class static System.Data.DataTable table = new System.Data.DataTable(); static double Evaluate(string expression) => Convert.ToDouble(table.Compute(expression, string.Empty)); btn_c_Click and btn_ce_Click This code tbox_entry.Text = "0" is being used in multiple places so you can define a helper method for this private void SetEntryToZero() => tbox_entry.Text = "0"; private void btn_c_Click(object sender, EventArgs e) { SetEntryToZero(); tbox_expression.Text = ""; last_number_entry = 0; } private void btn_ce_Click(object sender, EventArgs e) => SetEntryToZero(); btn_addition_Click ... btn_division_Click As I can see their code are almost identical except that part which comes after the Evaluate call, so the common part can be extracted private void btn_addition_Click(object sender, EventArgs e) => PrepareForTheSecondOperand("+");
{ "domain": "codereview.stackexchange", "id": 42859, "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#, calculator, winforms", "url": null }
c#, calculator, winforms private void btn_addition_Click(object sender, EventArgs e) => PrepareForTheSecondOperand("+"); private void btn_subtraction_Click(object sender, EventArgs e) => PrepareForTheSecondOperand("-"); private void btn_multiplication_Click(object sender, EventArgs e) => PrepareForTheSecondOperand("*"); private void btn_division_Click(object sender, EventArgs e) => PrepareForTheSecondOperand("/"); private void PrepareForTheSecondOperand(string operation) { last_number_entry = GetEntryAsNumber(); if (!equals_last_pressed) tbox_expression.Text += tbox_entry.Text; tbox_expression.Text = $"{Evaluate(tbox_expression.Text)} {operation} "; SetEntryToZero(); equals_last_pressed = false; } Instead of using the == false you can simply use the negation operator btn_sqrtx_Click ... btn_1dividex_Click All three methods can be implemented as a one-liner In case of 1dividex you can use the conditional operator private void btn_sqrtx_Click(object sender, EventArgs e) => tbox_entry.Text = $"{Math.Sqrt(GetEntryAsNumber())}"; private void btn_x2_Click(object sender, EventArgs e) => tbox_entry.Text = $"{Math.Pow(GetEntryAsNumber(), 2)}"; private void btn_1dividex_Click(object sender, EventArgs e) => tbox_entry.Text = tbox_entry.Text == "0" ? tbox_entry.Text : $"{1 / GetEntryAsNumber()}"; btn_equals_Click Two minor things: You don't need to use string interpolation when you do the assignment for tbox_expression.Text You don't need to use Convert.ToString static method, you can simply call the ToString instance method on the double private void btn_equals_Click(object sender, EventArgs e) { last_number_entry = GetEntryAsNumber(); if (equals_last_pressed) return; equals_last_pressed = !equals_last_pressed; tbox_expression.Text += tbox_entry.Text; tbox_entry.Text = Evaluate(tbox_expression.Text).ToString(); } btn_period_Click, btn_changesign_Click and btn_percentage_Click
{ "domain": "codereview.stackexchange", "id": 42859, "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#, calculator, winforms", "url": null }
c#, calculator, winforms btn_period_Click, btn_changesign_Click and btn_percentage_Click All three methods can be implemented as a one-liner In case of period you can use Linq's Any to find a dot In case of changesign you can use conditional operator private void btn_period_Click(object sender, EventArgs e) => tbox_entry.Text += tbox_entry.Text.ToCharArray().Any(c => c == '.') ? "" : "."; private void btn_changesign_Click(object sender, EventArgs e) => tbox_entry.Text = tbox_entry.Text.Contains("-") ? tbox_entry.Text.Remove(0, 1): "-" + tbox_entry.Text; private void btn_percentage_Click(object sender, EventArgs e) => tbox_entry.Text = Convert.ToString(last_number_entry / 100 * GetEntryAsNumber());
{ "domain": "codereview.stackexchange", "id": 42859, "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#, calculator, winforms", "url": null }
python, python-3.x Title: Python : Is it possible to combine these two functions into one? Question: I have been creating a scoring program for a game of hearts. If there is a an even number of players then players will pass across. And an odd number there is no pass across. I created these 2 functions that work fine. But I keep scratching my head trying to simplify them into only 1 function. I know its possible but I just can't get it right. This is the block of code I'm working with: #this function is for an odd number of players def no_across(): global pass_counter if pass_counter == 1: print("WE ARE PASSING LEFT") pass_counter = pass_counter + 1 elif pass_counter == 2: print("WE ARE PASSING RIGHT") pass_counter = pass_counter + 1 elif pass_counter == 3: print("WE ARE HOLDING") pass_counter = pass_counter - 2 #this function is for an even number of players def yes_across(): global pass_counter if pass_counter == 1: print("WE ARE PASSING LEFT") pass_counter = pass_counter + 1 elif pass_counter == 2: print("WE ARE PASSING RIGHT") pass_counter = pass_counter + 1 elif pass_counter == 3: print("WE ARE PASSING ACROSS") pass_counter = pass_counter + 1 elif pass_counter == 4: print("WE ARE HOLDING") pass_counter = pass_counter - 3 #determines which of the 2 previous functions to call if player_count % 2 == 0: yes_across() else: no_across() As you can see in the first block and second block I have repeated code but I know it can be simplified. All help is appreciated. EDIT: Below is the complete code. Don't judge me because I just whipped it together last night as a test to see if it would work. Also I am integrating this into a different project I have that will use a GUI. I just needed a rough copy of the program to work. #this program is meant to keep track of score during a game of hearts
{ "domain": "codereview.stackexchange", "id": 42860, "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 #displays a greeting print("Welcome to the player score keeper!") #score limit reached allows game to continue until changed score_limit_reached = False #these are the players names John = 0 Elaine = 0 Austin = 0 Bridgette = 0 Rocky = 0 #these following variables help determine if the program should have certain #passing in game. also keeps track of score limit. player_count = 0 player_count = int(input("How many players are going to play? ")) score_limit = 0 pass_counter = 1 score_limit = int(input("What is the score limit? ")) #this function is for an odd number of players def no_across(): global pass_counter if pass_counter == 1: print("WE ARE PASSING LEFT") pass_counter = pass_counter + 1 elif pass_counter == 2: print("WE ARE PASSING RIGHT") pass_counter = pass_counter + 1 elif pass_counter == 3: print("WE ARE HOLDING") pass_counter = pass_counter - 2 #this function is for an even number of players def yes_across(): global pass_counter if pass_counter == 1: print("WE ARE PASSING LEFT") pass_counter = pass_counter + 1 elif pass_counter == 2: print("WE ARE PASSING RIGHT") pass_counter = pass_counter + 1 elif pass_counter == 3: print("WE ARE PASSING ACROSS") pass_counter = pass_counter + 1 elif pass_counter == 4: print("WE ARE HOLDING") pass_counter = pass_counter - 3
{ "domain": "codereview.stackexchange", "id": 42860, "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 #here begins the actual scoring section of the game while score_limit_reached == False: #determines which of the 2 previous functions to call if player_count % 2 == 0: yes_across() else: no_across() #user input keeps track of score John = John + int(input("john: ")) Elaine = Elaine + int(input("elaine: ")) Austin = Austin + int(input("austin: ")) Bridgette = Bridgette + int(input("bridgette: ")) Rocky = Rocky + int(input("rocky: ")) #prints current score of each player print("\n\nJohn's score - " + str(John)) print("Elaine's score - " + str(Elaine)) print("Austin's score - " + str(Austin)) print("Bridgette's score - " + str(Bridgette)) print("Rocky's score - " + str(Rocky) + "\n\n") #if the score limit has been reached it will end the while loop if John >= score_limit: score_limit_reached = True if Elaine >= score_limit: score_limit_reached = True if Austin >= score_limit: score_limit_reached = True if Bridgette >= score_limit: score_limit_reached = True if Rocky >= score_limit: score_limit_reached = True #prints the final score for each player print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nJohn - " + str(John)) print("Elaine - " + str(Elaine)) print("Austin - " + str(Austin)) print("Bridgette - " + str(Bridgette)) print("Rocky - " + str(Rocky) + "\n") #if any number of players has lost will declare each #player a poopy, followed by which score was the highest if John >= score_limit: print("John is a poopy!") if Elaine >= score_limit: print("Elaine is a poopy!") if Austin >= score_limit: print("Austin is a poopy!") if Bridgette >= score_limit: print("Bridgette is a poopy!") if Rocky >= score_limit: print("Rocky is a poopy!") biggest_poopy = str(max(John, Elaine, Austin, Bridgette, Rocky)) print("\nThe biggest poopy is " + biggest_poopy + "!")
{ "domain": "codereview.stackexchange", "id": 42860, "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 print("\nThe biggest poopy is " + biggest_poopy + "!") Answer: Yes, it can be easily done. Just pass some indication of parity into the function. The most straightforward way is to check player_count in the function like this: def both_across(): global pass_counter global player_count if pass_counter == 1: print("WE ARE PASSING LEFT") pass_counter = pass_counter + 1 elif pass_counter == 2: print("WE ARE PASSING RIGHT") pass_counter = pass_counter + 1 elif pass_counter == 3 and player_count%2==0: print("WE ARE PASSING ACROSS") pass_counter = pass_counter + 1 elif pass_counter == 3 and player_count%2==1: print("WE ARE HOLDING") pass_counter = pass_counter - 2 elif pass_counter == 4: print("WE ARE HOLDING") pass_counter = pass_counter - 3 But this code is still bad in many ways; the most obvious bad thing is using globals instead of arguments and returning a value. def both_across(counter, players): if counter == 1: print("WE ARE PASSING LEFT") return counter + 1 elif counter == 2: print("WE ARE PASSING RIGHT") return counter + 1 elif counter == 3 and players%2==0: print("WE ARE PASSING ACROSS") return counter + 1 elif counter == 3 and players%2==1: print("WE ARE HOLDING") return counter - 2 elif counter == 4: print("WE ARE HOLDING") return counter - 3 #somewhere down the code... pass_counter = both_across(pass_counter, player_count)
{ "domain": "codereview.stackexchange", "id": 42860, "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 Now, examining the function gives me an insight: in every branch we can find the returning value without calculations. If we know the value of counter, we can find the value of counter+1, counter-2 etc.: def both_across(counter, players): if counter == 1: print("WE ARE PASSING LEFT") return 2 elif counter == 2: print("WE ARE PASSING RIGHT") return 3 elif counter == 3 and players%2==0: print("WE ARE PASSING ACROSS") return 4 elif counter == 3 and players%2==1: print("WE ARE HOLDING") return 1 elif counter == 4: print("WE ARE HOLDING") return 1 The last two elifs can be combined, probably in the same else: ... elif counter == 3 and players%2==0: print("WE ARE PASSING ACROSS") return 4 else: print("WE ARE HOLDING") return 1 At this point it becomes clear that pass_counter values are in fact not integers but some symbols. They can be, say, strings - and even that strings we're printing: pass_counter = "HOLDING" def both_across(counter, players): if counter == "HOLDING": print("WE ARE PASSING LEFT") return "PASSING LEFT" elif counter == "PASSING LEFT": print("WE ARE PASSING RIGHT") return "PASSING RIGHT" elif counter == 3 and players%2==0: print("WE ARE PASSING ACROSS") return "PASSING ACROSS" else: print("WE ARE HOLDING") return "HOLDING" And now, we can combine all prints: pass_counter = "HOLDING" def both_across(counter, players): if counter == "HOLDING": return "PASSING LEFT" elif counter == "PASSING LEFT": return "PASSING RIGHT" elif counter == 3 and players%2==0: return "PASSING ACROSS" else: return "HOLDING" while not score_limit_reached: pass_counter = both_across(pass_counter, player_count) print("WE ARE", pass_counter)
{ "domain": "codereview.stackexchange", "id": 42860, "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 Good enough? For the rest of the code: Use functions. Don't leave the code just lying around, gather it into some functions and call them. Use lists and loops. You have the code for five names repeated - gather that into lists like scores = [0,0,0,0,0] names = ["John", "Elaine", "Austin", "Bridgette", "Rocky"] ... for i in range(5): scores[i] += int(input(names[i]+': ')) ... for i in range(5): print(names[i] + " - " + str(scores[i])) Use format strings. The last line can be rewritten as print(f'{names[i]} - {scores[i]}') Don't stop learning. Learn classes. This code will make much more sense with classes.
{ "domain": "codereview.stackexchange", "id": 42860, "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 }
c++, hash-map Title: Implementation of generic hash table Question: I am learning how to write generic code in C++ and I decided to write a hash table. Its key needs to be a primitive type and value can be any type. The hash function needs to be provided by the user. Type of the function is enforced to the user. I am looking for tips on efficiency of the code and whether forwarding of the arguments are working as intended (perfect forwarding). Also in the get method, would it be better to return value type pointer instead of std::optional? It only contains emplace back and get methods keep things tidy. #pragma once #include <list> #include <optional> #include <type_traits> template< class KeyType > using hashFunction_t = size_t(const KeyType& key); template < class KeyType, class ValueType, size_t nHashGroups, hashFunction_t<KeyType>* hashFunction> class BasicHash { public: template< class... ValueArgTypes > void EmplaceBack(KeyType&& key, ValueArgTypes&&... args) { size_t hash = Hash(std::forward<KeyType>(key)); for (auto& pair : hashGroups[hash]) if (pair.key == key) return; hashGroups[hash].emplace_back( std::forward<KeyType>(key), std::forward<ValueType>(ValueType{ args... }) ); } decltype(auto) Get(KeyType&& key) { size_t hash = Hash(std::forward<KeyType>(key)); for (auto& pair : hashGroups[hash]) if (pair.key == key) return std::optional<ValueType>{ pair.value }; return std::optional<ValueType>{}; } private: size_t Hash(KeyType&& key) { return (*hashFunction)(static_cast<const KeyType&>(key)) % nHashGroups; } struct KeyValuePair { KeyValuePair(KeyType&& key, ValueType&& value) : key(key), value(value) { } KeyType key; ValueType value; }; std::list<KeyValuePair> hashGroups[nHashGroups]; };
{ "domain": "codereview.stackexchange", "id": 42861, "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++, hash-map", "url": null }
c++, hash-map std::list<KeyValuePair> hashGroups[nHashGroups]; }; Minimal usage of the hash table: #include "BasicHash.h" #include <string> #include <iostream> //djb2 size_t hashFunction(const std::string& key) { unsigned long hash = 5381; int c; const char* str = key.c_str(); while (c = *str++) hash = ((hash << 5) + hash) + c; return hash; } class TwoNumberStore { public: TwoNumberStore(int a, int b) : n1{ a }, n2{ b } { } int n1 = 0; int n2 = 0; }; int main() { BasicHash<std::string, TwoNumberStore, 50, hashFunction> table; table.EmplaceBack("First Two", 1, 2); auto firstTwo = table.Get("First Two"); if (firstTwo.has_value()) { std::cout << firstTwo.value().n1 << '\n'; std::cout << firstTwo.value().n2; } } I just realised I was copying value in std::optional. Changed get to return a optional reference_wrapper instead. decltype(auto) Get(KeyType&& key) { size_t hash = Hash(std::forward<KeyType>(key)); for (auto& pair : hashGroups[hash]) if (pair.key == key) return std::optional<std::reference_wrapper<ValueType>>{ pair.value }; return std::optional<std::reference_wrapper<ValueType>>{}; } This makes retrieving data even messier. if (firstTwo.has_value()) { std::cout << firstTwo.value().get().n1 << '\n'; std::cout << firstTwo.value().get().n2; }
{ "domain": "codereview.stackexchange", "id": 42861, "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++, hash-map", "url": null }
c++, hash-map Answer: Make it look like std::unordered_map When in Rome, do as the Romans do. In C++, if you are writing a container, it would be very nice if it has the same API as any other STL container. This avoids having to learn a different interface, and also makes it easier to use your container as a drop-in for an STL container without having to rewrite a lot of code that uses it. This is also part of making code more generic. In particular, make sure the public member functions look like those of the closest matching STL container, which would be a std::unordered_map. So: Change EmplaceBack() to emplace() Consider changing Get() to operator[] which looks up or inserts. Add other typical STL container functions, like clear(), size(), erase(). Note that the STL containers don't return std::optionals. Of course, the STL containers themselves were designed way before std::optional was a thing. Sometimes you know the item already exists, or maybe if you don't and it doesn't, you just want a default-constructed one. In those cases, operator[]() and at() do exactly what you want. A different function that returns a std::optional might be nice though, since the standard way to do the same with STL containers: auto it = container.find(key); if (it != container.end()) { auto &value = it->second; ... }
{ "domain": "codereview.stackexchange", "id": 42861, "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++, hash-map", "url": null }
c++, hash-map ...is quite annoying. Perhaps a better name than Get() could be used though, which hints that an optional value will be returned. Passing a hash function Passing a function as a template parameter limits the types of functions you can pass. The STL containers that take a hash function take this as a parameter to the constructor. You can do the same thing: template < class KeyType, class ValueType, size_t nHashGroups, class HashFunction> class BasicHash { public: BasicHash(const HashFunction& hashFunction = HashFunction()) : hashFunction(hashFunction) {} ... private: size_t Hash(const KeyType& key) { return hashFunction(key) % nHashGroups; } ... HashFunction hashFunction; }; The only drawback is that you have to pass the hash function as a function object, but that's not a problem if you use lambdas: auto hashFunction = [](const std::string& key) -> size_t { ... return hash; } ... BasicHash<std::string, TwoNumberStore, 50, decltype(hashFunction)> table(hashFunction); Another option would be to not make the hash function type a template parameter, but to pass the hash function using a std::function<size_t(const KeyType&)>. This has pros and cons; the advantage is that you don't need to specify the hash function type explicitly anymore, and you can pass a regular function to the constructor. The con is that there might be some performance overhead associated with std::function. Pass by const reference where appropriate You pass key to Get() and Hash() using an r-value reference. However, this is not necessary, since you are not going to move from it. It also might prevent some optimizations. Prefer using const reference whenever you want to pass a parameter you are not going to modify in any way. One issue with r-value references is that they cannot bind to a const l-value. Consider writing this: std::string key = "First Two"; auto firstTwo = table.Get(key);
{ "domain": "codereview.stackexchange", "id": 42861, "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++, hash-map", "url": null }
c++, hash-map This would fail to compile if Get() takes an r-value reference. A const reference parameter will take anything. Missing std::move() in the constructor of KeyValuePair The constructor of KeyValuePair takes r-value references, but it just copies the values of the parameters into the member variables. You have to explicitly use std::move() to ensure the move constructor is used if possible: KeyValuePair(KeyType&& key, ValueType&& value) : key(std::move(key)), value(std::move(value)) {} Efficient storage of keys and values Your hash table works well if you provide a good hash function and now up front how many elements you are going to store. However, it is usually hard to know exactly how much you are going to store up front, and therefore requiring nHashGroups to be specified as a template constant is either going to make the hash table too small, leading to large buckets and eventually \$O(N)\$ performance, or it is too large and you waste a lot of memory on empty buckets. Consider making the size of the hash table dynamic. Let the user optionally reserve() a certain size if they do have a good estimate. Furthermore, an empty std::list uses 24 bytes on a 64-bit architecture, and the moment you start using it, it will have to allocate memory to store the actual contents. Instead of using buckets, consider just using a single array of KeyValuePairs, and use open addressing to handle collisions. This does require that you can resize your hash table though. Fix your hash function GCC and Clang will warn about using the result of the assignment in the while-loop in hashFunction() as the condition. You could solve it by adding some parentheses, but I would rewrite it to proper C++ instead: for (auto c: key) hash = ((hash << 5) + hash) + c; Also note that std::strings can contain an arbitrary number of NUL-characters.
{ "domain": "codereview.stackexchange", "id": 42861, "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++, hash-map", "url": null }
python, json Title: Elegantly combine list of records into JSON for a Python post request? Question: I'm parsing a Pandas DataFrame table for an API post request (using requests, of course). I'm working on building my script in Jupyter Notebooks. result = df.to_json(orient="records") parsed_json = json.loads(result) I've seen a lot of JSON manipulations with format(), so my first impulse was to use f-strings: je_json = json.dumps({ 'BatchId': '1', 'userId': 'myID', 'journalEntries': f'{parsed_json }' }) It would be very readable and elegant, but of course it doesn't work as the result is escaped and will not POST: '{"BatchId": "1", "userId": "myID", "journalEntries": "[{\\"JENumber\\":\\"PR2022-01-23\\",\\"Date\\":\\"01\\\\/23\\\\/2022\\",\\"JEComment\\": [...] I solved the problem by reconstructing the list/dicts: je_json = { 'BatchId': '1', 'userId': 'myID', 'journalEntries': '' } je_json['journalEntries'] = [] for record in parsed_json: je_json['journalEntries'].append(record) payload = json.dumps(je_json) Is there a simpler or more elegant solution? Request data_headers = { 'Authorization': str(parsed_data.get('BearerToken')), 'Content-Type': 'application/json', 'Cookie': 'ss-opt=temp; ss-pid=xxxxxxxxxxxxxxxxxxx' } response = requests.request(method="POST", url=URL, headers=data_headers, data=payload)
{ "domain": "codereview.stackexchange", "id": 42862, "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, json", "url": null }
python, json Explanation of my testing methodology Since running tests in Jupyter notebooks can be tricky, I'm going to mention here my methodology. Right now, I'm testing the payload variable and request in a separate cells. After a successful record insertion via the API, I don't reload the whole notebook, and simply reload the payload and request cells: 1) Change the successful payload cell into type 'raw'; 2) Add new cell with modified payload variable for testing; 3) reload the payload and request cells; 4) examine the results; 5) toggle cell type 'code' and 'raw' to return to the success version and verify underlying code; 6) repeat. What makes this work is toggling cell type, and never mutating variables once assigned--there is no assignment to any variable name assigned to a cell above it. Answer: I fail to see a reason for the long way around. If you already have parsed JSON, why not use it directly? result = df.to_json(orient="records") parsed_json = json.loads(result) je_json = json.dumps({ 'BatchId': '1', 'userId': 'myID', 'journalEntries': parsed_json }) It would be even better to not serialize and deserialize the JSON data twice: je_json = json.dumps({ 'BatchId': '1', 'userId': 'myID', 'journalEntries': df.to_dict(orient="records") }) On a side-note I find it funny, how pandas' method name to_dict() is absolutely misleading, since it returns a list in the above case. Also, you don't need to serialize the JSON payload manually, since requests will do it for you: from requests import post payload = { 'BatchId': '1', 'userId': 'myID', 'journalEntries': df.to_dict(orient="records") } response = post('https://yourapp.com/submit', json=payload)
{ "domain": "codereview.stackexchange", "id": 42862, "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, json", "url": null }
php, mysql, android, security Title: Is this session manager secure? Question: I'm looking for best practices for writing secure session managers. I'm making a table for the authorization token (UUID OR GUIDv4) with autoincrement, user_id, token, status (enum) then update status onPause() onResume() so when I update a token I get a new autoincrement to store with the token in shared preference. Then on token update I just insert the old token with the user_id in another table for history. The problems that I'm having: it's good for a single device but when I want to update like password and update token I will have to end all user sessions and only the one I'm using will be updated. should I add timestamp and keep the autoincrement inserted for a certain time of token updates or days or should I let it insert new autoincerment? Is it good practice or there is a better way? I already read about: shared preference exploit on root. Is Shared Preferences safe for private datas? shared preference not secured even if I encrypt data. Android SharedPreference security ANDROID_ID can be null and can change upon factory reset. data will be not safe if sensitive data is exploited I came across this but could not find any other articles that approve the method he used SQL injection I already use a prepared statement: <?php $db_name = "mysql:host=localhost;dbname=DATABSE;charset=utf8"; $db_username = "root"; $db_password = ""; try { $PDO = new PDO($db_name, $db_username, $db_password); //echo "connection success"; } catch (PDOException $error) { //echo "Error: " . $error->getMessage(); //echo "connection error"; exit; } $user_id = $_POST['user_id']; $stmt = $PDO->prepare(" SELECT tableA.name AS name, TABLEB.logo AS logo FROM tableA LEFT JOIN TABLEB ON TABLEB.id = tableA.id WHERE tableA.id = :USERID ; "); $stmt->bindParam(':USERID', $user_id);
{ "domain": "codereview.stackexchange", "id": 42863, "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": "php, mysql, android, security", "url": null }
php, mysql, android, security $stmt->execute(); $row = $stmt->fetchAll(PDO::FETCH_ASSOC); if (!empty($user_id)) { $returnApp = new stdClass(); $returnApp->LOADPROFILE = 'LOAD_SUCCESSFUL'; $returnApp->LOAD_SUCCESSFUL = $row; echo json_encode($returnApp); } else { $returnApp = array('LOADPROFILE' => 'LOAD_FAILED'); echo json_encode($returnApp); } Answer: I don't see code for some of your items of concern, so I'll focus on reviewing the provided code. Your code should consistently respond with the same general formatted json string so that the receiving code can remain simple and elegant. I think your business logic indicates that an empty array as a response is somehow a failure. A non-empty array will be success. You are not validating the submitted value. If the submission is anything other than a positive integer, then you can safely give the failure response -- even before bothering with a database connection. I recommend eliminating single-use variables in any script unless they provide a valuable benefit. Unconditionally return the empty array or array of associative arrays that is provided by fetchAll(). New code: if (empty($_POST['user_id']) || !ctype_digit($_POST['user_id'])) { exit('[]'); } $pdo = new PDO( "mysql:host=localhost;dbname=DATABSE;charset=utf8", "root", "" ); $stmt = $pdo->prepare( "SELECT tableA.name AS name, TABLEB.logo AS logo FROM tableA LEFT JOIN TABLEB ON TABLEB.id = tableA.id WHERE tableA.id = ?" ); $stmt->execute([$_POST['user_id']]); echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)); In terms of security, I am concerned about the fact that anyone can anonymously/trivially fire a bunch of integers at this code and get a direct feed of result set data. Maybe this is why you mentioned UUIDs -- you might think that obscuring the identifier may improve security -- but it won't, it will only potentially slow down a persistent attacker.
{ "domain": "codereview.stackexchange", "id": 42863, "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": "php, mysql, android, security", "url": null }
python, python-3.x, file-system Title: Get the total file size from a directory for each date using map and pairs Question: I'm working on a project where the file name consists of actual dates but the data for the dates are split into multiple files. Developed the following program to count the number of files for each date (part of the filename) and also the total size. Wondering, if the same can be written in a better way. import os import glob import os import collections directory_name = "\\SpeicifDir\\" # Get a list of files (file paths) in the given directory list_of_files = filter( os.path.isfile, glob.glob(directory_name + '*.txt') ) mapOfDateFileSize = collections.defaultdict(list) # For all the files for file_path in list_of_files: file_size = os.stat(file_path).st_size filename = os.path.basename(file_path) splitFilename = filename.split('-') # Extract the file and split the file using - as a separator dtForFile = splitFilename[1] + "-" + splitFilename[2] + "-" + splitFilename[3] # Get the file name and size if dtForFile in mapOfDateFileSize: dataFromDictionary = mapOfDateFileSize[dtForFile] dataFromDictionary = dataFromDictionary[0] totalCount = dataFromDictionary[0] totalSize = dataFromDictionary[1] totalCount = totalCount + 1 totalSize = totalSize + file_size # Update the file size and count mapOfDateFileSize[dtForFile] = [ (totalCount, totalSize) ] else: mapOfDateFileSize[dtForFile].append((1,file_size)) # For each date get the total size, total file count for dt,elements in mapOfDateFileSize.items(): dataFromDictionary = elements[0] totalCount = dataFromDictionary[0] totalSize = dataFromDictionary[1] print (dt, ",", totalCount , ",", totalSize)
{ "domain": "codereview.stackexchange", "id": 42864, "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, file-system", "url": null }
python, python-3.x, file-system Answer: Default Dictionary You are using this wrong. ... mapOfDateFileSize = collections.defaultdict(list) for file_path in list_of_files: ... if dtForFile in mapOfDateFileSize: ... mapOfDateFileSize[dtForFile] = [ (totalCount, totalSize) ] else: mapOfDateFileSize[dtForFile].append((1,file_size)) ... The whole point of a default dictionary is so you can use the mapOfDateFileSize[key] without worrying about whether the key exists or not. Since you explicitly test if dtForFile in mapOfDateFileSize, you could use a regular dictionary, and create the list yourself in the else: clause with: ... else: mapOfDateFileSize[dtForFile] = [(1, file_size)] ... Unnecessary nesting dataFromDictionary = mapOfDateFileSize[dtForFile] dataFromDictionary = dataFromDictionary[0] totalCount = dataFromDictionary[0] totalSize = dataFromDictionary[1] You are storing a tuple, in a one-element list, in a dictionary. What is the purpose of this one-element list? It is not adding anything, and making things way more complicated. if dtForFile in mapOfDateFileSize: total_count, total_size = mapOfDateFileSize[dtForFile] total_count += 1 total_size += file_size # Update the file size and count mapOfDateFileSize[dtForFile] = (total_count, total_size) else: mapOfDateFileSize[dtForFile] = (1, file_size) # Tuple unpacking even works when iterating through the dictionary! for dt, (total_count, total_size) in mapOfDateFileSize.items(): print (dt, ",", total_count, ",", total_size)
{ "domain": "codereview.stackexchange", "id": 42864, "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, file-system", "url": null }
python, python-3.x, file-system A Real Default Dictionary The if dtForFile in mapOfDateFileSize is still annoying. You wanted to use a defaultdict. What you need is a default dict that returns the tuple (0, 0) if no entry exists. ... mapOfDateFileSize = collections.defaultdict(lambda: (0, 0)) for file_path in list_of_files: ... total_count, total_size = mapOfDateFileSize[dtForFile] total_count += 1 total_size += file_size # Update the file size and count mapOfDateFileSize[dtForFile] = (total_count, total_size) ... PEP 8 The Style Guide for Python Code has many guidelines you should follow. Of particular note, variable names should be snake_case, not bumpyWordsCommonlyUsedInOtherProgrammingLanguages since they are really hard to read.
{ "domain": "codereview.stackexchange", "id": 42864, "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, file-system", "url": null }
c++, performance, strings, error-handling, c++20 Title: Custom string-to-int converter Question: I have written the following function: #include <iostream> #include <utility> #include <string> #include <string_view> #include <limits> #include <optional> #include <stdexcept> // header file std::optional<int> isInteger( const std::string_view token, const std::pair<int, int> acceptableRange = std::pair<int, int>( std::numeric_limits<int>::min( ), std::numeric_limits<int>::max( ) ) ) noexcept; // source file std::optional<int> isInteger( const std::string_view token, const std::pair<int, int> acceptableRange ) noexcept { if ( token.empty( ) ) { return { }; // not convertible } try { std::size_t pos { 0 }; const int result_integer { std::stoi( std::string{ token }, &pos, 10 ) }; const auto& [ minAcceptableValue, maxAcceptableValue ] { acceptableRange }; if ( pos == token.length( ) && ( result_integer <= maxAcceptableValue && result_integer >= minAcceptableValue ) ) { return result_integer; // convertible, this is the happy ending } else { return { }; // not convertible } } catch ( const std::invalid_argument& ia ) { return { }; } // not convertible catch ( const std::out_of_range& oor ) { return { }; } // not convertible catch ( const std::length_error& le ) { return { }; } // not convertible catch ( const std::bad_alloc& ba ) { return { }; } // not convertible } // call site int main( ) { const std::string str { "12" }; const std::pair<int, int> acceptableRange { std::make_pair<int, int>( 0, 50 ) }; const std::optional<int> tempInteger { isInteger( str, acceptableRange ) }; if ( tempInteger ) { std::cout << "Converted value: " << tempInteger.value( ) << '\n'; } else { std::cout << "Conversion failed" << '\n'; } }
{ "domain": "codereview.stackexchange", "id": 42865, "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++, performance, strings, error-handling, c++20", "url": null }
c++, performance, strings, error-handling, c++20 The above function converts any string_view to an int if possible, otherwise returns an empty std::optional. I thought that returning an empty optional acts as an error code and informs the caller of the failure. So there isn't any need to let it throw and then handle the exceptions in the call site. I think that stack unwinding is unnecessary in this case. I have a few questions: Is this function good in terms of performance? Or should I use an alternative from another library? If so, then what can be the alternative? Does it cover all the edge cases? I have tested it with many different (valid and invalid) inputs but it never failed. Is it good that it's handling the possible exceptions inside its scope? I declared it noexcept and this decreased the size of the executable (just a little). Do you recommend doing this for this function since no exception will escape its body? Can anything about this function be further improved? Also I use GCC v11.2 (just in case you need to know). Answer: Wrapping a convenience wrapper in a convenience wrapper is generally just wasteful. Instead of calling std::stol(), go directly for std::strtol(). No need to convert to a std::string, which is potentially expensive and can fail. Instead, after trimming yourself, reject if too long, otherwise copy into a fixed-length buffer and add terminator. No need to catch any exceptions, as the wrapper adding them is avoided. As an aside, if you want to catch all exceptions and treat them equally, use the catch-all catch(...). Even if you don't forget any, writing them out and verifying is just tedious, and potentially bloats your executable. The compiler is unlikely to figure out you are really catching all possible exceptions, and thus the superfluous runtime type checks stay. Marking all functions which cannot throw by design (in contrast to those which do so by happenstance) noexcept is a good idea. It spells the contract out for users and lets the compiler take advantage too.
{ "domain": "codereview.stackexchange", "id": 42865, "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++, performance, strings, error-handling, c++20", "url": null }
c++, performance, strings, error-handling, c++20 CV-qualifiers on parameters in pure declarations (not definitions) are just noise, as they have no effect on the functions signature. I'm really not sold on packing the maximum and minimum into a pair, instead of passing them individually. If you use pre-C++17 with a back-ported replacement for std::string_view, this code might be of interest: auto trim(std::string_view s) noexcept { auto space = [](unsigned char c){ return std::isspace(c); }; while (!s.empty() && space(s.front())) s.remove_prefix(1); while (!s.empty() && space(s.back())) s.remove_suffix(1); return s; } std::optional<int> parseInteger(std::string_view s, int min, int max) noexcept { s = trim(s); constexpr size_t nBuffer = std::numeric_limits<int>::digits / 3 + 3; if (!s.size() || s.size() >= nBuffer) return {}; char buffer[nBuffer]; std::copy(s.begin(), s.end(), buffer); nBuffer[s.size()] = 0; char* end; long r = std::strtol(buffer, &end, 10); if (end - buffer != s.size() || r < min || r > max) return {}; return r; } Since C++17, you can use std::from_chars() for the parsing, which while a bit more basic, is also more amenable to fitting into your own code however you want. It avoids copying and even results in shorter code: std::optional<int> parseInteger(std::string_view s, int min, int max) noexcept { s = trim(s); if (!s.size()) return {}; if (s.size() > 1 && s[0] == '+' && s[1] != '-') s.remove_prefix(1); int r; auto result = std::from_chars(s.begin(), s.end(), r, 10); if (result.ec || result.ptr != s.end() || r < min || r > max) return {}; return r; }
{ "domain": "codereview.stackexchange", "id": 42865, "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++, performance, strings, error-handling, c++20", "url": null }
javascript Title: Categorize similar transactions Question: Please review the code to categorize some uncategorized objects: const categorizeSimilarTransactions = (transactions) => { if (!(Array.isArray(transactions) && transactions.length)) return []; const uncategorized = []; const categorized = []; const orderIds = transactions.map(transaction => transaction.id); transactions.forEach(transaction => { transaction.category ? categorized.push(transaction) : uncategorized.push(transaction); }); uncategorized.forEach(uncat => { let lowestDiff = Math.min(); categorized.forEach(cat => { if (cat.targetAccount === uncat.targetAccount) { lowestDiffComp = Math.abs(cat.amount - uncat.amount); if (lowestDiffComp < lowestDiff && lowestDiffComp < 1000) { lowestDiff = lowestDiffComp; uncat.category = cat.category; } } }) }); const merged = [...categorized, ...uncategorized]; merged.sort((a,b) => { return orderIds.indexOf(a.id) - orderIds.indexOf(b.id); }) return merged; }; This is what a categorized transaction looks like: { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -350, currency: "EUR", category: "eating_out", time: "2021-03-12T12:34:00Z" } An uncategorized transaction does not have category property. This is what an uncategorized transaction looks like: { id: "0f0ffbf9-2e26-4f5a-a6c0-fcbd504002f8", sourceAccount: "my_account", targetAccount: "eating_out", amount: -1900, time: "2021-03-12T12:34:00Z" } The following two transactions are similar: { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -350, category: "eating_out", time: "2021-03-12T12:34:00Z" }
{ "domain": "codereview.stackexchange", "id": 42866, "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": "javascript", "url": null }
javascript and { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -620, time: "2021-04-10T10:30:00Z" } Example test Input categorizeSimilarTransactions([ { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 350, time: "2021-04-10T10:30:00Z", }, { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -150, category: "eating_out", time: "2021-03-12T12:34:00Z", }, { id: "6359091e-1187-471f-a2aa-81bd2647210f", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 100, category: "entertainment", time: "2021-01-12T08:23:00Z", }, { id: "a8170ced-1c5f-432c-bb7d-867589a9d4b8", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -1690, time: "2021-04-12T08:20:00Z", }, ]); Expected Output [ { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 350, category: "entertainment", time: "2021-04-10T10:30:00Z", }, { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -150, category: "eating_out", time: "2021-03-12T12:34:00Z", }, { id: "6359091e-1187-471f-a2aa-81bd2647210f", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 100, category: "entertainment", time: "2021-01-12T08:23:00Z", }, { id: "a8170ced-1c5f-432c-bb7d-867589a9d4b8", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -1690, time: "2021-04-12T08:20:00Z", }, ]; The feedback provided was inefficient code not readable
{ "domain": "codereview.stackexchange", "id": 42866, "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": "javascript", "url": null }
javascript The feedback provided was inefficient code not readable Answer: I'd like to disagree with @riskypenguin in two points of his otherwise great review: Partitioning @riskypenguin suggests for partitioning the transactions into categorized and uncategorized to use .filter() twice. While his code certainly is concise, it is quite ugly IMO. Partitioning by a predicate (at least this is the name I know it by) is a relatively common operation, so personally I'd extract it into a function such as: function partitionBy(list, predicate) { return list.reduce( (acc, value) => { acc[!!predicate(value)].push(value); return acc; }, {true: [], false: []} ); } And then use it as: const {true: categorized, false: uncategorized} = partitionBy(transactions, t => t.category); Performance I believe the problem with this solution performance-wise is the merging and sorting at the end especially due to the use of .indexOf in the sorting function. Actually I'd suggest (unless there is expected to be a huge number of transactions) to avoid the partitioning and to simply loop over the original array twice, and use a guardian statement to skip over the "wrong" elements: for (let uncat of transactions) { if (uncat.category) { continue; } for (let cat of transactions) { if (!cat.category) { continue; } if (cat.targetAccount === uncat.targetAccount) { // ... } } } (I prefer for ... of over .forEach()). Or if partitioning is preferred then I'd suggest to only work with indexes so that the merging at the end can be avoided: const indexes = transactions.map((_, i) => i); const {true: categorizedIndexes, false: uncategorizedIndexes} = partitionBy(indexes, i => transactions[i].category);
{ "domain": "codereview.stackexchange", "id": 42866, "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": "javascript", "url": null }
javascript uncategorizedIndexes.forEach(uncatIndex => { const uncat = transactions[uncatIndex]; categorizedIndexes.forEach(catIndex => { const cat = transactions[catIndex]; if (cat.targetAccount === uncat.targetAccount) { // ... } }) });
{ "domain": "codereview.stackexchange", "id": 42866, "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": "javascript", "url": null }
python, api, rest, automation Title: Python API testing Question: I have written a rudimentary code in Python: That reads the API collection from Swagger/Postman and extracts the payload, link, and method It creates the response with the token(Generated from the token link) It records the response in a CSV. Need help in further formatting the code in terms of creating functions. Reducing lines of code. Performance tuning using multithreading from urllib.request import urlopen import requests from bs4 import BeautifulSoup import json from jsonpath_ng import jsonpath, parse def GenerateToken(): link = "<link>" page = urlopen(link) # Link to generate token contents = page.read() soup = BeautifulSoup(contents) shred = list(soup.stripped_strings) token = shred[2] # gets the token return token with open("TestResults.csv", "w") as f_object: fields = ["API_Endpoint", "Method", "Status_Code", "Message", "Timestamp"] writer = csv.DictWriter(f_object, fieldnames=fields) writer.writeheader() headers = {"Authorization": "Bearer {}".format(GenerateToken())} with open("postman_collection.json") as f: data = json.load(f) for res in data["item"]: for d in res["request"]: if "GET" in res["request"]["method"]: payload = {} url = res["request"]["url"]["raw"] method = res["request"]["method"] try: response = requests.get(url, headers=headers, data=payload)
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation if response.status_code == 200: rows1 = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": "OK", "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows1) # writer.writerows(rows1) else: rows2 = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": response.text, "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows2) # print(response.json().get("message")) except requests.ConnectionError: print("failed to connect")
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation elif "POST" in res["request"]["method"]: url = res["request"]["url"]["raw"] method = res["request"]["method"] payload = res["request"]["body"]["raw"] try: # response = requests.request("GET",url,headers=headers, data=payload) response = requests.request( "POST", url, headers=headers, data=payload ) # print(response.json()) if response.status_code == 200: rows3 = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": "OK", "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows3) else: rows4 = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": response.text, "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows4) # print(response.json().get("message")) except requests.ConnectionError: print("failed to connect")
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation else: url = res["request"]["url"]["raw"] method = res["request"]["method"] payload = res["request"]["body"]["raw"] try: # response = requests.request("GET",url,headers=headers, data=payload) response = requests.request( "POST", url, headers=headers, data=payload ) # print(response.json()) if response.status_code == 200: rows5 = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": "OK", "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows5) else: rows6 = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": response.text, "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows6) # print(response.json().get("message")) except requests.ConnectionError: print("failed to connect") f_object.close()
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation Answer: There is indeed a lot of repetition in this code. You have 3 cases: GET, POST, other. So we have: if "GET" in res["request"]["method"]: payload = {} url = res["request"]["url"]["raw"] method = res["request"]["method"] elif "POST" in res["request"]["method"]: url = res["request"]["url"]["raw"] method = res["request"]["method"] payload = res["request"]["body"]["raw"] else: url = res["request"]["url"]["raw"] method = res["request"]["method"] payload = res["request"]["body"]["raw"] Now that we have an simple overview we see that the whole block can be reduced as follows: url = res["request"]["url"]["raw"] method = res["request"]["method"] if "GET" in res["request"]["method"]: payload = {} else: payload = res["request"]["body"]["raw"] There is only a slight difference between methods: the payload. Then we proceed to the request proper: # GET response = requests.get(url, headers=headers, data=payload) # POST response = requests.request( "POST", url, headers=headers, data=payload ) # other response = requests.request( "POST", url, headers=headers, data=payload ) Again, all very similar. We can build an all-purpose statement like this: method = res["request"]["method"] response = requests.request(method, url, headers=headers, data=payload) There is no need for 3 different statements since they all pass the same arguments. The only thing that is different is the method, and you can pass that as an argument too. So now that you have a single statement to issue the request, we need to look at the result. It's a simple condition of 200 or other. Thus: if response.status_code == 200: result = "OK" else: result = response.text rows = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": result, "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows)
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation As far as I can see you are repeating the same stuff 6 times. The only thing that varies is the method + the HTTP status code and the resulting response message. That can be easily simplified. The final f_object.close() is not required since you are using the context manager (with). Accordingly, your code can already be shortened like this (untested but the concision is hopefully becoming perceptible): with open("TestResults.csv", "w") as f_object: fields = ["API_Endpoint", "Method", "Status_Code", "Message", "Timestamp"] writer = csv.DictWriter(f_object, fieldnames=fields) writer.writeheader() headers = {"Authorization": "Bearer {}".format(GenerateToken())} with open("postman_collection.json") as f: data = json.load(f) for res in data["item"]: for d in res["request"]: # common for all methods url = res["request"]["url"]["raw"] method = res["request"]["method"] # empty payload for GET if "GET" in res["request"]["method"]: payload = {} else: payload = res["request"]["body"]["raw"] try: response = requests.request(method, url, headers=headers, data=payload) if response.status_code == 200: result = "OK" else: result = response.text
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation rows = [ { "API_Endpoint": url, "Method": method, "Status_Code": response.status_code, "Message": result, "Timestamp": datetime.datetime.utcnow(), } ] writer.writerows(rows) # print(response.json().get("message")) except requests.ConnectionError: print("failed to connect")
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python, api, rest, automation So the code is now becoming more manageable after removing duplicate code. Basically we went from 118 lines to 43. That block of code could fit into a function, which name should reflect the actual purpose (that we don't know). Then it would be good to pass file names as arguments, rather than have them hardcoded inside the function. If you are going to perform repeated requests against a host then you should use requests.session to improve performance and simplifying handling of state, cookies, headers etc. To address some of your concerns: if the intention is to perform parallel processing or multithreading, there is more than one way to do that in Python. Which is best depends on your circumstances. May I suggest one link as a tutorial: Python Multithreading and Multiprocessing Tutorial. But you have two distinct tasks: writing to a CSV file and sending data to an API. So it makes sense to split the code in two functions. If you will be doing parallel processing, then basically you would read the JSON one item at a time and feed a "queue". So you need some kind of function that accepts a URL, with optional payload and return whatever you want, that could be the just the response message based on the HTTP status code. Perhaps you can build something around existing code if you look at the link quoted above, and adapt it to your need. I might edit this post later to add more suggestions on that. I also recommend the book Expert Python Programming by Tarek Jaworski & Michal Ziade if you want to get more in depth knowledge on such topics.
{ "domain": "codereview.stackexchange", "id": 42867, "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, api, rest, automation", "url": null }
python Title: Three ways to add pronoun method/property to gendered class in Python Question: Say you have a Python class for something that has an optional gender field. You'd like a helper property/method to get the appropriate pronoun for an instance. You'd also like to be able to get the possessive version of the pronoun. The use for these helpers will be in creating human-readable emails and other such messages related to the object. Below are three ways to do it. Which is best in terms of style and design and why? Option 1 @property def pronoun(self): return "he" if self.gender == 'male' else "she" if self.gender == 'female' else "they" @property def possessive_pronoun(self): return "his" if self.gender == 'male' else "her" if self.gender == 'female' else "their" Option 2 def pronoun(self, possessive=False): if possessive: return "his" if self.gender == 'male' else "her" if self.gender == 'female' else "their" else: return "he" if self.gender == 'male' else "she" if self.gender == 'female' else "they" Option 3 def pronoun(self, possessive=False): pronouns = ("he", "his") if self.gender == 'male' else ("she", "her") if self.gender == 'female' \ else ("they", "their") return pronouns[1] if possessive else pronouns[0] Feel free to suggest an even better fourth option. P.S. In case you are wondering, I like to use double quotes for strings meant for human consumption, single quotes otherwise. Answer: Option 1 looks to be best in my opinion as it enforces readability of the intent in the instance usage, e.g. u.subject_pronoun.capitalize() + " is buying the new widget for " + u.possesive_pronoun + " own use." Versus: u.pronoun().capitalize() + " is buying the new widget for " + u.pronoun(True) + " own use."
{ "domain": "codereview.stackexchange", "id": 42868, "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 Versus: u.pronoun().capitalize() + " is buying the new widget for " + u.pronoun(True) + " own use." In the latter case the meaning is lost on the possessive pronoun since the consumer of the class didn't supply the argument name. Another approach to getting the values by a nested dictionary (similar to the Ruby way suggested by Josay) would be: self._pronouns = { 'male': { 'possessive': 'his', 'object': 'him', 'subject': 'he' }, 'female': { 'possessive': 'hers', 'object': 'her', 'subject': 'she' }, 'unspecified': { 'possessive': 'theirs', 'object': 'them', 'subject': 'they' } } @property def object_pronoun(self): return self._pronouns[self.gender]['object'] if self.gender else self._pronouns['unspecified']['object'] def possessive_pronoun(self): return self._pronouns[self.gender]['possessive'] if self.gender else self._pronouns['unspecified']['possessive'] def subject_pronoun(self): return self._pronouns[self.gender]['subject'] if self.gender else self._pronouns['unspecified']['subject'] This approach allows for more types to be added easily as shown by adding the subject type. Edit: Updated per comment suggestions.
{ "domain": "codereview.stackexchange", "id": 42868, "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++, design-patterns, c++11 Title: Still an observer pattern? Question: Usually when I see tutorials about Observer Pattern I see an unique method called notify, but I'm wondering. What if I have different methods that can be called in different moments but needs to notify the others when this happen? Like events, am I doing this wrong? or still begin the observer pattern? #include <iostream> #include <algorithm> #include <vector> class Observer { public: virtual void notifyBefore() = 0; virtual void notifyAfter() = 0; }; class Subject { public: void attachObserver(Observer * observer) { observers.push_back(observer); } void detachObserver(Observer * observer) { auto index = std::find(observers.begin(), observers.end(), observer); if (index != observers.end()) { observers.erase(index); } } virtual void notifyBefore() { for (auto current : observers) { current->notifyBefore(); } } virtual void notifyAfter() { for (auto current : observers) { current->notifyAfter(); } } private: std::vector<Observer *> observers; }; class ConcreteObserver : public Observer { public: void notifyBefore() { std::cout << "You called me before..." << std::endl; } void notifyAfter() { std::cout << "You called me after..." << std::endl; } }; class ConcreteSubject : public Subject { public: }; int main() { auto subject = new ConcreteSubject; subject->attachObserver(new ConcreteObserver); subject->notifyBefore(); for (int i = 0; i < 5; ++i) std::cout << i << std::endl; subject->notifyAfter(); }
{ "domain": "codereview.stackexchange", "id": 42869, "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++11", "url": null }
c++, design-patterns, c++11 for (int i = 0; i < 5; ++i) std::cout << i << std::endl; subject->notifyAfter(); } Answer: Yes its still the observer pattern (details in my comment on the question). But there are a few implementation details that are bad for a C++ context. Good interface for your observer: class Observer { public: virtual void notifyBefore() = 0; virtual void notifyAfter() = 0; }; But you should also make the destructor virtual. It is quite probable that these objects will be destroyed via a pointer to the base class. Without a virtual destructor this is undefined behavior. You have the basics of subject correct. class Subject { public: void attachObserver(Observer * observer) { observers.push_back(observer); } My one problem is here. You are passing a pointer to an observer. Pointers do not express ownership. So it is unclear for future users of your object if you should pass a dynamically allocated object or a a pointer to an automatic object. It becomes clear by reading your class that you are not taking ownership of the pointer and your class always assumes that it is not NULL. So in this case it is probably better to pass it by reference. If there are cases were ownership can be passed then you should use smart pointers. A quick search on google for smart pointers or ownership semantics should give you lots of references. void attachObserver(Observer& observer) { observers.push_back(&observer); // Save the address of the observer // It is the responsibility of the observer // to make sure it lives long enough or // detaches itself on destruction. } Implementation: class ConcreteObserver : public Observer { public: void notifyBefore() { std::cout << "You called me before..." << std::endl; }
{ "domain": "codereview.stackexchange", "id": 42869, "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++11", "url": null }
c++, design-patterns, c++11 void notifyAfter() { std::cout << "You called me after..." << std::endl; } }; In C++11 we added the override keyword. This should be used in case you refactor your class. This will help in finding locations were you have misnamed the functions: void notifyAfter() override .... This is not Java auto subject = new ConcreteSubject; subject->attachObserver(new ConcreteObserver); You should prefer to use automatic objects (that is perfect here). If you are going to use new then you should wrap the result in a smart pointer to make sure the allocation is exception safe.
{ "domain": "codereview.stackexchange", "id": 42869, "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++11", "url": null }
design-patterns, rust, dependency-injection Title: Image scraper using Dependecy Injection in Rust with generics Question: I'm writing a scraper that downloads images from a given subreddit. I'm new to Rust, and in the majority of my previous projects I was using C++ or Java, where it's easy to do Dependency Injection. I wanted to use DI in this project, so I could inject a mock service for tests, and because I think that's how it's supposed to be done - but maybe that's not the case, and one should use a totally different design pattern in Rust? My code (I'm on an early stage of development): reddit_service.rs: pub trait RedditService { fn get_next_urls(self) -> Vec<String>; fn from_new() -> Self; fn get_one_url(self) -> String; } pub struct MockRedditService {} impl RedditService for MockRedditService { fn get_next_urls(self) -> Vec<String> { Vec::new() } fn from_new() -> MockRedditService { MockRedditService {} } fn get_one_url(self) -> String { String::from("example url") } } manager.rs: use super::reddit_service::RedditService; pub struct Manager<RS> { reddit_service: RS, } impl<RS: RedditService> Manager<RS> { pub fn new(reddit_service: RS) -> Manager<RS> { Manager { reddit_service } } pub fn scrap(self, subreddit: &str, limit: u32) -> () { println!("Scrapping {} images from {}", limit, subreddit); println!("Scrapped: {}", self.reddit_service.get_one_url()) } } and in main.rs: let app_manager = Manager::<MockRedditService>::new(MockRedditService::from_new()); app_manager.scrap(subreddit, limit); My two questions are: is that how DI is supposed to be done in Rust? (I've also read about using Box<dyn Trait>, but I didn't like it) is the DI even useful here? Maybe there's a better way of achieving clean code, which is easy to test, without using it? Answer: is that how DI is supposed to be done in Rust?
{ "domain": "codereview.stackexchange", "id": 42870, "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": "design-patterns, rust, dependency-injection", "url": null }
design-patterns, rust, dependency-injection Answer: is that how DI is supposed to be done in Rust? The core concept of dependency injection is: don't make your data/service dependencies hard-coded, but provide some way for the caller/configuration to provide an alternative. You've identified two ways to do it — trait objects and generics, both of which start with a trait, i.e. polymorphism — and those are both fine but you don't necessarily need to use polymorphism to do dependency injection. In particular, since your application is a kind of network client, one straightforward approach to testing is to direct your client to connect to a different server (in particular, one that you started up locally, that pretends to be Reddit). Thus, instead of providing a different type of implementation of RedditService, you provide a different server address. Advantages of using a local server for testing: The client code is not constrained by needing to pass through the specific RedditService interface you designed — it can be structured however is convenient for its actual job, and refactoring that structure does not require modifying the tests. You are exercising more of the stack — not just your scraping logic, but also the HTTP client you use. When writing mocks of the interfaces between individual “objects”, it can be very easy to write a test that technically has 100% code coverage, but is not actually useful because the behavior of the mock does not accurately represent the behavior of the real subsystem it's meant to imitate. Disadvantages: Writing a test-double server probably requires providing more fake data and other API details than implementing RedditService. You're testing a larger unit of code, so it's harder to nail down exactly where a failure is. Now, commentary on your actual code: pub trait RedditService { ... fn from_new() -> Self; Such a constructor is usually called new(), not from_new().
{ "domain": "codereview.stackexchange", "id": 42870, "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": "design-patterns, rust, dependency-injection", "url": null }
design-patterns, rust, dependency-injection Such a constructor is usually called new(), not from_new(). It is often not a great idea to include zero-argument constructors like this in traits. By including it, you're requiring that every implementation can be constructed from zero information, which is a bad idea especially for a network client: The real implementation should probably be constructed with some configuration (server address, throttling policy, User-Agent string, etc.) The mock implementation should probably be constructed with some test data. So, remove this method entirely, and just let each individual implementation have an inherent new() that takes whatever parameters are useful. (In cases where a zero-argument constructor makes sense, consider using the standard library's Default trait for that purpose.) fn get_next_urls(self) -> Vec<String>; fn get_one_url(self) -> String; These two methods take self by value, meaning that once you call them you can't use the value you called them on any more. They should probably take a reference instead: fn get_next_urls(&mut self) -> Vec<String>; fn get_one_url(&mut self) -> String; This isn't a matter of style, though: it's something that you will find you need to change one way or another to make your code actually work. pub fn scrap(self, subreddit: &str, limit: u32) -> () { -> () is the default return type; you can leave those symbols out entirely. The Rust toolchain includes a linter that will tell you things like this: run cargo clippy and see what it says. Clippy lints (as opposed to compiler built-in lints) are not always good ideas; they're deliberately more ambitious and more likely wrong than compiler lints. However, they are designed to tell you about a lot of possible issues that you can run into a beginner, so I recommend reading what they have to say.
{ "domain": "codereview.stackexchange", "id": 42870, "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": "design-patterns, rust, dependency-injection", "url": null }
design-patterns, rust, dependency-injection Finally, a point of English rather than Rust: The tool you're writing is a scraper to scrape Reddit, not a scrapper to scrap Reddit. They are both standard English words but they mean different things.
{ "domain": "codereview.stackexchange", "id": 42870, "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": "design-patterns, rust, dependency-injection", "url": null }
c++ Title: Complicated AST manipulation looks ugly in C++. How to refactor it? Question: Here is a code I have recently written in the compiler for my programming language, written in C++. It rewrites code such as: array_name[random_generator()] += 1; to a code such as: Integer32 temporary_subscriptXXXX; temporary_subscriptXXXX := random_generator(); array_name[temporary_subscriptXXXX] := array_name[temporary_subscriptXXXX] + 1; Notice that simply rewriting it as something like: array_name[random_generator()] := array_name[random_generator()] + 1; would not do the trick, because then the random generator would have been called twice instead of once, each time presumably giving a different result.
{ "domain": "codereview.stackexchange", "id": 42871, "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++", "url": null }
c++ } else if (text.size() == 2 and text[1] == '=') // The assignment operators "+=", "-=", "*=" and "/="... { if (children.at(0).text.back() == '[') { // https://github.com/FlatAssembler/AECforWebAssembly/issues/15 // https://discord.com/channels/530598289813536771/847014270922391563/934823770307301416 /* * So, what follows is a bit of an ugly and incomprehensible code * that does the following. It rewrites code such as: * ``` * array_name[random_generator()] += 1; * ``` * to a code such as: * ``` * Integer32 temporary_subscriptXXXX; * temporary_subscriptXXXX := random_generator(); * array_name[temporary_subscriptXXXX] := * array_name[temporary_subscriptXXXX] + 1; * ``` * Notice that simply rewriting it as something like: * ``` * array_name[random_generator()] := array_name[random_generator()] * + 1; * ``` * would not do the trick, because then the random generator would * have been called twice instead of once, each time presumably * giving a different result. * TODO: Refactor that code to be more legible. I have made a * StackExchange question asking how to do that, but it got * closed for some reason: * https://codereview.stackexchange.com/questions/273535/complicated-ast-manipulation-looks-ugly-in-c-how-to-refactor-it */ TreeNode fakeInnerFunctionNode("Does", lineNumber, columnNumber); std::string subscriptName = "temporary_subscript" + std::to_string(rand()); while (context.variableTypes.count(subscriptName))
{ "domain": "codereview.stackexchange", "id": 42871, "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++", "url": null }
c++ while (context.variableTypes.count(subscriptName)) subscriptName = "temporary_subscript" + std::to_string(rand()); TreeNode declarationOfSubscript("Integer32", lineNumber, columnNumber); declarationOfSubscript.children.push_back( TreeNode(subscriptName, lineNumber, columnNumber)); fakeInnerFunctionNode.children.push_back(declarationOfSubscript); TreeNode subscriptAssignment(":=", lineNumber, columnNumber); subscriptAssignment.children.push_back( TreeNode(subscriptName, lineNumber, columnNumber)); subscriptAssignment.children.push_back(children[0].children.at(0)); fakeInnerFunctionNode.children.push_back(subscriptAssignment); TreeNode convertedToSimpleAssignment(":=", lineNumber, columnNumber); convertedToSimpleAssignment.children.push_back(TreeNode( children[0].text, children[0].lineNumber, children[0].columnNumber)); convertedToSimpleAssignment.children[0].children.push_back( TreeNode(subscriptName, lineNumber, columnNumber)); convertedToSimpleAssignment.children.push_back( TreeNode(text.substr(0, 1), lineNumber, columnNumber)); convertedToSimpleAssignment.children[1].children.push_back(TreeNode( children[0].text, children[0].lineNumber, children[0].columnNumber)); convertedToSimpleAssignment.children[1].children[0].children.push_back( TreeNode(subscriptName, lineNumber, columnNumber)); convertedToSimpleAssignment.children[1].children.push_back( children.at(1)); fakeInnerFunctionNode.children.push_back(convertedToSimpleAssignment); CompilationContext fakeContext = context; fakeContext.stackSizeOfThisScope = 0; fakeContext.stackSizeOfThisFunction = 0; assembly += fakeInnerFunctionNode.compile(fakeContext) + "\n"; } else { TreeNode convertedToSimpleAssignment(":=", lineNumber, columnNumber);
{ "domain": "codereview.stackexchange", "id": 42871, "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++", "url": null }
c++ } else { TreeNode convertedToSimpleAssignment(":=", lineNumber, columnNumber); convertedToSimpleAssignment.children.push_back(children[0]); convertedToSimpleAssignment.children.push_back(*this); convertedToSimpleAssignment.children[1].text = convertedToSimpleAssignment.children[1].text.substr(0, 1); assembly += convertedToSimpleAssignment.compile(context); }
{ "domain": "codereview.stackexchange", "id": 42871, "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++", "url": null }
c++ It definitely looks incomprehensible. How would you write it better? Answer: The biggest improvement you can make is simply to use reasonably short names. Name length should be proportional to scope length; there is no reason to have names like convertedToSimpleAssignment as local variables. Just by renaming, your else branch goes from TreeNode convertedToSimpleAssignment(":=", lineNumber, columnNumber); convertedToSimpleAssignment.children.push_back(children[0]); convertedToSimpleAssignment.children.push_back(*this); convertedToSimpleAssignment.children[1].text = convertedToSimpleAssignment.children[1].text.substr(0, 1); assembly += convertedToSimpleAssignment.compile(context); down to simply auto n = TreeNode(":=", lineNumber, columnNumber); n.children.push_back(children[0]); n.children.push_back(*this); n.children[1].text = n.children[1].text.substr(0, 1); assembly += n.compile(context); Also, s.substr(0, 1) is just s[0], so: n.children[1].text = n.children[1].text[0]; Your next step would be to look at operations you do over and over, and factor them out into functions so that the code reflects a high-level view of what you're doing. For example, this specific bit seems to be creating a node with two children and a "text" in the middle (the name of the operator). So I'd look for a way to write it as: text = text[0]; // turn "+=" into "+", "*=" into "*", etc auto n = TreeNode( line, column, ":=", { children[0], *this } ); assembly += n.compile(ctx); Then, try to apply the same techniques throughout your code.
{ "domain": "codereview.stackexchange", "id": 42871, "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++", "url": null }
rust Title: Rust wrapper around Win32 Fiber Question: So this one was quite rough to implement. I needed to pass an FnOnce to a foreign function through a c_void which requires double boxing. Another fun detail is that the callback is not called until someone actually calls SwitchFiber which isn't required to happen. So simply passing the ownership to the callback was not an option, because then it would like if it wasn't called. Instead I needed to keep track of whether the callback actually consumed the FnOnce, which ended up being another Box. I would love some feedback to see if this code can be cleaned up in any way, perhaps reducing its complexity (or at least the amount of boxes). use windows_sys::{ Win32::Foundation::*, Win32::System::Threading::*, }; use std::os::raw::c_void; use crate::PlatformError; struct FiberInternals { handle: *mut c_void, entry_point: *mut Box<dyn FnOnce()> } pub struct Fiber(Box<FiberInternals>); impl Fiber { fn new<F>(entry_point: F) -> Result<Fiber, PlatformError> where F: FnOnce() -> () + 'static { let entry_point_box_box: Box<Box<dyn FnOnce()>> = Box::new(Box::new(entry_point)); let entry_point_box_ptr = Box::into_raw(entry_point_box_box); let mut internals = Box::new(FiberInternals { handle: std::ptr::null_mut(), entry_point: entry_point_box_ptr }); internals.handle = unsafe { CreateFiber(0, Some(fiber_entry_point), &mut *internals as *mut _ as *mut c_void) }; if internals.handle == std::ptr::null_mut() { Err(PlatformError::new(unsafe { GetLastError() })) } else { Ok(Fiber(internals)) } } } impl Drop for Fiber { fn drop(&mut self) { if self.0.entry_point != std::ptr::null_mut() { let entry_point = unsafe { Box::from_raw(self.0.entry_point) }; } } }
{ "domain": "codereview.stackexchange", "id": 42872, "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": "rust", "url": null }
rust extern "system" fn fiber_entry_point(parameter: *mut c_void) { unsafe { let mut internals = &mut *(parameter as *mut FiberInternals); let entry_point = Box::from_raw(internals.entry_point); internals.entry_point = std::ptr::null_mut(); entry_point(); } } ``` Answer: FiberInternals::entry_point could simply be an Option<Box<dyn FnOnce()>>. In fiber_entry_point, you could use Option::take() to take ownership of the Box and leave a None in its place. You could then remove your Drop implementation, because the compiler will drop the Box automatically if the value is a Some.
{ "domain": "codereview.stackexchange", "id": 42872, "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": "rust", "url": null }
c#, multithreading, thread-safety, lazy Title: Task manager object for lazy initialization Question: The Problem I am developing a Visual Studio extension for importing code from a server. Because of the way Visual Studio works, multiple threads could try to perform the same operation at the same time. Thus, I wanted a class that would ensure that a) each Task would only be performed when needed and b) each Task would only be performed once. The only exception to b) is if the requesters cancel and then later another request is made in which case if the operation was not finished, it should be retried. Intended functionality: A TaskManager object is created. At some point, TaskManager.Value is called on the object and the Task is set to run. If TaskManger.Value is called multiple times (possibly on other threads), the other executions are set waiting on the Task that is already in progress. If the CancellationToken indicates a cancellation request, only if all the requestors agree should the Task be cancelled. If the TaskManager object is cancelled before completion and later is requested again, the Task should be reinitialized. The Code public class TaskManager<T> { readonly Func<CancellationToken, Task<T>> _initializer; public TaskManager(Func<CancellationToken, Task<T>> initializer) => _initializer = initializer; Task<T>? _task; CancellationTokenSource _cancellationToken = new CancellationTokenSource(); readonly object _initializationLock = new(); readonly ConcurrentBag<CancellationToken> _cancellationTokens = new(); public Task<T> Value (CancellationToken cancellationToken) { if (cancellationToken != default) { if (cancellationToken.IsCancellationRequested) return Task.FromResult<T>(default);
{ "domain": "codereview.stackexchange", "id": 42873, "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#, multithreading, thread-safety, lazy", "url": null }
c#, multithreading, thread-safety, lazy _cancellationTokens.Add(cancellationToken); cancellationToken.Register(() => { if (_task is not { IsCompleted: true } && _cancellationTokens.All(c => c.IsCancellationRequested)) _cancellationToken.Cancel(); }); } if (_task != null && !_cancellationToken.IsCancellationRequested) return _task; lock (_initializationLock) { if (_task != null) return _task; _cancellationToken = new CancellationTokenSource(); _task = _initializer(_cancellationToken.Token); } return _task; } } Example Usage public static class CodepediaApi { private static readonly RestClient client = new RestClient("https://localhost:5001"); // Test Server private static readonly Dictionary<string, TaskManager<SearchResult[]>> responses = new Dictionary<string, TaskManager<SearchResult[]>>(); public static Task<SearchResult[]> Search(string query, CancellationToken cancellationToken) => responses.TryGetOrAdd(query, () => new TaskManager<SearchResult[]>(async c => (await client.GetAsync<SearchResult[]>(new RestRequest("/api/search").AddQueryParameter("q", query), c)) ?? new SearchResult[0] ) ).Value(cancellationToken); } where TryGetOrAdd is defined as follows: public static class Extensions { public static TValue TryGetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> d, TKey key, Func<TValue> toAdd) { if (d.TryGetValue(key, out TValue value)) return value; TValue adding = toAdd(); lock (d) { if (d.TryGetValue(key, out value)) return value; d.Add(key, adding); } return adding; } } Another Example Usage Here is one of my classes: public class CodepediaUtil { public readonly Workspace Workspace; public readonly SnapshotSpan Range;
{ "domain": "codereview.stackexchange", "id": 42873, "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#, multithreading, thread-safety, lazy", "url": null }
c#, multithreading, thread-safety, lazy public readonly TaskManager<(Document document, SemanticModel semanticModel, SyntaxNode outerNode, UnresolvedMethodCallInfo unresolvedInvocation)?> CodeAnalysisInfo; public readonly TaskManager<SearchResult[]> SearchResults; public readonly TaskManager<Dictionary<SearchResult, WikiEntry>> SearchResultsInfo; public async Task<UnresolvedMethodCallInfo?> UnresolvedInvocation (CancellationToken cancellationToken) { var unresolvedInvocationInfo = await CodeAnalysisInfo.Value(cancellationToken); if (unresolvedInvocationInfo is not (_, _, _, UnresolvedMethodCallInfo unresolvedInvocation)) return null; return unresolvedInvocation; } public CodepediaUtil (Workspace workspace, SnapshotSpan range) { Workspace = workspace; Range = range; CodeAnalysisInfo = new TaskManager<(Document document, SemanticModel semanticModel, SyntaxNode outerNode, UnresolvedMethodCallInfo unresolvedInvocation)?> ( async (CancellationToken cancellationToken) => { Document? document = Range.Snapshot.TextBuffer.GetRelatedDocuments().FirstOrDefault(); if (document == null) return null; SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken); if (semanticModel == null) return null; SyntaxNode? outerNode = await CodeAnalyzer.GetOuterNodeAsync(semanticModel, Range.Start, cancellationToken); if (outerNode == null) return null; UnresolvedMethodCallInfo? unresolvedInvocation = outerNode.FindUnresolvedInvocation(semanticModel); if (unresolvedInvocation == null) return null;
{ "domain": "codereview.stackexchange", "id": 42873, "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#, multithreading, thread-safety, lazy", "url": null }
c#, multithreading, thread-safety, lazy return (document, semanticModel, outerNode, unresolvedInvocation); } ); SearchResults = new TaskManager<SearchResult[]> ( async (CancellationToken cancellationToken) => { UnresolvedMethodCallInfo? unresolvedInvocation = await UnresolvedInvocation(cancellationToken); if (unresolvedInvocation == null) return new SearchResult[0]; return await CodepediaApi.Search(unresolvedInvocation.Name, cancellationToken); } ); SearchResultsInfo = new TaskManager<Dictionary<SearchResult, WikiEntry>> ( async (CancellationToken cancellationToken) => { // UnresolvedMethodCallInfo? unresolvedInvocation = await UnresolvedInvocation(cancellationToken); // if (unresolvedInvocation == null) return new Dictionary<SearchResult, WikiEntry>(); // string invocationName = unresolvedInvocation.Name; return await CodepediaApi.InterpretSearchResults(await SearchResults.Value(cancellationToken), cancellationToken); } ); } } This coding pattern should allow other classes to request exactly what they need on a per-need basis. What I want reviewed Is my code useful? (Is there a better way to do this?) Could the performance/elegance of my code improved? (Any comments to make it better would be appreciated.) Did I make a mistake? (Is my code thread-safe? Are there any race conditions or ways it could get stuck?) Answer: Here are my observations: TryGetOrAdd of Extensions Naming a parameter to d is not really a good choice I guess you have performed the TryGetValue twice due to the double-checked lock I would like to warn you with Jon Skeet's words
{ "domain": "codereview.stackexchange", "id": 42873, "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#, multithreading, thread-safety, lazy", "url": null }
c#, multithreading, thread-safety, lazy I would like to warn you with Jon Skeet's words Double-checking locking now works in Java as well as C# (the Java memory model changed and this is one of the effects). However, you have to get it exactly right. If you mess things up even slightly, you may well end up losing the thread safety. Locking on the d is not a good idea since it is provided by the caller (so, it can be considered as public) Related SO topic Pluralsight Best practices Instead of having three return statements you can achieve the same with two private static readonly object syncObject = new(); public static TValue TryGetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> toAdd) { if (dict.TryGetValue(key, out TValue value)) return value; lock (syncObject) { if (!dict.TryGetValue(key, out value)) { value = toAdd(); dict.Add(key, value); } return value; } } TaskManager Is there any particular reason why did you not use target-typed new expression for _cancellationToken? By the way _cancellationToken is a really bad name for this member since it is a CancellationTokenSource not a CancellationToken It is not absolutely clear for me why did you pass the initializer via the ctor and the cancellationToken via the Value method Can't you pass the the two either via ctor or via the method? In case of C# a method usually starts with verb, so GetValue or RetrieveValue might be better If the IsCancellationRequested is true then would it make more sense to call Task.FromCanceled<T>(cancellationToken) instead? Here yet again you can simplify your lock block to have a single return statement lock (_initializationLock) { if (_task is null) { _cancellationTokenSource = new(); _task = _initializer(_cancellationTokenSource.Token); } return _task; } CodepediaApi's Search Here I've only two tiny suggestions
{ "domain": "codereview.stackexchange", "id": 42873, "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#, multithreading, thread-safety, lazy", "url": null }
c#, multithreading, thread-safety, lazy CodepediaApi's Search Here I've only two tiny suggestions c is not the best name for CancellationToken Instead of allocating empty array (new SearchResult[0] rather prefer Array.Empty<SearchResult>() UPDATE #1: Reflect to the first comment The method of creating a static variable called syncObject would mean that only one Dictionary could be accessed at a time by the TryGetOrAdd function. In my code's case that work fine as the only Dictionary is the search dictionary. The issue with using another object as a sync object is that since dict is not locked, the first call to dict.TryGetValue(key, out TValue value) could be accessing the Dictionary while it's an invalid state. So, the only solution would be to surround the whole function with lock (syncObject) which would decrease performance The core problem here is ownership. Since the dictionary is not owned by the method or the class of the method anyone can access it (and potentially modify it) since the lock scope is the method, not the object. Let me demonstrate with a simple example: public static void Main() { var dict = new Dictionary<string, int>(); var lockAcquired = new TaskCompletionSource<object>(); _ = Task.Run(async () => { await lockAcquired.Task; dict.Add("1", 1);}); Add(dict, lockAcquired); } public static void Add(Dictionary<string, int> dict, TaskCompletionSource<object> signal) { lock(dict) { signal.SetResult(null); Thread.Sleep(100); dict.Add("1", 1); } } This code will throw an exception inside the Add method: System.ArgumentException: An item with the same key has already been added. Key: 1 So, as you can see neither mine nor your solution is fine.
{ "domain": "codereview.stackexchange", "id": 42873, "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#, multithreading, thread-safety, lazy", "url": null }
c#, hash-map Title: Adding to a dictionary and skipping duplicate keys Question: What is the cleanest way to use dictionaries and protect against an unhandled ArgumentException if the key already exists in the dictionary? I'd like to say that I can always guarantee uniqueness upstream, but I'm dealing with legacy code and mildly corrupt data from an old bug in the system. I find myself using this pattern frequently but wonder if there is a better way. public void AddToDictionaryContainsKey(Dictionary<int,string> myDictionary, int myKey, string myValue ) { if (!myDictionary.ContainsKey(myKey)) { myDictionary.Add(myKey, myValue); } } Maybe a try/catch block - but this seems less readable. The advantage is that if I ever do decide to log the problem I have a place to do it. public void AddToDictionaryTryCatch(Dictionary<int, string> myDictionary, int myKey, string myValue) { try { myDictionary.Add(myKey, myValue); } catch (ArgumentException e) { // keep on truckin' } } The dictionaries are relatively small (typically < 1000 entries) so I prefer readability over performance. Answer: Generating and handling exceptions is considered to be an expensive operation, so if(! x.ContainsKey()) is better. Yeah, the code example I see in MSDN uses try/catch but that's to illustrate the exception not advocate that as "best practice." Documentation I've read is pretty adamant about not throwing exceptions needlessly. And you don't need try/catch to trap the duplicate key; just an else to the above if.
{ "domain": "codereview.stackexchange", "id": 42874, "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#, hash-map", "url": null }
c, file-system Title: Program that checks if two files match. Is this implementation the most appropriate? Question: I wrote a program that checks if two files (with a different path / name) match or not. The hard and symbolic links between the files are followed to determine it. I know this is not the best implementation, so I would like some suggestions for improvement, possible problems. What you should change? code: #include <unistd.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> void printUsage() { printf("Use: ./leg <name_file1> <name_file2>.\n"); } int createStat(const char* file, struct stat* fileStat) { if(stat(file,fileStat) < 0) { fprintf(stderr,"Error! File %s does not exist.\n",file); return 0; } return 1; } int main(int argc, char **argv) { if(argc < 3) { printf("Insufficient number of parameters.\n"); printUsage(); return -1; } struct stat fileStat1; struct stat fileStat2; if(createStat(argv[1],&fileStat1) == 0) { return -1; } if(createStat(argv[2],&fileStat2) == 0) { return -1; } if(S_ISREG(fileStat1.st_mode) && S_ISREG(fileStat2.st_mode)){ if((fileStat1.st_dev == fileStat2.st_dev) && (fileStat1.st_ino == fileStat2.st_ino)){ printf("Files'%s' and '%s' coincide.\n", argv[1], argv[2]); } else printf("Files '%s' and '%s' do not match.\n", argv[1], argv[2]); } else fprintf(stderr,"'%s' and '%s' there are no files.\n",argv[1],argv[2]); return 0; } Answer: if(createStat(argv[1],&fileStat1) == 0) { return -1; } It's a good idea to output a diagnostic there: if(createStat(argv[1], &fileStat1) == 0) { perror(argv[1]); return EXIT_FAILURE; } The S_ISREG test seems at best unnecessary, and at worst harmful - what if the files you want to compare are device files? Or directories? Both of those seem valid uses.
{ "domain": "codereview.stackexchange", "id": 42875, "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, file-system", "url": null }
c, file-system Please be consistent with the use of braces. Some conditionals have them only for the if block and not the else. Code is easier to read correctly if you're consistent; I recommend using braces even for single statements. The program would be more useful if it returned 0 only if the pathnames refer to the same file, so that scripts can easily use it (although test -ef already exists for that purpose, so perhaps unnecessary). if(argc < 3) { printf("Insufficient number of parameters.\n"); printUsage(); return -1; } We should probably at least warn if too many arguments are supplied, and the error message ought to go to the standard error stream. if (argc != 3) { fputs("Incorrect number of arguments.\n", stderr); printUsage(stderr); return EXIT_FAILURE; } if(stat(file,fileStat) < 0) { fprintf(stderr,"Error! File %s does not exist.\n",file); Misleading error message - the file might exist, but have insufficient permissions for us to access. Or any of the other reasons listed in the man page (though mostly they prevent the file existing).
{ "domain": "codereview.stackexchange", "id": 42875, "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, file-system", "url": null }
html, web-scraping, xpath, xslt Title: Extracting information from HTML with XSLT 3.0 when data is grouped visually as siblings in a td separated by blank lines
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt Question: I have a work-in-progress where I'm using XSLT 3 to extract information from some preprocessed archaic HTML. I'd like to produce JSON showing the relationships between the various entities for further loading, replacing part of our existing pipeline which uses some frankly nightmarish Python. We've used this approach to good effect elsewhere, but I'm encountering some unique challenges with this input. One of the challenges here is that the attorneys for one party are all in one td consisting of b, text() and i elements, with the individual attorneys grouped by blank lines. I've used xsl:for-each-group to handle this, which seems to be the standard approach, but is interfering with other of my challenges. Specifically, there's some attorneys whose address is listed as "(See above for address)", which needs to be resolved correctly before loading. My first thought was to use xsl:key or xsl:accumulator to create a map of valid addresses with the name as the key, but I couldn't figure out how to express "the address" coherently in Xpath when starting from the b tag that contains the attorney name, nor how to effectively use xsl:accumulator in conjunction with xsl:for-each-group. My eventual solution was to simply create a map in a variable, but this feels messy and redundant. Is there a better way?
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt The other style question I'd like to ask is about the use of mode. Using an unbounded xsl:apply-templates introduced a significant peformance hit, but I wanted to keep the approach of "This kind of table represents all the parties and should produce a map-entry with an array, these kinds of rows represent a party and should produce a map-entry in that array," etc. I settled on using a apply-templates elements with a select to specify which parts of the document to process while using mode with more generic template matches to let me group chains of templates to fire off for contained elements. This arrangement was more performant, but I'm wondering if there's a more accepted approach for this situation where a large input needs only specific pieces processed. The transformation is being run in saxon-js with the '-ns:##html5' option enabled to avoid constantly restating the html namespace in Xpaths. Input (lightly edited to remove a tremendous number of case history table rows): <html:html xmlns:html="http://www.w3.org/1999/xhtml"><html:head><html:title>CM/ECF LIVE - U.S. District Court:txed - Docket Report</html:title></html:head><html:body bgcolor="66FFFF" text="000000">
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:table align="right" width="100%" border="0" cellspacing="5"> <html:tbody><html:tr><html:td align="right">CLOSED, FRC, JURY, MEDIATION</html:td></html:tr> </html:tbody></html:table><html:br/> <html:h3 align="center">&#160; U.S. District Court [LIVE]<html:br/> Eastern District of TEXAS LIVE (Texarkana)<html:br/> CIVIL DOCKET FOR CASE #: 5:01-cv-00302-DF</html:h3> <html:table width="100%" border="0" cellspacing="5"><html:tbody><html:tr> <html:td valign="top" width="60%"><html:br/>Broadcom Corporation v. Intel Corporation<html:br/> Assigned to: Judge David Folsom<html:br/> Demand: $0<html:br/> Cause: 35:145 Patent Infringement</html:td> <html:td valign="top" width="40%"><html:br/>Date Filed: 11/19/2001<html:br/> Nature of Suit: 830 Patent<html:br/> Jurisdiction: Federal Question</html:td> </html:tr></html:tbody></html:table> <html:table width="100%" border="0" cellspacing="5"> <html:tbody><html:tr> <html:td><html:b><html:u>Mediator</html:u></html:b></html:td> </html:tr> <html:tr> <html:td valign="top" width="40%"> <html:b>Robert M Parker</html:b> </html:td> <html:td valign="top" width="20%" align="right">represented&#160;by</html:td><html:td valign="top" width="40%"><html:b>Robert M Parker</html:b> <html:br/>Parker Clayton <html:br/>100 E Ferguson <html:br/>Suite 1114 <html:br/>Tyler, TX 75702 <html:br/>903-533-9288 <html:br/>Email: rmparker@pbatyler.com <html:br/>PRO SE</html:td></html:tr><html:tr><html:td/></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr> <html:td><html:b><html:u>Plaintiff</html:u></html:b></html:td> </html:tr> <html:tr> <html:td valign="top" width="40%"> <html:b>Broadcom Corporation</html:b> </html:td> <html:td valign="top" width="20%" align="right">represented&#160;by</html:td><html:td valign="top" width="40%"><html:b>Nicholas H Patton</html:b> <html:br/>Patton &amp; Tidwell <html:br/>4605 Texas Blvd <html:br/>PO Box 5398 <html:br/>Texarkana, TX 75505-5398 <html:br/>903/792-7080 <html:br/>Fax: 19037928233 <html:br/>Email: nickpatton@texarkanalaw.com <html:br/><html:i>LEAD ATTORNEY</html:i> <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Alda C Leu</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16505655100<html:br/><html:br/> <html:b>Alice Catherine Garber</html:b> <html:br/>Kirkland &amp; Ellis LLP - California <html:br/>555 California St <html:br/>Floor 24 <html:br/>San Francisco, CA 94104 <html:br/>415/439-1452 <html:br/>Fax: 415/439-1352 <html:br/>Email: agarber@kirkland.com<html:br/><html:br/> <html:b>Andrew S Dallmann</html:b> <html:br/>McDermott Will &amp; Emery <html:br/>3150 Porter Drive <html:br/>Palo Alto, Ca 94304 <html:br/>650/813-500 <html:br/>Fax: 16508135100 <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Behrooz Shariati</html:b> <html:br/>McDermott Will Emery <html:br/>3150 Porter Drive <html:br/>Palo Alto, CA 94304-1212 <html:br/>650/813-5000 <html:br/>Fax: 16508135100 <html:br/>Email: bshariati@mwe.com<html:br/><html:br/> <html:b>Bradford J Goodson</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16505655100<html:br/><html:br/> <html:b>Christopher D Bright</html:b>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:br/>Fax: 16505655100<html:br/><html:br/> <html:b>Christopher D Bright</html:b> <html:br/>McDermott Will &amp; Emergy <html:br/>18191 Von Karman Ave <html:br/>Suite 500 <html:br/>Irvine, Ca 92612 <html:br/>949-851-0633 <html:br/>Fax: 19498519348 <html:br/>Email: cbright@mwe.com<html:br/><html:br/> <html:b>David A Caine</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16505655100 <html:br/>Email: dcaine@wsgr.com<html:br/><html:br/> <html:b>David L Fligor</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 650-493-9300<html:br/><html:br/> <html:b>David C Wang</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 650-493-9300<html:br/><html:br/> <html:b>Irwin R Gross</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 650-493-9300<html:br/><html:br/> <html:b>J Thad Heartfield</html:b> <html:br/>Law Offices of J. Thad Heartfield <html:br/>2195 Dowlen Rd <html:br/>Beaumont, TX 77706 <html:br/>409/866-3318 <html:br/>Fax: 14098665789 <html:br/>Email: thad@jth-law.com <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>James C Yoon</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16504936811 <html:br/>Email: jyoon@wsgr.com<html:br/><html:br/> <html:b>Jennifer L Yokoyama</html:b> <html:br/>McDermott Will &amp; Emergy <html:br/>18191 Von Karman Ave <html:br/>Suite 500 <html:br/>Irvine, Ca 92612 <html:br/>949/851-0633 <html:br/>Fax: 949/851-9348 <html:br/>Email: jyokoyama@mwe.com<html:br/><html:br/>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:br/>Fax: 949/851-9348 <html:br/>Email: jyokoyama@mwe.com<html:br/><html:br/> <html:b>Julie M Holloway</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16504936811 <html:br/>Email: jholloway@wsgr.com<html:br/><html:br/> <html:b>Keaton S Parekh</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Rd <html:br/>Palo Alto, CA 94304-1050 <html:br/>650/493-9300 <html:br/>Fax: 650/493-9300<html:br/><html:br/> <html:b>Matthew R Reed</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650/565-3990 <html:br/>Fax: 650/493-6811 <html:br/>Email: mreed@wsgr.com<html:br/><html:br/> <html:b>Matthew F Weil</html:b> <html:br/>McDermott Will &amp; Emergy <html:br/>18191 Von Karman Ave <html:br/>Suite 500 <html:br/>Irvine, Ca 92612 <html:br/>949-851-0633 <html:br/>Fax: 19498519348<html:br/><html:br/> <html:b>Michael A Ladra</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-320-4869 <html:br/>Fax: 16504936811 <html:br/>Email: mladra@wsgr.com<html:br/><html:br/> <html:b>Michael R O'Neill</html:b> <html:br/>McDermott Will &amp; Emery - Irvine <html:br/>18191 Von Karman Avenue <html:br/>Suite 400 <html:br/>Irvine, CA 92612-7108 <html:br/>949/851-0633 <html:br/>Fax: 949/851-9348 <html:br/>Email: moneill@mwe.com<html:br/><html:br/> <html:b>Robert J Blanch</html:b> <html:br/>McDermott Will &amp; Emery <html:br/>3150 Porter Drive <html:br/>Palo Alto, Ca 94304 <html:br/>650/813-500 <html:br/>Fax: 16508135100 <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Ron E Shulman</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-496-4083 <html:br/>Email: rshulman@wsgr.com<html:br/><html:br/>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:br/>650-496-4083 <html:br/>Email: rshulman@wsgr.com<html:br/><html:br/> <html:b>Stephen J Ferenchick</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16505655100<html:br/><html:br/> <html:b>Theresa E Norton</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 16505655100<html:br/><html:br/> <html:b>Tung-On Kong</html:b> <html:br/>Wilson Sonsini Goodrich &amp; Rosati <html:br/>650 Page Mill Road <html:br/>Palo Alto, CA 94304-1050 <html:br/>650-493-9300 <html:br/>Fax: 650-493-9300<html:br/><html:br/> <html:b>Vera M Elson</html:b> <html:br/>McDermott Will Emery <html:br/>3150 Porter Drive <html:br/>Palo Alto, CA 94304-1212 <html:br/>650/813-5000 <html:br/>Fax: 650/813-5000</html:td></html:tr><html:tr><html:td/></html:tr> <html:tr><html:td valign="top"><html:br/>V.<html:br/></html:td></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr> <html:td><html:b><html:u>Defendant</html:u></html:b></html:td> </html:tr> <html:tr> <html:td valign="top" width="40%"> <html:b>Intel Corporation</html:b> <html:br/><html:i>a Delaware Corporation</html:i> </html:td> <html:td valign="top" width="20%" align="right">represented&#160;by</html:td><html:td valign="top" width="40%"><html:b>Damon Michael Young</html:b> <html:br/>Young Pickett &amp; Lee <html:br/>4122 Texas Blvd <html:br/>PO Box 1897 <html:br/>Texarkana, TX 75504-1897 <html:br/>903/794-1303 <html:br/>Fax: 19037925098 <html:br/>Email: dyoung@youngpickettlaw.com <html:br/><html:i>TERMINATED: 01/28/2002</html:i> <html:br/><html:i>LEAD ATTORNEY</html:i> <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Andrew D Skale</html:b> <html:br/>Fish &amp; Richardson - San Diego <html:br/>12390 El Camino Real <html:br/>San Diego, CA 92130 <html:br/>858/678-5070 <html:br/>Fax: 858/678-5099 <html:br/>Email: skale@fr.com<html:br/><html:br/> <html:b>Daniel T Pascucci</html:b> <html:br/>Fish &amp; Richardson <html:br/>4350 La Jolla Village Drive <html:br/>Suite 500 <html:br/>San Diego, Ca 92122 <html:br/>858-678-5070 <html:br/>Fax: 18586785099<html:br/><html:br/> <html:b>David S Shuman</html:b> <html:br/>Fish &amp; Richardson <html:br/>12390 El Camino Real <html:br/>San Diego, CA 92130 <html:br/>858-678-5070 <html:br/>Fax: 18586785099 <html:br/>Email: shuman@fr.com<html:br/><html:br/> <html:b>Elton Joe Kendall</html:b> <html:br/>Provost Umphrey - Dallas <html:br/>3232 McKinney Ave <html:br/>Suite 700 <html:br/>Dallas, TX 75204 <html:br/>214/744-3000 <html:br/>Fax: 12147443015 <html:br/>Email: jkendall@provostumphrey.com<html:br/><html:br/> <html:b>Garret Wesley Chambers</html:b> <html:br/>McKool Smith - Dallas <html:br/>300 Crescent Court <html:br/>Suite 1500 <html:br/>Dallas, TX 75201 <html:br/>214/978-4000 <html:br/>Fax: 12149784044
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:br/>Suite 1500 <html:br/>Dallas, TX 75201 <html:br/>214/978-4000 <html:br/>Fax: 12149784044 <html:br/>Email: gchambers@mckoolsmith.com<html:br/><html:br/> <html:b>Janet Craycroft</html:b> <html:br/>Intel Corporation <html:br/>2200 Mission College Blvd SC4-202 <html:br/>Santa Clara, Ca 95052 <html:br/>408/765-4493 <html:br/>Fax: 14087655175<html:br/><html:br/> <html:b>John A Dragseth</html:b> <html:br/>Fish &amp; Richardson <html:br/>3300 Dain Rauscher Plaza <html:br/>60 South Sixth Street <html:br/>Minneapolis, Mn 55402 <html:br/>612/335-5070 <html:br/>Fax: 16122889696 <html:br/>Email: dragseth@fr.com<html:br/><html:br/> <html:b>John E Gartman</html:b> <html:br/>Fish &amp; Richardson - San Diego <html:br/>12390 El Camino Real <html:br/>San Diego, CA 92130 <html:br/>858-678-5070 <html:br/>Fax: 18586785099 <html:br/>Email: gartman@fr.com<html:br/><html:br/> <html:b>John W Thornburgh</html:b> <html:br/>Fish &amp; Richardson - San Diego <html:br/>12390 El Camino Real <html:br/>San Diego, CA 92130 <html:br/>858/678-5070 <html:br/>Fax: 858/678-5099 <html:br/>Email: thornburgh@fr.com<html:br/><html:br/> <html:b>Justin M Barnes</html:b> <html:br/>Fish &amp; Richardson <html:br/>4350 La Jolla Village Drive <html:br/>Suite 500 <html:br/>San Diego, Ca 92122 <html:br/>858-678-5070 <html:br/>Fax: 18586785099<html:br/><html:br/> <html:b>Lance Lee</html:b> <html:br/>Young Pickett &amp; Lee <html:br/>4122 Texas Blvd <html:br/>PO Box 1897 <html:br/>Texarkana, TX 75504-1897 <html:br/>903/794-1303 <html:br/>Fax: 19037945098 <html:br/>Email: wlancelee@aol.com <html:br/><html:i>TERMINATED: 01/28/2002</html:i><html:br/><html:br/> <html:b>Lloyd A Farnham</html:b> <html:br/>Keker &amp; Van Nest <html:br/>710 Sansome St <html:br/>San Francisco, CA 94111 <html:br/>415/391-5400 <html:br/>Fax: 14153977188<html:br/><html:br/> <html:b>Michael Brett Johnson</html:b> <html:br/>Fish &amp; Richardson - Dallas <html:br/>1717 Main St. <html:br/>Suite 5000 <html:br/>Dallas, TX 75201
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:br/>1717 Main St. <html:br/>Suite 5000 <html:br/>Dallas, TX 75201 <html:br/>(214)747-5070 <html:br/>Fax: 12147472091 <html:br/>Email: mbjohnson@fr.com<html:br/><html:br/> <html:b>Robert A Van Nest</html:b> <html:br/>Keker &amp; Van Nest <html:br/>710 Sansome St <html:br/>San Francisco, CA 94111 <html:br/>415/391-5400 <html:br/>Fax: 14153977188 <html:br/>Email: rvn@kvn.com<html:br/><html:br/> <html:b>Samuel Franklin Baxter</html:b> <html:br/>Attorney at Law <html:br/>P O Box O <html:br/>Marshall, TX 75671 <html:br/>903/927-2111 <html:br/>Fax: 19039272622 <html:br/>Email: sbaxter@mckoolsmith.com <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Seth M Sproul</html:b> <html:br/>Fish &amp; Richardson - San Diego <html:br/>12390 El Camino Real <html:br/>San Diego, CA 92130 <html:br/>858-678-4343 <html:br/>Email: sproul@fr.com<html:br/><html:br/> <html:b>Stuart L Gasner</html:b> <html:br/>Keker &amp; Van Nest <html:br/>710 Sansome St <html:br/>San Francisco, CA 94111 <html:br/>415/391-5400 <html:br/>Fax: 14153977188<html:br/><html:br/> <html:b>Thomas M Melsheimer</html:b> <html:br/>Fish &amp; Richardson - Dallas <html:br/>1717 Main St <html:br/>5000 Bank One Center <html:br/>Dallas, TX 75201 <html:br/>214/747-5070 <html:br/>Fax: 12147472091 <html:br/>Email: melsheimer@fr.com <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i></html:td></html:tr><html:tr><html:td/></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr> <html:td><html:b><html:u>Amicus</html:u></html:b></html:td> </html:tr> <html:tr> <html:td valign="top" width="40%"> <html:b>Gail Peterson</html:b> <html:br/><html:i>Technical Advisor on case</html:i> </html:td> <html:td valign="top" width="20%" align="right">represented&#160;by</html:td><html:td valign="top" width="40%"><html:b>Gail Peterson</html:b> <html:br/>Cox and Smith <html:br/>112 E. Pecan Street <html:br/>Suite 1800 <html:br/>San Antonio, TX 78205-1521 <html:br/>PRO SE</html:td></html:tr><html:tr><html:td/></html:tr> <html:tr> <html:td><html:b><html:u>Counter Claimant</html:u></html:b></html:td> </html:tr> <html:tr> <html:td valign="top" width="40%"> <html:b>Intel Corporation</html:b> </html:td> <html:td valign="top" width="20%" align="right">represented&#160;by</html:td><html:td valign="top" width="40%"><html:b>Damon Michael Young</html:b> <html:br/>(See above for address) <html:br/><html:i>TERMINATED: 01/28/2002</html:i> <html:br/><html:i>LEAD ATTORNEY</html:i> <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>John W Thornburgh</html:b> <html:br/>(See above for address)<html:br/><html:br/> <html:b>Lance Lee</html:b> <html:br/>(See above for address) <html:br/><html:i>TERMINATED: 01/28/2002</html:i><html:br/><html:br/> <html:b>Michael Brett Johnson</html:b> <html:br/>(See above for address)<html:br/><html:br/> <html:b>Thomas M Melsheimer</html:b> <html:br/>(See above for address) <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i></html:td></html:tr><html:tr><html:td/></html:tr> <html:tr><html:td valign="top"><html:br/>V.<html:br/></html:td></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr> <html:td><html:b><html:u>Counter Defendant</html:u></html:b></html:td> </html:tr> <html:tr> <html:td valign="top" width="40%"> <html:b>Broadcom Corporation</html:b> </html:td> <html:td valign="top" width="20%" align="right">represented&#160;by</html:td><html:td valign="top" width="40%"><html:b>Nicholas H Patton</html:b> <html:br/>(See above for address) <html:br/><html:i>LEAD ATTORNEY</html:i> <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>J Thad Heartfield</html:b> <html:br/>(See above for address) <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Andrew S Dallmann</html:b> <html:br/>(See above for address) <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i><html:br/><html:br/> <html:b>Robert J Blanch</html:b> <html:br/>(See above for address) <html:br/><html:i>ATTORNEY TO BE NOTICED</html:i></html:td></html:tr><html:tr><html:td/></html:tr> </html:tbody></html:table> <html:br/><html:table align="center" width="99%" border="1" rules="all" cellpadding="5" cellspacing="0"><html:tbody><html:tr><html:td width="94" nowrap=""><html:h4>Date Filed</html:h4></html:td> <html:td align="center" width="60"><html:h4>#</html:h4></html:td><html:td align="center"><html:h4>Docket Text</html:h4></html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">11/19/2001</html:td><html:td width="60" valign="top" align="right"><html:a href="/cgi-bin/show_case_doc?1,52660,,,,,2">1</html:a></html:td><html:td valign="top">Original Complaint with Jury Demand filed. Cause: 35:145 Patent Infringement (92 pages with exhibits) (sm) Modified on 11/20/2001 (Entered: 11/20/2001)</html:td></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr><html:td width="94" nowrap="" valign="top">11/19/2001</html:td><html:td width="60" valign="top" align="right">&#160;</html:td><html:td valign="top"> Filing Fee Paid; FILING FEE $ 150 RECEIPT # 96539 (sm) (Entered: 11/20/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">11/19/2001</html:td><html:td width="60" valign="top" align="right">&#160;</html:td><html:td valign="top">Summons(es) issued for Intel Corporation (sm) (Entered: 11/20/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">11/20/2001</html:td><html:td width="60" valign="top" align="right">2</html:td><html:td valign="top">Form mailed to Commissioner of Patents and Trademarks. (sm) (Entered: 11/20/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">11/20/2001</html:td><html:td width="60" valign="top" align="right">&#160;</html:td><html:td valign="top">Magistrate consent forms mailed to Broadcom Corporation . (sm) (Entered: 11/20/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">12/10/2001</html:td><html:td width="60" valign="top" align="right">3</html:td><html:td valign="top"> Notice of CORPORATE disclosure by Broadcom Corporation (sm) (Entered: 12/10/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">12/14/2001</html:td><html:td width="60" valign="top" align="right"><html:a href="/cgi-bin/show_case_doc?4,52660,,,,,8">4</html:a></html:td><html:td valign="top">First Amended complaint by Broadcom Corporation , amending [1-1] complaint (exhibits not scanned) (sm) Modified on 12/18/2001 (Entered: 12/14/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">12/14/2001</html:td><html:td width="60" valign="top" align="right">&#160;</html:td><html:td valign="top">Summons(es) reissued for Intel Corporation along with amended complaint filed (sm) (Entered: 12/14/2001)</html:td></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr><html:td width="94" nowrap="" valign="top">12/18/2001</html:td><html:td width="60" valign="top" align="right">5</html:td><html:td valign="top">Return of service executed as to Intel Corporation via personal service on 12/14/01 Answer due on 1/3/02 for Intel Corporation (sm) (Entered: 12/18/2001)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/03/2002</html:td><html:td width="60" valign="top" align="right"><html:a href="/cgi-bin/show_case_doc?6,52660,,,,,11">6</html:a></html:td><html:td valign="top">Answer to first amended complaint by Intel Corporation (sm) (Entered: 01/03/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/03/2002</html:td><html:td width="60" valign="top" align="right">6</html:td><html:td valign="top">Counterclaim by Intel Corporation against Broadcom Corporation (sm) (Entered: 01/24/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/03/2002</html:td><html:td width="60" valign="top" align="right">7</html:td><html:td valign="top">MOTION by Intel Corporation to transfer case to Northern Dist of California (sm) (Entered: 01/24/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/07/2002</html:td><html:td width="60" valign="top" align="right"><html:a href="/cgi-bin/show_case_doc?8,52660,,,,,12">8</html:a></html:td><html:td valign="top">ORDER Setting Civil Action for Rule 16 Mgt Cnf, set management conference for 10:15 2/11/02 before Judge David Folsom ( signed by Judge David Folsom ) cc: attys of record 1/8/02 (sm) (Entered: 01/08/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/15/2002</html:td><html:td width="60" valign="top" align="right">9</html:td><html:td valign="top">Notice of Corporate Disclosure by Intel Corporation (sm) (Entered: 01/15/2002)</html:td></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <html:tr><html:td width="94" nowrap="" valign="top">01/15/2002</html:td><html:td width="60" valign="top" align="right">10</html:td><html:td valign="top">Motion by Intel Corporation for John Thornburgh to appear pro hac vice (sm) (Entered: 01/15/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/15/2002</html:td><html:td width="60" valign="top" align="right">&#160;</html:td><html:td valign="top">PHV Filing Fee paid by atty John Thornburgh; PHV FILING FEE $ 25 RECEIPT # 96655 (sm) (Entered: 01/15/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/16/2002</html:td><html:td width="60" valign="top" align="right"><html:a href="/cgi-bin/show_case_doc?11,52660,,,,,16">11</html:a></html:td><html:td valign="top">ORDER granting [10-1] motion for John Thornburgh to appear pro hac vice ( signed by Judge David Folsom ) cc: attys of record 1/16/02 (sm) (Entered: 01/16/2002)</html:td></html:tr> <html:tr><html:td width="94" nowrap="" valign="top">01/18/2002</html:td><html:td width="60" valign="top" align="right"><html:a href="/cgi-bin/show_case_doc?12,52660,,,,,18">12</html:a></html:td><html:td valign="top">Response by Broadcom Corporation to [7-1] motion to transfer case to the Northern Dist of Californiao (Exh A-N not scanned due to voluminus) (sm) (Entered: 01/22/2002)</html:td></html:tr>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt </html:tbody></html:table><html:br/><html:br/><html:hr/><html:center><html:table border="1" bgcolor="WHITE" width="400"><html:tbody><html:tr><html:th colspan="4"><html:font size="+1" color="DARKRED">PACER Service Center</html:font></html:th></html:tr><html:tr><html:th colspan="4"><html:font color="DARKBLUE">Transaction Receipt</html:font></html:th></html:tr><html:tr/><html:tr/><html:tr><html:td colspan="4" align="CENTER"><html:font size="-1" color="DARKBLUE">01/16/2007 19:34:11</html:font></html:td></html:tr><html:tr><html:th align="LEFT"><html:font size="-1" color="DARKBLUE">PACER Login:</html:font></html:th><html:td align="LEFT"><html:font size="-1" color="DARKBLUE">ss5619</html:font></html:td><html:th align="LEFT"><html:font size="-1" color="DARKBLUE">Client Code:</html:font></html:th><html:td align="LEFT"><html:font size="-1" color="DARKBLUE">dev </html:font></html:td></html:tr><html:tr><html:th align="LEFT"><html:font size="-1" color="DARKBLUE">Description:</html:font></html:th><html:td align="LEFT"><html:font size="-1" color="DARKBLUE">Docket Report</html:font></html:td><html:th align="LEFT"><html:font size="-1" color="DARKBLUE">Search Criteria:</html:font></html:th><html:td align="LEFT"><html:font size="-1" color="DARKBLUE">5:01-cv-00302-DF </html:font></html:td></html:tr><html:tr><html:th align="LEFT"><html:font size="-1" color="DARKBLUE">Billable Pages:</html:font></html:th><html:td align="LEFT"><html:font size="-1" color="DARKBLUE">27</html:font></html:td><html:th align="LEFT"><html:font size="-1" color="DARKBLUE">Cost:</html:font></html:th><html:td align="LEFT"><html:font size="-1" color="DARKBLUE"> 2.16</html:font></html:td></html:tr></html:tbody></html:table></html:center><html:hr/></html:body></html:html> Stylesheet: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:map="http://www.w3.org/2005/xpath-functions/map" version="3.0">
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <xsl:output method="json"/> <xsl:strip-space elements="div ul p"/> <xsl:key name="tables" match="table" use="@width"/> <xsl:variable name="atty_addr" as="map(*)"> <xsl:map> <xsl:for-each-group select="key('tables', '100%')/tbody/tr[contains(td[2], 'represented')]/td[3]/text()" group-by="./preceding-sibling::b[1] => generate-id()"> <xsl:variable name="name" select="./preceding-sibling::b[1] => normalize-space()"/> <xsl:variable name="address" select="current-group()[normalize-space(.)] => string-join()"/> <xsl:if test="not(contains($address, 'See above for address'))"> <xsl:map-entry key="$name" select="$address"/> </xsl:if> </xsl:for-each-group> </xsl:map> </xsl:variable> <!-- Overrides default template for text--> <xsl:template match="text()"/> <xsl:template match="/"> <xsl:map> <xsl:apply-templates mode="flags" select="key('tables', '100%')[1]//tr/td[@align='right']"/> <xsl:apply-templates mode="parties" select="key('tables', '100%')[./tbody/tr/td/b/u][1]"/> </xsl:map> </xsl:template> <!-- Flags--> <xsl:template match="td" mode="flags"> <xsl:map-entry key="'flags'" select="array{normalize-space(.) => tokenize(', ')}"/> </xsl:template>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt <!-- Parties--> <xsl:template match="table" mode="parties"> <xsl:map-entry key="'party_types'"> <xsl:variable name="party_types" as="map(*)*"> <xsl:for-each-group select="./tbody/tr[not(./td[1]/b/u)][./td[1]/b]" group-by="./preceding-sibling::tr[td[1]/b/u][1] => normalize-space()"> <xsl:map-entry key="current-grouping-key()"> <xsl:variable name="parties" as="map(*)*"> <xsl:apply-templates mode="parties" select="current-group()"/> </xsl:variable> <xsl:sequence select="array{$parties}"/> </xsl:map-entry> </xsl:for-each-group> </xsl:variable> <xsl:sequence select="array{$party_types}"/> </xsl:map-entry> </xsl:template> <xsl:template match="tr" mode="parties"> <xsl:map> <xsl:map-entry key="'name'" select="./td[1]/b => string()"/> <xsl:map-entry key="'represented by'"> <xsl:variable name="represented_by" as="map(*)*"> <xsl:apply-templates mode="parties" select="./td[3]"/> </xsl:variable> <xsl:sequence select="array{$represented_by}"/> </xsl:map-entry> </xsl:map> </xsl:template> <xsl:template match="td[b]" mode="parties"> <xsl:for-each-group select="text() | i" group-by="./preceding-sibling::b[1] => normalize-space()"> <xsl:map> <xsl:map-entry key="'name'" select="current-grouping-key()"/> <xsl:map-entry key="'address'" select="map:get($atty_addr, current-grouping-key())"/> <xsl:map-entry key="'meta'" select="array{current-group()[self::i]/string()}"/> </xsl:map> </xsl:for-each-group> </xsl:template> </xsl:stylesheet>
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt Desired output: { "party_types": { "Mediator": [ { "represented by": [ { "address": "Parker Clayton\n100 E Ferguson\nSuite 1114\nTyler, TX 75702\n903-533-9288\nEmail: rmparker@pbatyler.com\nPRO SE", "name": "Robert M Parker", "meta": [] }], "name": "Robert M Parker" }], "Counter Claimant": [ { "represented by": [ { "address": "Young Pickett & Lee\n4122 Texas Blvd\nPO Box 1897\nTexarkana, TX 75504-1897\n903/794-1303\nFax: 19037925098\nEmail: dyoung@youngpickettlaw.com\n", "name": "Damon Michael Young", "meta": ["TERMINATED: 01/28/2002", "LEAD ATTORNEY", "ATTORNEY TO BE NOTICED" ] }, { "address": "Fish & Richardson - San Diego\n12390 El Camino Real\nSan Diego, CA 92130\n858/678-5070\nFax: 858/678-5099\nEmail: thornburgh@fr.com", "name": "John W Thornburgh", "meta": [] }, { "address": "Young Pickett & Lee\n4122 Texas Blvd\nPO Box 1897\nTexarkana, TX 75504-1897\n903/794-1303\nFax: 19037945098\nEmail: wlancelee@aol.com\n", "name": "Lance Lee", "meta": ["TERMINATED: 01/28/2002"] }, { "address": "Fish & Richardson - Dallas\n1717 Main St.\nSuite 5000\nDallas, TX 75201\n(214)747-5070\nFax: 12147472091\nEmail: mbjohnson@fr.com", "name": "Michael Brett Johnson", "meta": [] }, { "address": "Fish & Richardson - Dallas\n1717 Main St\n5000 Bank One Center\nDallas, TX 75201\n214/747-5070\nFax: 12147472091\nEmail: melsheimer@fr.com\n", "name": "Thomas M Melsheimer", "meta": ["ATTORNEY TO BE NOTICED"] }],
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt "meta": ["ATTORNEY TO BE NOTICED"] }], "name": "Intel Corporation" }], "Plaintiff": [ { "represented by": [ { "address": "Patton & Tidwell\n4605 Texas Blvd\nPO Box 5398\nTexarkana, TX 75505-5398\n903/792-7080\nFax: 19037928233\nEmail: nickpatton@texarkanalaw.com\n", "name": "Nicholas H Patton", "meta": ["LEAD ATTORNEY", "ATTORNEY TO BE NOTICED"] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16505655100", "name": "Alda C Leu", "meta": [] }, { "address": "Kirkland & Ellis LLP - California\n555 California St\nFloor 24\nSan Francisco, CA 94104\n415/439-1452\nFax: 415/439-1352\nEmail: agarber@kirkland.com", "name": "Alice Catherine Garber", "meta": [] }, { "address": "McDermott Will & Emery\n3150 Porter Drive\nPalo Alto, Ca 94304\n650/813-500\nFax: 16508135100\n", "name": "Andrew S Dallmann", "meta": ["ATTORNEY TO BE NOTICED"] }, { "address": "McDermott Will Emery\n3150 Porter Drive\nPalo Alto, CA 94304-1212\n650/813-5000\nFax: 16508135100\nEmail: bshariati@mwe.com", "name": "Behrooz Shariati", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16505655100", "name": "Bradford J Goodson", "meta": [] }, { "address": "McDermott Will & Emergy\n18191 Von Karman Ave\nSuite 500\nIrvine, Ca 92612\n949-851-0633\nFax: 19498519348\nEmail: cbright@mwe.com", "name": "Christopher D Bright",
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt "name": "Christopher D Bright", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16505655100\nEmail: dcaine@wsgr.com", "name": "David A Caine", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 650-493-9300", "name": "David L Fligor", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 650-493-9300", "name": "David C Wang", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 650-493-9300", "name": "Irwin R Gross", "meta": [] }, { "address": "Law Offices of J. Thad Heartfield\n2195 Dowlen Rd\nBeaumont, TX 77706\n409/866-3318\nFax: 14098665789\nEmail: thad@jth-law.com\n", "name": "J Thad Heartfield", "meta": ["ATTORNEY TO BE NOTICED"] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16504936811\nEmail: jyoon@wsgr.com", "name": "James C Yoon", "meta": [] }, { "address": "McDermott Will & Emergy\n18191 Von Karman Ave\nSuite 500\nIrvine, Ca 92612\n949/851-0633\nFax: 949/851-9348\nEmail: jyokoyama@mwe.com", "name": "Jennifer L Yokoyama", "meta": [] }, {
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }
html, web-scraping, xpath, xslt "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16504936811\nEmail: jholloway@wsgr.com", "name": "Julie M Holloway", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Rd\nPalo Alto, CA 94304-1050\n650/493-9300\nFax: 650/493-9300", "name": "Keaton S Parekh", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650/565-3990\nFax: 650/493-6811\nEmail: mreed@wsgr.com", "name": "Matthew R Reed", "meta": [] }, { "address": "McDermott Will & Emergy\n18191 Von Karman Ave\nSuite 500\nIrvine, Ca 92612\n949-851-0633\nFax: 19498519348", "name": "Matthew F Weil", "meta": [] }, { "address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-320-4869\nFax: 16504936811\nEmail: mladra@wsgr.com", "name": "Michael A Ladra", "meta": [] }, { "address": "McDermott Will & Emery - Irvine\n18191 Von Karman Avenue\nSuite 400\nIrvine, CA 92612-7108\n949/851-0633\nFax: 949/851-9348\nEmail: moneill@mwe.com", "name": "Michael R O'Neill", "meta": [] }, { "address": "McDermott Will & Emery\n3150 Porter Drive\nPalo Alto, Ca 94304\n650/813-500\nFax: 16508135100\n", "name": "Robert J Blanch", "meta": ["ATTORNEY TO BE NOTICED"] }, {
{ "domain": "codereview.stackexchange", "id": 42876, "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": "html, web-scraping, xpath, xslt", "url": null }