text
stringlengths
1
2.12k
source
dict
json, web-scraping, xpath, xslt <html:div id="returned-detail-content"> <html:p><html:span class="dateTitle">Complaint Filed</html:span> <html:span class="Returneddate">10/22/2019</html:span></html:p> <html:p><html:span class="dateTitle">Date of Institution</html:span> <html:span class="Returneddate">11/27/2019</html:span></html:p> <html:p><html:span class="mainTitle">Markman Hearing Dates</html:span></html:p> <html:p><html:span class="SubTitle">Start </html:span> <html:span class="Returneddate"/></html:p> <html:p><html:span class="SubTitle">End </html:span> <html:span class="Returneddate"/></html:p> <html:p><html:span class="mainTitle"> Evidentiary Hearing Dates</html:span></html:p> <html:p><html:span class="SubTitle"> Scheduled Start </html:span> <html:span class="Returneddate">07/21/2020</html:span></html:p> <html:p><html:span class="SubTitle"> Scheduled End </html:span> <html:span class="Returneddate">07/24/2020</html:span></html:p> <html:p><html:span class="SubTitle"> Actual Start </html:span> <html:span class="Returneddate">11/16/2020</html:span></html:p> <html:p><html:span class="SubTitle"> Actual End </html:span> <html:span class="Returneddate">11/19/2020</html:span></html:p> <html:p><html:span class="mainTitle"> Target Date</html:span>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:p><html:span class="mainTitle"> Target Date</html:span> <html:span class="Returneddate">08/20/2021</html:span></html:p> <html:p><html:span class="mainTitle"> Final ID On Violation</html:span></html:p> <html:p><html:span class="SubTitle"> Due Date</html:span> <html:span class="Returneddate">04/20/2021</html:span></html:p> <html:p><html:span class="SubTitle"> Issue Date</html:span> <html:span class="Returneddate">04/20/2021</html:span></html:p> <html:p><html:span class="mainTitle"> Non Final (Terminating) ID Issued </html:span> <html:span class="Returneddate"/></html:p> <html:p><html:span class="mainTitle"> Final Determination of No Violation</html:span> <html:span class="Returneddate">07/20/2021</html:span></html:p> <html:p><html:span class="mainTitle"> Final Determination of Violation</html:span> <html:span class="Returneddate"/></html:p> <html:p><html:span class="mainTitle"> Termination Date</html:span> <html:span class="Returneddate">07/20/2021</html:span></html:p> </html:div> <html:div>&#160;</html:div> <!-- END of Prcedural history -->
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <!-- START of invUnfairAct --> <html:div id="returned-detail-content2"> <html:div id="right-filter-content-detailnested"><html:h3>Unfair Act Alleged<html:span class="expand float_right">+</html:span></html:h3></html:div> <html:table id="investigations" width="100%" class="visible_none" cellpadding="0px" cellspacing="0px"> <html:tbody><html:tr> <html:th style="width:65%">Type </html:th> <html:th>Active - Inactive</html:th> </html:tr> <html:tr> <html:td>Patent Infringement</html:td> <html:td>11/22/2019 - </html:td> </html:tr> </html:tbody></html:table> </html:div> <html:div>&#160;</html:div> <!-- END of invUnfairAct --> <!-- START of IP --> <html:div id="returned-detail-content2"> <html:div id="right-filter-content-detailnested"><html:h3>Patent Number(s) <html:span class="expand float_right">+</html:span></html:h3> </html:div>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:table id="investigations" class="visible_none" width="100%" cellpadding="0px" cellspacing="0px"> <html:tbody><html:tr> <html:th>Number </html:th> <html:th>Active - Inactive</html:th> </html:tr> <html:tr> <html:td>10,018,371</html:td> <html:td>11/22/2019 - 07/20/2021</html:td> </html:tr> <html:tr> <html:td>8,131,497</html:td> <html:td>11/22/2019 - 07/20/2021</html:td> </html:tr> <html:tr> <html:td>8,432,322</html:td> <html:td>11/22/2019 - 07/20/2021</html:td> </html:tr>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:tr> <html:tr> <html:td>8,498,753</html:td> <html:td>11/22/2019 - 12/15/2020</html:td> </html:tr> </html:tbody></html:table> <html:div id="right-filter-content-detailnested"><html:h3>HTS Number(s) <html:span class="expand float_right">+</html:span></html:h3></html:div> <html:table id="investigations" class="visible_none" width="100%" cellpadding="0" cellspacing="0"> <html:tbody><html:tr> <html:th>Number </html:th> <html:th>Category Basket</html:th> </html:tr> <html:tr> <html:td>90321000</html:td> <html:td>Consumer Electronics Products</html:td> </html:tr> <html:tr>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:tr> <html:td>90322000</html:td> <html:td>Consumer Electronics Products</html:td> </html:tr> <html:tr> <html:td>90328960</html:td> <html:td>Consumer Electronics Products</html:td> </html:tr> </html:tbody></html:table> </html:div> <html:div>&#160;</html:div> <!-- END of IP --> <!-- START of TEO --> <!-- END of TEO --> <!-- START of Remand --> <!-- END of Remand --> </html:div> <!--End right-container --> <!-- Start landing-container --> <html:div id="detail-left-filter"> <html:div id="left-filter-content"><html:h2><html:img src="/337external/static/images/participants_icon.png" width="24" height="20" alt="People Icon"/> Participant Information</html:h2></html:div> <html:div id="returned-detail-content3"> <html:div id="left-filter-content">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:div id="left-filter-content"> <html:h3> <html:div class="float_right"> <html:div id="active">&#9745; <html:span style="font-size:0.6em; padding-right:5px"> - Active </html:span></html:div> <html:div id="inactive">&#9746;<html:span style="font-size:0.6em"> - Inactive </html:span></html:div> </html:div> Complainant Information </html:h3> </html:div> <html:table id="investigations" width="100%" cellpadding="0" cellspacing="0"> <html:tbody><html:tr> <html:th>Name - City/State/Country</html:th> <html:th>Lead Counsel for Service</html:th> <html:th>Active Inactive Date</html:th> </html:tr> <html:tr> <html:td> <html:div id="active"> &#9745; </html:div> <html:div id="name"> EcoFactor, Inc. - Palo Alto , CA , United States of America </html:div> </html:td> <html:td>Russ August &amp; Kabat</html:td> <html:td>11/22/2019 - </html:td> </html:tr> </html:tbody></html:table> <html:div id="left-filter-content">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:div id="left-filter-content"> <html:h3> <html:div class="float_right"> <html:div id="active">&#9745; <html:span style="font-size:0.6em; padding-right:5px"> - Active </html:span></html:div> <html:div id="inactive">&#9746;<html:span style="font-size:0.6em"> - Inactive </html:span></html:div> </html:div> Respondent Information </html:h3> </html:div> <html:div id="bbGrid-subgrid"> <html:div class="bbGrid-container"> <html:table id="investigations" class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th class="icon-plus-main" style="width:15px">+</html:th> <html:th rowspan="2">Name - City/State/Country</html:th> <html:th rowspan="2">Lead Counsel for Service</html:th> <html:th rowspan="2">Active Inactive Date</html:th> </html:tr> </html:thead> <html:tbody> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:td> <html:td> <html:div id="active"> &#9745;</html:div> <html:div id="name">Alarm.com Holdings, Inc. - Tysons , VA , United States</html:div> </html:td> <html:td> Foster, Murphy, Altman &amp; Nickel, PC </html:td> <html:td>10/22/2019 - </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> No Violation Found 07/20/2021</html:td> <html:td> 07/20/2021</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td> <html:td> <html:div id="active"> &#9745;</html:div> <html:div id="name">Alarm.com Incorporated - Tysons , VA , United States</html:div> </html:td> <html:td> Foster, Murphy, Altman &amp; Nickel, PC </html:td> <html:td>11/22/2019 - </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> No Violation Found 07/20/2021</html:td> <html:td> 07/20/2021</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:td> <html:td><html:div id="inactive">&#9746;</html:div> <html:div id="name">Daikin America, Inc. - Orangeburg , NY , United States</html:div> </html:td> <html:td> Latham &amp; Watkins LLP </html:td> <html:td>11/22/2019 - 07/01/2020 </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> Settlement 07/01/2020</html:td> <html:td> 07/01/2020</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td> <html:td><html:div id="inactive">&#9746;</html:div> <html:div id="name">Daikin Industries, Ltd. - Osaka , , Japan</html:div> </html:td> <html:td> Latham &amp; Watkins LLP </html:td> <html:td>11/22/2019 - 07/01/2020 </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> Settlement 07/01/2020</html:td> <html:td> 07/01/2020</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:td> <html:td><html:div id="inactive">&#9746;</html:div> <html:div id="name">Daikin North America LLC - Houston , TX , United States</html:div> </html:td> <html:td> Latham &amp; Watkins LLP </html:td> <html:td>11/22/2019 - 07/01/2020 </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> Settlement 07/01/2020</html:td> <html:td> 07/01/2020</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td> <html:td> <html:div id="active"> &#9745;</html:div> <html:div id="name">Ecobee Ltd. - Toronto , , Canada</html:div> </html:td> <html:td> Venable LLP </html:td> <html:td>11/22/2019 - </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> No Violation Found 07/20/2021</html:td> <html:td> 07/20/2021</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:td> <html:td> <html:div id="active"> &#9745;</html:div> <html:div id="name">Ecobee, Inc. - Toronto , , Canada</html:div> </html:td> <html:td> Venable LLP </html:td> <html:td>11/22/2019 - </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead> <html:tbody>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> No Violation Found 07/20/2021</html:td> <html:td> 07/20/2021</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead> <html:tbody>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td> <html:td> <html:div id="active"> &#9745;</html:div> <html:div id="name">Google LLC - Mountain View , CA , United States</html:div> </html:td> <html:td> WHITE &amp; CASE LLP </html:td> <html:td>11/22/2019 - </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> No Violation Found 07/20/2021</html:td> <html:td> 07/20/2021</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:td> <html:td><html:div id="inactive">&#9746;</html:div> <html:div id="name">Schneider Electric SE - Rueil-Malmaison , , France</html:div> </html:td> <html:td> Jenner &amp; Block LLP </html:td> <html:td>11/22/2019 - 08/31/2020 </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> Settlement 08/31/2020</html:td> <html:td> 08/31/2020</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td> <html:td><html:div id="inactive">&#9746;</html:div> <html:div id="name">Schneider Electric USA, Inc. - Andover , MA , United States</html:div> </html:td> <html:td> Jenner &amp; Block LLP </html:td> <html:td>11/22/2019 - 08/31/2020 </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> Settlement 08/31/2020</html:td> <html:td> 08/31/2020</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> <html:tr class="bbGrid-row"> <html:td class="bbGrid-subgrid-control"> <html:span class="icon-plus">+</html:span> </html:td>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:td> <html:td> <html:div id="active"> &#9745;</html:div> <html:div id="name">Vivant, Inc. - Provo , UT , United States</html:div> </html:td> <html:td> Williams Simons &amp; Landis PLLC </html:td> <html:td>11/22/2019 - </html:td> </html:tr> <html:tr class="bbGrid-subgrid-row visible_none"> <html:td/> <html:td colspan="4"> <html:div class="bbGrid-container"> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Disposition, Date</html:th> <html:th>Disposition by Unfair Acts, Date</html:th> <html:th>Remedial Orders Issued, Issue Date, Status, Change Date</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> <html:tr class="bbGrid-row" bgcolor="white"> <html:td> No Violation Found 07/20/2021</html:td> <html:td> 07/20/2021</html:td> <html:td> </html:td> </html:tr> </html:tbody> </html:table> <html:table class="bbGrid-grid table table-bordered table-condensed" width="100%" cellpadding="0" cellspacing="0"> <html:thead class="bbGrid-grid-head"> <html:tr class="bbGrid-grid-head-holder"> <html:th>Customs Enforcement Desc</html:th> <html:th>Forum</html:th> <html:th>Receipt Customs Letter</html:th> <html:th>Seizure Forfeiture Order</html:th> <html:th>Documents</html:th> </html:tr> </html:thead>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:thead> <html:tbody> </html:tbody> </html:table> </html:div> </html:td> </html:tr> </html:tbody> </html:table> </html:div></html:div> </html:div> <html:div id="left-filter-content"> <html:h2><html:img src="/337external/static/images/participants_icon.png" width="24" height="20" alt="People Icon"/> Agency Participant Information</html:h2> </html:div> <html:div id="returned-detail-content3"> <html:div style="width:35%;float:left;"> <html:div id="left-filter-content"><html:h3>Office of Unfair Import Investigations (OUII)</html:h3> </html:div> <html:div id="returned-detail-content"> <html:p> <html:span style="font-weight:bolder">Level of Participation:</html:span> <html:span style="margin-left:.5em;"> Full </html:span> </html:p> <html:br/>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:p> <html:br/> <html:table id="investigations" width="100%" cellpadding="0px" cellspacing="0px"> <html:tbody><html:tr> <html:th>Name </html:th> </html:tr> <html:tr> <html:td> <html:div id="active"> &#9745; </html:div> <html:div class="name"> Jeffrey Hsu</html:div> </html:td> </html:tr> <html:tr> <html:td> <html:div id="active"> &#9745; </html:div> <html:div class="name"> Paul Gennari</html:div> </html:td> </html:tr> </html:tbody></html:table> </html:div>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:div> </html:div> <html:div style="width:30%;float:left;"> <html:div id="left-filter-content"><html:h3>General Counsel (GC)</html:h3> </html:div> <html:div id="returned-detail-content"> <html:table id="investigations" width="100%" cellpadding="0px" cellspacing="0px"> <html:tbody><html:tr> <html:th>Name </html:th> </html:tr> <html:tr> <html:td> <html:div id="active"> &#9745; </html:div> Michael Liberman </html:td> </html:tr> <html:tr> <html:td> <html:div id="active"> &#9745; </html:div>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt Megan Valentine </html:td> </html:tr> <html:tr> <html:td> <html:div id="inactive"> &#9746; </html:div> Houda Morad </html:td> </html:tr> </html:tbody></html:table> </html:div> </html:div>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <html:div style="width:35%;float:left;"> <html:div id="left-filter-content"><html:h3>Administrative Law Judge (ALJ) </html:h3> </html:div> <html:div id="returned-detail-content"> <html:p> </html:p><html:table id="investigations" width="100%" cellpadding="0px" cellspacing="0px"> <html:tbody><html:tr> <html:th>Name </html:th> </html:tr> <html:tr> <html:td> <html:div id="active"> &#9745; </html:div> David Shaw </html:td> </html:tr> </html:tbody></html:table> </html:div> </html:div> <html:div style="float:right;width:100%">
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:div> <html:div style="float:right;width:100%"> <html:div style="float:right;"> <html:div id="active">&#9745; <html:span style="font-size:0.6em; padding-right:5px"> - Active </html:span></html:div> <html:div id="inactive">&#9746;<html:span style="font-size:0.6em"> - Inactive </html:span></html:div> </html:div> </html:div> <html:br clear="all"/> </html:div> </html:div> </html:div> <!--End landing-container --> <html:div style="clear: both;"/> </html:div> <html:div id="footer"> <html:p> </html:p> <html:div class="address"> &#8230; </html:div> <html:p> </html:p> <html:div class="midSection" align="left"> &#8230; </html:div> <html:p/> <html:p> </html:p> <html:div class="midSectionRight" align="left"> &#8230; </html:div> <html:p/> <html:p> </html:p> <html:div class="right" align="left"> </html:div> </html:div> <html:div style="clear: both;"/>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </html:div> </html:div>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt This is my desired output: {'Office of Unfair Import Investigations (OUII)': {'Level of Participation': 'Full', 'people': [{'name': 'Jeffrey Hsu', 'status': 'active'}, {'name': 'Paul Gennari', 'status': 'active'}]}, 'Administrative Law Judge (ALJ) ': {'people': [{'name': 'David Shaw', 'status': 'active'}]}, 'General Counsel (GC)': {'people': [{'name': 'Michael Liberman', 'status': 'active'}, {'name': 'Megan Valentine', 'status': 'active'}, {'name': 'Houda Morad', 'status': 'inactive'}]}, 'Patent Number(s)': [{'Number': '10,018,371', 'Active - Inactive': '11/22/2019 - 07/20/2021'}, {'Number': '8,131,497', 'Active - Inactive': '11/22/2019 - 07/20/2021'}, {'Number': '8,432,322', 'Active - Inactive': '11/22/2019 - 07/20/2021'}, {'Number': '8,498,753', 'Active - Inactive': '11/22/2019 - 12/15/2020'}], 'Investigation Type': 'Violation', 'Investigation Number': '337-TA-1185', 'Investigation Status': 'Terminated', 'Respondent Information': [{'Active Inactive Date': '10/22/2019 -', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/20/2021', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'No Violation Found 07/20/2021'}], 'Lead Counsel for Service': 'Foster, Murphy, Altman & Nickel, PC', 'Name - City/State/Country': 'Alarm.com Holdings, Inc. - Tysons , VA , United States'}, {'Active Inactive Date': '11/22/2019 -', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/20/2021', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'No Violation Found 07/20/2021'}], 'Lead Counsel for Service': 'Foster, Murphy, Altman & Nickel, PC', 'Name - City/State/Country': 'Alarm.com Incorporated - Tysons , VA , United States'}, {'Active Inactive Date': '11/22/2019 - 07/01/2020', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/01/2020', 'Remedial Orders Issued, Issue Date, Status, Change Date': '',
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'Settlement 07/01/2020'}], 'Lead Counsel for Service': 'Latham & Watkins LLP', 'Name - City/State/Country': 'Daikin America, Inc. - Orangeburg , NY , United States'}, {'Active Inactive Date': '11/22/2019 - 07/01/2020', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/01/2020', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'Settlement 07/01/2020'}], 'Lead Counsel for Service': 'Latham & Watkins LLP', 'Name - City/State/Country': 'Daikin Industries, Ltd. - Osaka , , Japan'}, {'Active Inactive Date': '11/22/2019 - 07/01/2020', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/01/2020', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'Settlement 07/01/2020'}], 'Lead Counsel for Service': 'Latham & Watkins LLP', 'Name - City/State/Country': 'Daikin North America LLC - Houston , TX , United States'}, {'Active Inactive Date': '11/22/2019 -', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/20/2021', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'No Violation Found 07/20/2021'}], 'Lead Counsel for Service': 'Venable LLP', 'Name - City/State/Country': 'Ecobee Ltd. - Toronto , , Canada'}, {'Active Inactive Date': '11/22/2019 -', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/20/2021', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'No Violation Found 07/20/2021'}], 'Lead Counsel for Service': 'Venable LLP', 'Name - City/State/Country': 'Ecobee, Inc. - Toronto , , Canada'}, {'Active Inactive Date': '11/22/2019 -', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/20/2021', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'No Violation Found 07/20/2021'}],
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt 'Disposition, Date': 'No Violation Found 07/20/2021'}], 'Lead Counsel for Service': 'WHITE & CASE LLP', 'Name - City/State/Country': 'Google LLC - Mountain View , CA , United States'}, {'Active Inactive Date': '11/22/2019 - 08/31/2020', 'Dispositions': [{'Disposition by Unfair Acts, Date': '08/31/2020', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'Settlement 08/31/2020'}], 'Lead Counsel for Service': 'Jenner & Block LLP', 'Name - City/State/Country': 'Schneider Electric SE - Rueil-Malmaison , , France'}, {'Active Inactive Date': '11/22/2019 - 08/31/2020', 'Dispositions': [{'Disposition by Unfair Acts, Date': '08/31/2020', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'Settlement 08/31/2020'}], 'Lead Counsel for Service': 'Jenner & Block LLP', 'Name - City/State/Country': 'Schneider Electric USA, Inc. - Andover , MA , United States'}, {'Active Inactive Date': '11/22/2019 -', 'Dispositions': [{'Disposition by Unfair Acts, Date': '07/20/2021', 'Remedial Orders Issued, Issue Date, Status, Change Date': '', 'Disposition, Date': 'No Violation Found 07/20/2021'}], 'Lead Counsel for Service': 'Williams Simons & Landis PLLC', 'Name - City/State/Country': 'Vivant, Inc. - Provo , UT , United States'}], 'Docket Number': '3418', 'HTS Number(s)': [{'Category Basket': 'Consumer Electronics Products', 'Number': '90321000'}, {'Category Basket': 'Consumer Electronics Products', 'Number': '90322000'}, {'Category Basket': 'Consumer Electronics Products', 'Number': '90328960'}], 'Procedural History': {'Non Final (Terminating) ID Issued': '', 'Final Determination of No Violation': '07/20/2021', 'Final Determination of Violation': '', 'Termination Date': '07/20/2021', 'Due Date': '04/20/2021', 'Evidentiary Hearing Dates': {'Scheduled Start': '07/21/2020', 'Actual Start': '11/16/2020', 'Actual End': '11/19/2020',
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt 'Actual Start': '11/16/2020', 'Actual End': '11/19/2020', 'Scheduled End': '07/24/2020'}, 'Complaint Filed': '10/22/2019', 'Issue Date': '04/20/2021', 'Scheduled Start': '07/21/2020', 'Date of Institution': '11/27/2019', 'Actual Start': '11/16/2020', 'Final ID On Violation': {'Due Date': '04/20/2021', 'Issue Date': '04/20/2021'}, 'Markman Hearing Dates': {'Start': '', 'End': ''}, 'Actual End': '11/19/2020', 'Target Date': '08/20/2021', 'Scheduled End': '07/24/2020', 'Start': '', 'End': ''}, 'Unfair Act Alleged': [{'Type': 'Patent Infringement', 'Active - Inactive': '11/22/2019 -'}], 'Complainant Information': [{'Active Inactive Date': '11/22/2019 -', 'Lead Counsel for Service': 'Russ August & Kabat', 'Name - City/State/Country': ''}], 'title': 'Certain Smart Thermostats, Smart HVAC Systems, and Components Thereof; Inv. No. 337-TA-1185'}
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt This is the current state of my XSLT that produces that JSON. <?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"> <xsl:output method="json"/> <xsl:template match='/'> <xsl:map> <xsl:map-entry key="'title'" select="string(//div[@id='titlecontainer']/h2)"/> <xsl:apply-templates/> </xsl:map> </xsl:template> <!-- Overrides default template for text--> <xsl:template match="text()"/> <!--Used for title block info, Procedural History, and Office of Unfair Import Investigations (OUII) tables--> <xsl:template match="p[count(span) = 2]"> <xsl:map-entry key="translate(normalize-space(./span[1]), ':', '')" select="normalize-space(./span[2])"/> </xsl:template> <!-- Procedural History--> <xsl:template match="div[@id='right-filter']/div[@id = 'returned-detail-content']"> <xsl:map-entry key="'Procedural History'"> <xsl:map> <xsl:for-each-group select=".//p[span[contains(@class, 'SubTitle')]]" group-by="normalize-space(preceding-sibling::p[span[contains(@class, 'mainTitle')]][1])"> <xsl:map-entry key="current-grouping-key()"> <xsl:map> <xsl:apply-templates select="current-group()"/> </xsl:map> </xsl:map-entry> </xsl:for-each-group> <xsl:apply-templates/> </xsl:map> </xsl:map-entry> </xsl:template>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <!--Rightmost tables and Complainant Information--> <xsl:template match="table[preceding-sibling::div[@id = 'right-filter-content-detailnested' or @id='left-filter-content']]"> <xsl:map-entry key="normalize-space(translate(./preceding-sibling::div[1]/h3/text()[normalize-space(.)], '+', ''))"> <xsl:variable name="headers" select=".//th"/> <xsl:sequence select="array{.//tr[td] ! map:merge(for $i in 1 to count($headers) return map{normalize-space($headers[$i]): normalize-space(./td[$i]/text()[normalize-space(.)])})}"/> </xsl:map-entry> </xsl:template> <!-- Agency Participant Information tables--> <xsl:template match="div[@id='returned-detail-content3']/div[contains(@style, 'float:left;')]"> <xsl:map> <xsl:map-entry key="string(./div[@id='left-filter-content']/h3)"> <xsl:map> <xsl:apply-templates/> </xsl:map> </xsl:map-entry> </xsl:map> </xsl:template> <xsl:template match="tbody[tr/th[normalize-space(.) = 'Name']]"> <xsl:variable name="people" as="map(*)*"> <xsl:apply-templates/> </xsl:variable> <xsl:map-entry key="'people'" select="array{$people}"/> </xsl:template> <!--OUII rows--> <xsl:template match="div[contains(@style, 'float:left;')]//td[div[contains(@class, 'name')]]"> <xsl:map> <xsl:map-entry key="'name'" select="normalize-space(./div[contains(@class, 'name')])"/> <xsl:map-entry key="'status'" select="string(./div[1]/@id)"/> </xsl:map> </xsl:template> <!--Other rows--> <xsl:template match="div[contains(@style, 'float:left;')]//td[count(div)=1 and div[@id='active' or @id='inactive']]"> <xsl:map> <xsl:map-entry key="'name'" select="normalize-space(./text()[normalize-space(.)])"/> <xsl:map-entry key="'status'" select="string(./div[1]/@id)"/> </xsl:map> </xsl:template>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt <!-- Respondent Information--> <xsl:template match="div[@id='bbGrid-subgrid']"> <xsl:map-entry key="normalize-space(./preceding-sibling::div[1]/h3/text()[normalize-space()])"> <xsl:variable name="rows" as="map(*)*"> <xsl:apply-templates select="./div/table/tbody/tr[not(.//table)]"/> </xsl:variable> <xsl:sequence select="array{$rows}"/> </xsl:map-entry> </xsl:template> <xsl:template match="tr[contains(@class, 'bbGrid-row')]"> <xsl:map> <xsl:variable name="headers" select="./ancestor::table[1]/thead/tr/th"/> <xsl:for-each select="td[not(contains(span/@class, 'icon-plus'))]"> <xsl:variable name="index" select="count(preceding-sibling::td) + 1"/> <xsl:map-entry key="string($headers[$index])" select="if (./div[2]) then normalize-space(./div[2]) else normalize-space(.)"/> </xsl:for-each> <xsl:if test="following-sibling::tr[1][td/div/table]"> <xsl:map-entry key="'Dispositions'"> <xsl:variable name="dispositions" as="map(*)*"> <xsl:apply-templates select="following-sibling::tr[1]"/> </xsl:variable> <xsl:sequence select="array{$dispositions}"/> </xsl:map-entry> </xsl:if> </xsl:map> </xsl:template> <xsl:template match="td/div[1][contains(@id, 'active')]"> <xsl:map-entry key="'status'" select="string(@id)"/> </xsl:template> </xsl:stylesheet>
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
json, web-scraping, xpath, xslt </xsl:stylesheet> We're fairly happy with the approach so far. I mainly wanted to ask for feedback on the XSLT, as I am returning to the language after a long absence. My premium is on maintainability and comprehensibility for other programmers. I've tried a few different approaches to see how I like them. For instance, the <!--Rightmost tables and Complainant Information--> template is very compact and produces the desired output but is maybe not very comprehensible. Comments on how to improve the approach of applying XSLT 3.0 to real-world HTML from Python are also welcome. Answer: I don't see any glaring problems with your code (on a pretty quick scan). You might like to try the arrow operator: normalize-space(translate(./preceding-sibling::div[1]/h3/text()[normalize-space(.)], '+', '')) can be written preceding-sibling::div[1]/h3/text()[normalize-space(.)] => translate('+', '') => normalize-space() which I find more readable. But is this use of text() correct? Your only h3 has a span element within it. If there were two child text nodes separated by a span then your code would fail with a type error. I don't know your data of course. You might also find that you can simplify the whitespace handling if you strip whitespace from block-level elements, for example <xsl:strip-space elements="div ul p"/> Another observation: as an alternative to calling out to SaxonJS running under node.js, you could use the Python binding in SaxonC.
{ "domain": "codereview.stackexchange", "id": 42807, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "json, web-scraping, xpath, xslt", "url": null }
python, time-limit-exceeded, dynamic-programming Title: HackerRank: Sam and substrings | How can dynamic programming be used in my code? Question: Given a number as a string, no leading zeros, determine the sum of all integer values of substrings of the string. Given an integer as a string, sum all of its substrings cast as integers. As the number may become large, return the value modulo 10**9+7. Example: n='42' ans=4+2+42=48 Full problem: https://www.hackerrank.com/challenges/sam-and-substrings My code: def substrings(n): ans=0 l=len(n) for i in range(l): ans+=int(n[i])*(i+1)*((10**(l-i)-1)//9) return ans%(10**9+7) It's currently getting timed out otherwise passing all test cases. Even though the problem category is dynamic programming, I don't understand how it could be used, and I'm not sure what's slowing my code down. Answer: Instead of treating each digit separately, you could compute the answer for each prefix. Similar to how Horner's method is fast for evaluating polynomials. Let's look at an example and how the answer changes when appending another digit: 567 => 567 + 56 + 5 + 67 + 6 + 7 = 5*111 + 6*22 + 7*3 5678 => 5*1111 + 6*222 + 7*33 + 8*4 (looks like 10 times the previous answer plus something extra, let's call that x) = (5*111 + 6*22 + 7*3) * 10 + x = 5*1110 + 6*220 + 7*30 + x => x = 5*1 + 6*2 + 7*3 + 8*4 So just multiply the previous answer by 10 and add that x (after updating that itself). Use modulo on the intermediate values for efficiency (at least for ans... For x it would be detrimental, as it doesn't grow very large anyway, and the extra modulo would cost more time than it saves). def substrings(n): ans = x = 0 mod = 10**9 + 7 for i, digit in enumerate(n, 1): x += int(digit) * i ans = (ans * 10 + x) % mod return ans
{ "domain": "codereview.stackexchange", "id": 42808, "lm_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, time-limit-exceeded, dynamic-programming", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing Title: Implementation of versatile IIR digital filter in C++ Question: I have realized that all the digital filters of the IIR type have the same structure. They are described by difference equation in following form: $$ y(k) = b_0\cdot x(k) + b_1\cdot x(k-1) + \ldots + b_M\cdot x(k-M) -a_1\cdot y(k-1) - a_2\cdot y(k-2) - \ldots - a_N\cdot y(k-N) $$ Based on that I have attempted to define a C++ template class which can be used for implementation of any IIR filter based on passing values of the coefficients of the difference equation comming from design in Matlab or Scilab software package. The class is intended to be used in digital signal processor (with floating point ALU) for filtering in real time. #ifndef IIRFILTER_H #define IIRFILTER_H #include <cstdint> #include <iostream> /** * @brief Versatile digital filter with infinite impulse response * i.e. difference equation in the form: * * $\f * y(k) = b_0\cdot x(k) + b_1\cdot x(k-1) + \ldots + b_M\cdot x(k-M) * -a_1\cdot y(k-1) - a_2\cdot y(k-2) - \ldots - a_N\cdot y(k-N) * $\f * * where $\f x(k) \ldots x(k-M)$\f are the input samples, * $\f y(k) \ldots y(k-N)$\f are the output samples, * $\f b_0, b_1, \ldots , b_M $\f are the input coefficients and * $\f a_1, a_2, \ldots , a_N $\f are the output coefficients */ template <uint32_t NO_INPUT_COEFFICIENTS, uint32_t NO_OUTPUT_COEFFICIENTS> class IirFilter { public: /** * @brief Constructor accepting coefficients of the difference equation. * The coefficients are expected in following order: * * $\f b_0, b_1, \ldots , b_M, -a_1, -a_2, \ldots, a_N $\f * * i.e. at the beginning $\f M+1 $\f \emph{b} coefficients followed by $\f N $\f * \emph{a} coefficients with negative sign. */ template <typename... Args> constexpr IirFilter(const Args &... args) : input_buffer{}, output_buffer{}, input_index{0}, output_index{0}, coefficients{args...} { }
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing /** * @brief Method passes the filtered value into the filter * @param input filtered input */ void setInput(float input) { input_buffer[input_index++] = input; if (input_index == NO_INPUT_COEFFICIENTS) { input_index = 0; } } /** * @brief Method calculates the filter. */ void calculate() { // filter implemented in the direct form convolveInputs(); convolveOutputs(); calculateOutput(); storeOutput(); } /** * @brief Method returns output of the filter. * @return filter output */ float getOutput() const { return output; } private: static const uint32_t kFirstInputCoefficientIndex = 0; static const uint32_t kFirstOutputCoefficientIndex = kFirstInputCoefficientIndex + NO_INPUT_COEFFICIENTS; /**< Circular buffer for the input samples x(k) */ float input_buffer[NO_INPUT_COEFFICIENTS]; /**< Circular buffer for the output samples y(k) */ float output_buffer[NO_OUTPUT_COEFFICIENTS]; /**< Coefficients of the difference equation */ const float coefficients[NO_INPUT_COEFFICIENTS + NO_OUTPUT_COEFFICIENTS]; /**< Position of the current oldest sample of the input sequence in the * input circular buffer */ uint32_t input_index; /**< Position of the current oldest sample of the output sequence in the * output circular buffer */ uint32_t output_index; /**< Convolution of the last $\fM+1$\f input samples */ float input_convolution; /**< Convolution of the last $\fN$\f input samples */ float output_convolution; /**< Current output $\fy(k)$\f */ float output;
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing /** * @brief Method calculates the convolution of the last $\fM+1$\f * input samples i.e. * * $\f * b_0\cdot x(k) + b_1\cdot x(k-1) + \ldots + b_M\cdot x(k-M) * $\f * */ void convolveInputs() { input_convolution = convolve(input_buffer, NO_INPUT_COEFFICIENTS, input_index, coefficients, kFirstInputCoefficientIndex, NO_INPUT_COEFFICIENTS); } /** * @brief Method calculates the convolution of the last $\fN$\f * input samples i.e. * * $\f * -a_1\cdot y(k-1) - a_2\cdot y(k-2) - \ldots - a_N\cdot y(k-N) * $\f * */ void convolveOutputs() { output_convolution = convolve( output_buffer, NO_OUTPUT_COEFFICIENTS, output_index, coefficients, kFirstOutputCoefficientIndex, NO_OUTPUT_COEFFICIENTS); } /** * @brief Method calculates current sample of the output sequence * $\f y(k) $\f */ void calculateOutput() { output = input_convolution + output_convolution; } /** * @brief Method inserts current sample of the output sequence into * the output buffer */ void storeOutput() { output_buffer[output_index++] = output; if (output_index == NO_OUTPUT_COEFFICIENTS) { output_index = 0; } }
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing /** * @brief Method calculates convolution of the sequence stored * in the circular buffer with given impulse response. * @param circular_buffer circular buffer where the input sequence is stored * @param circular_buffer_length length of the circular buffer * @param circular_buffer_oldest_sample_index index of the current oldest * sample of the input sequence in the circular buffer * @param impulse_response array where the impulse response samples are stored * @param impulse_response_first_sample_index index of the first sample of the * impulse response * @param impulse_response_length number of samples per impulse response * @return convolution of the sequence stored in the circular buffer with given * impulse response */ float convolve(const float circular_buffer[], const uint32_t circular_buffer_length, const uint32_t circular_buffer_oldest_sample_index, const float impulse_response[], const uint32_t impulse_response_first_sample_index, const uint32_t impulse_response_length) { float convolution = 0; // position of the last inserted i.e. newest sample of the input sequence int32_t j = circular_buffer_oldest_sample_index - 1; if (j < 0) { // last inserted sample is at the end of the buffer j = circular_buffer_length - 1; } // iterate over the last "impulse_response_length" samples of the input // sequence in direction from the "newest" to the "oldest" sample for (uint32_t i = impulse_response_first_sample_index; i < impulse_response_first_sample_index + impulse_response_length; i++) { convolution += impulse_response[i] * circular_buffer[j]; if (--j < 0) { j = circular_buffer_length - 1; } } return convolution; } }; #endif /* IIRFILTER_H */
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing #endif /* IIRFILTER_H */ Below is a code example documenting usage of the IirFilter class (namely calculation of a step response of a filter with following transfer function $$H(z) = \frac{0.0008663387 + 0.001732678\cdot z^{-1} + 0.0008663387\cdot z^{-2}}{1 - 1.919129\cdot z^{-1} + 0.9225943\cdot z^{-2}}$$) int main(int argc, char** argv) { const uint32_t kInputLength = 64; float x[kInputLength] = {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}; IirFilter<3, 2> iir(0.0008663387f, 0.001732678f, 0.0008663387f, 1.919129f, -0.9225943f); for (uint32_t i = 0; i < kInputLength; i++) { iir.setInput(x[i]); iir.calculate(); std::cout << iir.getOutput() << std::endl; } return 0; }
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing Answer: Doxygen errors It's great that you are using Doxygen to document the code, and also that you include the formulas that your filter implements. However, you did not use the right opening and closing tags for the formulas. You have to use \f$...\f$ instead of $\f...$\f. Furthermore, you cannot use \$\LaTeX\$ commands in the normal text in Doxygen, use Doxygen's own commands instead. For example, you cannot write \emph{a} coefficients, you have to write \em a coefficients if you really just wanted emphasis, but I think it's better to write \f$a\f$-coefficients. You are also missing @params for the constructor of IirFilter. Make sure you validate that your Doxygen documentation is correct by creating a Doxygen config file if you haven't already, and set all WARN_* parameters, including WARN_AS_ERROR, to YES. Let functions take parameters and return values There is no reason to make calculate() a function that takes no parameters and returns no value, and then have separate functions setInput() and getOutput() to set the input to the calculation and get the result of the calculation. Instead, make it look like this: float calculate(float input) { setInput(input); ... return getOutput(); } Now also apply this principle to the private member functions. And once you've done this with everything, you'll note while before you needed to store all intermediate results in member variables to pass them from function to function, now you can avoid that in several places. Consider rewriting calculate() like so: float calculate(float input) { setInput(input); float output = convolveInputs() + convolveOutputs(); storeOutput(output); return output; }
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
c++, object-oriented, template-meta-programming, numerical-methods, signal-processing Make more member functions const You made getOutput() const, which is great, but there are more functions that don't modify any of the member variables, and thus should be marked as being const, like convolve(). And if you modified the functions to take and return values as mentioned above, then you should be able to make convoleInputs() and convolveOutputs() const as well. Consider implementing a circular buffer class You don't have actual circular buffers in your code, you only have the array coefficients[]. It is convolve() that not only does the convolution, but also has to implement the circular buffer semantics. Ideally, you would have a circular buffer class that stores the input and output values, and that allows you to push new values into them, and that acts like a regular STL container, including providing iterators. Then convolve() would be much simpler. In fact, you wouldn't even need to implement convolve() yourself anymore, you could then just use std::inner_product(). Consider being able to write: #include <numeric> template <...> class IirFilter { public: ... float calculate(float input) { inputs.push(input); float input_convolution = std::inner_product( inputs.begin(), inputs.end(), coeffients.begin(), 0.f); float input_convolution = std::inner_product( outputs.begin(), outputs.end(), coeffients.begin() + NO_INPUT_COEFFICIENTS, 0.f); float output = input_convolution + output_convolution; outputs.push(output); return output; } ... private: circular_buffer<float, NO_INPUT_COEFFICIENTS> inputs; circular_buffer<float, NO_OUTPUT_COEFFICIENTS> outputs; ... };
{ "domain": "codereview.stackexchange", "id": 42809, "lm_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++, object-oriented, template-meta-programming, numerical-methods, signal-processing", "url": null }
java, algorithm, array Title: Change values in array until no consecutive values Question: I have to find an algorithm to solve this question : You have an array with n integers in it. Make an algorithm that changes array so that there are no consecutive expressions in it and returns the amount of changes to be made. For example in array [1,1,2,2,2] the smallest amount of changes is 2 to get it to [1,3,2,1,2]. [1,2,3,4,5] results output "0", [1,1,1,1,1] results output "2". I have to change as less values as possible and my code does work as intended. On the other hand, I have the impression that it is not very efficient. What do you think ? Here it is : import java.util.Arrays; public static int untilNoConsecutive(int[] arr) { int rounds = 0; int arrSize = arr.length; for (int i = 0; i < arrSize - 2; i++) { if (arr[i] == arr[i + 1]) { arr[i + 1]++; if (arr[i + 1] == arr[i + 2]) arr[i + 1]++; rounds++; } } if (arr[arrSize - 2] == arr[arrSize - 1]) { arr[arrSize - 1]++; rounds++; } System.out.println(Arrays.toString(arr)); // for testing purpose return rounds; } public static void main(String[] args) { int arr[] = { 1, 1, 2, 1, 1 }; int arr2[] = { 1, 2, 3, 4, 5 }; int arr3[] = { 1, 1, 1, 1, 1 }; System.out.println(untilNoConsecutive(arr)); System.out.println(untilNoConsecutive(arr2)); System.out.println(untilNoConsecutive(arr3)); Thanks. Answer: I'd avoid repeating the logic outside the loop. Just let the loop run until i < arrSize - 1, and add the condition i + 2 < arrSize to the inner if. If I'm not mistaken, if the inner if condition is true, then the next loop unnecessarily checks the same values again, so I believe you could add i++ to that inner if block. Finally some style remarks: You should always use braces, even on one line blocks. I'm not really happy with the variable names:
{ "domain": "codereview.stackexchange", "id": 42810, "lm_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, array", "url": null }
java, algorithm, array You should always use braces, even on one line blocks. I'm not really happy with the variable names: arr should probably be called array or maybe something that doesn't represent the data format such as numbers. arrSize could just be called size or len(gth). And rounds should (based on the task description) be changes.
{ "domain": "codereview.stackexchange", "id": 42810, "lm_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, array", "url": null }
python, json Title: How to not use the output of a function for the arguments of another function Question: I wrote this first function that use a JSON datafile as an input def jsonfile_loader_work_rate(filename): '''Load the json file, to retrieve the interventions id and the cars id ''' try: with open(filename, "r") as jsonfile: json_data = json.load(jsonfile) cars = [ json_data["cars"][val]["id"] for val in range(len(json_data["cars"]))] interventions = [ json_data["interventions"][val]["id"] for val in range(len(json_data["interventions"])) ] return cars,interventions except: print('No date or no file')
{ "domain": "codereview.stackexchange", "id": 42811, "lm_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 This is the json file { "interventions": [ { "id": 1, "name": "batteria cambio", "parts_spec": [ {"type": "battery", "count": 1} ] }, { "id": 2, "name": "Cambio de lo disc y de la plakette", "parts_spec": [ {"type": "front_brake_pad", "count": 2}, {"type": "front_brake_disc", "count": 2} ] } ], "cars": [ { "id": 1, "manufacturer": "Peugeot", "model": "307 CC", "version": "2.0 16v 140cv"}, { "id": 2, "manufacturer": "BMW", "model": "Série 3", "version": "318i 136cv"}, { "id": 3, "manufacturer": "Toyota", "model": "Rav 4 3", "version": "2.2 D-4D 4WD 136cv"} ], "parts": [ {"id": 1, "type": "battery", "car_id": 1, "price": "95.99"}, {"id": 10, "type": "battery", "car_id": 1, "price": "106.00"}, {"id": 11, "type": "battery", "car_id": 1, "price": "84.40"}, {"id": 12, "type": "battery", "car_id": 2, "price": "121.00"}, {"id": 13, "type": "battery", "car_id": 2, "price": "150.05"}, {"id": 4, "type": "battery", "car_id": 2, "price": "123.10"}, {"id": 14, "type": "battery", "car_id": 3, "price": "109.00"}, {"id": 7, "type": "battery", "car_id": 3, "price": "97.99"}, {"id": 14, "type": "battery", "car_id": 3, "price": "200.00"}, {"id": 2, "type": "front_brake_pad", "car_id": 1, "price": "17.20"}, {"id": 3, "type": "front_brake_disc", "car_id": 1, "price": "80.00"}, {"id": 5, "type": "front_brake_pad", "car_id": 2, "price": "24.5"}, {"id": 6, "type": "front_brake_disc", "car_id": 2, "price": "110.4"}, {"id": 8, "type": "front_brake_pad", "car_id": 3, "price": "30.34"}, {"id": 9, "type": "front_brake_disc", "car_id": 3, "price": "120.50"} ], "workshops": [ {"id": 1, "name": "XYZ", "hourly_rate": "67.00", "preferred_part_price": "median"}, {"id": 2, "name": "ZYX", "hourly_rate": "72.99", "preferred_part_price": "most_expensive"},
{ "domain": "codereview.stackexchange", "id": 42811, "lm_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 {"id": 2, "name": "ZYX", "hourly_rate": "72.99", "preferred_part_price": "most_expensive"}, {"id": 3, "name": "YZX", "hourly_rate": "63.50", "preferred_part_price": "cheapest"} ] }
{ "domain": "codereview.stackexchange", "id": 42811, "lm_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 When I'm running jsonfile_loader_work_rate('data.json'), it gives me the following result ([1, 2, 3], [1, 2]). I'm then using the output of the function, in another function def retrieve_with_api_url_labour_time(loader_cars_interv,url): cars, interventions = loader_cars_interv spent_time_by_op_results = [] for val_car in cars: for val_interv in interventions: results = requests.get(f"{url}/{val_car}/{val_interv}") time_load = json.loads(results.text) time_load = time_load["labourTime"] spent_time_by_op_results.append( {"car_id": val_car, "interv_id": val_interv, "time_spent": time_load} ) return spent_time_by_op_results I cannot give you the URL as I don't want to display it publicly. However, I can give you a sample of the results when I query the API {"labourTime":"00:20:00"} Below is the final desired result. My two functions, imbricated, provides it. [{'car_id': 1, 'interv_id': 1, 'time_spent': '00:20:00'}, {'car_id': 1, 'interv_id': 2, 'time_spent': '01:10:00'}, {'car_id': 2, 'interv_id': 1, 'time_spent': '00:25:00'}, {'car_id': 2, 'interv_id': 2, 'time_spent': '01:40:00'}, {'car_id': 3, 'interv_id': 1, 'time_spent': '00:29:00'}, {'car_id': 3, 'interv_id': 2, 'time_spent': '01:55:00'}] I run the two functions like that print(retrieve_with_api_url_labour_time(jsonfile_loader_work_rate('data.json'),'https://www.acme.ie/apipint')) The question is the following: Is there another way to run the script retrieve_with_api_url_labour_time, instead of what I'm doing?
{ "domain": "codereview.stackexchange", "id": 42811, "lm_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 Answer: Use PEP484 type hints. Don't use range(len()) on your data; iterate over the inner dictionaries directly. Never bare except; let exceptions fall through so that they can be properly handled at the outer level. If you do want to translate internal exception traces to user-friendly messages, you can; but the way shown in the original post is not the way to do it. Among other reasons, The caller will not know that anything failed until it tries to use the return value and finds out - surprise - that it's None. A user-break (Ctrl+C) issued during the execution of that function will be swallowed by your except:, when it shouldn't be. Which is it: no data, no file, or something else? The message is both not specific enough and not accurate enough. If you handle the exception at the outer level, you should have separate except clauses covering the specific failure being described. Whenever you call requests, make sure to check for failure - which it doesn't by default. Don't call json.loads on a Requests response; use its own .json() method instead. Don't use dictionaries for internal data representation; use class instances - dataclass or NamedTuple being two reasonable options. Don't use a string type for your time_spent when it's actually a timedelta. Incredibly, Python timedelta parsing is pretty garbage and so some simple manual parsing something like I've shown will be necessary. Consider using generators instead of building up lists for your API function. It's fine to return two iterables from your loader, but they should be unpacked to two separate variables instead of passed around together. Suggested import json from datetime import timedelta from typing import Iterable, Collection, Iterator, NamedTuple import requests as requests def jsonfile_loader_work_rate(filename: str) -> tuple[ list[int], # car IDs list[int], # intervention IDs ]: """Load the json file, to retrieve the interventions id and the cars id """
{ "domain": "codereview.stackexchange", "id": 42811, "lm_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 with open(filename, 'r') as jsonfile: json_data = json.load(jsonfile) cars = [ car['id'] for car in json_data['cars'] ] interventions = [ intervention['id'] for intervention in json_data['interventions'] ] return cars, interventions class LabourTime(NamedTuple): car_id: int intervention_id: int time_spent: timedelta IMAGINARY = True def parse_timedelta(text: str) -> timedelta: h, m, s = (int(t) for t in text.split(':')) return timedelta(hours=h, minutes=m, seconds=s) def retrieve_with_api_url_labour_time( car_ids: Iterable[int], intervention_ids: Collection[int], url: str, ) -> Iterator[LabourTime]: for car_id in car_ids: for interv_id in intervention_ids: if IMAGINARY: time_load = {'labourTime': '25:20:01'} else: with requests.get(f'{url}/{car_id}/{interv_id}') as resp: resp.raise_for_status() time_load = resp.json() yield LabourTime( car_id=car_id, intervention_id=interv_id, time_spent=parse_timedelta(time_load['labourTime']), ) def main() -> None: car_ids, intervention_ids = jsonfile_loader_work_rate('273228.json') for labour_time in retrieve_with_api_url_labour_time( car_ids=car_ids, intervention_ids=intervention_ids, url='https://www.acme.ie/apipint', ): print(labour_time) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 42811, "lm_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 }
multithreading, connection-pool, nim Title: Implementing Database Connection Pooling Question: I am re-implementing a web-application, partially as a learning exercise to learn nim as well as multi-threaded programming. As part of that learning exercise, I want to implement connection pooling as there is no library or package in nim that I am aware of that implements it for me, while also allowing me to use the ORM of my choosing. The database I am connecting to is sqlite. As such, I wrote what I think is correct code: I made a global object POOL of type ConnectionPool that is merely a sequence of connections to the sqlite datbase and that also has a lock. Every connection has a clearly defined lifetime after which it gets destroyed, and new connections get made if a connection is needed but none is available. You can get a connection by using borrowConnection, and return it by using recycleConnection. Both of these procs lock the POOL object to retrieve a connection or put said connection back. import ../applicationSettings import constructor/defaults import std/[times, locks, db_sqlite] proc createRawDatabaseConnection(): DbConn = return open(applicationSettings.database, "", "", "") type PoolConnection* {.defaults.} = object connection*: DbConn = createRawDatabaseConnection() deathTime: DateTime = now() + initTimeInterval(days = 1) implDefaults(PoolConnection) type ConnectionPool* = object connections: seq[PoolConnection] lock: Lock var POOL {.global.}: ConnectionPool proc isEmptyPool(): bool = POOL.connections.len() == 0 proc initConnectionPool*(initialPoolSize: static int) = POOL.connections = @[] initLock(POOL.lock) withLock POOL.lock: for i in 1..initialPoolSize: POOL.connections.add(initPoolConnection()) proc borrowConnection*(): PoolConnection {.gcsafe.} = {.cast(gcsafe).}: withLock POOL.lock: if isEmptyPool(): return initPoolConnection() result = POOL.connections.pop()
{ "domain": "codereview.stackexchange", "id": 42812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, connection-pool, nim", "url": null }
multithreading, connection-pool, nim proc recycleConnection*(connection: sink PoolConnection) {.gcsafe.} = if connection.deathTime < now(): return {.cast(gcsafe).}: withLock POOL.lock: POOL.connections.add(connection) proc destroyConnectionPool*() = deinitLock(POOL.lock) Are there any glaring issues with the code above? I think this doesn't copy memory around wildly, but I could be wrong there, so please tell me if I am. Answer: Leorize from the nim discord server made a valid suggestion. The above has several issues: You make a lot of connection-creations and destructions that serve no purpose by killing a connection after a set amount of time, whether it's needed or not Use monoTime instead of Time objects, its less wasted memory and you're working with simpler objects that capture durations better A design that you can follow instead is giving the pool a fixed limit of connections that it can contain. Then also give it a "burstMode" that allows it to grow beyond that limit, but only as long as its "burstModeTimer" allows for it. That burstModeTimer is fixed to 30 minutes (set that to whatever you want) and extended every time you borrow a connection while you borrow a connection and the pool isn't overflowing. That is this way, since "burst mode" ads an entire batch of connections, which means they're only unnecessary if the pool is overflowing under normal load. While the pool is in burst mode, it will accept any connection it can get from the recycle proc. Once burst mode is over, any connection returned while it is full will just be closed and garbage collected. import ../applicationSettings import std/[times, monotimes, locks, db_sqlite] proc createRawDatabaseConnection(): DbConn = return open(applicationSettings.database, "", "", "") type ConnectionPool = object connections: seq[DbConn] lock: Lock defaultPoolSize: int burstEndTime: MonoTime isInBurstMode: bool
{ "domain": "codereview.stackexchange", "id": 42812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, connection-pool, nim", "url": null }
multithreading, connection-pool, nim var POOL {.global.}: ConnectionPool proc isPoolEmpty(): bool = POOL.connections.len() == 0 proc isPoolFull(): bool = POOL.connections.len() >= CONNECTION_POOL_SIZE proc refillPoolConnections() = withLock POOL.lock: for i in 1..POOL.defaultPoolSize: POOL.connections.add(createRawDatabaseConnection()) proc initConnectionPool*() = POOL.connections = @[] POOL.isInBurstMode = false POOL.burstEndTime = getMonoTime() POOL.defaultPoolSize = CONNECTION_POOL_SIZE initLock(POOL.lock) refillPoolConnections() proc activateBurstMode() = POOL.isInBurstMode = true POOL.burstEndTime = getMonoTime() + initDuration(minutes = 30) refillPoolConnections() proc updatePoolBurstModeState() = if not POOL.isInBurstMode: return if getMonoTime() > POOL.burstEndTime: POOL.isInBurstMode = false proc extendBurstModeLifetime() = if POOL.isInBurstMode == false: raise newException(DbError, "Tried to extend pool lifetime while Pool wasn't in burst mode, there's a logic issue") let hasMaxLifetimeDuration: bool = POOL.burstEndTime - getMonoTime() > initDuration(minutes = 30) if hasMaxLifetimeDuration: return POOL.burstEndTime = POOL.burstEndTime + initDuration(seconds = 5) proc borrowConnection(): DbConn {.gcsafe.} = {.cast(gcsafe).}: withLock POOL.lock: if isPoolEmpty(): activateBurstMode() elif not isPoolFull() and POOL.isInBurstMode: extendBurstModeLifetime() result = POOL.connections.pop() echo "After Borrow: POOL size: " & $POOL.connections.len() proc recycleConnection(connection: DbConn) {.gcsafe.} = {.cast(gcsafe).}: withLock POOL.lock: updatePoolBurstModeState() if isPoolFull() and not POOL.isInBurstMode: connection.close() else: POOL.connections.add(connection) echo "After Recycle: POOL size: " & $POOL.connections.len() proc destroyConnectionPool*() = deinitLock(POOL.lock)
{ "domain": "codereview.stackexchange", "id": 42812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, connection-pool, nim", "url": null }
multithreading, connection-pool, nim proc destroyConnectionPool*() = deinitLock(POOL.lock) template withDbConn*(connection: untyped, body: untyped) = #Borrows a database connection, executes the body and then recycles the connection block: #ensures connection exists only within the scope of this block let connection: DbConn = borrowConnection() try: body finally: recycleConnection(connection) Small usage example: withDbConn(connection): #connection is of type DbConn, which is a connection to an sqlite3 db connection.select(entries, "campaign_id.name = ?", campaignName) The template is very convenient and ideally your only public part of the module since it automatically fetches and recycles your connection for you.
{ "domain": "codereview.stackexchange", "id": 42812, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, connection-pool, nim", "url": null }
c#, game, console Title: Ping pong game (console) Question: I've made a 2 player game in c# console that is a ping pong game. I've made it in more or less 4 hours and in my opinion it is the best performing game I've made so far. Just to let you know, I am a new programmer and I've started with C# coding, as I believe it's a good beginner language. I've made a few C# console projects before, and one of them were a snake game. I hope you don't go to harsh on me, but I would love to know all of the improvements I could learn to make this and future games better! For now I am sticking to Console and in the future will dip toes into GUI coding Here's the code (Made with Visual studio 2022) Console.CursorVisible = false; int playerpos = 0; int player2pos = 0; int prevpos = 1; GameLoop(playerpos, player2pos, prevpos);
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console static void GameLoop(int playerpos, int player2pos, int prevpos) { Console.Write("When youre ready press any key!"); Console.ReadKey(); // when you ready press any key ConsoleKeyInfo cki = new ConsoleKeyInfo(); string gamestart = ""; while (gamestart != "N") { int score = 0; int lenght = 50 * 2; int height = 20 * 2; playerpos = height / 2; player2pos = height / 2; int[] ballpos = new int[] { lenght, height / 2, 1, 1 }; Board(height, lenght); int who = 0; bool game = true; while (game != false) { do { while (Console.KeyAvailable == false) { Thread.Sleep(20); score = Score(height, lenght, score, playerpos, ballpos); Player(playerpos, height, lenght, player2pos, who); ballpos = Ball(lenght, height, ballpos, playerpos, player2pos); if (ballpos[3] == 5 || ballpos[3] == 6) { game = false; break; } } if (ballpos[3] == 5 || ballpos[3] == 6) break; cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.W || cki.Key == ConsoleKey.S) { who = 1; playerpos = Move(cki, playerpos, height, player2pos); } if (cki.Key == ConsoleKey.UpArrow || cki.Key == ConsoleKey.DownArrow) { who = 2; player2pos = Move(cki, playerpos, height, player2pos); } } while (cki.Key != ConsoleKey.W || cki.Key != ConsoleKey.S || ballpos[3] != 5 || ballpos[3] != 6); } Console.Clear(); if (ballpos[3] == 5)
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console } Console.Clear(); if (ballpos[3] == 5) Console.WriteLine("Player 2 Won the game! With a score of = " + score); if (ballpos[3] == 6) Console.WriteLine("Player 1 Won the game!"); Console.WriteLine("\nDo you want to end the game? N = exit, anything else continue"); gamestart = Console.ReadLine().ToUpper(); } }
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console static void Board(int height, int lenght) { Console.SetCursorPosition(0, 0); for (int i = 0; i < height; i++){ Console.CursorVisible = false; for (int j = 0; j < lenght; j++){ if(j == lenght - 1) { Console.Write("# \n"); continue; } if(i == 0 || i == height-1) { Console.Write("##"); continue; } if((j == 0) && (i != 0 || i != height-1)) { Console.Write("# "); continue; } if(j == lenght/2 && i != 0 && i != height-1) { Console.Write("| "); continue; } if( i != 0 || i != height-1 || j != 0 ||j != lenght - 1) { Console.Write(" "); continue; } } } } static int Score(int height, int lenght, int score, int p1, int[] ballpos) { if ((ballpos[1] == p1 - 2 || ballpos[1] == p1 - 1 || ballpos[1] == p1 || ballpos[1] == p1 + 1 || ballpos[1] == p1 + 2) && (ballpos[3] == 4 && ballpos[0] == 4 || ballpos[3] == 2 && ballpos[0] == 4) && ballpos[3] != 5) score++; string scr = "Score of this game is:"; Console.CursorVisible = false; Console.SetCursorPosition(lenght - scr.Length/2, height ); Console.Write(scr); Console.SetCursorPosition( lenght - (scr.Length / 2), height + 2); Console.Write(score); return score; }
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console static void Player(int playerpos, int height, int lenght, int player2pos, int who) { if (who == 1) { for (int i = 1; i < height - 1; i++) { Console.SetCursorPosition(4, i); Console.Write(" "); } for (int i = -2; i < 3; i++) { if (playerpos + i == 0) return; Console.SetCursorPosition(4, playerpos + i); Console.Write("█"); } } else if (who == 2) { for (int i = 1; i < height - 1; i++) { Console.SetCursorPosition(lenght * 2 - 6, i); Console.Write(" "); } for (int i = -2; i < 3; i++) { if (player2pos + i == 0) return; Console.SetCursorPosition(lenght * 2 - 6, player2pos + i); Console.Write("█"); } } } static int Move(ConsoleKeyInfo cki, int playerpos, int height, int player2pos) { switch (cki.Key) { case ConsoleKey.W: if (playerpos == 3) return playerpos; playerpos--; return playerpos; case ConsoleKey.S: if (playerpos == height - 4) return playerpos; playerpos++; return playerpos; case ConsoleKey.UpArrow: if (player2pos == 3) return player2pos; player2pos--; return player2pos; case ConsoleKey.DownArrow: if (player2pos == height - 4) return player2pos; player2pos++; return player2pos; default: return playerpos; } } static int[] Ball(int lenght, int height, int[] ballpos, int playerpos, int player2pos) { Console.SetCursorPosition(ballpos[0], ballpos[1]); Console.Write(" ");
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console if(ballpos[0] == lenght) { for (int i = 1; i < height-1; i++) { Console.SetCursorPosition(lenght, i); Console.Write("|"); } } if (ballpos[1] == height - 2 && ballpos[3] == 3) // From Down -> To Up -> { ballpos[3] = 1; ballpos[2] = 1; } if (ballpos[1] == height - 2 && ballpos[3] == 4) // From Down <- To Up <- { ballpos[3] = 2; ballpos[2] = 3; } if (ballpos[1] == 1 && ballpos[3] == 1) // From Up -> To Down -> { ballpos[3] = 3; ballpos[2] = 2; } if (ballpos[1] == 1 && ballpos[3] == 2) // From Up <- To Down <- { ballpos[3] = 4; ballpos[2] = 4; } if ((ballpos[1] == player2pos - 2 || ballpos[1] == player2pos - 1 || ballpos[1] == player2pos || ballpos[1] == player2pos + 1 || ballpos[1] == player2pos + 2) && ballpos[3] == 3 && ballpos[0] == lenght*2 - 6 || (ballpos[1] == player2pos - 2 || ballpos[1] == player2pos - 1 || ballpos[1] == player2pos || ballpos[1] == player2pos + 1 || ballpos[1] == player2pos + 2) && ballpos[3] == 1 && ballpos[0] == lenght*2 - 6) // From Up -> To Up <- { if (ballpos[3] == 1) { ballpos[3] = 2; ballpos[2] = 3; } else { ballpos[3] = 4; ballpos[2] = 4; } } if (ballpos[0] == lenght * 2 - 2 && ballpos[3] == 1 || ballpos[0] == lenght * 2 - 2 && ballpos[3] == 3) // From Up -> To Up <- { ballpos[3] = 6; return ballpos; } if ((ballpos[1] == playerpos - 2 || ballpos[1] == playerpos - 1 || ballpos[1] == playerpos || ballpos[1] == playerpos + 1 || ballpos[1] == playerpos + 2) && ballpos[3] == 4 && ballpos[0] == 4 || (ballpos[1] == playerpos - 2 || ballpos[1] == playerpos - 1 || ballpos[1] == playerpos || ballpos[1] == playerpos + 1 || ballpos[1] == playerpos + 2) && ballpos[3] == 2 && ballpos[0] == 4) // From Player 1 Succsess {
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console { if (ballpos[3] == 4){ ballpos[3] = 3; ballpos[2] = 2; } else{ ballpos[3] = 1; ballpos[2] = 1;} } if(ballpos[0] == 0 && ballpos[3] == 2 || ballpos[0] == 0 && ballpos[3] == 4) // Player 1 fail { ballpos[3] = 5; return ballpos; }
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console if (ballpos[2] == 1) // Up -> { ballpos[0] += 2; ballpos[1]--; } if (ballpos[2] == 2) // Down -> { ballpos[0] += 2; ballpos[1]++; } if (ballpos[2] == 3) // Up <- { ballpos[0] -= 2; ballpos[1]--; } if (ballpos[2] == 4) // Down <- { ballpos[0] -=2 ; ballpos[1]++; } Console.SetCursorPosition(ballpos[0], ballpos[1]); Console.Write("0"); return ballpos; }
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console Answer: Structure A first step in improving the structure of the code for extensibility would be to define what the game actually is. If we consider the scenario where you will implement this game in a GUI as well, it would be desirable to split the functionality so that the game remains the same and only the input and output need to be changed. A first step would be to rename GameLoop to RunConsolePongGame. As the "game loop" typically is the while loop that handles input, game-logic, and drawing of graphics. In your case, the first while loop inside GameLoop. A second step would be to split all the logic into these three functions and when you would implement the GUI version in the future you could re-use the game-logic function straight up! Abstraction Reasons to abstract functionality (break out chunks of code into its own function under a name) is for readability and re-useability. Player "Player" would conventionally refer to some sort of class implementation, an object. As a rule of thumb; a function that has a side effect (such as drawing to a screen) and does not return a value, should always have a verb in it. DrawPlayer, FireRockets etc. It is something that is performed, a Player is just something that exists. Ball This function does two things, it draws to the console and returns a new position for the ball. This should be split into two separate implementations: DrawBall which does not return anything, and something like newBallPosition, gameTick, or newGameState, that advances the game according to the game logic. newBallPosition Would take a ball position, player positions and return a new position. gameTick or newGameState Would take player input as well as player positions and ball position and return new player positions and a new ball position. Player input This should be put in its own function and return the actions the players have taken, e.g. getPlayerInput. Example
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console Example This is pseudocode just to show an example of the structure, it is not valid code in any language. class GameState: running, ball, playerPosition1, playerPosition2
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
c#, game, console class PlayerInput: player1Up, player1Down player2Up, player2Down playerQuit def runConsolePongGame: gameState = new GameState while gameState.running payerInput = getPlayerInput() gameState = gameTick(playerInput, gameState) drawGame(gameState) As per C# style the whole game might fit better into a Game class instead which holds these functions, but I will not comment further on that and take especially the naming with a grain of salt, I am not too familiar with C# and C# conventions. Data, Objects, Classes Right now you only use primitive values in variables and arguments, such as string, int, int[], and bool. It is desirable to "clump" together variables that belong together in the same context under a specified name, such as the GameState in my example and instead of an int[] array representing the ball position you could define the ball as a class: class Ball { int x; int y; Color color; } (And color here itself refers to another class which contains color data) And you could pass an object of type Ball around instead: Ball ball = new Ball() This makes it easy to add properties (such as color) to this object that can be used everywhere the ball is referenced.
{ "domain": "codereview.stackexchange", "id": 42813, "lm_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#, game, console", "url": null }
javascript, css, sass Title: Small Bayes Calculator to learn Javascript Question: I am trying to learn UI design so I threw together a Bayes Calculator (i.e. calculate the posterior probability of being sick given a positive/negative test result using the specificity, sensitivity of the test and current incidence rate). Since I already wrote markdown for a static site generator (hugo) I similarly created a html content page which is wrapped by the hugo theme fuji. This theme did not include styling for input elements (likely because it is intended for blogpost like markdown and not html). So I had to add some custom SCSS styling (but using existing color variables). In particular I added some logic to only activate form validation styling once an input element was modified once (add the class "wasModified"). The end result looks like this:
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass I am unsure how to align the input elements. A table would work, but then I lose the wrap around on mobile putting the labels above the input fields. Are there any best practices? HTML <!--content/blog/tools/bayes-helper.html --> --- title: Bayes Helper date: "2022-01-22" tags: [maths, tools, health] draft: true --- <form id="bayes-form"> <label for="incidence">Incidence Rate</label> <input type="number", id="incidence", name="incidence", min="0", max="100000", step="1", placeholder="per 100 000", required> <br> <label for="sensitivity">Sensitivity</label> <input type="number", id="sensitivity", name="sensitivity", min="0", max="100", step=".01", placeholder="in percent", required> <br> <label for="specificity">Specificity</label> <input type="number", id="specificity", name="specificity", min="0", max="100", step=".01", placeholder="in percent", required> <br> <label for="test_positive">Test positive?</label> <input type="checkbox", id="test_positive", name="test_positive"> <br> <label for="posterior" >Likelihood to be infected:</label> <output id="posterior" name="posterior">Input not Valid</output> </form> <script> function _calculatePosterior(prior, sensitivity, specificity, test_positive) { const p_test_given_pos = test_positive ? sensitivity : 1-sensitivity if (prior==0 || p_test_given_pos == 0){ return 0 } const p_test_given_neg = test_positive ? 1-specificity : specificity return 1/(1+ p_test_given_neg*(1-prior)/(p_test_given_pos*prior)) }
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass function calculatePosterior() { this.posterior.value = _calculatePosterior( this.incidence.value/100000.0, this.sensitivity.value/100.0, this.specificity.value/100.0, this.test_positive.checked ) *100 + "%"; } document.getElementById("bayes-form").oninput = calculatePosterior document.getElementById("bayes-form").onreset = calculatePosterior function add_wasModified() { this.classList.add("wasModified"); } for (const input of document.getElementsByTagName("input")) { input.oninput = add_wasModified; } </script> SCSS // assets/scss/_custom_rules.scss // Override CSS rules with that file input { color: var(--color-font); background-color: var(--color-bg); border: 2px solid var(--color-divider); border-radius: 2px; padding: 5px; margin: 10px; &:hover { border: 2px solid var(--color-primary); }; accent-color: var(--color-primary); } input.wasModified:invalid { border: 2px solid $border-red-light; } button { color: var(--color-font); background-color: var(--color-codebg); border-color: var(--color-primary); border-radius: 2px; }
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass Appendix: Math For those interested (on request). So "sensitivity" is the likelihood of a test being positive conditional on truly having the condition, let us denote this by $$P(\text{test_p}|\text{pos})$$ "Specificity" is the likelihood of a test being negative conditional on not having the condition (being negative), denoted by $$P(\text{test_n} | \text{neg})$$ Now we want to know the probability of having the condition conditional on the test result, i.e. $$\begin{align} P(\text{pos}|\text{test}) &= \frac{P(\text{pos}, \text{test})}{P(\text{test})} = \frac{P(\text{test}| \text{pos}) P(\text{pos})}{P(\text{test}, \text{pos}) +P(\text{test},\text{neg})}\\ &=\frac{ P(\text{test}| \text{pos})P(\text{pos}) }{ P(\text{test}| \text{pos})P(\text{pos}) +P(\text{test}|\text{neg})(1-P(\text{pos})) }\\ &=\frac{1}{1+\frac{ P(\text{test}|\text{neg})(1-P(\text{pos})) }{ P(\text{test}| \text{pos})P(\text{pos})} } \end{align}$$ Okay so what do we need to calculate this. First of all we need the prior probability to have the condition (before doing the test), P(pos), this is the incidence rate. For the two conditional probabilities we need we just need to look at specificity and sensitivity. For a positive test result we have $$\begin{align} P(\text{test} | \text{pos}) &= P(\text{test_p} | \text{pos}) =\text{specificity}\\ P(\text{test} | \text{neg}) &= P(\text{test_p} | \text{neg}) = P(\text{test_n} | \text{neg}) = 1-\text{sensitivity} \end{align}$$ for a negative test result we have $$\begin{align} P(\text{test} | \text{pos}) &= P(\text{test_n} | \text{pos}) = 1- \text{specificity}\\ P(\text{test} | \text{neg}) &= P(\text{test_n} | \text{neg}) = \text{sensitivity} \end{align}$$ This explains the ternary operator. Then you just need to do some considerations for the probability zero cases and you just need to type up the algorithm.
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass Answer: UX Overall, fine. Good use of labels. Getting an invalid input error off the bat is a bit jarring. Consider formatting the result to a readable number of decimal places (say, 2) unless you have good reason to be more precise. Code style In general, try to stick to conventions and be consistent. JS JS uses camelCase rather than snake_case (p_test_given_pos). add_wasModified uses a mix and isn't a style I see much of in JS. Add space between operators: if (prior==0 || p_test_given_pos == 0){ should have prior == 0. return 1/(1+ p_test_given_neg*(1-prior)/(p_test_given_pos*prior)) is clearer with intermediate variables and spaces around operators. These are good variable names, though. Use === always. == does confusing type coercions so it can easily lead to bugs. Always using === eliminates all of these bugs and improves readability by making intent explicit (explicitly coerce when necessary). Stick to using semicolons after every statement or skip them entirely except when necessary. It's more common to use them. Once again, it eliminates a whole class of bugs, quickly becomes second nature, and isn't really less "clean" looking in my opinion. I doubt it impacts development speed meaningfully. See Do you recommend using semicolons after every statement in JavaScript? I'm not sure why _calculatePosterior has a leading underscore. I guess because it's a "private" helper function for calculatePosterior, which does DOM interaction and formatting. It's good to separate the two, but maybe choose clearer variable names. For the handler, you can use handlePosteriorRecalculation (since it's an event handler) and calculatePosterior for the non-I/O math. I typically see leading underscores for private class methods and variables, neither of which applies here. JS usually uses 2-space indentation. I see 4 from time to time, so it's a minor point. CSS
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass CSS CSS names usually use kebab-case, so wasModified would be was-modified (I'd just call it modified though). But you got it right with bayes-form (although "form" might be redundant -- maybe form.bayes-calculator is clearer? I don't know the best practice here). Your SCSS structure looks fine but perhaps move accent-color: var(--color-primary); up above the &hover block. In a larger app, scope your CSS selectors specifically: .bayes-calculator input instead of input. HTML In the HTML, type="number", id="incidence", ... shouldn't have commas. I don't like long HTML lines for the same reason as long code lines. I suggest: <input type="number" id="incidence" name="incidence" min="0" max="100000" step="1" placeholder="per 100 000" required > Don't use <br> for styling; it's inflexible and semantically conflates structure (HTML) with style (CSS). Prefer CSS's margin-bottom and display: block or similar. If these are block lines, wrap them in <div>s or wrap the <label> around the <input> instead of using for=. <br> is only for breaks in <p> elements, as in an address. See When to use <p> vs. <br>. Code design There's not much of an app to speak of design, so this is premature, but... Usually, functions with a flag that switches between multiple behaviors is poor design. This has been given comprehensive treatment elsewhere, so I'll just point the way: Is it wrong to use a boolean parameter to determine behavior?. TL;DR quote from the top answer in the link: Yes, this is likely a code smell, which would lead to unmaintainable code that is difficult to understand and that has a lower chance of being easily re-used.
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass The solution is to break positive and negative into two separate functions, then call a third function for the shared math logic to keep that DRY. Your use of oninput and onreset has a thread on Stack Overflow as well: addEventListener vs onclick. I'd prefer addEventListener, but oninput seems acceptable here. I also prefer not to use this to refer to a form. Possible rewrite const calculatePosterior = (prior, pTestGivenPos, pTestGivenNeg) => prior === 0 || pTestGivenPos === 0 ? 0 : 1 / (1 + pTestGivenNeg * (1 - prior) / (pTestGivenPos * prior)) ; const calculatePositivePosterior = (prior, sensitivity, specificity) => calculatePosterior(prior, sensitivity, 1 - specificity) ; const calculateNegativePosterior = (prior, sensitivity, specificity) => calculatePosterior(prior, 1 - sensitivity, specificity) ; const handlePosteriorRecalculation = ({target: {form}}) => { const posteriorFn = form["test-positive"].checked ? calculatePositivePosterior : calculateNegativePosterior ; form.posterior.value = posteriorFn( +form.incidence.value / 100000, +form.sensitivity.value / 100, +form.specificity.value / 100, ) * 100 + "%"; }; const bayesForm = document.getElementById("bayes-form"); bayesForm.addEventListener("input", handlePosteriorRecalculation); bayesForm.addEventListener("reset", handlePosteriorRecalculation);
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
javascript, css, sass for (const input of document.getElementsByTagName("input")) { input.addEventListener("input", () => input.classList.add("modified")); } <form id="bayes-form"> <div> <label for="incidence">Incidence Rate</label> <input type="number" name="incidence" id="incidence" min="0" max="100000" step="1" placeholder="per 100 000" required > </div> <div> <label>Sensitivity <input type="number" id="sensitivity" name="sensitivity" min="0" max="100" step=".01" placeholder="in percent" required > </label> </div> <div> <label for="specificity">Specificity</label> <input type="number" name="specificity" id="specificity" min="0" max="100" step=".01" placeholder="in percent" required > </div> <div> <label for="test-positive">Test positive?</label> <input type="checkbox" name="test-positive" id="test-positive" > </div> <div> <label for="posterior">Likelihood to be infected:</label> <output name="posterior" id="posterior"> Input not Valid </output> </div> </form>
{ "domain": "codereview.stackexchange", "id": 42814, "lm_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, css, sass", "url": null }
c++, heap Title: Binary Heap Structure Class C++ Question: I wrote a binary heap structure class in C++. It is a templated class with a comparison type as one of the template parameters to allow for a min or max heap. I have not written anything in C++ in a bit and I am primarily looking for feedback on whether I am using obsolete practices, generally incorrectly using try/throw/catch, missed opportunity on qualifiers/tags, or anything of the sort. Any feedback pertinent to general C++ usage and the specific heap structure implementation would be amazing. Thank you in advance. #pragma once #include <functional> #include <iostream> #include <stdexcept> #include <vector> template <typename T, typename C=std::greater<T>> // by default a max heap class Heap { public: Heap() = default; ~Heap() = default; void insert(T value); T top() const; void remove_top(); template <typename _T, typename _C> friend std::ostream& operator<<(std::ostream &cout, const Heap<_T, _C> &_heap); private: void switch_elements(size_t index1, size_t index2); void sift_down(size_t index); void sift_up(size_t index); std::vector<T> container; }; template <typename T, typename C> void Heap<T, C>::insert(T value) { container.push_back(value); sift_up(container.size() - 1); } template <typename T, typename C> T Heap<T, C>::top() const { try { if (container.empty()) throw std::out_of_range("ERROR: The heap is empty!"); } catch (const std::out_of_range &err) { std::cerr << err.what() << '\n'; } return container[0]; }
{ "domain": "codereview.stackexchange", "id": 42815, "lm_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++, heap", "url": null }
c++, heap template <typename T, typename C> void Heap<T, C>::remove_top() { try { if (container.empty()) throw std::out_of_range("ERROR: The heap is empty! Cannot remove an element."); } catch (const std::out_of_range &err) { std::cerr << err.what() << '\n'; } container.front() = container.back(); container.pop_back(); if (!container.empty()) sift_down(0); } template <typename T, typename C> std::ostream& operator<<(std::ostream &cout, const Heap<T, C> &_heap) { for (const T &elem : _heap.container) cout << elem << ' '; return cout; } template <typename T, typename C> void Heap<T, C>::switch_elements(size_t index1, size_t index2) { T temp = container[index1]; container[index1] = container[index2]; container[index2] = temp; } template <typename T, typename C> void Heap<T, C>::sift_down(size_t index) { C compare; size_t left_child_index = index * 2 + 1; size_t right_child_index = index * 2 + 2; size_t target_index = index; if (left_child_index < container.size() && compare(container[left_child_index], container[target_index])) target_index = left_child_index; if (right_child_index < container.size() && compare(container[right_child_index], container[target_index])) target_index = right_child_index; if (index != target_index) { switch_elements(target_index, index); sift_down(target_index); } } template <typename T, typename C> void Heap<T, C>::sift_up(size_t index) { if (index == 0) return; C compare; size_t parent_index = (index - 1) / 2; if (compare(container[index], container[parent_index])) { switch_elements(index, parent_index); sift_up(parent_index); } } ```
{ "domain": "codereview.stackexchange", "id": 42815, "lm_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++, heap", "url": null }
c++, heap Answer: Consider using the standard library's heap functions As slepic already mentioned, C++ has functions to manipulate heaps. However, these are just free functions that manipulate other containers, and nothing prevents you from destroying the heap property. So implementing your own heap class that strictly enforces the heap property might be beneficial. Still, you can use standard library functions inside your class's member functions, like std::push_heap(). Of course, ignore this advice if you want to practice implementing heap manipulating algorithms yourself. Avoid declaring constructors/destructors unnecessarily You don't have to declare the constructor and destructor if they don't do anything, not even using = default. See the rule of zero. Consider following the naming conventions of STL containers While some of your member function names match those of the STL containers, remove_top() does not. Consider giving your class the same interface as std::stack(), so push() instead of insert(), and pop() instead remove_top(). Also consider adding an emplace() function to allow pushing a new element with potentially less copying: template<typename... Args> void emplace(Args&&... args) { container.emplace_back(std::forward<Args>(args)...); sift_up(container.size() - 1); } Pass values by reference where appropriate Your insert() function takes its parameter by value, which means a copy will be made. Similarly, your top() returns by value, which also makes a copy. Make those functions pass by const reference instead: void push(const T& value); const T& top() const;
{ "domain": "codereview.stackexchange", "id": 42815, "lm_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++, heap", "url": null }
c++, heap You don't have to change anything in the body of those functions. If you look at std::stack::push(), you'll notice it has two forms; one takes a const reference, the other takes an r-value reference. The latter makes it possible to efficiently move values into your container. Consider adding that overload as well: void push(T&& value) { container.push_back(std::move(value)); sift_up(container.size() - 1); } Remove the operator<<() I recommend that you remove the operator<<() function. The reason is that it is very likely that it will not do what the caller wants. There are many ways to format a list of items; space separated is just one, but someone might want comma separated, or every entry on one line. Also consider that the output is ambiguous if individual elements, when printed, might contain spaces (consider a Heap<std::string> for example). Also consider that you are printing things in the order in which they appear in the container, when the caller might want to see the elements in sorted order. Just remove this responsibility from your class, and leave it up to the caller to format the output. Write std::size_t instead of size_t The C++ standard defines size_t to be inside the std namespace. Don't rely on bare size_t working, as this is implementation defined behavior. Use std::swap() You don't need to write your own switch_elements(), std::swap() can easily swap two elements of a container. For example: std::swap(container[target_index], container[index]); Allow the comparator function to be specified in the constructor Merely storing the type of the comparator as a template parameter is not enough to allow all possible types of comparator functions to be used. Consider passing a lambda function with captures: auto compare = [i = 3](int& a, int& b){ return a + i < b; } Heap<int, decltype(compare)> heap; // lambda closure type has a deleted default constructor
{ "domain": "codereview.stackexchange", "id": 42815, "lm_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++, heap", "url": null }
c++, heap You should allow the comparator to be specified in the constructor: template <typename T, typename C = std::greater<T>> class Heap { C compare; public: Heap(const C& compare = C()): compare(compare) {} ... }; Now the above lambda can be passed as the comparator function like so: Heap<int, decltype(compare)> heap(compare); Don't catch your own exceptions Your functions that throw also catch their own exceptions, causing an error to be written to std::cerr, but then dereferencing the out-of-range element still happens, leading to undefined behavior. Don't catch your own exceptions, let the caller handle them if so desired.
{ "domain": "codereview.stackexchange", "id": 42815, "lm_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++, heap", "url": null }
python, programming-challenge, pandas Title: Extract and write fasta files using Biopython based on input from another file Question: I have the below code that takes a sequence file and another file with a list of contigs and extracts the sequences and writes them to a file, specifically based on the file with the contig list. The code works great.. However, I'm having to do SeqIO.parse('SAMPLE.fasta', 'fasta') inside the for-loop every time making it very slow. If I read the file in earlier using a variable, eg. sample_f (see commented out line), it fails to identify the records. from Bio import SeqIO import pandas as pd genomes_l = pd.read_csv('test_data.tsv', sep='\t', header=None, names=['anonymous_gsa_id', 'genome_id']) # sample_f = SeqIO.parse('SAMPLE.fasta', 'fasta') for i, r in genomes_l.iterrows(): genome_name = r['anonymous_gsa_id'] genome_ids = r['genome_id'].split(',') genome_contigs = [rec for rec in SeqIO.parse('SAMPLE.fasta', 'fasta') if rec.id in genome_ids] print(genome_contigs) with open(f'out_dir/{genome_name}_contigs.fasta', 'w') as handle: SeqIO.write(genome_contigs, handle, 'fasta') Would appreciate your help in improving this. Thank you! Update: adding examples as suggested The contigIDs are comma-separated within the second column (example below) 424182.1 H|S1|C933685,H|S1|C449562,H|S1|C172291,H|S1|C1169825 1217675.1 H|S1|C1168525,H|S1|C573086,H|S1|C357867,H|S1|C85072,H|S1|C965427,H|S1|C1724718 585503.1 H|S1|C874141,H|S1|C529585 I have another file called SAMPLE.fasta that contains contigIDs and the respective sequences in the next line for each contigID (example below) >H|S1|C933685 GAAAGTTCTTGACCTGTGGACAGGCTGTGAATCGGGTTGGACAAGT >H|S1|C85072 GGAAACGGCTGCTGCCATCCTTGCCCTTCGCCCAAG >H|S1|C965427 CTCAAGAAATTCGGTATCACCGGTAACTATGAGGCAGTCGAGGTCG etc... etc... etc..
{ "domain": "codereview.stackexchange", "id": 42816, "lm_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, programming-challenge, pandas", "url": null }
python, programming-challenge, pandas Based on this information, I would like to create a separate file for each genomeID (example(s) below) Output_file: 424182.1.fasta >H|S1|C933685 GAAAGTTCTTGACCTGTGGACAGGCTGTGAATCGGGTTGGACAAGT Output_file: 1217675.1.fasta >H|S1|C85072 GGAAACGGCTGCTGCCATCCTTGCCCTTCGCCCAAG >H|S1|C965427 CTCAAGAAATTCGGTATCACCGGTAACTATGAGGCAGTCGAGGTCG Answer: SeqIO.parse streams through records one at a time, but it doesn't store them, which is why it doesn't work when you do it outside the loop. This is handy when you have giant files (saves a lot of memory), and in general it lets you pick the best storage solution for the task at hand (if you need to store things at all). In this case, you want to look things up by their ids, so a python dictionary is probably the best option. If you put the following outside the loop: contig_lookup = {record.id: record for record in SeqIO.parse('SAMPLE.fasta', 'fasta')} And then change your contig lookup: genome_contigs = [contig_lookup[_id] for _id in genome_ids if _id in contig_lookup] You should get a decent speedup.
{ "domain": "codereview.stackexchange", "id": 42816, "lm_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, programming-challenge, pandas", "url": null }
c++, design-patterns, abstract-factory Title: Abstract Factory in C++ Question: I have tried my hand at the abstract factory pattern in C++: #include <iostream> class AbstractFactory; class AbstractDoor; class AbstractWindow; class AbstractDoor; class AbstractFactory { public: virtual AbstractWindow* buildWindow() = 0; virtual AbstractDoor* buildDoor() = 0; }; class AbstractDoor { public: virtual void identify() = 0; }; class WoodDoor : public AbstractDoor { public: void identify() override { std::cout << "This is a wooden door" << std::endl; } }; class GumDoor: public AbstractDoor { public: void identify() override { std::cout << "This is a gum door" << std::endl; } }; class AbstractWindow { public: virtual void identify() = 0; }; class WoodWindow : public AbstractWindow { public: void identify() override { std::cout << "This is a wooden window" << std::endl; } }; class GumWindow : public AbstractWindow { public: void identify() override { std::cout << "This is a gum window" << std::endl; } }; class GumFactory : public AbstractFactory { public: AbstractWindow* buildWindow() override { auto* window = new GumWindow(); return window; } AbstractDoor* buildDoor() override { auto* door = new GumDoor(); return door; } }; class WoodFactory : public AbstractFactory { public: AbstractWindow* buildWindow() override { return new WoodWindow(); } AbstractDoor* buildDoor() override { return new WoodDoor(); } }; int main() { std::cout << "Let's build a wooden window!" << std::endl; WoodFactory woodfac = WoodFactory(); AbstractWindow* woodwindow = woodfac.buildWindow(); woodwindow->identify(); std::cout << "Let's build a gum door!" << std::endl; GumFactory gumfac = GumFactory(); AbstractDoor* gumdoor = gumfac.buildDoor(); gumdoor->identify(); return 0; } Questions:
{ "domain": "codereview.stackexchange", "id": 42817, "lm_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, abstract-factory", "url": null }
c++, design-patterns, abstract-factory return 0; } Questions: Is the Abstract Factory Pattern correctly implemented? I'm probably not using any of the newer features (C++14) I should be using as I haven't touched C++ in more than a decade. What can be done to improve the code? I would appreciate pointers in any and all directions. Answer: Decide Which Pattern You are Implementing Do you actually want an abstract factory type that can hold different types of factories? Are you going to need, say, a hash table that looks up factories of different types and returns a polymorphic reference to an abstract factory object? Are these factories going to need instance data, or should they be singletons with static methods? Or is what you want a specific type of factory that can return abstracted references to an interface? Would a templated singleton work for you just as well? If you do want the pattern you implemented here, with polymorphic abstract factory interfaces, I’ll implement it after the simpler versions. Use Smart Pointers, not new Currently, your factory objects all look something like return new WoodWindow();
{ "domain": "codereview.stackexchange", "id": 42817, "lm_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, abstract-factory", "url": null }
c++, design-patterns, abstract-factory These references must be manually managed.. They leak if you ever forget to free them. They’ll corrupt the heap if you free them twice. You can’t use a different allocator, for example if you need each thread in the program to allocate from its own local pool. Any class that contains a reference from the factory cannot use the default destructor, copy constructor or assignment. In fact, as I’ll get to, the only reason your program doesn’t crash with a memory leak or corruption bug (that’d be a real pain to find) is that you never bothered to free any of your memory. More on this later. If your class has very little per-instance data or is moveable, it’s efficient to return a temporary of the class and assign it. Here, you cannot, because you explicitly want a polymorphic pointer. Therefore, your want to return a std::unique_ptr<AbstractWindow> or a std::unique_ptr<AbstractDoor>. This factory function is already in the STL, in >memory>. const std::unique_ptr<AbstractWindow> upWoodWindow = std::make_unique<WoodWindow>(); Unlike an abstract factory, this could create the object using a constructor specific to that type of window, and store it in an abstract pointer, such as the hypothetical: std::make_unique<WoodWindow>( WoodWindow::teak, WoodWindow::shutters );
{ "domain": "codereview.stackexchange", "id": 42817, "lm_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, abstract-factory", "url": null }
c++, design-patterns, abstract-factory Any object that contains one of these smart pointers will automatically free its memory when it’s destroyed. A class that contains only smart pointers, and not raw pointers created with new (or C-style resource allocations) can use the implicit destructor, and it will just work. If you need some other type of pointer, you could create it by assigning from std::unique_ptr. For example, one tricky thing about a unique_ptr is that you cannot copy them—there is supposed to be one and only one in existence at any given time! So you might instead want a std::shared_ptr, which keeps a reference count and destroys the object only when there are no reference left. You can get one of those with: const std::shared_ptr<const AbstractDoor> spGumDoor = std::make_unique<GumDoor>(); Or if you want a polymorphic object reference: const std::unique_ptr<AbstractWindow> upWindow = std::make_unique<WoodWindow>(); auto& woodWindow = *upWindow; // Reference to AbstractWindow. upWindow->identify(); woodWindow.identify();
{ "domain": "codereview.stackexchange", "id": 42817, "lm_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, abstract-factory", "url": null }