text stringlengths 1 2.12k | source dict |
|---|---|
html, web-scraping, xpath, xslt
"meta": ["ATTORNEY TO BE NOTICED"]
},
{
"address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-496-4083\nEmail: rshulman@wsgr.com",
"name": "Ron E Shulman",
"meta": []
},
{
"address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16505655100",
"name": "Stephen J Ferenchick",
"meta": []
},
{
"address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 16505655100",
"name": "Theresa E Norton",
"meta": []
},
{
"address": "Wilson Sonsini Goodrich & Rosati\n650 Page Mill Road\nPalo Alto, CA 94304-1050\n650-493-9300\nFax: 650-493-9300",
"name": "Tung-On Kong",
"meta": []
},
{
"address": "McDermott Will Emery\n3150 Porter Drive\nPalo Alto, CA 94304-1212\n650/813-5000\nFax: 650/813-5000",
"name": "Vera M Elson",
"meta": []
}],
"name": "Broadcom Corporation"
}],
"Counter Defendant": [
{
"represented by": [
{
"address": "Patton & Tidwell\n4605 Texas Blvd\nPO Box 5398\nTexarkana, TX 75505-5398\n903/792-7080\nFax: 19037928233\nEmail: nickpatton@texarkanalaw.com\n",
"name": "Nicholas H Patton",
"meta": ["LEAD ATTORNEY", "ATTORNEY TO BE NOTICED"]
},
{
"address": "Law Offices of J. Thad Heartfield\n2195 Dowlen Rd\nBeaumont, TX 77706\n409/866-3318\nFax: 14098665789\nEmail: thad@jth-law.com\n",
"name": "J Thad Heartfield",
"meta": ["ATTORNEY TO BE NOTICED"]
}, | {
"domain": "codereview.stackexchange",
"id": 42876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, web-scraping, xpath, xslt",
"url": null
} |
html, web-scraping, xpath, xslt
"meta": ["ATTORNEY TO BE NOTICED"]
},
{
"address": "McDermott Will & Emery\n3150 Porter Drive\nPalo Alto, Ca 94304\n650/813-500\nFax: 16508135100\n",
"name": "Andrew S Dallmann",
"meta": ["ATTORNEY TO BE NOTICED"]
},
{
"address": "McDermott Will & Emery\n3150 Porter Drive\nPalo Alto, Ca 94304\n650/813-500\nFax: 16508135100\n",
"name": "Robert J Blanch",
"meta": ["ATTORNEY TO BE NOTICED"]
}],
"name": "Broadcom Corporation"
}],
"Defendant": [
{
"represented by": [
{
"address": "Young Pickett & Lee\n4122 Texas Blvd\nPO Box 1897\nTexarkana, TX 75504-1897\n903/794-1303\nFax: 19037925098\nEmail: dyoung@youngpickettlaw.com\n",
"name": "Damon Michael Young",
"meta": ["TERMINATED: 01/28/2002",
"LEAD ATTORNEY",
"ATTORNEY TO BE NOTICED"
]
},
{
"address": "Fish & Richardson - San Diego\n12390 El Camino Real\nSan Diego, CA 92130\n858/678-5070\nFax: 858/678-5099\nEmail: skale@fr.com",
"name": "Andrew D Skale",
"meta": []
},
{
"address": "Fish & Richardson\n4350 La Jolla Village Drive\nSuite 500\nSan Diego, Ca 92122\n858-678-5070\nFax: 18586785099",
"name": "Daniel T Pascucci",
"meta": []
},
{
"address": "Fish & Richardson\n12390 El Camino Real\nSan Diego, CA 92130\n858-678-5070\nFax: 18586785099\nEmail: shuman@fr.com",
"name": "David S Shuman",
"meta": []
},
{ | {
"domain": "codereview.stackexchange",
"id": 42876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, web-scraping, xpath, xslt",
"url": null
} |
html, web-scraping, xpath, xslt
"name": "David S Shuman",
"meta": []
},
{
"address": "Provost Umphrey - Dallas\n3232 McKinney Ave\nSuite 700\nDallas, TX 75204\n214/744-3000\nFax: 12147443015\nEmail: jkendall@provostumphrey.com",
"name": "Elton Joe Kendall",
"meta": []
},
{
"address": "McKool Smith - Dallas\n300 Crescent Court\nSuite 1500\nDallas, TX 75201\n214/978-4000\nFax: 12149784044\nEmail: gchambers@mckoolsmith.com",
"name": "Garret Wesley Chambers",
"meta": []
},
{
"address": "Intel Corporation\n2200 Mission College Blvd SC4-202\nSanta Clara, Ca 95052\n408/765-4493\nFax: 14087655175",
"name": "Janet Craycroft",
"meta": []
},
{
"address": "Fish & Richardson\n3300 Dain Rauscher Plaza\n60 South Sixth Street\nMinneapolis, Mn 55402\n612/335-5070\nFax: 16122889696\nEmail: dragseth@fr.com",
"name": "John A Dragseth",
"meta": []
},
{
"address": "Fish & Richardson - San Diego\n12390 El Camino Real\nSan Diego, CA 92130\n858-678-5070\nFax: 18586785099\nEmail: gartman@fr.com",
"name": "John E Gartman",
"meta": []
},
{
"address": "Fish & Richardson - San Diego\n12390 El Camino Real\nSan Diego, CA 92130\n858/678-5070\nFax: 858/678-5099\nEmail: thornburgh@fr.com",
"name": "John W Thornburgh",
"meta": []
},
{
"address": "Fish & Richardson\n4350 La Jolla Village Drive\nSuite 500\nSan Diego, Ca 92122\n858-678-5070\nFax: 18586785099",
"name": "Justin M Barnes",
"meta": []
},
{ | {
"domain": "codereview.stackexchange",
"id": 42876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, web-scraping, xpath, xslt",
"url": null
} |
html, web-scraping, xpath, xslt
"name": "Justin M Barnes",
"meta": []
},
{
"address": "Young Pickett & Lee\n4122 Texas Blvd\nPO Box 1897\nTexarkana, TX 75504-1897\n903/794-1303\nFax: 19037945098\nEmail: wlancelee@aol.com\n",
"name": "Lance Lee",
"meta": ["TERMINATED: 01/28/2002"]
},
{
"address": "Keker & Van Nest\n710 Sansome St\nSan Francisco, CA 94111\n415/391-5400\nFax: 14153977188",
"name": "Lloyd A Farnham",
"meta": []
},
{
"address": "Fish & Richardson - Dallas\n1717 Main St.\nSuite 5000\nDallas, TX 75201\n(214)747-5070\nFax: 12147472091\nEmail: mbjohnson@fr.com",
"name": "Michael Brett Johnson",
"meta": []
},
{
"address": "Keker & Van Nest\n710 Sansome St\nSan Francisco, CA 94111\n415/391-5400\nFax: 14153977188\nEmail: rvn@kvn.com",
"name": "Robert A Van Nest",
"meta": []
},
{
"address": "Attorney at Law\nP O Box O\nMarshall, TX 75671\n903/927-2111\nFax: 19039272622\nEmail: sbaxter@mckoolsmith.com\n",
"name": "Samuel Franklin Baxter",
"meta": ["ATTORNEY TO BE NOTICED"]
},
{
"address": "Fish & Richardson - San Diego\n12390 El Camino Real\nSan Diego, CA 92130\n858-678-4343\nEmail: sproul@fr.com",
"name": "Seth M Sproul",
"meta": []
},
{
"address": "Keker & Van Nest\n710 Sansome St\nSan Francisco, CA 94111\n415/391-5400\nFax: 14153977188",
"name": "Stuart L Gasner",
"meta": []
},
{ | {
"domain": "codereview.stackexchange",
"id": 42876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, web-scraping, xpath, xslt",
"url": null
} |
html, web-scraping, xpath, xslt
"name": "Stuart L Gasner",
"meta": []
},
{
"address": "Fish & Richardson - Dallas\n1717 Main St\n5000 Bank One Center\nDallas, TX 75201\n214/747-5070\nFax: 12147472091\nEmail: melsheimer@fr.com\n",
"name": "Thomas M Melsheimer",
"meta": ["ATTORNEY TO BE NOTICED"]
}],
"name": "Intel Corporation"
}],
"Amicus": [
{
"represented by": [
{
"address": "Cox and Smith\n112 E. Pecan Street\nSuite 1800\nSan Antonio, TX 78205-1521\nPRO SE",
"name": "Gail Peterson",
"meta": []
}],
"name": "Gail Peterson"
}]
},
"flags": ["CLOSED", "FRC", "JURY", "MEDIATION"]
} | {
"domain": "codereview.stackexchange",
"id": 42876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, web-scraping, xpath, xslt",
"url": null
} |
html, web-scraping, xpath, xslt
Answer: I think you're trying to do too much in one transformation. Start by splitting the problem into two phases: an up-conversion phase where you get the input document into sensible shape, followed by an extraction phase where you extract the information you're looking for. This approach will simplify the problem, and the first phase is reusable for when you want to extract something different.
The intermediate "up-converted" form could be JSON or XML, or you could do XML to JSON conversion as another processing phase between the other two. The more you can split your complex task into a sequence of simpler tasks, the easier it will be.
I can't see where the problem with "mode" arose, but then I'm not sure whether the XSLT code shown is before or after the change you describe. SaxonJS, however, is less "smart" about apply-templates than SaxonJ, it's more inclined to do a complete search of all the template rules in the chosen mode. This might be the issue, but I don't see a large number of template rules, so I may have got the wrong end of the stick.
It's unclear to me, reading your post again, whether this is a problem in achieving the functionality required, or in writing good XSLT code to achieve it, or in achieving improved performance. In short, it's not really clear what your problem is: perhaps you need to address one concern at a time. | {
"domain": "codereview.stackexchange",
"id": 42876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, web-scraping, xpath, xslt",
"url": null
} |
java
Title: Is this a good example of the composite pattern?
Question: I am studying the composite pattern and have created a very simple project that uses composite to introduce family members. I have decided to go with the 'fully transparent' implementation by defining all of my common functions in the interface class, I feel this is the neatest implementation and am considering throwing an exception in Leaf classes if client tries to call add / remove...
Below are the sample classes I have created. I would like to get some thoughts on how I implemented.
Am I implementing composite correctly?
Is this a good piece of sample code?
Thoughts on throwing an exception in leaf class for un-needed function implementations like add / remove Person?
Client class
public class Client {
public static void main(String args[]) {
Person gretchen = new Parent("gretchen", 101);
Person steve = new Parent("Steve", 57);
Person mary = new Parent("Mary", 56);
Person timmy = new Child("Timmy", 10);
Person molly = new Child("Molly", 5);
gretchen.add(steve);
gretchen.add(mary);
steve.add(timmy);
steve.add(molly);
mary.add(timmy);
mary.add(molly);
//introduces entire family
gretchen.introduce();
}
}
Component Class
public interface Person {
public String getName();
public int getAge();
public int getNumOfChildren();
public void add(Person person);
public void remove(Person person);
public void introduce();
}
Composite class
public class Parent implements Person {
private String name;
private int age;
private List<Person> children = new ArrayList<Person>();
public Parent(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() { | {
"domain": "codereview.stackexchange",
"id": 42877,
"lm_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",
"url": null
} |
java
public void introduce() {
System.out.println("Hi, I am ".concat(getName()));
System.out.println("I am ".concat(Integer.toString(getAge()).concat(
" years old")));
System.out.println("I have ".concat(Integer.toString(children.size()).concat(" kids.")));
System.out.println("Children... introduce your selves!");
for (Person person : children) {
person.introduce();
}
}
@Override
public String getName() {
return this.name;
}
@Override
public int getAge() {
return this.age;
}
@Override
public int getNumOfChildren() {
return this.children.size();
}
@Override
public void add(Person person) {
children.add(person);
}
@Override
public void remove(Person person) {
children.remove(person);
}
}
Leaf class
public class Child implements Person {
private String name;
private int age;
public Child(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void introduce() {
System.out.println("Hi, I am ".concat(getName()));
System.out.println("I am ".concat(Integer.toString(getAge()).concat(
" years old")));
}
@Override
public String getName() {
return this.name;
}
@Override
public int getAge() {
return this.age;
}
@Override
public int getNumOfChildren() {
return 0;
}
@Override
public void add(Person person) {
// no implementation here, throw exception maybe?
}
@Override
public void remove(Person person) {
// no implementation here, throw exception maybe?
}
}
Answer:
Am I implementing composite correctly. | {
"domain": "codereview.stackexchange",
"id": 42877,
"lm_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",
"url": null
} |
java
}
}
Answer:
Am I implementing composite correctly.
Although you are doing it correctly, a part of me wonders if it was the correct solution for you problem. The reason I ask is because a interface usually means that each method that you define is going to need to be implemented differently for each sub class that implements it. In your case it doesn't matter what type of person you have they will always introduce themselves the same way, and they will always say their name the same way, and they will always tell their age the same way. That being said an abstract class would have been a better choice because the basics will be the same for both parent and child (and even if you decide to add another branch of a person) for things such as their name, and age. The introduction would possibly be the only exception if you added a culture to this mixture. Since different cultures introduce themselves differently in almost all scenarios that would be a good candidate for a interface.
Is this a good piece of sample code?
The code appears to be in good order. It is easy to read and easy to understand. My only issue (and it is debatable) is having the age part of the constructor. In this context it makes sense, but when i first introduce my self to someone I don't say, "Hi my name is Robert Snyder, I'm 30 years old". Instead I just introduce my self as "Robert" but judging by the context of your code it might be fair to have the age (such as in the case of the entrance to a liquor store, they want your id which has your name and age)
Thoughts on throwing an exception in leaf class for un-needed function implementations like add / remove Person?
No. Never. Only in the higher levels do you want that to happen. This forces the user to use child classes. If your child classes are "dangerous" then people will either make their own, or not use yours. | {
"domain": "codereview.stackexchange",
"id": 42877,
"lm_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",
"url": null
} |
php, sql
Title: Is this a good way to process an order? (SQL+PHP)
Question: I'm making a simple webshop, it's not the full code, there are more security procedures. I'm just want to know your opinions. Thank you.
These SQL tables I have:
(I have more column in this table this is just an example)
customers:
id
name
phone
address
zip
city
country
o_date
1
Test
12345
Test Adress
1234
Test City
Test Country
01-02-2022
orders
customerid
orderid
orderdate
total_price
1
OS1
01-02-2022
19
orderitems
id
orderid
productid
item_price
1
OS1
P1
19
shipping
orderid
shipping_method
shipping_price
tracking_id
status
sent_date
OS1
courier
0
12345
sent
02-01-2022
products
product_id
productprice
currency
productqty
productname
weight
P1
19
19
USD
1
Test Product | {
"domain": "codereview.stackexchange",
"id": 42878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql",
"url": null
} |
php, sql
You must have noticed that I have 3 times the price of the order/product in the tables. The reason why is in the products table I have the current product price this can be changed, and in the another tables I have the product price which was at the time of ordering.
After submitting the form the customer will land on this page:
order.php
/// Insert into customers table
$data = [
'name' => $name,
'phone' => $phone,
'adress' => $adress,
'zip' => $zip,
'city' => $city,
'country' => $country,
'o_date' => $date
];
$sqlinsertcustomer = "INSERT INTO customers (id, name, phone, adress, zip, city, country, o_date ) VALUES ( '', :name, :phone, :adress, :zip, :city, :country, :o_date)";
$stmt = $conn->prepare($sqlinsertcustomer);
$stmt->execute($data);
$last_id = $conn->lastInsertId();
$order_id = "OS". $last_id;
/// Get the total price from the actual product.
$stmtpprice = $conn->prepare("SELECT productprice FROM products WHERE product_id = :product_id;");
$stmtpprice->execute([":product_id"=>$productid]);
$productprice = $stmtsms->fetch();
$totalpprice = $productprice["productprice"];
/// Insert into Orders, Orderitems, Shipping Table
$stmtorders = $conn->prepare("INSERT INTO orders (customerid, orderid, orderdate, total_price) VALUES (:customerid, :orderid, :orderdate, :total_price);");
$stmtorderitems = $conn->prepare("INSERT INTO orderitems (id, orderid, productid, item_price) VALUES ('', :orderid, :productid, :itemprice);");
$stmtshipping = $conn->prepare("INSERT INTO shipping (orderid, shipping_method, shipping_price, tracking_id, status, sent_date) VALUES (:orderid, :shipping_method, :shipping_price, '0', '0', :sent_date);");
$stmtorders->execute([":customerid"=>$last_id,
":orderid"=>$order_id,
":orderdate"=>$date],
":totalprice"=>$totalpprice]); | {
"domain": "codereview.stackexchange",
"id": 42878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql",
"url": null
} |
php, sql
":totalprice"=>$totalpprice]);
$stmtorderitems->execute([":orderid"=>$order_id,
":productid"=>$productid],
":itemprice"=>$totalpprice]);
$stmtshipping->execute([":orderid"=>$order_id,
":shipping_method"=>$shippingmethod,
":shipping_price"=>$shippingprice,
":sent_date"=>$date]); | {
"domain": "codereview.stackexchange",
"id": 42878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql",
"url": null
} |
php, sql
What do you thing about processing and about the table structure? Thank you!
Answer: Some minor suggestions:
I would move the code that retrieves the current product price to a dedicated function.
The main code should be a standalone function too
You should use a transaction to wrap up the whole sequence of operations, so that in case of error, you don't end up with inconsistent data and orphaned records.
Separate the three blocks that write to tables Orders, Orderitems, Shipping Table.
Add spacing where appropriate eg: $stmtorderitems->execute([":orderid" => $order_id,...
Improve naming a little bit, for example $last_id should be $customer_id so that there is no misunderstanding.
One potentially misleading statement: $totalpprice is the product price and not the total amount of the order as one might think. So just call it $product_price and there is no ambiguity.
$productprice = $stmtsms->fetch();
$totalpprice = $productprice["productprice"];
The order ID is generated like this: $order_id = "OS". $last_id;. Why not simply use an ID as well ? A client may have more than one order...
One problem in your code is that it requires horizontal scrolling, the SQL statement lines are too long. Wrap them up to have a better overview. I would perhaps do like this:
$stmtorders = $conn->prepare(
"INSERT INTO orders (customerid, orderid, orderdate, total_price)
VALUES (:customerid, :orderid, :orderdate, :total_price);"
);
But you have considerable freedom here. | {
"domain": "codereview.stackexchange",
"id": 42878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql",
"url": null
} |
javascript, jquery, html5, form
Title: Dynamic country, state select options
Question: Here is code I wrote to dynamically choose between three country options (United States, Canada, Other). After the user selects a country it will show the related select option or an empty input (when "Other" country is chosen). Then I pass the previous value into an input called spr(state/province/region). The end result is two values are saved: country and spr.
I'm here because I think the code could be refactored, and I'm not thinking about it in an efficient way.
const country = '#country';
const province = '#province';
const region = '#region';
const state = '#state';
const spr = '#spr';
const usa = '#usa';
const canada = '#canada';
const otherCountry = '#otherCountry';
hideCountryOptions(); //initial hide
$(country).on('change', function() {
hideCountryOptions();
selectSPR($(country).val());
switch ($(country).val()) {
case "UNITED STATES":
$(usa).show();
break;
case "CANADA":
$(canada).show();
break;
default:
$(otherCountry).show();
}
})
$(state + "," + province + "," + region).on('change', function() {
selectSPR($(country).val());
});
function hideCountryOptions() {
$(canada).hide();
$(usa).hide();
$(otherCountry).hide();
} | {
"domain": "codereview.stackexchange",
"id": 42879,
"lm_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, jquery, html5, form",
"url": null
} |
javascript, jquery, html5, form
function hideCountryOptions() {
$(canada).hide();
$(usa).hide();
$(otherCountry).hide();
}
function selectSPR(country) { //pass value into the state/province/region input
$(spr).val("");
switch (country) {
case "UNITED STATES":
$(spr).val($(state).val());
break;
case "CANADA":
$(spr).val($(province).val());
break;
default:
$(spr).val($(region).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="country">*Country</label>
<select name="country" id="country" required>
<option value="">CHOOSE…</option>
<option value="UNITED STATES">UNITED STATES</option>
<option value="CANADA">CANADA</option>
<option value="AFGHANISTAN">AFGHANISTAN</option>
</select>
</div>
<div id="usa">
<label for="state">*State</label>
<select name="state" id="state">
<option value="">CHOOSE...</option>
<option value="ALABAMA">ALABAMA</option>
<option value="ALASKA">ALASKA</option>
</select>
</div>
<div id="canada">
<label for="province">*Province</label>
<select class="custom-select" name="province" id="province">
<option value="">CHOOSE...</option>
<option value="ALBERTA">ALBERTA</option>
<option value="BRITISH COLUMBIA">BRITISH COLUMBIA</option>
</select>
</div>
<div id="otherCountry">
<label for="region">*Region</label>
<input type="text" name="region" id="region" placeholder="Region">
</div>
<div>
<input type="text" name="spr" id="spr">
</div>
Answer: There are 4 different places in the code, where you do something for every country. That makes it complicated to add more countries, and also makes the code very long if you have many. But you can get around this by designing your HTML for the task. | {
"domain": "codereview.stackexchange",
"id": 42879,
"lm_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, jquery, html5, form",
"url": null
} |
javascript, jquery, html5, form
First of all, I've changed some names, and used the generic term 'region' everywhere. 'states' and 'provinces' are handled the same in the code, so a common name makes it easier. It also avoid a potential clash of IDs when adding more countries.
I've given each list of regions a common class to group them together, and a data-* attribute to match them with their country. I decided to use the 3-letter country codes, since we only need a unique identifier for each country, not the full display name.(1)
I use a class to indicate which region is active, and use CSS to hide the rest.
I've removed most name attributes, since they are not being used. Unless you are submitting this in a form, in which case I've left two, the 'country' and 'region', which are the two you wanted to save.
const country = $('#country');
const regions = $('.region');
const regionOther = $('.region[data-country=OTHER]');
const selectedRegion = $('#selectedRegion');
country.on('change', function() {
let activeRegion = $(`.region[data-country=${country.val()}]`);
if(!activeRegion.length) {
activeRegion = regionOther;
}
regions.removeClass('active');
activeRegion.addClass('active');
updateSelectedRegion();
})
regions.on('change', updateSelectedRegion);
function updateSelectedRegion() {
let activeRegion = $('.region.active select, .region.active input');
selectedRegion.val(activeRegion.val());
}
.region:not(.active) {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="country">*Country</label>
<select id="country" name="country" required>
<option value="">CHOOSE…</option>
<option value="USA">UNITED STATES</option>
<option value="CAN">CANADA</option>
<option value="AFG">AFGHANISTAN</option>
</select>
</div> | {
"domain": "codereview.stackexchange",
"id": 42879,
"lm_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, jquery, html5, form",
"url": null
} |
javascript, jquery, html5, form
<div class="region" data-country="USA">
<label for="regionUSA">*State</label>
<select id="regionUSA">
<option value="">CHOOSE...</option>
<option value="ALABAMA">ALABAMA</option>
<option value="ALASKA">ALASKA</option>
</select>
</div>
<div class="region" data-country="CAN">
<label for="regionCAN">*Province</label>
<select id="regionCAN">
<option value="">CHOOSE...</option>
<option value="ALBERTA">ALBERTA</option>
<option value="BRITISH COLUMBIA">BRITISH COLUMBIA</option>
</select>
</div>
<div class="region" data-country="OTHER">
<label for="regionOTHER">*Region</label>
<input type="text" id="regionOTHER" placeholder="Region">
</div>
<div>
<input type="text" id="selectedRegion" name="region" readonly>
</div>
Now if you want to add another country, all you have to change in the code is... nothing. You don't need to touch the code at all, just add the HTML. Just add another option
<option value="AUS">AUSTRALIA</option>
If the country doesn't have regions, that's it, the default will be used. If it does have, add this
<div class="region" data-country="AUS">
<label for="regionAUS">*State</label>
<select id="regionAUS">
<option value="">CHOOSE...</option>
<option value="NEW SOUTH WALES">NEW SOUTH WALES</option>
<option value="QUEENSLAND">QUEENSLAND</option>
</select>
</div>
Here's a full example with a few more countries http://jsfiddle.net/7fnwohb3/3/
(1) You can use short codes for the individual regions too. Most countries should have official region codes in 2-3 letters. This list have links to them. If you want to get the name from the code, have them in a list you can use everywhere in your code, like below. You could potentially use this list to generate the HTML options.
const regionNamesUSA = {
AL: 'Alabama',
AK: 'Alaska',
AZ: 'Arizona',
...
} | {
"domain": "codereview.stackexchange",
"id": 42879,
"lm_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, jquery, html5, form",
"url": null
} |
python, python-3.x, pandas
Title: Pandas MultiIndex DataFrame groupby apply to generate List[Dict[str,str|Dict[...]]]
Question: I have a MultiIndex DataFrame
df = pd.DataFrame({
('paramA','levelA'):np.random.randint(100, size=(5)),
('paramA','levelB'):np.random.randint(100, size=(5)),
('paramB','levelA'):np.random.randint(100, size=(5)),
('paramB','levelB'):np.random.randint(100, size=(5))
},
).T
df.index.set_names(['parameter','level'], inplace=True)
df.columns = np.arange('2021-10-22T00', '2021-10-22T05', dtype='datetime64[h]')
df.columns.set_names('validTime', inplace=True)
df['units']=['a','a','b','b']
which looks something like this
validTime 2021-10-22 00:00:00 ... units
parameter level ...
paramA levelA 32 ... a
levelB 50 ... a
paramB levelA 56 ... b
levelB 28 ... b
[4 rows x 6 columns]
and a method to generate....
List[Dict[str, str|List[Dict[str, str|List[Dict[str, str|int]]]]]]
I start by splitting the units and format the columns
df_values:pd.DataFrame = df.iloc[:,:-1]
df_values.rename(columns=df_values.columns.to_series().dt.strftime('%Y-%m-%d %H:%m:%SZ'))
units:pd.Series = df.iloc[:,-1]
then perform groupby(x).apply(...).values.tolist() to generate the object
df_values.groupby('parameter').apply(
lambda parameter: {
'parameter': parameter.index.get_level_values('parameter')[0],
'unit': units[parameter.index.get_level_values('parameter')[0]][0],
'levels': parameter.groupby('level').apply(
lambda level: {
'level': level.index.get_level_values('level')[0],
'values': level.apply(
lambda value: {
'validTime': str(value.name),
'value': value.values[0]
}).values.tolist()
}).values.tolist()
}).values.tolist() | {
"domain": "codereview.stackexchange",
"id": 42880,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
python, python-3.x, pandas
Answer: Don't use np.random.randint; it's deprecated.
When initialising units - and in some other places - prefer immutable tuples rather than lists.
Problem one with your data is that units is denormalised and repeats itself within the param index level. This needs to be pulled away into its own series indexed only by param.
Problem two with your data is that validTime pretends to be columns but functionally is a misrepresented index. This can be fixed with stack.
When you're manipulating sub-sub-dictionaries and the like, all hope of vectorisation is given up and so apply doesn't buy you much. Also note that your lambdas compile to one anonymous function each. Since this is already happening, you might as well replace them with one named function each that is an explicit generator with argument names and parameter and return types defined.
Your current method that relies on apply suffers from losing the grouped index value and having to recall it again with get_level_values. This can be avoided by simple iteration over the group object.
It's also worth mentioning that since you intend for this to be an API response, I presume that you need to JSON-serialise this and your current code is broken for that case since the in-built json module doesn't know how to serialise Numpy integers. In your current values indexing operation you would need an int cast; with the method I show that will not be necessary.
Suggested
import json
from typing import Iterator
import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(seed=0)
def example_data() -> pd.DataFrame:
def rand() -> np.ndarray:
return rng.integers(low=0, high=100, size=5) | {
"domain": "codereview.stackexchange",
"id": 42880,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
python, python-3.x, pandas
df = pd.DataFrame({
('paramA', 'levelA'): rand(),
('paramA', 'levelB'): rand(),
('paramB', 'levelA'): rand(),
('paramB', 'levelB'): rand()
}).T
df.index.set_names(('parameter', 'level'), inplace=True)
df.columns = np.arange('2021-10-22T00', '2021-10-22T05', dtype='datetime64[h]')
df.columns.set_names('validTime', inplace=True)
df['units'] = ('a', 'a', 'b', 'b')
return df
def process_op(df: pd.DataFrame) -> list:
df_values: pd.DataFrame = df.iloc[:, :-1]
df_values.rename(columns=df_values.columns.to_series().dt.strftime('%Y-%m-%d %H:%m:%SZ'))
units: pd.Series = df.iloc[:, -1]
return df_values.groupby('parameter').apply(
lambda parameter: {
'parameter': parameter.index.get_level_values('parameter')[0],
'unit': units[parameter.index.get_level_values('parameter')[0]][0],
'levels': parameter.groupby('level').apply(
lambda level: {
'level': level.index.get_level_values('level')[0],
'values': level.apply(
lambda value: {
'validTime': str(value.name),
'value': int(value.values[0]),
}
).values.tolist()
}
).values.tolist(),
}
).values.tolist()
def process_new(df: pd.DataFrame) -> tuple:
def iter_param() -> Iterator[dict]:
for param_value, param_group in df.groupby(level=0):
yield {
'parameter': param_value,
'unit': units[param_value],
'levels': tuple(iter_level(param_group)),
}
def iter_level(param_group: pd.Series) -> Iterator[dict]:
for level_value, level_group in param_group.groupby(level=1):
yield {
'level': level_value,
'values': tuple(iter_time(level_group)),
} | {
"domain": "codereview.stackexchange",
"id": 42880,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
python, python-3.x, pandas
def iter_time(level_group: pd.Series) -> Iterator[dict]:
for (param, level, time), value in level_group.iteritems():
yield {
'validTime': str(time),
'value': value,
}
# Group by the "param" index level, ignore the "level" index level,
# and take the first unit value of each group
units = df.groupby(level=0).units.first()
# validTime is functionally an index but misrepresented as columns; fix that
df = df.drop(columns=['units']).stack()
return tuple(iter_param())
def test() -> None:
df = example_data()
result = process_new(df)
print(json.dumps(result, indent=4))
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 42880,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
python, python-3.x, pandas
Output
[
{
"parameter": "paramA",
"unit": "a",
"levels": [
{
"level": "levelA",
"values": [
{
"validTime": "2021-10-22 00:00:00",
"value": 85
},
{
"validTime": "2021-10-22 01:00:00",
"value": 63
},
{
"validTime": "2021-10-22 02:00:00",
"value": 51
},
{
"validTime": "2021-10-22 03:00:00",
"value": 26
},
{
"validTime": "2021-10-22 04:00:00",
"value": 30
}
]
},
{
"level": "levelB",
"values": [
{
"validTime": "2021-10-22 00:00:00",
"value": 4
},
{
"validTime": "2021-10-22 01:00:00",
"value": 7
},
{
"validTime": "2021-10-22 02:00:00",
"value": 1
},
{
"validTime": "2021-10-22 03:00:00",
"value": 17
},
{
"validTime": "2021-10-22 04:00:00",
"value": 81
}
]
}
]
},
{
"parameter": "paramB",
"unit": "b",
"levels": [
{
"level": "levelA",
"values": [
{
"validTime": "2021-10-22 00:00:00",
"value": 64 | {
"domain": "codereview.stackexchange",
"id": 42880,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
python, python-3.x, pandas
"validTime": "2021-10-22 00:00:00",
"value": 64
},
{
"validTime": "2021-10-22 01:00:00",
"value": 91
},
{
"validTime": "2021-10-22 02:00:00",
"value": 50
},
{
"validTime": "2021-10-22 03:00:00",
"value": 60
},
{
"validTime": "2021-10-22 04:00:00",
"value": 97
}
]
},
{
"level": "levelB",
"values": [
{
"validTime": "2021-10-22 00:00:00",
"value": 72
},
{
"validTime": "2021-10-22 01:00:00",
"value": 63
},
{
"validTime": "2021-10-22 02:00:00",
"value": 54
},
{
"validTime": "2021-10-22 03:00:00",
"value": 55
},
{
"validTime": "2021-10-22 04:00:00",
"value": 93
}
]
}
]
}
] | {
"domain": "codereview.stackexchange",
"id": 42880,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
c++, algorithm, pathfinding, dijkstra
Title: Pathfinders.hpp - Dijkstra's algorithm
Question: I have this Visual Studio 2022 project, in which I compared the performance of 4 point-to-point shortest path algorithms. This one presents the Dijkstra's algorithm:
#ifndef COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_DIJKSTRA_HPP
#define COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_DIJKSTRA_HPP
#include "DirectedGraph.hpp"
#include "Pathfinders.SharedUtils.hpp"
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace com::github::coderodde::pathfinders {
using namespace com::github::coderodde::directed_graph;
using namespace com::github::coderodde::pathfinders::util;
template<typename Node = int, typename Weight = double>
Path<Node, Weight>
runDijkstrasAlgorithm(DirectedGraph<Node>& graph,
DirectedGraphWeightFunction<Node, Weight>& weight_function,
Node& source_node,
Node& target_node) {
checkTerminalNodes(graph, source_node, target_node);
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>> OPEN;
std::unordered_set<Node> CLOSED;
std::unordered_map<Node, Weight> distance_map;
std::unordered_map<Node, Node*> parent_map;
OPEN.push(new HeapNode<Node, Weight>(source_node, Weight{}));
distance_map[source_node] = {};
parent_map[source_node] = nullptr;
while (!OPEN.empty()) {
HeapNode<Node, Weight>* top_heap_node = OPEN.top();
OPEN.pop();
Node current_node = top_heap_node->getElement();
delete top_heap_node; | {
"domain": "codereview.stackexchange",
"id": 42881,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, pathfinding, dijkstra
if (current_node == target_node) {
// Found the path:
cleanPriorityQueue<Node, Weight>(OPEN);
Path<Node, Weight> path =
tracebackPath(
target_node,
parent_map,
weight_function);
cleanParentMap<Node>(parent_map);
return path;
}
if (CLOSED.contains(current_node)) {
continue;
}
CLOSED.insert(current_node);
const std::unordered_set<Node>* children =
graph.getChildNodesOf(current_node);
for (Node const& child : *children) {
if (CLOSED.contains(child)) {
// The optimal distance from source_node to child
// is known. Omit:
continue;
}
Weight distance =
distance_map[current_node] +
weight_function.getWeight(current_node, child);
if (!parent_map.contains(child)
|| distance < distance_map[child]) {
OPEN.push(new HeapNode<Node, Weight>(child, distance));
distance_map[child] = distance;
Node* elem_ptr = new Node{ current_node };
parent_map[child] = elem_ptr;
}
}
}
throw PathDoesNotExistException{
buildPathNotExistsErrorMessage(source_node, target_node) };
}
} // End on namespace 'com::github::coderodde::pathfinders'.
#endif // COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_DIJKSTRA_HPP
Critique request
I am interested in these:
possible undefined behavior,
memory leaks,
efficiency issues,
code readability,
idiomacy of the code.
Answer:
possible undefined behavior,
Don't see any.
memory leaks,
You did not provide all the code so impossible to say definitely. | {
"domain": "codereview.stackexchange",
"id": 42881,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, pathfinding, dijkstra
Don't see any.
memory leaks,
You did not provide all the code so impossible to say definitely.
It looks like you leak if you don't find a path.
Looks like you leak children.
ALSO your usage of new is a bad and anti-idiomatic.
efficiency issues,
Nothing pops up.
code readability,
Using all capitols OPEN and CLOSED is not nice (breaks all coding conventions I have seen). All caps is usually reserved for macros.
could use using in a couple of places to simplify the types.
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>> OPEN;
Might have been nicer to write as:
using LocalNode = HeapNode<Node, Weight>*;
using QueueStorage = std::vector<LocalNode>;
using Compare = HeapNodeComparator<Node, Weight>;
using PriorityQueue = std::priority_queue<LocalNode, QueueStorage, Compare>;
PriorityQueue OPEN;
idiomacy of the code.
Looks like it should work.
But your usage of new and delete and passing around RAW pointers ins non idiomatic. RAW pointers do not have ownership semantics so it is hard to understand if you need to delete them. Also they are not exception safe so will leak if there are any exceptions in your code.
Modern C++ has moved to using smart_pointer to hold owned pointers and view(s) and references to hold non owned pointers and containers to hold non-polymorphic groups of objects.
BUT I see no need for any dynamic memory management at all, as the containers you use will all handle this very efficiently.
Even in old C++ NVO optimization removed most copies and in modern C++ we have move semantics that makes copy a last resort and simple move operations the common way things get done automatically.
Code Review
Nice:
#ifndef COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_DIJKSTRA_HPP
#define COM_GITHUB_CODERODDE_GRAPH_PATHFINDERS_DIJKSTRA_HPP | {
"domain": "codereview.stackexchange",
"id": 42881,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, pathfinding, dijkstra
#include <algorithm> // Do you use any algorithms?
#include <sstream> // Did I miss the string stream.
#include <stdexcept> // I don't see you creating any exceptions
Not sure what these do:
checkTerminalNodes(graph, source_node, target_node);
tracebackPath(
target_node,
parent_map,
weight_function);
cleanParentMap<Node>(parent_map);
So can't really comment on them.
You don't need to use pointers here. There is no polymorphism. So simply add the objects to your queue.
std::priority_queue<
HeapNode<Node, Weight>*,
std::vector<HeapNode<Node, Weight>*>,
HeapNodeComparator<Node, Weight>> OPEN;
// Could just as easily have written:
std::priority_queue<
HeapNode<Node, Weight>, // No Star
std::vector<HeapNode<Node, Weight>>, // No Star
HeapNodeComparator<Node, Weight>> open;
That would have worked better, as you don't need to worry about any memory leaks now.
I would have simplified even more by going.
using MyHeapNode = std::tupple<Weight, Node>;
Notice the order. :-) The tuple has a built in comparitor so you don't need to define one explicitly for your priority_queue and that simplifies your declaration even further.
std::priority_queue<MyHeapNode> open;
Sure this is one way.
OPEN.push(new HeapNode<Node, Weight>(source_node, Weight{}));
But if you had used the above. You could simplify this to:
open.emplace_back(source_node, Weight{});
Stop creating things with new and passing the pointers around.
const std::unordered_set<Node>* children =
graph.getChildNodesOf(current_node);
You should return the unordered_set<Node> from getChildNodesOf(). The standard containers implement move semantics, so this will be cheap (and much cheaper than leaking memory). | {
"domain": "codereview.stackexchange",
"id": 42881,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, pathfinding, dijkstra
for (Node const& child : *children) {
// Premature optimization.
// But does no harm. So no real complaint.
if (CLOSED.contains(child)) {
// The optimal distance from source_node to child
// is known. Omit:
continue;
}
// Another premature optimization
// Not causing a bug yet but I can see potential for a
// a bug in the future.
//
// You are defining distance_map[child] even though
// you don't yet know it is the shortest distance.
// If some code tries to use 'distance_map' for actual
// distance calculations you must make sure that the node
// is also in the `CLOSED` set.
//
// You don't enforce this condition in your code so there
// is a potential for a bug to sneak in later when the
// function is modified with new requirements.
if (!parent_map.contains(child)
|| distance < distance_map[child]) {
// Even if you throw an exception
// You still should clean up all the memory you allocated
// with new.
//
// This is exactly why it is rare to see plain `new` and
// `delete` in modern C++ code. It is usually placed in
// handeled by smart pointers.
//
// OR better to use value semantics (as I showed above.
throw PathDoesNotExistException{
buildPathNotExistsErrorMessage(source_node, target_node) }; | {
"domain": "codereview.stackexchange",
"id": 42881,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, dijkstra",
"url": null
} |
python, game, wordle
Title: Wordle clone in Python
Question: I spent some time making a simple Wordle clone in Python. The word bank consists of all words of a specified length taken from nltk's Brown corpus. I would appreciate any advice or criticism to improve my program's coherence and efficiency.
import random
import re
from nltk.corpus import brown
from termcolor import colored
allowed_attempts = 6
word_length = 5
word_bank = [word.upper() for word in brown.words() if len(word) == word_length and word.isalpha()]
def validate(attempt, answer, current_alpha):
result = ''
for pos, char in enumerate(attempt):
if char == list(answer)[pos]: # Letter is correct and in right position
result += (' ' + colored(char, 'green') + ' ')
current_alpha = current_alpha.replace(char, (colored(char, 'green')))
elif char in answer: # Letter is correct but in wrong position
result += (' ' + colored(char, 'yellow') + ' ')
current_alpha = current_alpha.replace(char, (colored(char, 'yellow')))
else: # Letter is incorrect
result += (' ' + char + ' ')
current_alpha = current_alpha.replace(char, (colored(char, 'red')))
print('\n' + result + '\n')
return current_alpha | {
"domain": "codereview.stackexchange",
"id": 42882,
"lm_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, game, wordle",
"url": null
} |
python, game, wordle
def guess(answer):
alphabet = ('\n\n Q W E R T Y U I O P \n A S D F G H J K L \n Z X C V B N M \n\n')
print('\nEnter your ' + str(allowed_attempts) + ' guesses. \n')
for i in range(allowed_attempts):
while True:
print(alphabet)
attempt = input('Attempt #' + str(i + 1) + ': ').upper()
if len(attempt) == word_length and attempt in word_bank: # Ensures user input is valid
break
else:
print(colored('\nNot in word bank.', 'red'))
if attempt == answer: # Checks if user won
return True
else:
alphabet = validate(attempt, answer, alphabet)
return False
def main():
print('\n\n\nI am thinking of a ' + str(word_length) + '-letter word. Can you guess in ' + str(allowed_attempts) + ' tries? \n')
print('If a letter is in the right place, it will be ' + colored('green', 'green') + '.\n' +
'If it is in the word but in the wrong place, it will be ' + colored('yellow', 'yellow') + '.\n' +
'If it is not in the word, it will be ' + colored('red', 'red') + '.\n')
while True:
answer = random.choice(word_bank) # Picks a word for this turn
if guess(answer):
print(colored('\nCongratulations! You won!\n', 'green', attrs=['bold']))
else:
print('\nYou lost! The word was ' + colored(answer, 'green') + '\n')
if input('\nWant to play again with a new word? Type anything to keep playing, or type Q to quit. ').upper() == 'Q':
print('\nThanks for playing.\n')
exit()
main() | {
"domain": "codereview.stackexchange",
"id": 42882,
"lm_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, game, wordle",
"url": null
} |
python, game, wordle
main()
Answer: Very good code overall! Just some improvements that came to mind:
What if the data is not yet downloaded
If the corpus is not yet downloaded the code will crash, you should do instead:
import nltk
try:
word_bank = [word.upper() for word in brown.words() if len(word) == word_length and word.isalpha()]
except RuntimeError: # data is not yet downloaded.
nltk.download(brown)
word_bank = [word.upper() for word in brown.words() if len(word) == word_length and word.isalpha()]
Remove repetition
In this if else chain the only thing changing is the color so:
if char == list(answer)[pos]: # Letter is correct and in right position
result += (' ' + colored(char, 'green') + ' ')
current_alpha = current_alpha.replace(char, (colored(char, 'green')))
elif char in answer: # Letter is correct but in wrong position
result += (' ' + colored(char, 'yellow') + ' ')
current_alpha = current_alpha.replace(char, (colored(char, 'yellow')))
else: # Letter is incorrect
result += (' ' + char + ' ')
current_alpha = current_alpha.replace(char, (colored(char, 'red')))
becomes:
if char == list(answer)[pos]: # Letter is correct and in right position
color = 'green'
elif char in answer: # Letter is correct but in wrong position
color = 'yellow'
else: # Letter is incorrect
color = 'default' # or white or black
current_alpha = current_alpha.replace(char, colored(char, color))
So it is clear that the if else is only deciding the color.
Even better would be to return a data structure [ (character, guessing_level), ...] for simpler testing and debugging and then go from the data structure to a pretty output.
Constant UPPERCASE
Just a useful convention in Python.
allowed_attempts = 6
word_length = 5
should be uppercase.
Small user friendlyness improvement.
if input('\nWant to play again with a new word? Type anything to keep playing, or type Q to quit. ').upper() == 'Q': | {
"domain": "codereview.stackexchange",
"id": 42882,
"lm_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, game, wordle",
"url": null
} |
python, game, wordle
should be:
if input('\nWant to play again with a new word? Type anything to keep playing, or type [q]uit to quit. ').upper().startswith('Q'):
So that if the user types "quit" it also works. | {
"domain": "codereview.stackexchange",
"id": 42882,
"lm_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, game, wordle",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
Title: C++14 Lock-free Multi-producer, Multi-Consumer Queue
Question: Introduction
This is a follow-up to a previous question of mine, where I presented another queue of the same type to get some feedback on it. Some people pointed out some fundamental errors I had made, and I came to learn that I was very naive when it comes to how I was padding variables. So this is an updated version, created using the feedback I got in the previous thread.
The new queue is 32bit and is intended to be portable and light-weight
Bounded Circular Buffer & Two Cursors
I'm still using a bounded circular buffer to store/load the data. And it still uses two cursors which indicate to the next producer/consumer which index on the buffer they should be working with. When a producer/consumer wishes to increment their respective cursor, both cursors are loaded at the same time, as they are both contained within an aligned structure. This is intended to ensure true-sharing of access to the cursors because they are never loaded individually. Once the cursors have been loaded, a fullness/emptiness check is performed before a CAS on the object holding both cursors. If either of the cursors has changed in the interim, the CAS will fail and another attempt is made. When the CAS succeeds, the data can be put into or removed from the buffer. In order to calculate the index on the buffer, an index-mask is used which will be one less than a power of two because we can use a bitwise-and instead of modulo to have the index wrap back to zero. For this to work the queue size must be a power of two, so the size specified by the user is raised up to the next power of two.
The Circular Buffer Nodes & Spin-locks | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
While the cursors maybe be protected by a CAS operation, each node on the buffer is protected by a spin-lock. This is to prevent the case where a consumer may try to read some data before a producer has finished putting it in. Or the opposite case, where a producer tries to add some data before a consumer has finished reading it.
The Code
Here's the full source, with many Doxygen style comments removed for clarity.
// SPDX-License-Identifier: GPL-2.0-or-later
/**
* C++14 32bit Lockless Bounded Circular MPMC Queue type.
* Author: Primrose Taylor
*/
#ifndef BOUNDED_CIRCULAR_MPMC_QUEUE_H
#define BOUNDED_CIRCULAR_MPMC_QUEUE_H
#include "stdio.h"
#include "stdlib.h"
#include <atomic>
#include <stdint.h>
#include <functional>
#include <thread>
#define CACHE_LINE_SIZE 64U
#if defined(_MSC_VER)
#define HARDWARE_PAUSE() _mm_pause();
#define _ENABLE_ATOMIC_ALIGNMENT_FIX 1 // MSVC atomic alignment fix.
#define ATOMIC_ALIGNMENT 4
#else
#define ATOMIC_ALIGNMENT 16
#if defined(__clang__) || defined(__GNUC__)
#define HARDWARE_PAUSE() __builtin_ia32_pause();
#endif
#endif | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
/**
* Lockless, Multi-Producer, Multi-Consumer, Bounded Circular Queue type.
* The type is intended to be light weight & portable.
* The sub-types are all padded to fit within cache lines. Padding may be put
* inbetween member variables if the variables are accessed seperatley.
*/
template <typename T, uint_least32_t queue_size, bool should_yield_not_pause = false>
class bounded_circular_mpmc_queue final
{
/**
* Simple, efficient spin-lock implementation.
* A function that takes a void lambda function can be used to
* conveiniently do something which will be protected by the lock.
* @cite Credit to Erik Rigtorp https://rigtorp.se/spinlock/
*/
class spin_lock
{
std::atomic<bool> lock_flag;
public:
spin_lock()
: lock_flag{false}
{
}
void do_work_through_lock(const std::function<void()> functor)
{
lock();
functor();
unlock();
}
void lock()
{
while (true)
{
if (!lock_flag.exchange(true, std::memory_order_acquire))
{
break;
}
while (lock_flag.load(std::memory_order_relaxed))
{
should_yield_not_pause ? std::this_thread::yield() : HARDWARE_PAUSE();
}
}
}
void unlock()
{
lock_flag.store(false, std::memory_order_release);
}
}; | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
/**
* Structure that holds the two cursors.
* The cursors are held together because we'll only ever be accessing
* them both at the same time.
* We don't directly align the struct because we need to use it as an
* atomic variable, so we must align the atomic variable instead.
*/
struct cursor_data
{
uint_fast32_t producer_cursor;
uint_fast32_t consumer_cursor;
uint8_t padding_bytes[CACHE_LINE_SIZE -
sizeof(uint_fast32_t) -
sizeof(uint_fast32_t)
% CACHE_LINE_SIZE];
cursor_data(const uint_fast32_t in_producer_cursor = 0,
const uint_fast32_t in_consumer_cursor = 0)
: producer_cursor(in_producer_cursor),
consumer_cursor(in_consumer_cursor),
padding_bytes{0}
{
}
};
/**
* Structure that represents each node in the circular buffer.
* Access to the data is protected by a spin lock.
* Contention on the spin lock should be minimal, as it's only there
* to prevent the case where a producer/consumer may try work with an element before
* someone else has finished working with it. The data and the spin lock are seperated by
* padding to put them in differnet cache lines, since they are not accessed
* together in the case mentioned previously. The problem with this is
* that in low contention cases, they will be accessed together, and thus
* should be in the same cache line. More testing is needed here.
*/
struct buffer_node
{
T data;
uint8_t padding_bytes_0[CACHE_LINE_SIZE -
sizeof(T) % CACHE_LINE_SIZE];
spin_lock spin_lock_;
uint8_t padding_bytes_1[CACHE_LINE_SIZE -
sizeof(spin_lock)
% CACHE_LINE_SIZE];
buffer_node()
: spin_lock_(),
padding_bytes_0{0},
padding_bytes_1{0}
{
} | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
void get_data(T& out_data) const
{
spin_lock_.do_work_through_lock([&]()
{
out_data = data;
});
}
void set_data(const T& in_data)
{
spin_lock_.do_work_through_lock([&]()
{
data = in_data;
});
}
};
/**
* Strucutre that contains the index mask, and the circular buffer.
* Both are accessed at the same time, so they are not seperated by padding.
*/
struct alignas(CACHE_LINE_SIZE) circular_buffer_data
{
const uint_fast32_t index_mask;
buffer_node* circular_buffer;
uint8_t padding_bytes[CACHE_LINE_SIZE -
sizeof(const uint_fast32_t) -
sizeof(buffer_node*)
% CACHE_LINE_SIZE];
circular_buffer_data()
: index_mask(get_next_power_of_two()),
padding_bytes{0}
{
static_assert(queue_size > 0, "Can't have a queue size <= 0!");
static_assert(queue_size <= 0xffffffffU,
"Can't have a queue length above 32bits!");
static_assert(
std::is_copy_constructible_v<T> ||
std::is_copy_assignable_v<T> ||
std::is_move_assignable_v<T> ||
std::is_move_constructible_v<T>,
"Can't use non-copyable, non-assignable, non-movable, or non-constructible type!"
);
/** Contigiously allocate the buffer.
* The theory behind using calloc and not aligned_alloc
* or equivelant, is that the memory should still be aligned,
* since calloc will align by the type size, which in this case
* is a multiple of the cache line size.
*/
circular_buffer = (buffer_node*)calloc(
index_mask + 1, sizeof(buffer_node));
} | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
~circular_buffer_data()
{
if(circular_buffer != nullptr)
{
free(circular_buffer);
}
}
private:
/**
* @cite https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
*/
uint_least32_t get_next_power_of_two()
{
uint_least32_t v = queue_size;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
};
public:
bounded_circular_mpmc_queue()
: cursor_data_(cursor_data{}),
circular_buffer_data_()
{
}
bool push(const T& in_data)
{
cursor_data current_cursor_data;
// An infinite while-loop is used instead of a do-while, to avoid
// the yield/pause happening before the CAS operation.
while(true)
{
current_cursor_data = cursor_data_.load(std::memory_order_acquire);
// Check if the buffer is full..
if (current_cursor_data.producer_cursor + 1 == current_cursor_data.consumer_cursor)
{
return false;
}
// CAS operation used to make sure the cursors have not been incremented
// by another producer/consumer before we got to this point, and to then increment
// the cursor by 1 if it hasn't been changed.
if (cursor_data_.compare_exchange_weak(current_cursor_data,
{current_cursor_data.producer_cursor + 1,
current_cursor_data.consumer_cursor},
std::memory_order_release, std::memory_order_relaxed))
{
break;
}
should_yield_not_pause ? std::this_thread::yield() : HARDWARE_PAUSE();
} | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
should_yield_not_pause ? std::this_thread::yield() : HARDWARE_PAUSE();
}
// Set the data
circular_buffer_data_.circular_buffer[
current_cursor_data.producer_cursor & circular_buffer_data_.index_mask
].set_data(in_data);
return true;
}
bool pop(T& out_data)
{
cursor_data current_cursor_data;
while(true)
{
current_cursor_data = cursor_data_.load(std::memory_order_acquire);
// Check if the queue is empty..
if (current_cursor_data.consumer_cursor == current_cursor_data.producer_cursor)
{
return false;
}
if (cursor_data_.compare_exchange_weak(current_cursor_data,
{current_cursor_data.producer_cursor,
current_cursor_data.consumer_cursor + 1},
std::memory_order_release, std::memory_order_relaxed))
{
break;
}
should_yield_not_pause ? std::this_thread::yield() : HARDWARE_PAUSE();
}
// Get the data
circular_buffer_data_.circular_buffer[
current_cursor_data.consumer_cursor & circular_buffer_data_.index_mask
].get_data(out_data);
return true;
}
uint_fast32_t size() const
{
const cursor_data cursors = cursor_data_.load(std::memory_order_acquire);
return cursors.producer_cursor - cursors.consumer_cursor;
}
bool empty() const
{
return size() == 0;
} | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
bool empty() const
{
return size() == 0;
}
bool full() const
{
return size() == circular_buffer_data_.index_mask + 1;
}
private:
alignas(CACHE_LINE_SIZE) std::atomic<cursor_data> cursor_data_;
circular_buffer_data circular_buffer_data_;
private:
bounded_circular_mpmc_queue(
const bounded_circular_mpmc_queue&) = delete;
bounded_circular_mpmc_queue& operator=(
const bounded_circular_mpmc_queue&) = delete;
};
#endif
I'm wondering if my push/pop methods work as I think they do? Is there any chance of the ABA problem? And is the use of the spin-lock to guard each node they best way of doing it? I'm using one because in theory it shouldn't really need to be used very often, as in the vast majority of cases where no-one else is still in the middle of working with the node.
Any help would be greatly appreatiated! Cheers.
Answer: Remove do_work_through_lock()
The intention behind this function is good, and the implementation looks reasonable for its intended use. However, since you added lock() and unlock() member functions, you can use a std::lock_guard to lock your spin_lock. This means that you can write:
void set_data(const T& in_data)
{
std::lock_guard lg(spin_lock_);
data = in_data;
}
If the function you would pass to do_work_through_lock() would be more complicated and could potentially throw exceptions, you cannot guarantee that unlock() would be called. std::lock_guard however takes care of that.
Use an enum class for should_yield_not_pause
Suppose you want to declare a queue that should yield, you have to write something like:
bounded_circular_mpmc_queue<int, 10, true> queue; | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
While it's very normal to see a value type and a size being passed as template parameters for a container, that true says very little. It's not only hard for someone reading this code to understand what it means, it might also be unclear for someone writing this code whether true means yield or pause. You can make it much more explicit by passing it as an enum class type template parameter, like so:
enum class wait_method {
YIELD,
PAUSE,
};
template <typename T, uint_least32_t queue_size, wait_method yield_or_pause = wait_method::YIELD>
class bounded_circular_mpmc_queue final
{
...
};
And when you need to decide whether to yield or pause write:
yield_or_pause == wait_method::YIELD ? std::this_thread::yield() : HARDWARE_PAUSE();
It might also help to make a private member function that yields-or-pauses, so you only have to write this logic once. Finally, while I wouldn't recommend it over the enum class solution, you could consider passing a function pointer as a template parameter:
template <typename T, uint_least32_t queue_size, void (*wait_method)() = std::this_thread::yield>
class bounded_circular_mpmc_queue final
{
...
}; | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
And then just call wait_method() whenever you need to wait. This allows the user to pass an arbitrary non-member function.
Yet another solution is to take away the choice from the user, and instead do something like pausing for the first 10 iterations or so, and if you still haven't got a lock by then, start yielding.
Proper way to align things
Maybe CACHE_LINE_SIZE is set correctly for the CPU you are running on your code on, but it might be wrong on another CPU. Since your code only compiles with C++17 and up, consider using std::hardware_destructive_interference_size to get the size objects need to be apart to avoid cache line sharing. (Note that it might not be implemented in the C++ standard library you are using, so use the fallback shown in the example.)
Furthermore, there is no need to add padding bytes to structs you want to align. Your calculations for the size is incorrect anyway, as % has a higher operator precedence than -, and it would fail to compile if CACHE_LINE_SIZE is smaller than the size of the data you want to align, since taking the remainder of a negative number might be negative in C++.
So consider writing:
struct buffer_node
{
alignas(std::hardware_destructive_interference_size) T data;
alignas(std::hardware_destructive_interference_size) spin_lock spin_lock_;
...
};
std::atomic<T> does not guarantee it is lock-free
While most built-in types will be lock-free on most platforms when used atomically, the use of std::atomic does not automatically guarantee that. Check with is_lock_free() that, for example, std::atomic<cursor_data> is lock-free, otherwise your whole queue will no longer be lock-free. Note that if you pad it to be the size of a cache line, it will very likely not be lock-free.
Avoid memory allocations
The theory behind using calloc() and not aligned_alloc()
or equivelant, is that the memory should still be aligned,
since calloc will align by the type size, which in this case
is a multiple of the cache line size. | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
Unfortunately, that is not the case. It will return a pointer which is suitably aligned for any built-in type (this will probably be smaller than the cache line size), but it will not align it to the size parameter you pass to calloc(). Also, a buffer_node can be larger than a cache line, given a large enough T.
new will actually see the type of the object you are trying to allocate, including its alignment restrictions. So just by adding alignas attributes to the member variables of buffer_node, new buffer_node[index_mask + 1] will allocate a suitably aligned array.
Even better that new/delete would be to use a std::unique_ptr. But even better than that would be not to have to allocate memory at all. Consider writing:
/* Note: outside circular_buffer_data */
static constexpr uint_least32_t get_next_power_of_two()
{
uint_least32_t v = queue_size();
...
return v;
}
struct circular_buffer_data
{
static constexpr uint_fast32_t index_mask = get_next_power_of_two();
buffer_node circular_buffer[index_mask + 1];
};
Now this struct just has a single member variable, consider removing it entirely and just declare this directly in bounded_circular_mpmc_queue:
static constexpr uint_fast32_t index_mask = get_next_power_of_two();
buffer_node circular_buffer_data_[index_mask + 1]; | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
Move the static_assert()s to the top of bounded_circular_mpmc_queue
The static_assert()s you had in the constructor of buffer_node don't depend on any parameter of buffer_node itself. So they should just be in bounded_circular_mpmc_queue directly. Also note that unlike assert(), static_assert() is a declaration, which means you don't need to put it inside a function. You can write it directly at the top of bounded_circular_mpmc_queue:
template <typename T, uint_least32_t queue_size, ...>
class bounded_circular_mpmc_queue final
{
static_assert(queue_size > 0, "Can't have a queue size <= 0!");
static_assert(queue_size <= 0xffffffffU, "Can't have a queue length above 32bits!");
...
};
Incorrect check for full queue
Your cursors are 32-bit integers that you increment indefinitely. Only when using it to index an item in circular_buffer[] do you AND it with the index_mask. This is fast and avoids the ABA problem for small queues. However, your check for whether the queue is full looks like this:
if (current_cursor_data.producer_cursor + 1 == current_cursor_data.consumer_cursor)
This is however incorrect. Consider what happens if the producers adds more than queue_size items to the queue before any consumer finishes consuming a single item. You should apply the mask on both sides of the equality operator:
if ((current_cursor_data.producer_cursor + 1) & circular_buffer_data_.index_mask ==
current_cursor_data.consumer_cursor & circular_buffer_data_.index_mask)
Producers can still overwrite data a consumer is working on
You still have the same problem as in the first iteration of your code. Again, simplifying your push() and pop() function:
push(const T& in_data)
{
auto produced_cursor = claim_cursor_for_push();
circular_buffer_data_[producer_cursor].set_data(in_data);
}
pop(T& out_data)
{
auto consumer_cursor = claim_cursor_for_pop();
circular_buffer_data_[consumer_cursor].get_data(out_data);
} | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
c++, multithreading, concurrency, queue, producer-consumer
In both cases, the act of claiming the cursor itself is an atomic operation, but getting/setting the data is a separate operation. This means that by calling pop(), consumer_cursor might be claimed, but another thread might then do a push() operation, which might overwrite the data at the consumer_cursor, since as far as cursor_data_ is concerned, the consumer just freed that index, so it is free for the taking of a producer. | {
"domain": "codereview.stackexchange",
"id": 42883,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, concurrency, queue, producer-consumer",
"url": null
} |
python, object-oriented, random, simulation, pygame
Title: Robotic swarm simulation: aggregation
Question: This program simulates the phenomenon of aggregation of a swarm of robots with no cooperation between each other and each robot following a very simple rule:
The velocity of this robot has a random direction and the absolute value of this velocity is inversely proportional to the number of robots inside of a threshold distance from this robot.
This means that the robot will move slower the more friends it has nearby, so it will spend more time near other robots rather than far away, and this is enough to create aggregation of robots, with no communication nor cooperation needed.
The program does a live representation of the swarm of robots and a live plot of the average number of neighbors of each robot, that is increasing over time.
Screenshot after some time
Graph of average number of neighbors over time
Graph of average number of neighbors over time, higher time limit
Code
import sys
import pygame
from pygame.locals import QUIT
import random
import math
from operator import mul, truediv
from statistics import mean
from itertools import combinations
import matplotlib.pyplot as plt
import numpy as np
class Robot:
def __init__(self, x, y, v=0, v0=None, aggregating_mode=True):
self.x = x
self.y = y
self.v = 0
self.aggregating_mode = aggregating_mode
self.v0 = v0 or (20 if aggregating_mode else 2)
def distance_to_robot(self, other):
return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
def count_nears(self, robots, threshold=100):
return sum(1 for robot in robots if self.distance_to_robot(robot) < threshold)
def update_speed(self, robots, threshold=100):
# Denominator is never 0 because the robot will always count at least itself
operation = truediv if self.aggregating_mode else mul
self.v = self.v0 * operation(1.0, self.count_nears(robots, threshold=threshold)) | {
"domain": "codereview.stackexchange",
"id": 42884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, random, simulation, pygame",
"url": null
} |
python, object-oriented, random, simulation, pygame
def update_position(self, width, height):
theta = random.random() * 2 * math.pi
self.x += math.cos(theta) * self.v
self.y += math.sin(theta) * self.v
self.x %= width
self.y %= height
def draw_self(self, SCREEN):
color = (255, 0, 0) if self.aggregating_mode else (0, 255, 0)
pygame.draw.circle(SCREEN, color, (self.x, self.y), 10)
def __repr__(self):
return f"Robot({self.x}, {self.y}, {self.v}"
def main():
pygame.init()
pygame.display.set_caption("Swarm robotics simulation: aggregation and distancing")
FPS = 60
FPS_CLOCK = pygame.time.Clock()
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
WIDTH, HEIGHT = pygame.display.Info().current_w, pygame.display.Info().current_h
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
def random_pos():
return (random.randint(0, WIDTH), random.randint(0, HEIGHT))
robots = [Robot(*random_pos(), aggregating_mode=True) for _ in range(140)]
# Game loop.
i = 0
average_counts = []
is_ = []
PLOTTING = True
while True:
i += 1
SCREEN.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Update and Draw
for robot in robots:
robot.update_speed(robots)
robot.update_position(WIDTH, HEIGHT)
robot.draw_self(SCREEN)
if i % 100 == 0:
average_near_count = mean((robot.count_nears(robots) for robot in robots))
average_counts.append(average_near_count)
if PLOTTING:
is_.append(i)
plt.axis([0, 15000, 0, 14])
plt.xlabel("Timestep")
plt.ylabel("Average number of neightbours")
plt.scatter(is_, average_counts)
plt.pause(0.1)
plt.show() | {
"domain": "codereview.stackexchange",
"id": 42884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, random, simulation, pygame",
"url": null
} |
python, object-oriented, random, simulation, pygame
plt.show()
print(average_near_count)
pygame.display.flip()
FPS_CLOCK.tick(FPS)
if __name__ == "__main__":
main()
Answer: Your user interface is fairly awkward, halting the simulation periodically to show and then destroy a graph.
You've chosen to use pygame, but matplotlib has built-in animation support. I am going to suggest that you switch to that, because:
It will allow for a seamless, concurrent display of the bot positions and whatever other statistics you want, in separate portions of a figure grid
This is an analysis project and not strictly a game
Your representation of a single robot as a class, whereas it's mathematically sound, is inefficient. Numpy is good at vectorisation, which means
Don't represent a robot as a single object; represent it as a row in an array
Don't even separate your x and y coordinates; keep them in columns of one array
Don't call count_nears once for every robot; instead set up a three-dimensional matrix: source robots by destination robots by x/y, and apply the Euclidean norm over the outermost axis to get a vectorised distance.
Don't call into math or operator; stick to Numpy. | {
"domain": "codereview.stackexchange",
"id": 42884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, random, simulation, pygame",
"url": null
} |
python, object-oriented, random, simulation, pygame
Spelling: neightbours -> neighbours.
I find a scatterplot for your mean to be an odd choice, and would expect a line plot instead.
Topology
I'll have to ask for forgiveness from my mathematician friends, since I'm speaking out of my depth:
You've (perhaps inadvertently) created a coordinate space topologically homeomorphic to a toroid. This is due to your modulus wrap-around. This is not bad in itself, but it's incompatible with another decision of yours - you have a discontinuity in your use of the Euclidean norm.
Imagine two points near the left-hand side. Their distance is low. Then one point drifts past the boundary and moves to the far right-hand side. Their distance is high. But should it be, really? The amount of space one point needs to traverse to intersect with the other point is still low, so the distance should be considered low.
There are two different ways to address this. To keep your space fully continuous, you'll need to change your use of the Euclidean norm such that - for each point - you don't measure against one other point; you measure against the shortest toroidal path among four.
The less continuous - but certainly the simpler - to implement, is to replace your modulus with max and min calls. I've not implemented either in my suggested code.
Suggested
from typing import Optional
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
from matplotlib.collections import Collection
from numpy.random import default_rng
FPS = 60 | {
"domain": "codereview.stackexchange",
"id": 42884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, random, simulation, pygame",
"url": null
} |
python, object-oriented, random, simulation, pygame
FPS = 60
class Swarm:
def __init__(
self,
width: float = 1000,
height: float = 1000,
near_threshold: float = 100,
v0: Optional[float] = None,
n: int = 140,
aggregate: bool = True,
seed: int = 0,
) -> None:
self.width, self.height, self.near_threshold, self.n, self.aggregate = (
width, height, near_threshold, n, aggregate,
)
self.v0 = v0 or (20 if aggregate else 2)
self.rand = default_rng(seed=seed).random
self.pos = width*self.rand((2, n))
self.n_near_mean: float
self.size = np.array((width, height))[:, np.newaxis]
def get_v(self) -> tuple[
np.ndarray, # new speeds
float, # new mean proximate-neighbour count
]:
displacement = self.pos[:, :, np.newaxis] - self.pos[:, np.newaxis, :]
distance = np.linalg.norm(displacement, axis=0)
n_near = np.count_nonzero(distance < self.near_threshold, axis=0)
if self.aggregate:
v = self.v0 / n_near
else:
v = self.v0 * n_near
return v, n_near.mean()
def update(self) -> None:
v, self.n_near_mean = self.get_v()
theta = 2*np.pi*self.rand(self.n)
projections = np.stack((
np.cos(theta), np.sin(theta),
))
self.pos = np.mod(self.pos + v*projections, self.size)
def display(swarm: Swarm) -> tuple[plt.Figure, FuncAnimation]:
fig: plt.Figure
ax_bot: plt.Axes
ax_stats: plt.Axes
fig, (ax_bot, ax_stats) = plt.subplots(nrows=1, ncols=2)
bot_scatter: Collection = ax_bot.scatter(*swarm.pos)
ax_bot.set_title('Robot positions')
ax_bot.set_xlabel('x')
ax_bot.set_ylabel('y')
ax_bot.axis((0, swarm.width, 0, swarm.height)) | {
"domain": "codereview.stackexchange",
"id": 42884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, random, simulation, pygame",
"url": null
} |
python, object-oriented, random, simulation, pygame
frames = []
means = []
stat_line: plt.Line2D
stat_line, = ax_stats.plot(frames, means)
ax_stats.set_title('Mean proximate neighbours')
ax_stats.set_xlabel('Timestep')
ax_stats.set_ylabel('Count')
ax_stats.axis((0, 15_000, 0, 14))
def init() -> tuple[plt.Artist, ...]:
return bot_scatter, stat_line
def update(frame: int) -> tuple[plt.Artist, ...]:
swarm.update()
bot_scatter.set_offsets(swarm.pos.T)
if frame % FPS:
return bot_scatter,
print(f'{swarm.n_near_mean:.1f}')
frames.append(frame)
means.append(swarm.n_near_mean)
stat_line.set_data(frames, means)
return bot_scatter, stat_line
anim = FuncAnimation(
fig=fig, func=update, init_func=init, interval=1e3/FPS, blit=True,
)
return fig, anim
def main() -> None:
swarm = Swarm()
print('Mean proximate neighbour count:')
fig, anim = display(swarm)
plt.show()
if __name__ == "__main__":
main()
Output | {
"domain": "codereview.stackexchange",
"id": 42884,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented, random, simulation, pygame",
"url": null
} |
c#, entity-framework
Title: How to optimize for loop with nested foreach
Question: I want to optimize this code of generate pdf file with many nested loops, what makes it slow that i have for loop with 20 items EmissionManchCoupEnvoi and then another nested foreach with method GetPropositionsQuest that do a query on a view in the database with 400k elements which is PropostionForPrint, now i have 12 secondes time to generate the file.
Here is my code :
for (int i = 1; i <= EmissionManchCoupEnvoi.Count; i++) {
foreach(var item in GetPropositionsQuest(datab, EmissionManchCoupEnvoi[i - 1].QId))
{
foreach(var subitem in item) {
if (subitem.reponse) {
tableCE.AddCell(new PdfPCell(new Phrase(subitem.position.ToString() + " - " + subitem.libelle, fontArialBold_Reponse)) {
Border = 0,
Colspan = 1
});
}
else {
tableCE.AddCell(new PdfPCell(new Phrase(subitem.position.ToString() + " - " + subitem.libelle, fontArial_Reponse)) {
Border = 0,
Colspan = 1
});
}
}
}
}
private static IEnumerable<dynamic> GetPropositionsQuest(Bdd12CdmContext datab, long id)
{
yield return datab.PropostionForPrint.Where(p => p.Id_question == id);
}
Answer: Since you've specifically asked about speeding your code up, I'll answer that first. The main issue you have here is that you're doing a server call for every value in EmissionManchCoupEnvoi, which you would really rather do once. With that in mind, we can get all of your items in one hit like so:
var IDs = EmissionManchCoupEnvoi
.Select(emce => emce.QId)
.ToList();
var items = datab.PropostionForPrint
.Where(p => IDs.contains(p.Id_question))
.ToLookup(p => p.Id_question); | {
"domain": "codereview.stackexchange",
"id": 42885,
"lm_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#, entity-framework",
"url": null
} |
c#, entity-framework
ToLookup will create an in-memory object with all of your items, grouped by ID so you can look them without doing a seperate database call each time. This is going to be a big increase in speed. Before I show you how to use this let me also point out something you've done in your for loop: you are starting at i = 1 and going while i <= EmissionManchCoupEnvoi.Count, which is very different to the usual method of starting at i = 0 and going while i < EmissionManchCoupEnvoi.Count. Doing this the usual way would have prevented you needing to subtract 1 to look up the QId inside your loop. What's more, you're just using this to look up a value in an indexable and presumably therefore IEnumerable object, probably a List or Array. You should just use another foreach loop here, iterating over the IDs, which we have already extracted:
foreach (var ID in IDs)
{
var item = items[ID];
}
Once you've done this something else becomes clear, you don't actually need to iterate over the IDs at all, just the collection of items you would get from each ID. With that in mind we can change our ILookup to an IGrouping and iterate over it directly:
var items = datab.PropostionForPrint
.Where(p => IDs.contains(p.Id_question))
.GroupBy(p => p.Id_question)
// in order to maintain ordering, use an OrderBy here
.OrderBy(p => p.Key);
foreach (var item in items)
{
foreach (var subitem in item)
{
...
}
}
You may not even need the GroupBy unless you're doing something else with the item here, if instead you just wanted to preserve ordering you can just use an OrderBy and then just have the outer loop:
var items = datab.PropostionForPrint
.Where(p => IDs.contains(p.Id_question))
.OrderBy(p => p.Id_question);
foreach (var subitem in items)
{
...
} | {
"domain": "codereview.stackexchange",
"id": 42885,
"lm_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#, entity-framework",
"url": null
} |
c#, entity-framework
foreach (var subitem in items)
{
...
}
Whether or not you can do this depends on if ordering is important and whether or not the IDs are ordered in EmissionManchCoupEnvoi, which I don't know. With that in mind I'll stick with the lookup, which is guaranteed to keep the same ordering as your current code. Now that you're here, note that what you're doing inside your if/else statement is almost the same in both branches. Here you can just select your font and otherwise call AddCell once. You can also simplify your string creation using the string interpolation syntax with $:
var font = subitem.response ? fontArialBold_Reponse : fontArial_Reponse;
tableCE.AddCell(new PdfPCell(new Phrase($"{subitem.position} - {subitem.libelle}", font))
{
Border = 0,
Colspan = 1
});
For ease of reading I would also extract the creation of the Phrase and PdfCell. Putting this all together, the final code looks like this:
var IDs = EmissionManchCoupEnvoi
.Select(emce => emce.QId)
.ToList();
var items = datab.PropostionForPrint
.Where(p => IDs.contains(p.Id_question))
.ToLookup(p => p.Id_question);
foreach (var ID in IDs)
{
var item = items[ID];
foreach (var subitem in item)
{
var font = subitem.response ? fontArialBold_Reponse : fontArial_Reponse;
var phrase = new Phrase($"{subitem.position} - {subitem.libelle}", font);
var cell = new PdfPCell(phrase)
{
Border = 0,
Colspan = 1
};
tableCE.AddCell(cell);
}
} | {
"domain": "codereview.stackexchange",
"id": 42885,
"lm_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#, entity-framework",
"url": null
} |
c#, entity-framework
EXTRA NOTES
This isn't a review of your code so much as some advice: make sure you have an index on you Id_question column. I cannot overstate this enough, if you do not have that index then it is going to slow things down a lot.
Additionally, entity framework has the ability to select only specific columns from a table. This can be useful if you only need a few columns from a table which has many, and can sometimes bring a noticeable speed increase. In your case it may be worth doing this if you are only querying these items and not modifying them. You can change your items query like so:
var items = datab.PropostionForPrint
.Where(p => IDs.contains(p.Id_question))
.Select(p => new
{
p.Id_question,
p.response,
p.position,
p.libelle
})
.ToLookup(p => p.Id_question); | {
"domain": "codereview.stackexchange",
"id": 42885,
"lm_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#, entity-framework",
"url": null
} |
java
Title: Modifiable array-of-structures to represent devices
Question: I'm really only a tinkerer in Java, but for work I need to write in Java for a while. Most of my experience is in C / C++ / JavaScript.
Anyway, the program needs arrays of structured data. Then, based on runtime criteria, the program needs to be able to add to or modify part of the data. Later the program will use the modified data to accomplish its objectives.
Today I spent a while looking for ways to do this in Java. I was able to achieve the goal using ArrayLists of class objects.
import java.util.*;
import java.util.regex.*;
class BusConfig extends Object {
public int bus;
public int gpio;
public ArrayList<String> devices = new ArrayList<String> ( );
public BusConfig( int newBus, int newGPIO, String[] newDevices ) {
this.bus = newBus;
this.gpio = newGPIO;
this.devices = new ArrayList<String>( Arrays.asList( newDevices ) );
}
public String toString() {
return String.format( "{ bus %d, gpio %d, devices %s }", this.bus, this.gpio, this.devices.toString() );
}
} | {
"domain": "codereview.stackexchange",
"id": 42886,
"lm_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",
"url": null
} |
java
class ConfigData {
public static void main(String[] args) {
final boolean IS_EXTENDED = false;
ArrayList<BusConfig> basicConfig = new ArrayList<BusConfig>();
basicConfig.add( new BusConfig( 0, -1, new String[] { "0xa6" } ) );
basicConfig.add( new BusConfig( 1, 35, new String[] { "0x80", "0xae", "0xe4" } ) );
basicConfig.add( new BusConfig( 2, 38, new String[] { "0x80", "0xae", "0xe4" } ) );
ArrayList<BusConfig> extendConfig = new ArrayList<BusConfig>();
extendConfig.add( new BusConfig( 8, -1, new String[] { "0xe8" } ) );
ArrayList<String> extendBus0Device = new ArrayList<String>( Arrays.asList( new String[] { "0xa8" } ) );
if( IS_EXTENDED ) {
basicConfig.get(0).devices.addAll(extendBus0Device);
basicConfig.addAll(extendConfig);
}
System.out.println( basicConfig );
}
}
The code is far more verbose than what I would write in either C or JavaScript. Is there a less verbose way to accomplish the same outcome in Java? Maybe another class, or a cleaner syntax for initializing structured data?
My team is not Java-savvy, so it is important that the code be easy to read for C/C++ programmers. The kinds of code changes that are most likely are adding and changing the BusConfig objects.
In JavaScript same code looks like this:
const IS_EXTENDED = true;
let basicConfig = [
{ bus: 0, gpio: -1, devices: [ "0xa6" ] },
{ bus: 1, gpio: 35, devices: [ "0x80", "0xae", "0xe4" ] },
{ bus: 3, gpio: 38, devices: [ "0x80", "0xae", "0xe4" ] },
];
let extendConfig = [
{ bus: 8, gpio: -1, devices: [ "0xe8" ] },
];
let extendBus0Device = [ "0xa8" ];
if( IS_EXTENDED ) {
basicConfig = basicConfig.concat( extendConfig );
basicConfig[0].devices = basicConfig[0].devices.concat( extendBus0Device );
}
console.log( JSON.stringify(basicConfig,null,4) ); | {
"domain": "codereview.stackexchange",
"id": 42886,
"lm_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",
"url": null
} |
java
console.log( JSON.stringify(basicConfig,null,4) );
Answer: Initializing variables that are set in the constructor is unnecessary. Working with the abstract List type instead of concrete ArrayList allows you to take full advantage of Arrays.asList without having to convert the result into an ArrayList every time. I personally dislike forcing constructor parameters to have different names than the fields they are assigned to. The this. reference is intended for making a distinction between the scope and I find it distracting when I have to read the code to figure out what parameter goes into which field.
public final List<String> devices;
public BusConfig(int bus, int gpio, String ... devices) {
this.bus = bus;
this.gpio = gpio;
this.devices = Arrays.asList(devices);
}
And then...
List<BusConfig> basicConfig = Arrays.asList(
new BusConfig(0, -1, "0xa6")),
new BusConfig(1, 35, "0x80", "0xae", "0xe4")),
new BusConfig(2, 38, "0x80", "0xae", "0xe4"))
); | {
"domain": "codereview.stackexchange",
"id": 42886,
"lm_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",
"url": null
} |
java
Whether that is easier to understand is subjective, but at least it is shorter and does not have too many unnecessary statements cluttering the code.
There are a few things that I would advise against; all fields being public and the devices-list being exposed and manipulated from outside of the BusConfig-class.
Addendum: I should have read the JavaDoc... I did look into the code and confirmed that Arrays.asList(...) does return an ArrayList, but with closer inspection, I found out it's not the java.util.ArrayList but an specialized internal ArrayList that is completely different! There doesn't seem to be a common utility library like Apache Commons or Google Commons that would have such a utility, which makes me think that there is a reason for that. If you know why, please add a comment. Anyway, you need to write your own:
public class ArrayListUtils {
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> ArrayList<T> asArrayList(T... elements) {
final ArrayList<T> list = new ArrayList<>(elements.length);
for (T e: elements) {
list.add(e);
}
return list;
}
}
and...
import static com.example.ArrayListUtils.toArrayList;
and instead of Arrays.asList(devices) just call
asArrayList(devices) | {
"domain": "codereview.stackexchange",
"id": 42886,
"lm_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",
"url": null
} |
c++, template, lambda, c++20
Title: Class accepting data input by variable, function pointer or lambda
Question: Background
I am writing a library that takes some data from the user and works with it. I was experimenting with ways to allow users to provide the data by the following methods:
As a (global) variable (taken by a const &)
As a function pointer
As a lambda (taken by value)
I am aware that I can just wrap the variable or function in a lambda to achieve the same result, but I think I can learn something by doing it the "hard" way.
I am targeting C++20.
Code
#include <cassert>
#include <cstdint>
#include <functional>
template <class T, bool = std::is_invocable_v<T>>
struct GetDataType
{
using type = typename std::invoke_result_t<T>;
};
template <class T>
struct GetDataType<T, false>
{
using type = T;
};
template <class T, bool = std::is_invocable_v<T>>
struct GetSourceType
{
using type = T;
};
template <class T>
struct GetSourceType<T, false>
{
using type = typename std::add_lvalue_reference_t<std::add_const_t<T>>;
};
template <typename DataSource>
class DataGetter
{
public:
using DataType = GetDataType<DataSource>::type;
using DataSourceType = GetSourceType<DataSource>::type;
DataGetter(const DataSource &f) : m_dataSource(f) {}
[[nodiscard]] bool dataMatches(DataType refData) const
{
return refData == getData();
}
private:
DataSourceType m_dataSource;
[[nodiscard]] DataType getData() const
{
if constexpr (std::invocable<DataSource>)
{
return std::invoke(m_dataSource);
}
else
{
return m_dataSource;
}
}
};
volatile uint32_t g_Data = 3;
uint32_t getData() { return g_Data + 1; }
int main(int argc, char **)
{
DataGetter fromLocal(argc);
DataGetter fromGlobal(g_Data);
DataGetter fromLambda([&argc]()
{ return argc + 1; });
DataGetter fromFunctionPointer(&getData); | {
"domain": "codereview.stackexchange",
"id": 42887,
"lm_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++, template, lambda, c++20",
"url": null
} |
c++, template, lambda, c++20
assert(fromLocal.dataMatches(1));
assert(fromGlobal.dataMatches(3));
assert(fromLambda.dataMatches(2));
assert(fromFunctionPointer.dataMatches(4));
argc++;
g_Data = g_Data + 1;
assert(fromLocal.dataMatches(2));
assert(fromGlobal.dataMatches(4));
assert(fromLambda.dataMatches(3));
assert(fromFunctionPointer.dataMatches(5));
return 0;
}
Compiler Explorer
Answer: Your initial traits can be simplified using std::conditional:
template <typename T>
using GetDataType = std::conditional_t<std::is_invocable_v<T>,
std::invoke_result<T>,
std::type_identity<T>>::type;
template <typename T>
using GetSourceType = std::conditional_t<std::is_invocable_v<T>,
std::type_identity_t<T>,
std::add_lvalue_reference_t<std::add_const_t<T>>>;
(From usage I would use const T& for non invokable for GetDataType)
Then
template <typename DataSource>
class DataGetter
{
public:
using DataType = GetDataType<DataSource>;
using DataSourceType = GetSourceType<DataSource>;
DataGetter(const DataSource &f) : m_dataSource(f) {}
[[nodiscard]] bool dataMatches(DataType refData) const
{
return refData == getData();
}
private:
DataSourceType m_dataSource;
[[nodiscard]] DataType getData() const
{
if constexpr (std::invocable<DataSource>)
{
return std::invoke(m_dataSource);
}
else
{
return m_dataSource;
}
}
};
Demo | {
"domain": "codereview.stackexchange",
"id": 42887,
"lm_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++, template, lambda, c++20",
"url": null
} |
c#, configuration
Title: Determine the URL to use for a REST API based on configuration
Question: There is a bit of if-else-if going in within the code.
Is there a construct which could come handy. Also the section names are very similar too
public string GetRestApiUrlFromHost()
{
var restApiUrl = string.Empty;
var HostUrl = Request.Host.Value;
var DevURL = _configuration.GetSection("DEV_API_URL").Value;
var QAURL = _configuration.GetSection("QA_API_URL").Value;
var ProdURL = _configuration.GetSection("PROD_API_URL").Value;
if (HostUrl.Contains(DevURL, StringComparison.CurrentCultureIgnoreCase))
{
restApiUrl = _configuration.GetSection("DEV_REST_API_URL").Value;
}
else if (HostUrl.Contains(QAURL, StringComparison.CurrentCultureIgnoreCase))
{
restApiUrl = _configuration.GetSection("QA_REST_API_URL").Value;
}
else if (HostUrl.Contains(ProdURL, StringComparison.CurrentCultureIgnoreCase))
{
restApiUrl = _configuration.GetSection("PROD_REST_API_URL").Value;
}
else
{
restApiUrl = _configuration.GetSection("Local_REST_API_URL").Value;
}
return restApiUrl;
}
Looks redundant to me. But cannot place it.
Which would be the most ideal way to refactor this code?
Answer: You could create an array of tuples with url keys and section keys and loop them like this:
(string urlKey, string sectionKey)[] keys = new [] {
("DEV_API_URL", "DEV_REST_API_URL"),
("QA_API_URL", "QA_REST_API_URL"),
("PROD_API_URL", "PROD_REST_API_URL")
};
string sectionKey = "Local_REST_API_URL";
foreach (var key in keys) {
if (HostUrl.Contains(key.urlKey, StringComparison.CurrentCultureIgnoreCase)) {
sectionKey = key.sectionKey;
break;
}
}
return _configuration.GetSection(sectionKey).Value; | {
"domain": "codereview.stackexchange",
"id": 42888,
"lm_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#, configuration",
"url": null
} |
c#, configuration
Or with LINQ (with same tuple array). .NET 6:
var key = keys.FirstOrDefault(
k => HostUrl.Contains(k.urlKey, StringComparison.CurrentCultureIgnoreCase),
(null, "Local_REST_API_URL")
);
return _configuration.GetSection(key.sectionKey).Value;
Uses the FirstOrDefault(IEnumerable, Func<TSource,Boolean>, TSource) extension method overload available since .NET 6
Framework versions prior to .NET 6:
var key = keys
.Where(
k => HostUrl.Contains(k.urlKey, StringComparison.CurrentCultureIgnoreCase))
.DefaultIfEmpty((null, "Local_REST_API_URL"))
.First();
);
return _configuration.GetSection(key.sectionKey).Value; | {
"domain": "codereview.stackexchange",
"id": 42888,
"lm_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#, configuration",
"url": null
} |
php, sql, database, laravel
Title: Search controller logic to search through models and manufacturers
Question: I have the following Laravel controller that searches through two models - Manufacturer and SearchTerm (which contains models of manufacturers, synonyms of models as well as common misspellings) using four different conditions: the first two for exact matches and the last two for partial matches.
I don't have a lot of experience with programming logic like this, and while it does thankfully work, it also seems to run very slow on my local server (2-3 seconds returning results from tables that are currently less than a hundred rows).
Controller
class SearchController extends Controller
{
public function index(Manufacturer $manufacturer) {
if (request("search")) {
$exact_terms = SearchTerm::with("manufacturer")->where('term', request("search"))->get();
if($exact_terms->isNotEmpty()) {
echo "Exact search term match!";
$results = $exact_terms;
foreach ($results as $result) {
$slug = $result->manufacturer->slug;
}
return redirect()->action([ManufacturerController::class, 'index'], ["manufacturer" => $slug]);
}
$exact_make = Manufacturer::where('slug', request("search"))->get();
if($exact_make->isNotEmpty()) {
echo "Exact manufacturer match!";
$results = $exact_make;
foreach ($results as $result) {
$slug = $result->slug;
}
return redirect()->action([ManufacturerController::class, 'index'], ["manufacturer" => $slug]);
} | {
"domain": "codereview.stackexchange",
"id": 42889,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, database, laravel",
"url": null
} |
php, sql, database, laravel
$search_terms = SearchTerm::with("manufacturer")->where('term', "like", '%' . request("search") . '%')->get()->unique("manufacturers");
if($search_terms->isNotEmpty()) {
echo "Search term match!";
foreach ($search_terms as $search_term) {
$search_term = $search_term->manufacturer;
}
$results = collect()->add($search_term); // Needed to always return a collection to the view, even if made up of one object
}
$search_make = Manufacturer::where('slug', 'like', '%' . request("search") . '%')->get();
if($search_make->isNotEmpty()) {
echo "Manufacturer match!";
$results = $search_make;
}
$results = isset($results) ? $results : collect();
}
return view("search", [
"manufacturer" => $manufacturer,
"results" => $results,
]);
}
}
View
@if(!$results->isEmpty())
<h1 class="my-5"> {{ $results->count() }} {{ $results->count() == 1 ? "result" : "results" }} found for <i>{{ request("search") }}</i></h1>
@foreach ($results as $result)
<img src="{{ asset("/images/badges/".$result->slug.".svg")}}" class="search-result-badge" alt="...">
<h2>{{$result->name}}</h2>
@endforeach
@else
<p><h1>Sorry! We couldn't find any results for <i>"{{ request("search") }}"</i>.</h1></p>
<br>
@endif
Answer: Controller
For loops with discarded $results
This is weird:
foreach ($results as $result) {
$slug = $result->slug; // or similar
}
You go through all that effort to get potentially a lot of matches, and then only use the last result. Why? If you only want one result, then you shouldn't get() a bunch of results. Only get the first(), perhaps after sorting appropriately. For example:
// First one:
$exact_terms = SearchTerm::with("manufacturer")->where('term', request("search"))->first();
// Highest ID:
$exact_terms = SearchTerm::with("manufacturer")->where('term', request("search"))->orderBy('id', 'DESC')->first(); | {
"domain": "codereview.stackexchange",
"id": 42889,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, database, laravel",
"url": null
} |
php, sql, database, laravel
I expect this is where the performance problem is.
Echos
What is the point of echo here? The only time that you would see it was while testing, so it should be removed after you've finished debugging those sections.
Sanitizing user input
The user can mess around with your like searches by entering a lot of %s in request("search") which may affect performance a little. I would strip these out, in addition to backslash and underscore.
(To clarify, you will need to keep the percents you are concatenating around request("search") as this is the only way to perform the query you want.)
Invert if
Your code has a bug, and this shows it. Where does $results come from when request("search") is missing? (Remember, frontend validation can be bypassed.)
if (!request("search")) {
return view("search", ["manufacturer" => $manufacturer, "results" => $results, ]);
}
// Otherwise... | {
"domain": "codereview.stackexchange",
"id": 42889,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, database, laravel",
"url": null
} |
php, sql, database, laravel
You'll have to have a return at the bottom but that's a small price to pay for not having so much indenting
Make the collection in a more readable way
collect()->add($search_term); becomes collect([$search_term]);, which is the same but more readable.
Null coalesce
$results = isset($results) ? $results : collect(); becomes $results ??= collect();. If you're not using PHP 7.4 to be able to do this, then update!
Return earlier with $search_terms
You throw away the results from a match with $search_terms when you have a match for $search_make. Not doing that would also allow you to streamline that part of the code.
View
Use whitespace for readability
Indent properly! The same goes for the controller.
Use spaces inside braces: {{ $content }}, not {{$content}}. Also use spaces around concatenation: $str . $str, not $str.$str.
Alt text
Don't use "..." as an alt text because that doesn't help a screen reader to know what's there. It seems appropriate here to leave it blank (to tell the screen reader to skip the image) as the image doesn't add anything to a screen reader beyond what they already can understand with $result->name on the next line.
Pluralization
In Laravel 9 you can use the helper str()->plural() (with the new, shorter syntax that makes it worth using in Blade). If you plan to localize, then you'll need to use trans_choice instead.
Invalid HTML
It's not valid to have a h1 inside a p.
Invert if
Specifically, !$results->isEmpty() can become $results->isNotEmpty() which is probably more readable.
My rewrite of your view
@if($results->isNotEmpty())
<h1 class="my-5"> {{ $results->count() . ' ' . str('result')->plural($results->count()) }} found for <i>{{ request("search") }}</i></h1>
@foreach ($results as $result)
<img src="{{ asset("/images/badges/" . $result->slug . ".svg")}}" class="search-result-badge" alt="">
<h2>{{ $result->name }}</h2>
@endforeach
@else | {
"domain": "codereview.stackexchange",
"id": 42889,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, database, laravel",
"url": null
} |
php, sql, database, laravel
<h2>{{ $result->name }}</h2>
@endforeach
@else
<h1>Sorry! We couldn't find any results for <i>"{{ request("search") }}"</i>.</h1>
<br>
@endif | {
"domain": "codereview.stackexchange",
"id": 42889,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, database, laravel",
"url": null
} |
php, sql, database, laravel
PS I'm not sure if asset("/images/badges/" . $result->slug . ".svg" is vulnerable to directory traversal. I hope your slug is not user-generated, or is otherwise heavily sanitized. | {
"domain": "codereview.stackexchange",
"id": 42889,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, database, laravel",
"url": null
} |
beginner, c, strings
Title: String Reversal in C - K&R Book Exercise 1-19
Question: I'm a Python programmer / teacher who was a CIS major in college. I'm going back to school to get my masters in CS probably, and the first course is a prerequisite Intro to Programming in C / C++. I've decided to work through the K&R book to prepare myself, and this is quite the learning experience!
For this particular review, I'm hoping you can help me identify unnecessary or potentially risky elements of this string reversal code. I'm using some inspiration from an earlier problem I solved in the book, but I was able to figure out the reversal on my own after looking up how to do a decrementing for loop properly and how to return a character array (or a pointer to it? - I haven't made it to the pointers stuff yet haha).
I'm also not getting why I need this particular if statement handling the newline, which was part of the original code in the book's example. How is this any different than what's happening in the for loop for the get_line() function?
Certainly there are other deficiencies, I'm happy to hear them.
Lastly, I've read a couple of related answers, and some folks are mentioning that the K&R book is perhaps suboptimal. Any recommendations on alternatives? I prefer to work harder if it means I learn more, but not so hard that I am hamstringing myself for the future :D.
if (c == '\n')
{
line[i] = c;
++i;
}
String Reversal Code
#include <stdio.h>
#define MAXLINE 1000
int get_line(char line[], int maxline);
char* reverse(char from[], int len, char reversed[]);
main()
{
int len; /* length of the line */
char line[MAXLINE];
char reversed[MAXLINE];
char *final;
while ((len = get_line(line, MAXLINE)) > 0)
final = reverse(line, len, reversed);
printf("%s", final);
return 0;
}
int get_line(char line[], int lim)
{
int c, i; | {
"domain": "codereview.stackexchange",
"id": 42890,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, strings",
"url": null
} |
beginner, c, strings
}
int get_line(char line[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c = getchar())!=EOF && c!= '\n'; ++i)
line[i] = c;
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
char* reverse(char from[], int len, char reversed[])
{
unsigned i;
int k, last_char_index;
k = 0;
last_char_index = len-1;
for (i = last_char_index; i-- > 0;)
{
reversed[k] = from[i];
k++;
}
return reversed;
}
Answer: Programming like it's 1980? Got one of those "micro" computer thingies, or are you using a timeshareing system at a university?
Seriously, a lot has changed since K&R was published in 1978. The C language evolved a lot, including the very way functions are declared. I see you're using the ANSI style for reverse but (as another answer has noted) you have a legacy definition for main with an implicit-int return type.
A big change you are not aware of is the repeal of the need to declare all local variables before any code in the function. As of C99, you can mix variable declarations and other statements. This is a very good idea. So it's quite silly to write:
int k, last_char_index;
k = 0;
last_char_index = len-1;
clearly you want:
int k= 0;
int last_char_index = len-1;
Another thing that was already figured out by the publication of K&R is the "nul-terminated string" convention. Your reverse function should look for a '\0' at as a terminating character, not take a length argument.
If your reading has not covered this yet: The literal string syntax "Hello" (double quotes) creates an array of char, like this:
static const char __InternalName[] = {'H','e','l','l','o','\0'}; | {
"domain": "codereview.stackexchange",
"id": 42890,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, strings",
"url": null
} |
beginner, c, strings
So if you write: const char *s = "Hello"; then s is a pointer to the character containing the value 'H'.
Not having strings as a first-class value type casts a huge shadow. You need naming conventions to indicate the ownership of strings returned, and whether or not new (dynamic memory) strings are created at all. Your function: appears to take an "out" parameter so the caller supplies storage for the result... but it also returns a char* so what is that for?
For example, if you have the function declared as char *name (params); (no conventions apparent) vs. establishing a convention that functions ending in Copy return allocated strings that the caller owns and must free, but functions ending in View are handed pointers that are owned elsewhere and must not be freed. The caller of name has no idea whether he needs to call free.
Concentrate on one thing. If you are learning basic algorithms like how to reverse a string, your code should be only for that. Use standard library and other library functions for the rest of the framework whose only purpose is to host your exhibition. You don't have to write all the primitive things from scratch, all at once!
You don't even need to worry about Input. Use fixed test cases in a test driver, or take a string to reverse on the command line (or both!). Just don't worry about "get line". That is a huge can of worms to get right, and that's not what your problem is all about. | {
"domain": "codereview.stackexchange",
"id": 42890,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, strings",
"url": null
} |
beginner, c, strings
If you want to learn C today, first get some up-to-date documentation. That would mean textbooks and references that are less than 11 years old, in order to cover the 2011 standard.
Also ask yourself why you want to use C. Is it for microcontroller projects where you want low-level pointers and such to be a big part of why you need it? Or what reasons (as opposed to learning C++)?
Also, learn that there is a standard library of functions and many conventions, hand-in-hand with learning the language itself. Otherwise you'll end up with very weird stuff.
requirements
You want to write a "reverse" string function. In-place or copying? If the latter, will it allocate a string or be provided storage?
Since the point is to do the reversing, doing it in-place avoids these added complexities. So, the function would be declared as:
void reverse (char* s); // reverse nul-terminated string in place
coding
You are to write a string reversing function. You're not to be distracted by writing semi-robust user input handling or a full GUI from scratch for that matter. Write only this function! So how do you package it up to see it work and test it?
test harness
You can call it and check the results using pre-defined values. In fact, write these first!
test ("hello", "olleh");
test ("", "");
test ("whatever", "whatever"); | {
"domain": "codereview.stackexchange",
"id": 42890,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, strings",
"url": null
} |
beginner, c, strings
The test function would make the call and print the result to begin with, and then make the call and automatically check the result for correctness.
Tip: You'll have to copy the parameter in order to reverse in-place
ad-hoc calls
If you want to call it on an arbitrary string you supply, don't do user-as-a-file input. Do it the way real UNIX programs work: on the command line. E.g. if the program is called reverse then from the prompt type reverse hello and get back olleh on the terminal. That is, just call the function with (a copy of) argv[1].
Closing
Good luck. Keep at it!
my solution
Here's how I might write it if I had to. I don't have to, because C++ has a reverse and a reverse_copy in its standard library.
void reverse (char* s)
{
char* e = s+strlen(s); // points at nul terminator
if (s==e) return;
--e; // last char of actual string contents
while (s < e) {
// swap these two characters
char tmp = *s;
*s = *e;
*e = tmp;
// advance pointers inward
--e;
++s;
}
}
In other languages you would do this with subscripts on a string object (or native value as implemented implicitly as part of the language). You might mimic that in C, but it would actually require more registers to do that. Use the pointers! Strings are not first class value-based objects, but pointers. So go with its strengths in this case.
The difficult part is getting the boundary conditions right, and keeping it elegant without extra testing or duplicated steps. It helps to follow it along on paper or a whiteboard, showing where each pointer is.
Just what are the boundary conditions?
NULL pointer for s. Not my problem, the function is documented to take a pointer to the beginning of a nul-terminated string, and does not have NULL as part of its domain. | {
"domain": "codereview.stackexchange",
"id": 42890,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, strings",
"url": null
} |
beginner, c, strings
empty string. This is a real issue because pointing to the first and last chars will not work. So this is tested first. Now, proceeding forward, the main algorithm implementation can assume there is at least 1 character that can be pointed to.
That's enough to write the forward and backward pointers without further special cases.
where the s and p meet — how to stop? The loop drops out if they meet or cross, so it handles both odd and even length strings, and naturally doesn't bother swapping the middle character with itself.
The pointer movement (--e) is done after the test tells it to go; that is, at the top of the loop that does one character. That way it will never try to back up the e pointer when it's at the beginning (think about a single-character string!)
These same issues are involved in many of the algorithms you will be studying, so this is indeed good practice. Remember: think about boundaries, and arrange the code so that you don't need extra tests or duplicated logic. | {
"domain": "codereview.stackexchange",
"id": 42890,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, strings",
"url": null
} |
python, python-3.x, wordle
Title: Wordle word match function / cheat engine
Question: What the code does short version: Given your hints for Wordle, narrows down the list of potential matches and returns them as a list.
Slightly longer version: It takes the positions and values of your green clues, positions and values of your yellow clues, and all your gray clues and creates a regular expression to filter the Wordle word bank (and then uses two control flows on top of that to further narrow it which is part of what I suspect could be done a lot cleaner and more efficiently)
Yesterday I wrote a quick and dirty Wordle cheat engine and a few parts of my code felt poorly written as I was writing them because I was kind of stuck on my first solution and couldn't figure out how to refactor them. I know using dictionaries instead of lists for the green and yellow letters feels needlessly complicated, but I already how to fix that and I'll clean it up when I make my refactor pass so the particulars I'm more concerned about are:
I couldn't figure out how to filter the matches list further without what feels like needlessly complicated control flows where I populate the matches2 and final_matches lists in the def statement for potential_answers(). It feels inefficient, the use of a generic flag variable feels like the wrong choice, and I don't like making 3 separate lists of increasingly narrow matches
Again, I used a generic flag variable in the local scope for the get_green() and get_yellow() functions and I think it needs a better variable name
But also if you have suggestions outside of those two points please feel free and let loose your fury upon me. I want to write cleaner, more readable code in general so any suggestions or code smells you notice are welcome.
"""
A program that takes your wordle clues and
gives you potential matches in the official
wordle answer bank
"""
import re | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
python, python-3.x, wordle
import re
# Loads wordle answers and stores as list
wordle_answers = []
with open('WordleAnswers.txt', 'r') as f:
for line in f:
for word in line[1:-1].split(','):
wordle_answers.append(word.strip('"'))
wordle_answers.sort() | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
python, python-3.x, wordle
def potential_answers(green: dict, yellow: dict, gray: str) -> list:
"""
Takes 2 dicts, green, yellow, and a string gray
example expected format:
green = {1:'a', 2:'', 3:'', 4:'', 5:'e'}
yellow = {1:'', 2:'ok', 3:'', 4: '', 5:''}
gray = 'brlm'
"""
search_sequence = ['.' for i in range(5)] # stores a wildcard in every position to start
# iterate over green dict and if the value isn't empty replace the character
# at the matching index in search_sequence
for key, val in green.items():
if val:
search_sequence[key-1] = val
# create an empty string to store letters we know are in the word but don't know where
# then we iterate over yellow dict and create a regex NOT term for each
# non-empty index and append the relavent terms to the in_word variable
# this way we know to look for words that have a letter but not at the Xth index
in_word = ''
for key, val in yellow.items():
in_word += val
if val and search_sequence[key-1] == '.':
search_sequence[key-1] = '[^' + val + ']'
# converts search_sequence list into a string then into a raw string and slices
# off the single quotes introduced through the repr function
search_sequence = repr(''.join(search_sequence))[1:-1]
r = re.compile(search_sequence)
# filters based on green known letters and which letters aren't at an index
# but doesn't enforce the presence of yellow letters
matches = list(filter(r.match, wordle_answers))
# iterate through each word in matches, then iterates through every letter
# we know must be in the word, if all letters are in the word we append the
# word to our matches2 list
matches2 = []
for word in matches:
flag = True
for letter in in_word:
if letter not in word:
flag = False
if flag:
matches2.append(word)
# iterate through every word in our matches2 list and then iterate through
# every letter we know NOT to be in the word. If it contains none of the gray | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
python, python-3.x, wordle
# every letter we know NOT to be in the word. If it contains none of the gray
# letters we append our word to our final output list
final_matches = []
for word in matches2:
flag = True
for letter in gray:
if letter in word:
flag = False
if flag:
final_matches.append(word)
print('Your potential matches are:\n')
return final_matches | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
python, python-3.x, wordle
def get_green() -> dict:
"""
Gets and validates user input for green letters and formats for feeding into
the function potential_answers()
"""
green = {1:'', 2:'', 3:'', 4:'', 5:''} # initialize green dict
print("Let's get your green letters:")
print("-----------------------------")
for i in range(1,6):
flag = 0 # helps us validate user, keeping us in the while loop if not y/n
while flag != 'y' and flag != 'n':
flag = input(f'Do you know what letter is in spot {i}? (y/n)\n')
if flag != 'y' and flag !='n':
print('Please only type y or n right now\n')
if flag == 'y':
letter = '0'
while not letter.isalpha() or len(letter) != 1:
letter = input(f'What letter do you have for spot {i}?\n')
if not letter.isalpha() or len(letter) != 1:
print('Please only type a single letter right now')
# store standardized user input in the correct index of green dict
green[i] = letter.lower()
else:
continue
return green
def get_yellow() -> dict:
"""
Gets and validates user input for yellow letters and formats for passing into
function potential_answers()
"""
yellow = {1:'', 2:'', 3:'', 4:'', 5:''}
print("Let's get your yellow letters:")
print("-----------------------------")
for i in range(1,6):
flag = 0 # again helps us validate user input
while flag != 'y' and flag != 'n':
flag = input(f'Do you know a yellow letter for spot {i}? (y/n)\n')
if flag != 'y' and flag !='n':
print('Please only type y or n right now\n')
if flag == 'y':
letter = '0'
while not letter.isalpha():
letter = input(f'What yellow letters do you know for spot {i}?\n(Type all that apply)\n')
if not letter.isalpha():
print('Please only type a letter right now')
# stores standardized user input in correct index of yellow dict
yellow[i] = letter.lower()
else:
continue
return yellow | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
python, python-3.x, wordle
def get_gray() -> str:
"""
Gets and validates user input for gray letters and formats for passing into
function potential_answers
"""
gray = ''
print(f"Let's get your gray letters:")
print('-----------------------------')
while not gray and not gray.isalpha():
gray = input(f'What are your gray letters?\n(Type all that apply)\n')
if not gray.isalpha():
print('Please only type letters')
return gray.lower()
if __name__ == '__main__':
green = get_green()
yellow = get_yellow()
gray = get_gray()
potential_answers(green, yellow, gray)
Answer: Return Values
Your get_green() and get_yellow() methods returns a dict. Since your dictionary keys are just the letter indices (1 through 5), each could simply return a list[str] with 5 elements.
Zero is not a letter
letter = '0' This is very hacky. I understand you want to start off with a string that isn't .isalpha(), so your while not letter.isalpha() loop will execute as least once. Better would be letter = '' as ''.isalpha() also returns False.
Usability
If your Wordle guess happens to hit all 5 letters, you can enter in 1 green letter and the 4 yellow letters, but then the program asks for gray letters and you don't have any, but it won't accept that, because ''.isalpha() is False! You have to make-up a gray letter, despite not actually having an actual gray letter.
There is no point asking about a yellow letter in position 3 if you have a green letter in position 3! Pass green into the get_yellow() function, so you can skip meaningless data entry.
Singular -vs- Plural
In get_yellow(), you ask for yellow letters (plural), but store the answer in letter (singular). Rename this.
Unnecessary Continue
for ...:
if ...:
...
else:
continue | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
python, python-3.x, wordle
There is no reason for the else: continue. These are unnecessary statements.
PEP-8
The Style Guide for Python Code specifies commas should be followed by a space (eg, range(1, 6)), and colons in dictionary keys should be followed by a space (eg, {1: '', 2: '', 3: '', 4: '', 5: ''}.
Standard indentation is 4 spaces, not 2.
Potential Answers
search_sequence could be initialized with search_sequence = ['0'] * 5. Better, if green was a list[str], you could use:
search_sequence = [letter if letter else '.' for letter in green]
Why are you using repr and stripping off quotes?
search_sequence = repr(''.join(search_sequence))[1:-1]
The result of ''.join() is already the required string:
search_sequence = ''.join(search_sequence))
The result of filter is a generator. You don't need to realize it as a list, wasting memory. Simply use it in the for loop:
matches = filter(r.match, wordle_answers)
for word in matches:
...
or even:
for word in filter(r.match, wordle_answers):
...
Use all() when you want to ensure all of an iterable collection of tests passes.
flag = True
for letter in in_word:
if letter not in word:
flag = False
becomes:
flag = all(letter in word for letter in in_word)
This means match2 could be simply:
match2 = [word for word in filter(r.match, wordle_answers)
if all(letter in word for letter in in_word)]
Even better: turn in_word into (or build it as) a set, and leave match2 as another generator:
in_word = set(in_word)
match2 = (word for word in filter(r.match, wordle_answers) if set(word) >= in_word)
Similarly, turn gray into a set. If set(gray) & set(word) is not empty, then word contains a letter in gray, and can be excluded.
in_word = set(in_word)
final_matches = [word for word in match2 if gray.isdisjoint(word)] | {
"domain": "codereview.stackexchange",
"id": 42891,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, wordle",
"url": null
} |
c++, multithreading, priority-queue
Title: C++ Thread safe priority queue implementation
Question: My first attempt at writing a thread safe priority_queue. It is not the most efficient because the locks can be even more fine grained if I add implementation of heap instead of using priority_queue but later.
Goal is to create a thread safe priority queue with timestamp as the ordering. Then extend it where a thread pool can pick up the earliest entry by using wait_pop() and work on it.
struct Entry
{
int timestamp;
int key;
int value;
Entry(int _timestamp, int _key, int _value) : timestamp(_timestamp), key(_key), value(_value) {}
bool operator < (const Entry& entry) const
{
return timestamp < entry.timestamp;
}
bool operator > (const Entry& entry) const
{
return timestamp > entry.timestamp;
}
};
struct Compare
{
template<class T>
bool operator()(const T& a, const T& b) const
{
return a > b;
}
};
template<typename T>
class threadsafe_priority_queue
{
private:
std::mutex mtx;
priority_queue<T, vector<T>, Compare> pq;
std::condition_variable data_cond;
public:
threadsafe_priority_queue(){}
void push(T val)
{
std::lock_guard<std::mutex> lk(mtx);
pq.push(std::move(val));
data_cond.notify_one();
}
//not using top() to avoid race condition between top() and pop()
//wait version
T wait_pop()
{
std::unique_lock<std::mutex> lk(mtx);
data_cond.wait(lk, [this] { return !pq.empty();});
T val = std::move(pq.top());
pq.pop();
return val;
}
//nowait version
T nowait_pop()
{
std::lock_guard<std::mutex> lk(mtx);
if (pq.empty())
{
throw std::exception("Cannot pop an empty priority queue");
}
T val = std::move(pq.top());
pq.pop();
return val;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(mtx);
return pq.empty();
}
}; | {
"domain": "codereview.stackexchange",
"id": 42892,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, priority-queue",
"url": null
} |
c++, multithreading, priority-queue
bool empty() const
{
std::lock_guard<std::mutex> lk(mtx);
return pq.empty();
}
};
int main() {
threadsafe_priority_queue<Entry> pq;
pq.push(Entry(1, 2, 4));
pq.push(Entry(5, 2, 4));
pq.push(Entry(2, 2, 4));
pq.push(Entry(7, 2, 4));
Entry e = pq.wait_pop();
cout << e.timestamp << endl;
return 0;
}
Answer: Haven't used locks too often, but a few things I noticed in general:
Your code is incomplete and lacks headers, even though it seems to be meant as a complete example (e.g. including main()).
Indentation is inconsistent, but this might be a result of pasting the code here.
More of a personal preference, but I'm not a fan of using template parameters over and over again, so I'd add one or two local aliases to avoid having to repeat them:
namespace {
using unique_lock = std::unique_lock<std::mutex>;
using lock_guard = std::lock_guard<std::mutex>;
}
Instead of implementing your own comparator, you could just use std::greater (if available).
You're using cout, vector, endl, and priority_queue without namespace. Any chance you're using using namespace std;? As you can see, this causes inconsistent code and might cause trouble if you reuse code somewhere else. Plus there's always the danger of some naming conflicts.
Your example/testing code doesn't use multiple threads, so no matter how often you try, you won't run into issues, unless there's some inherent bug somewhere. You should at least spawn one additional thread and let both do something for a bit.
Compare should be called greater or greater_than (ideally in a local/anonymous namespace), since it's only providing this type of comparison. But as mentioned, might be obsolete.
nowait_pop() is certainly debatable, but how about no_wait_pop or pop_immediate() to keep words separated or functionality grouped together? | {
"domain": "codereview.stackexchange",
"id": 42892,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, priority-queue",
"url": null
} |
c++, multithreading, priority-queue
Entry(int _timestamp, int _key, int _value): I'm not a fan of starting parameters with an underscore. I'd only do it to denote parameters not yet used (e.g. for future revisions). IMO you can totally reuse the member names in such a trivial context:
Entry(int timestamp, int key, int value) : timestamp(timestamp), key(key), value(value) {}
This code isn't ambiguous in any way and there's no danger of modifying the wrong value by accident.
More of a bonus thing: This is a multiple readers, one (or more) writers scenario, so one could try to avoid std::lock_guard and use std::unique_lock everywhere. If three threads want to check empty() at the same time, just let them do so. | {
"domain": "codereview.stackexchange",
"id": 42892,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, priority-queue",
"url": null
} |
javascript
Title: TapeEquilibrium - codility - JavaScript
Question: Problem
A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
We can split this tape in four places:
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7
Write a function:
function solution(A);
that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
the function should return 1, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−1,000..1,000].
My solution:
A = []
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
if (A.length > 0) {
let defArr = [];
let l = [];
let all = A.reduce((a, b) => {
l.push(a)
return a + b
})
l.forEach((item) => {
defArr.push(Math.abs(all - (item + item)))
})
return Math.min(...defArr)
}
return 0;
}
console.log(solution(A))
Answer: Logically, the code looks correct but from performance perspective, there are few things that can be improved. Let's look at the 2 points:
Time Complexity: O(n) - 1 loop, 1 reduce and 1 Math.min. All run in O(n) time.
Space Complexity: O(n) - Two arrays - defArr and l which have size n | {
"domain": "codereview.stackexchange",
"id": 42893,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
There is nothing can be done for time complexity but space complexity can be reduced to constant space. No need to have additional arrays. One can simply loop and store intermediate values in temporary variables.
I have re-written the same. Inside the loop, at each index, the difference is calculated and compared to a min variable. If the new min is lesser than existing one; then update min otherwise do next iteration.
A = []
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
function solution(A) {
let sum = A.reduce((total, value) => total + value, 0)
let min = Number.POSITIVE_INFINITY
let cumulativeSum = 0
for (let i = 0; i < A.length - 1; ++i) {
cumulativeSum = cumulativeSum + A[i]
sum = sum - A[i]
diff = Math.abs(sum - cumulativeSum)
if (diff < min) {
min = diff
}
}
return min
}
console.log(solution(A))
Hope it helps. Revert for any doubts/clarifications. | {
"domain": "codereview.stackexchange",
"id": 42893,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
python, python-3.x, reinventing-the-wheel, file-system
Title: A file class for Python
Question: This is the entire code segment. All the functions for file operations are working perfectly. I just need a professional to help me clarify that am following good standards, documentation, etc., because I am going to start doing professional work very soon and I need my code to be at a professional level.
import os
class FileHandle:
def __init__(self, file_path):
self.file_path = file_path
def file_exists(self) -> bool:
"""Determine if a file exists"""
if os.path.exists(self.file_path):
return True
return False
def read_string(self) -> str:
"""Read the string format of a file"""
with open(self.file_path, "r") as current_file_handle:
return current_file_handle.read()
def read_bytes(self) -> bytes:
"""Read the byte format of a file"""
with open(self.file_path, "rb") as current_file_handle:
return current_file_handle.read()
def read_string_lines(self) -> list:
"""Get a list of lines in string format from file"""
with open(self.file_path, "r") as current_file_handle:
return current_file_handle.readlines()
def read_byte_lines(self) -> list:
"""Get a list of lines in byte format from file"""
with open(self.file_path, "rb") as current_file_handle:
return current_file_handle.readlines()
def write_string(self, string: str) -> int:
"""Overwrite the file with a string"""
with open(self.file_path, "w") as current_file_handle:
current_file_handle.write(string)
return 0
def write_bytes(self, string: bytes) -> int:
"""Overwrite the file with bytes"""
with open(self.file_path, "wb") as current_file_handle:
current_file_handle.write(string)
return 0 | {
"domain": "codereview.stackexchange",
"id": 42894,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, reinventing-the-wheel, file-system",
"url": null
} |
python, python-3.x, reinventing-the-wheel, file-system
def append_string(self, string: str) -> int:
"""Add a string to a file"""
with open(self.file_path, "a") as current_file_handle:
current_file_handle.write(string)
return 0
def append_bytes(self, string: bytes) -> int:
"""Add a byte string to a file"""
with open(self.file_path, "ab") as current_file_handle:
current_file_handle.write(string)
return 0
def copy(self, dist: str) -> int:
"""Copy the file to the destination"""
os.system(f'copy "{self.file_path}" {dist}')
if os.path.exists(dist):
return 0
return 1
def move(self, dist: str):
"""Move the file to the destination"""
os.system(f'move "{self.file_path}" {dist}')
if os.path.exists(dist):
return 0
return 1
def delete(self) -> int:
"""Delete the file"""
os.remove(self.file_path)
if self.file_exists():
return 1
return 0
def add_attribute(self, attribute: str):
"""Add attributes to the file
Possible attributes:
1.H - for hidden file
2.A - for archive file
3.R - for readonly file
4.S - for system file
"""
os.system(f"attrib +{attribute.upper()} {self.file_path}")
def remove_attribute(self, attribute: str):
"""Removes attributes from the file
Possible attributes:
1.H - for hidden file
2.A - for archive file
3.R - for readonly file
4.S - for system file
"""
os.system(f"attrib -{attribute.upper()} {self.file_path}")
def rename(self, new_name: str) -> int:
"""Renames the file"""
os.system(f"ren {self.file_path} {new_name}")
if not os.path.exists(new_name):
return 1
return 0 | {
"domain": "codereview.stackexchange",
"id": 42894,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, reinventing-the-wheel, file-system",
"url": null
} |
python, python-3.x, reinventing-the-wheel, file-system
Answer: I'm about to say a lot of fairly unkind-sounding things. I'll say upfront, though, that this is generally good, simple, well-documented code. Unfortunately, it makes a pretty serious mistake that I think you would greatly benefit from understanding. If it were to be presented to me in a professional setting, I'd block any pull request including it as hard as I possibly could.
This code is dangerous
Suppose another developer were to take your class and use it like this:
fh = FileHandle(some_user_input_file)
fh.move(f"backup/{some_user_input_file}")
They'd expect that this would cause the file input by the user to be moved to the backup directory. All fine.
Now, I can't test this out myself right now so take it with a little grain of salt, but I bet that if a user were to input the filename a" b & calc & echo ", something quite surprising would happen. Take a look at this code:
some_user_input_file = """ a" b & calc & echo " """
fh = FileHandle(some_user_input_file)
fh.move(f"backup/{some_user_input_file}")
Think for a bit about what you expect to happen before running. Stop reading this answer and run it before you carry on.
You should have seen the Windows calculator pop up. If you didn't, I've screwed up that filename somewhere, which makes my point a little weaker, but fairly modest tweaks would still cause this vulnerability. In brief, your code would ultimately execute:
os.system(f'move " a" b & calc & echo " " backup/...') | {
"domain": "codereview.stackexchange",
"id": 42894,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, reinventing-the-wheel, file-system",
"url": null
} |
python, python-3.x, reinventing-the-wheel, file-system
This shell command will move some random file to somewhere else, then it'll run calc, then it'll echo some stuff to the terminal. Now suppose the command wasn't calc and was instead some command that wiped your hard drive, or downloaded some ransomware, or some other horrid thing.
I don't think anyone using a FileHandle class would expect it to be at all capable of doing that under any circumstances. If any developer were to use this class, they'd have to know that, if they failed to properly validate user data, your class could start executing arbitrary code.
This sort of surprising behaviour is exactly what caused the absolutely terrifying log4shell vulnerability - a logging library was able to execute arbitrary code, developers quite reasonably weren't expecting this so didn't validate the input themselves, and now millions of systems are vulnerable.
I can come up with three mitigations, in descending order of preference:
Remove your reliance on scary functions like os.system
You almost never need to execute shell commands - shell commands are usually just wrappers for much simpler and cleaner APIs. If you're interfacing with some third-party application, just type "name of application python API" into your favourite search engine and use that where possible. It'll be much easier and much safer.
In your case, there's no need to use os.system at all. The commands you're using can be replaced with shutil.copy, shutil.move, and win32api.SetFileAttributes.
Given the risks associated with os.system and the fairly straightforward alternatives, this is by far the best idea
If you absolutely have to shell out, use subprocess.run with a list of arguments
In the incredibly unusual event that you absolutely have to use a shell command, subprocess.run is far more secure. Rather than separating your commands with spaces, you'd put them in a list. Something like this:
subprocess.run(["move", self.file_path, dist]) | {
"domain": "codereview.stackexchange",
"id": 42894,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, reinventing-the-wheel, file-system",
"url": null
} |
python, python-3.x, reinventing-the-wheel, file-system
This makes sure that arguments are passed directly to the subprocess, without going via a shell that might get confused between what's an argument to a command and what's a separate command entirely.
You should not use subprocess.run in this case, since you do not need to shell out at all. Use my first suggestion, but know that this is an option for the rare case where you do need to shell out.
Validate input as though your users are attackers
This is very hard to get right. Sometimes, though, you really really need to accept user input and pass it to something dangerous.
In this case, have strict rules about what characters are valid. On windows, for instance, a filename cannot contain certain characters. At the very least, all methods that expect to take a file path should check that the input it's been given doesn't contain those characters and raise ValueError if it does. It's worth doing that validation anyway, since catching errors early makes your code easier to use.
Test your validation rigorously, and look up other characters that might have a special meaning and how to handle them safely, and be distinctly aware that your validation may not necessarily be complete, and that safer alternatives (like my other two solutions!) may also exist and be easier to use. | {
"domain": "codereview.stackexchange",
"id": 42894,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, reinventing-the-wheel, file-system",
"url": null
} |
c++, singleton
Title: C++ Settings Manager
Question: I'm starting a new project, and it needs to be set up using YAML files.
To handle all the settings, I've created a singleton class, I'd like you guys to review.
Here is the header:
#pragma once
#include <memory>
#include <string>
struct Settings {
struct General {
bool verbose;
bool debug;
} general;
struct Server {
uint16_t port;
} server;
struct SGX {
bool enabled;
struct RemoteAttestation {
bool enabled;
std::string server;
uint16_t port;
bool is_linkable;
bool use_rdrand;
bool quote_only;
std::string nonce;
std::string pubkey;
std::string spid;
bool epid_mode;
} remote_attestation;
} sgx;
};
class SettingsManager {
private:
Settings s {
.general = {
.verbose = false,
.debug = true
},
.server {
.port = 8080
},
.sgx = {
.enabled = true,
.remote_attestation {
.enabled = true,
.server = "localhost",
.port = 7777,
.is_linkable = true,
.use_rdrand = true ,
.quote_only = false,
.nonce = "" ,
.pubkey = "",
.spid = "",
.epid_mode = false,
}
}
};
bool open_and_parse(std::string file);
SettingsManager() {} // Disallow instantiation outside of the class.
public:
SettingsManager(const SettingsManager&) = delete;
SettingsManager& operator=(const SettingsManager &) = delete;
SettingsManager(SettingsManager &&) = delete;
SettingsManager & operator=(SettingsManager &&) = delete;
void print(); | {
"domain": "codereview.stackexchange",
"id": 42895,
"lm_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++, singleton",
"url": null
} |
c++, singleton
void print();
static std::shared_ptr<SettingsManager> instance(const std::string file) {
static std::shared_ptr<SettingsManager> instance(new SettingsManager());
if (instance->open_and_parse(file) == false)
instance = nullptr;
return instance;
}
const Settings& settings = s;
};
And the implementation:
#include "SettingsManager.h"
#include <fstream>
#include <streambuf>
#include <yaml-cpp/yaml.h>
#include <fmt/core.h>
bool SettingsManager::open_and_parse(const std::string file) {
// read file content to buffer
YAML::Node config = YAML::LoadFile(file);
s.general.debug = config["settings"]["general"]["debug"].as<bool>();
s.general.verbose = config["settings"]["general"]["verbose"].as<bool>();
s.server.port = config["settings"]["server"]["port"].as<uint16_t>();
s.sgx.enabled = config["settings"]["sgx"]["enabled"].as<bool>(); | {
"domain": "codereview.stackexchange",
"id": 42895,
"lm_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++, singleton",
"url": null
} |
c++, singleton
s.sgx.enabled = config["settings"]["sgx"]["enabled"].as<bool>();
s.sgx.remote_attestation.enabled = config["settings"]["sgx"]["remote_attestation"]["enabled"].as<bool>();
s.sgx.remote_attestation.server = config["settings"]["sgx"]["remote_attestation"]["server"].as<std::string>();
s.sgx.remote_attestation.port = config["settings"]["sgx"]["remote_attestation"]["port"].as<uint16_t>();
s.sgx.remote_attestation.is_linkable = config["settings"]["sgx"]["remote_attestation"]["is_linkable"].as<bool>();
s.sgx.remote_attestation.use_rdrand = config["settings"]["sgx"]["remote_attestation"]["use_rdrand"].as<bool>();
s.sgx.remote_attestation.quote_only = config["settings"]["sgx"]["remote_attestation"]["quote_only"].as<bool>();
s.sgx.remote_attestation.nonce = config["settings"]["sgx"]["remote_attestation"]["nonce"].as<std::string>();
s.sgx.remote_attestation.pubkey = config["settings"]["sgx"]["remote_attestation"]["pubkey"].as<std::string>();
s.sgx.remote_attestation.spid = config["settings"]["sgx"]["remote_attestation"]["spid"].as<std::string>();
s.sgx.remote_attestation.epid_mode = config["settings"]["sgx"]["remote_attestation"]["epid_mode"].as<bool>();
return true;
}
void SettingsManager::print() {
fmt::print("Settings:\n");
auto bool_to_symbol {
[](bool value) -> std::string {
if (value == true)
return "✅";
else
return "❌";
}
};
// print all the settings
}
I know singletons are considered as a bad practice, but it really helps making everything clean. Oh and yes, I hate naming a class "...Manager" too.
In advance, thanks everyone. | {
"domain": "codereview.stackexchange",
"id": 42895,
"lm_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++, singleton",
"url": null
} |
c++, singleton
Answer: A better way to make a singleton
You don't need to use a std::shared_ptr to make a singleton, and you also can do it with just one class, so no need for a "manager". See this post outlining how to make a singleton in C++11. In your case, it can look like this:
class Settings {
// Private constructor, also opens and parses the file
Settings(const std::string& file);
public:
// Deleted copy constructor and assignment
Settings(const Settings&) = delete;
void operator=(const Settings&) = delete;
// Static function for getting an instance
Settings& instance(const std::string& file) {
static Settings settings(file);
return settings;
}
// Any member functions operating on Settings
void print() const;
// The actual data members
struct {
bool verbose;
bool debug;
} general;
...
};
The only effective difference here is that you return an empty std::shared_ptr if the file could not be loaded, whereas here you always get a valid reference to the Settings singleton. You could decide to either throw an exception if loading settings failed, or add a boolean member variable to indicate whether settings were successfully loaded from a file or not.
Consider not using the singleton pattern
The singleton pattern really is not that great. Often when you need a singleton, you can just have a regular class or struct, and just instantiate one object of that type. In a header file you put this:
struct Settings {
...
};
extern Settings settings;
And then in exactly one source file you write:
Settings settings; | {
"domain": "codereview.stackexchange",
"id": 42895,
"lm_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++, singleton",
"url": null
} |
c++, singleton
extern Settings settings;
And then in exactly one source file you write:
Settings settings;
If you can make sure that you parse and load the file into settings before any other code starts using the contents of settings, the above will work absolutely fine. It also looks very clean to me. It avoids all the shenanigans with deleted destructors, instance() functions returning references to static member variables, or std::shared_ptrs in your code.
Also note that having to pass a filename to instance() everytime doesn't make a lot of sense. Also think about what would happen if two callers pass a different filename. | {
"domain": "codereview.stackexchange",
"id": 42895,
"lm_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++, singleton",
"url": null
} |
c++, beginner, datetime
Title: Create a formatted calendar
Question: I'm working on a project that creates a calendar based on user input of a month and a year. With that information, the code should count the number of days in that month and output a calendar. I would love to have extra eyes on my code. I'm still a beginner and limiting myself to just the libraries mentioned in the code!
I want to know if there is a simpler way to write this code or any suggestions on what I should change to make the code simpler. I was thinking of incorporating switch statements, but don't really know how to. Any feedback is appreciated! Right now my code looks oversimplified.. right?
#include <cmath>
#include <iostream>
using namespace std;
int month, day, year, start;
#define MONTHS_PER_YEAR 12 // Cannot change.
const unsigned short DAYS_PER_MONTH[MONTHS_PER_YEAR] =
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Cannot change.
const char MONTH_NAMES[MONTHS_PER_YEAR][10] =
{"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"}; // Cannot change.
bool leapYear()
{
if (((year % 4 == 0) && year % 100 != 0) || year % 400 == 0)
{
return false;
}
else
{
return true;
}
}
//I actually do not think I am supposed to use static.
int day_of()
{
static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
year = year - month < 3;
return ( year + year /4 - year /100 + year /400 + t[month-1] + day) % 7;
}
void printMonth()
{
start = day_of();
int count, days_in_month = DAYS_PER_MONTH[month - 1];
if (leapYear() && month == 2)
{
days_in_month = DAYS_PER_MONTH[month - 1] + 1;
}
if (start == 6)
{
start = -1;
cout << " ";
}
for (count = 0; count <= start; count++)
{
cout << (count > 0? " ": " "); | {
"domain": "codereview.stackexchange",
"id": 42896,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, datetime",
"url": null
} |
c++, beginner, datetime
}
for (day = 1; day <= days_in_month; day++)
{
if (++count > 6)
{
count = 0;
if (day > 9)
{
cout << day << '\n';
}
else
{
cout << day << '\n' << " ";
}
}
else
{
if (day >= 9)
{
cout << day;
}
else
{
cout << day << " ";
}
cout << " ";
}
}
cout << endl;
}
// Controls operation of the program.
int main()
{
cout << "Enter the month: ";
cin >> month;
cout << "Enter the year: ";
cin >> year;
cout << MONTH_NAMES[month - 1] << " " << year << std::endl;
cout << "Su" << " "<< "M" << " "<< "T"<< " " << "W" << " " << "Th" << " " << "F" << " " << "Sa\n";
printMonth();
cout << endl;
return 0;
}
Answer: That leapYear looks strange to me, to know if the year is leap year you need something like this:
bool leapYear()
{
return !(((year % 4 == 0) && year % 100 != 0) || year % 400 == 0) ;
}
Some function name are a bit weird. Also what happens if somebody type month > 12?
#include <cmath>
is not necesary, since no math functions are used. | {
"domain": "codereview.stackexchange",
"id": 42896,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, datetime",
"url": null
} |
c#, winforms, pdf
Title: How to optimize the code of my pdf generation from DGV code using iText5 & c#?
Question: I have 2 DGV's one containing bills info & another containing credit notes info. When at least one item from both the DGV's are selected then it should generate a pdf (result1) taking data from both the DGV's & some standard header, footer & letter format text using some info.
And when only billsDGV data is selected then it should be like below
Here is what I've done(button click event):
if (creditNotesDGV.SelectedRows.Count > 0)
{
if (creditNotesDGV.SelectedRows.Count > 3)
{
MetroMessageBox.Show(this,"Please select 3 or less Credit/Debit notes","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
return;
}
if (billsDGV.SelectedRows.Count > 0 && billsDGV.SelectedRows.Count < 9)
{
total = billsDGV.SelectedRows.OfType<DataGridViewRow>()
.Sum(t => Convert.ToDecimal(t.Cells[2].Value));
_total = creditNotesDGV.SelectedRows.OfType<DataGridViewRow>()
.Sum(t => Convert.ToDecimal(t.Cells[2].Value));
amt=total-_total;
if (amt < 0) {
MetroMessageBox.Show(this,"Sum of CN/DN value is higher than sum of Invoice value!","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
return;
}
Gen1stTable();
Gen2ndTable(pdoc);
GenLastPart();
pdoc.Close();
Process.Start(@"F:\test.pdf");
}
else{
MetroMessageBox.Show(this,"Please select minimum 1 item and/or maximum 8 items","Selection Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
} | {
"domain": "codereview.stackexchange",
"id": 42897,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms, pdf",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.