body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I'm currently learning <a href="https://nodejs.org/en/about/" rel="nofollow noreferrer">Node.js</a>. To practice, I've decided to create a login server. The program goes as follows:</p>
<ol>
<li>User connects to local website (10.0.0.79, props to <a href="https://stackoverflow.com/a/19387755/8968906">this users answer</a> for helping me figure out how to set it up)</li>
<li>User is presented with a login screen, with fields <b>username</b> and <b>password</b>.</li>
<li>User enters the username and password, and the server checks if there are any matches, reading from a <code>JSON</code> file, <code>creds.json</code>.</li>
</ol>
<p>This is the file layout:</p>
<pre><code>NodeServer
|-node_modules
|-(packages installed with node)
|-creds.json
|-index.html
|-index.js
|-log.txt
|-package-lock.json
|-package.json
</code></pre>
<p>There are a few areas I would like feedback on:</p>
<ul>
<li><strong>SECURITY</strong>: Is my website secure in any way, shape, or form? I'm wondering if I could implement any security measures other than the ones that are built in to the methods provided by <code>Node.js</code>. Also, I know the passwords are plainly obvious to guess, but they are like that to ensure logging in as different users works.</li>
<li><strong>EFFICIENCY</strong>: Is how I'm checking usernames and password efficient? Is there any better way to do this?</li>
<li><strong>BUILDING</strong>: Is how I loaded my website acceptable? Reading from a file and then ending the response?</li>
<li><strong>ASYNC/SYNC</strong>: I know I preform <code>async</code> and <code>sync</code> calls at the same time. Is there any problem to this?</li>
<li><strong>LOGGING</strong>: I log all connections to the server, and all login attempts. Is this a good practice, or am I overdoing what logging is supposed to accomplish?</li>
</ul>
<p>Any and all feedback is appreciated and considered!</p>
<p><strong>index.js</strong></p>
<pre><code>/* NODE START */
const http = require('http');
const fs = require('fs');
const url = require('url');
const port = 80;
var logFile = "log.txt";
const server = http.createServer(function(request, response) {
if(request.method = 'POST') {
let body = '';
request.on('data', chunk => {
body += chunk.toString();
});
request.on('end', () => {
//parse data
var credentials = body.split('&');
//Use below conditional in case there is an empty login attempt, or
//there is a page reload that contains no data
if(!(credentials[0] === '')) {
var username = credentials[0].substring(9);
var password = credentials[1].substring(9);
console.log(username + " " + password);
login(username, password, request);
}
});
}
//LOADING WEBPAGE
response.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', function(error, data) {
if(error) {
response.writeHead(404);
response.write("Error: File Not Found");
} else {
response.write(data);
}
response.end();
});
//LOGGING
var address = request.socket.remoteAddress;
var logData = "[*] CONNECTION \n";
logData += "\t[+] FROM - " + address + "\n";
logData += "\t[+] DATE - " + getDate() + "\n";
logData += "\t[+] TIME - " + getTime() + "\n";
if(!(request.url === '/favicon.ico')) {
fs.appendFileSync(logFile, logData);
}
});
server.listen(port, '0.0.0.0');
console.log("Server is listening on port " + port);
function getDate() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return month + "." + day + "." + year;
}
function getTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
return hour + ":" + min + "." + sec;
}
function login(username, password, request) {
let rawdata = fs.readFileSync('creds.json');
let creds = JSON.parse(rawdata);
let users = ['ben', 'hannah', 'kristen', 'tony', 'katherine'];
for(var i = 0; i < users.length; i++) {
var person = creds[users[i]];
if(person['username'] === username && person['password'] === password) {
console.log("User [" + username + "] logged in!");
//LOG USER LOGIN
var userLoginData = "[*] LOGIN \n";
var loginAddress = request.socket.remoteAddress;
userLoginData += "\t[+] USER - " + username + "\n";
userLoginData += "\t[+] FROM - " + loginAddress + "\n";
userLoginData += "\t[+] DATE - " + getDate() + "\n";
userLoginData += "\t[+] TIME - " + getTime() + "\n";
fs.appendFileSync(logFile, userLoginData);
break;
}
}
}
/* NODE END */
/*
STATUS CODES
2xx: Success
- 200: OK
- 201: Created
- 204: No Content
- 202: Accepted
3xx: Redirection
- 304: Not Modified
- 301: Moved Permanently
4xx: Client Error
- 404: Not Found
- 401: Unauthorized
- 400: Bad Request
- 403: Forbidden
- 409: Conflict
*/
</code></pre>
<p><strong>index.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Login Portal</title>
<style type="text/css">
input[type="text"], input[type="password"] {
border-radius: 10px;
width: 230px;
height: 35px;
font-size: 30px;
margin: 5px;
}
input[type="submit"] {
border-radius: 10px;
width: 100px;
height: 50px;
font-size: 20px;
}
label { font-size: 30px; }
#centered { text-align: center; margin-top: 200px; }
</style>
</head>
<body bgcolor="pink">
<div id="centered">
<h1>Login Portal</h1>
<form method="post" action="/">
<label>Username:</label>
<input type="text" name="username"><br>
<label>Password:</label>
<input type="password" name="password"><br>
<input type="submit">
</form>
</div>
</body>
</html>
</code></pre>
<p><strong>creds.json</strong></p>
<pre><code>{
"ben": {
"username": "benus123",
"password": "benpw123"
},
"hannah": {
"username": "hannahus123",
"password": "hannahpw123"
},
"kristen": {
"username": "kristenus123",
"password": "kristenpw123"
},
"tony": {
"username": "tonyus123",
"password": "tonypw123"
},
"katherine": {
"username": "katherineus123",
"password": "katherinepw123"
}
}
</code></pre>
<p><strong>Excerpt from the log file</strong></p>
<pre><code>[*] CONNECTION
[+] FROM - 10.0.0.79
[+] DATE - 06.29.2019
[+] TIME - 22:54.38
[*] LOGIN
[+] USER - benus123
[+] FROM - 10.0.0.79
[+] DATE - 06.29.2019
[+] TIME - 22:54.38
</code></pre>
| [] | [
{
"body": "<p>Just addressing one of your questions.</p>\n<blockquote>\n<p><em>"SECURITY: Is my website secure in any way, shape, or form?"</em></p>\n</blockquote>\n<h1><strong>No it is not!!!</strong></h1>\n<h2>Reasons</h2>\n<ol>\n<li><p>Insecure transport. You should never send private data via an unsecured protocol. HTTP will let anyone see all the data communicated between you (server) and the client. YOU MUST USE <a href=\"https://en.wikipedia.org/wiki/HTTPS\" rel=\"noreferrer\">HTTPS</a> or an alternative high level encryption when communicating any form of private data.</p>\n<p>Node.js supports <a href=\"https://nodejs.org/api/https.html\" rel=\"noreferrer\">HTTPS</a></p>\n</li>\n<li><p>Insecure Data Store. The file <code>creds.json</code> is open for anyone that can gain access to it. You should NEVER store private data unencrypted no mater how secure you think your server may be.</p>\n<p>Node.js provides an <a href=\"https://nodejs.org/api/crypto.html\" rel=\"noreferrer\">encryption module</a> you can use to secure server side data.</p>\n</li>\n<li><p>Insecure source code. You have user names in the source code, this should never be done. There should be only one source of private data (see point 2 above)</p>\n</li>\n<li><p>Insecure logging. You should never log data that contains private client data, or log information in such a way such that a reference/association can be made between a client and logged data without access to encryption keys.</p>\n</li>\n</ol>\n<h2>Private data</h2>\n<p>You must consider all data related to a client as extremely sensitive. Its not only the password but handles (usernames), IP addresses, log on/off time/dates and more.</p>\n<p>My advice is DON'T attempt to create your own authentication and log in system. Use existing services and/or systems.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T14:12:33.440",
"Id": "223245",
"ParentId": "223228",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "223245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T03:12:42.343",
"Id": "223228",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"server"
],
"Title": "Login Server with Node.js"
} | 223228 |
<p>I am designing my first payment service and here is my db structure.</p>
<p>Each user can have many businesses, each business can have many products. Some are recurring, some are paid once. Each product is tied to payment method. Some products are always free, and some are paid every X days.</p>
<pre><code>CREATE TABLE `payment_method` (
`payment_method_id` int(11) NOT NULL auto_increment,
`payment_method_name` VARCHAR(20) DEFAULT NULL,
`payment_method_status` ENUM('active','disabled') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'active',
PRIMARY KEY (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `product_type` (
`product_type_code` varchar(50) NOT NULL,
`product_type` varchar(150) NOT NULL,
`product_type_name` varchar(150) NOT NULL,
PRIMARY KEY (`product_type_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_price` decimal(12,2) DEFAULT NULL,
`product_duration` int(11) DEFAULT NULL,
`product_currency` varchar(50) NOT NULL,
`recurring` enum('yes','no') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'yes',
`daily_limit` int(11) DEFAULT NULL,
`monthly_limit` int(11) DEFAULT NULL,
`lifetime_limit` int(11) DEFAULT NULL,
`product_type_code` varchar(50) NOT NULL,
`product_description` varchar(150) DEFAULT NULL,
PRIMARY KEY (`product_id`),
FOREIGN KEY (product_type_code) REFERENCES product_type(product_type_code)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `product_detail` (
`product_detail_id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`key` varchar(150) DEFAULT NULL,
`value` varchar(150) DEFAULT NULL,
PRIMARY KEY (`product_detail_id`),
KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `business_product` (
`business_product_id` int(11) NOT NULL,
`product_id` int(11) DEFAULT NULL,
`business_id` int(11) DEFAULT NULL,
`added_by_user_id` int(11) NOT NULL,
`product_price` decimal(12,2) DEFAULT NULL,
`product_currency` varchar(5) NOT NULL,
`product_type` varchar(150) NOT NULL,
`business_product_status` enum('paid','canceled') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`start_date` date NOT NULL,
`end_date` date DEFAULT NULL,
`last_update_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`business_product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_authorized` (
`user_authorized_id` int(11) NOT NULL auto_increment,
`payment_method_id` int(11),
`authorized` varchar(150),
`autopay` enum('yes','no') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'yes',
PRIMARY KEY (`user_authorized_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
CREATE TABLE `billing` (
`billing_id` int(11) NOT NULL auto_increment,
`external_id` VARCHAR(100) DEFAULT NULL,
`invoice_date` datetime,
`bill_date` datetime,
`start_date` date,
`end_date` date,
`payment_method_id` int(11) default NULL,
`user_id` int(11) default NULL,
`authorized` VARCHAR(200) DEFAULT NULL,
`fee` decimal(12,2) default NULL,
`notes` varchar(500) default NULL,
`billing_status` ENUM('new','paid','returned','canceled', 'pending', 'overdue') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'new',
PRIMARY KEY (`billing_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;
CREATE TABLE `billing_detail` (
`billing_detail_id` int(11) NOT NULL auto_increment,
`billing_id` int(11) NOT NULL,
`product_id` int(11),
`business_id` int(11),
`product_price` decimal(12,2),
PRIMARY KEY (`billing_detail_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;
```
What do you think am I missing something?
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T10:57:36.430",
"Id": "432519",
"Score": "1",
"body": "Thanks for joining Code Review.SE and asking a clear question. It would be nice to have an ERD or clearer statement of the business requirements to provide helpful context for the code review for future questions you might do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T12:37:36.477",
"Id": "432524",
"Score": "0",
"body": "I also cannot review this until I know what it is going to be used for. Saying it is a \"payment service\" is super vague. Are these businesses paying or do they get paid? No taxes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T02:28:26.570",
"Id": "432583",
"Score": "0",
"body": "Hello, we are getting paid. We have one off products and recurring products"
}
] | [
{
"body": "<h3>Consistency</h3>\n\n<ul>\n<li>I like the naming convention of the auto-incrementing primary keys to be prefixed with the table name. This allows the use of <code>using (keyname)</code> when <em>joining</em> tables.</li>\n<li>Some tables are created with <code>IF NOT EXISTS</code>, other aren't. Is there a strategy behind this?</li>\n</ul>\n\n<h3>Design</h3>\n\n<ul>\n<li>I am missing tables <code>user</code> and <code>business</code>.</li>\n<li>Table <code>business_product</code> has a column <code>product_type</code> which overrides that of the referenced table <code>product_type</code>. Is this as designed?</li>\n<li>Perhaps table <code>user_authorized</code> should be renamed to <code>user</code>, update the name of the primary key and referenced foreign keys along. (This has an impact on the constraints below)</li>\n</ul>\n\n<h3>Constraints</h3>\n\n<ul>\n<li>Table <code>product_detail</code> is missing a foreign key to <code>product</code>.</li>\n<li>Table <code>business_product</code> is missing a foreign key to <code>product</code>, <code>user</code> and <code>business</code>.</li>\n<li>Table <code>billing</code> is missing a foreign key to <code>user</code> and <code>payment_method</code>.</li>\n<li>Table <code>billing_detail</code> is missing a foreign key to <code>billing</code>, <code>product</code> and <code>business</code>.</li>\n<li>Table <code>user_authorized</code> is missing a foreign key to <code>user</code> and <code>payment_method</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T03:51:56.917",
"Id": "223231",
"ParentId": "223229",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T03:35:19.493",
"Id": "223229",
"Score": "3",
"Tags": [
"sql",
"mysql"
],
"Title": "Billing and recurrent payment db structure"
} | 223229 |
<p>How can I improve this code?</p>
<pre><code>#import sys
#sys.setrecursionlimit(1500)
def get_input():
input_str = input("Enter elements to be sorted: ")
try:
lst = list(map(int, input_str.split()))
except:
raise TypeError("Please enter a list of integers only, seperated by a space!!")
return lst
def merge(thelist, start_idx, mid_idx, last_idx):
size_left = mid_idx - start_idx + 1
size_right = last_idx - mid_idx
left_lst = []
right_lst = []
for i in range(size_left):
left_lst.append(thelist[start_idx + i])
for j in range(size_right):
right_lst.append(thelist[mid_idx + 1 + j])
left_idx = 0
right_idx = 0
curr_idx = start_idx
while left_idx < size_left and right_idx < size_right:
if left_lst[left_idx] <= right_lst[right_idx]:
thelist[curr_idx] = left_lst[left_idx]
left_idx += 1
else:
thelist[curr_idx] = right_lst[right_idx]
right_idx += 1
curr_idx += 1
while left_idx < size_left:
thelist[curr_idx] = left_lst[left_idx]
curr_idx += 1
left_idx += 1
while right_idx < size_right:
thelist[curr_idx] = right_lst[right_idx]
curr_idx += 1
right_idx += 1
def merge_sort(thelist, start_idx, last_idx):
if len(thelist) == 0:
print("Empty list!!")
elif len(thelist) == 1:
print("Only one element!!")
elif start_idx < last_idx:
mid_idx = int((start_idx + last_idx) / 2)
merge_sort(thelist, start_idx, mid_idx)
merge_sort(thelist, mid_idx + 1, last_idx)
merge(thelist, start_idx, mid_idx, last_idx)
if __name__ == '__main__':
input_list = get_input()
merge_sort(input_list, 0, len(input_list) - 1)
print(*input_list, sep = ", ")
</code></pre>
| [] | [
{
"body": "<p>You can adhere to the <a href=\"https://www.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (Python Enhancement Proposal (PEP) 8) (there is tool support for this): </p>\n\n<p>Comment your code properly.<br>\nDocument your code properly.<br>\nIn the code, using <em>docstring</em>s, making the documentation accessible to IDEs and introspection. </p>\n\n<p>The first thing to document would be the interface of <code>merge_sort()</code>:<br>\nit may be of interest that it does not return something useful, but modifies <code>thelist</code>.<br>\nI think <code>start_idx</code> and <code>last_idx</code> should have default values. While I don't see how to specify something like <code>last_idx=len(thelist)</code> correctly, Python uses index -1 for <em>last element</em> - you'd need to document <code>last_idx</code> to be inclusive (as the name suggests, anyway). (Python commonly uses right index <em>exclusive</em>.) An alternative would be to use <code>None</code> for <em>to the end</em>.<br>\nBetter get rid of printing in a function of general use than document it does so for specific input. </p>\n\n<p>Having <code>merge()</code> work in-place, too, causes avoidable \"copies\" - allocate <em>one</em> buffer in (\"top-level\") merge_sort and \"merge to and fro'\".</p>\n\n<p>Python has a built-in for <em>selecting a range of items in a sequence object</em>: <a href=\"https://docs.python.org/3/reference/expressions.html?highlight=slice#slicings\" rel=\"nofollow noreferrer\">slicing</a> - do not use loops for this.</p>\n\n<p>You can denote <code>int(x / 2)</code> as <code>(x // 2)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T05:58:21.373",
"Id": "432508",
"Score": "0",
"body": "(I'm reluctant to present code as there are too many things I've seen done more to my liking or would to much differently myself.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T05:46:08.527",
"Id": "223234",
"ParentId": "223230",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T03:43:10.573",
"Id": "223230",
"Score": "1",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x"
],
"Title": "Python: Merge sort"
} | 223230 |
<p>EDIT: Improved/More Streamlined Code (rather than spaghetti below) now posted here: <a href="https://codereview.stackexchange.com/questions/223377/">Bookkeeping Coding - Check and Create Tabs, Copy filtered Data in Loop</a></p>
<p>I'm a relative newbie to coding and have "Frankensteined" my code from various pages on the web. At the moment I have no issues with this code as I have minimal lines of data but find that the time taken increases with data lines (as can only be expected.</p>
<p>The code I have does the following: </p>
<ol>
<li>Filters a Source Table of Data from a Defined List on another sheet </li>
<li>Checks if Data exists after filter
<ol>
<li>If no data exists
<ol>
<li>Checks if there is a tab for that Company and deletes existing data </li>
<li>If no tab move to next in loop </li>
</ol></li>
<li>If data does exists, check tab exists
<ol>
<li>If tab exists, clear data and copy filtered data across move to next in loop</li>
<li>If tab does not exist, create one from hidden template, check balance line exists in different sheet (if not create one) and then copy all filtered data and move to next in loop. </li>
</ol></li>
</ol></li>
<li>Remove all filters and go back to where I started.</li>
</ol>
<p>It seems quite complex to me as a newbie so I'm sure I have a fair amount of redundant lines present that can tidy up my code. </p>
<p>All help/suggestions/recommendations, gratefully received.</p>
<p>My Code:</p>
<pre><code> Sub Update_Backup_Sheets()
Dim sh As Worksheet
x = 4
Dim LastRow As Long
Dim MyCell As Range, MyRange As Range
Dim lrow As Long
Dim TargetTable As ListObject
Dim NumberOfAreas As Long
Dim rng As Range
Set Sourcetable = Sheets("Amalgamated Data").ListObjects("TableFullData")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
‘Get the Company name from the Company Tab
Do
With Sheets("General")
Company_Name = .Range("A" & x).Value
End With
‘ Clear all filter from table
Sourcetable.AutoFilter.ShowAllData
LastRow = Range("B" & Rows.count).End(xlUp).Row - 1
Set MyRange = Range("A20:V" & LastRow)
‘Filter by Company Name
Sourcetable.DataBodyRange.AutoFilter Field:=2, _
Criteria1:="=" & Company_Name
On Error Resume Next
If Sourcetable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count <= 1 Then
‘Clear Existing Data
On Error GoTo Continue
Set sh = Sheets(Company_Name)
On Error GoTo Continue
If WorksheetsExists = Not sh Is Nothing Then
GoTo Continue
Else
With Sheets(Company_Name).ListObjects(1)
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.count - 1, .DataBodyRange.Columns.count).Rows.Delete
.DataBodyRange.ClearContents
End With
GoTo Continue
End If
‘If Data Exists
‘Check if tab exists
Else
On Error Resume Next
If Sourcetable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count > 1 Then
On Error Resume Next
Set sh = Sheets(Company_Name)
If WorksheetsExists = Not sh Is Nothing Then
‘If Tab does not exist, create all relevent records
‘Unhide Template if hidden
If Sheets("Template").Visible = xlSheetHidden Then Sheets("Template").Visible = xlSheetVisible
‘Create and rename sheet highlight it yellow
Sheets("Template").Copy After:=Sheets(4)
ActiveSheet.Range("A20").ListObject.Name = "Table" & (Company_Name)
ActiveSheet.Name = (Company_Name)
With ActiveSheet.Tab
.Color = 65535
.TintAndShade = 0
End With
‘Check Balance Download Records
‘Search COMPANY nAME
Dim rgfound As Range
Set rgfound = Sheets("Balance Download").Range("A1", "A" & frow - 1).Find(Company_Name)
If rgfound Is Nothing Then
‘If not Found
‘Calculate last row
flrow = Sheets("Balance Download").Range("a" & Rows.count).End(xlUp).Row
‘Copy Last Row of Data and rename row
With Sheets("Balance Download")
.ListObjects(1).ListRows.Add
.Rows(flrow).Copy
.Range("A" & flrow + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone
Application.CutCopyMode = False
.Range("a" & flrow + 1).Value = Company_Name
End With
Else
End If
‘Hide template
Sheets("Template").Visible = xlSheetHidden
‘Confirmation Message
MsgBox "Worksheet for " & (Company_Name) & " created"
‘Set sh name
Set sh = Sheets(Company_Name)
GoTo Step2
Else
End If
End If
‘If tab and data exist
Step2:
‘Clear existing data and resize table
With Sheets(Company_Name).ListObjects(1)
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.count - 1, .DataBodyRange.Columns.count).Rows.Delete
.DataBodyRange.ClearContents
End With
Find first row of table (las row of sheet as data previously cleared)
lrow = Sheets(Company_Name).Range("B" & Rows.count).End(xlUp).Row
With Sourcetable.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy
With Sheets(Company_Name)
.Range("A" & lrow).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone
Application.CutCopyMode = False
End With
End With
End If
Continue:
‘Reset the variable sh
Set sh = Nothing
x = x + 1
‘Loop back to get a new Company's name in Employee Roster
Loop While Sheets("General").Range("A" & x).Value <> ""
‘At end of loop turn screen refresh etc back on
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Sheets("Amalgamated Data").Select
'Clear all filter from table
Sourcetable.AutoFilter.ShowAllData
MsgBox "All Sheets Updated"
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T22:07:23.937",
"Id": "432566",
"Score": "1",
"body": "Where is `WorksheetsExists` defined, or assigned? I don't think `If WorksheetsExists = Not sh Is Nothing Then` is doing what you mean it to be doing, and it only works by coincidence of `Variant/Empty` evaluating to `False` when coerced into a Boolean expression. A much clearer & robust condition would be `If sh Is Nothing`, true when the sheet doesn't exist. Does the code compile if you add `Option Explicit` at the top of the module?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:22:06.200",
"Id": "432605",
"Score": "0",
"body": "I don't think it is! I had grabbed the code from elsewhere on the t'internet (can't remember where having viewed so many sites to get to this). I was trying to establish if a worksheet with the looped name exists to run an if then else statement. I will have a go at the above. I have no idea what a Boolean is - so will take a look and learn!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:12:34.570",
"Id": "432657",
"Score": "1",
"body": "A Boolean is a data type that can take one of two values - `True`, or `False`. Every expression in every `If` condition is a Boolean expression. That's basic-basic stuff though, you'll want to read up on [VBA data types](https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/data-type-summary) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:17:05.100",
"Id": "432832",
"Score": "0",
"body": "Massively improved code (thanks to you all posted as new question) as advised. https://codereview.stackexchange.com/questions/223377/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:23:08.950",
"Id": "432835",
"Score": "0",
"body": "Appreciated, thank you for the help. Post now edited to include link to new question."
}
] | [
{
"body": "<p>I agree with the OP:</p>\n\n<blockquote>\n <p>It seems quite complex [...] a fair\n amount of redundant lines present that can tidy up [the] code.</p>\n</blockquote>\n\n<p>I am making an assumption that the code works - although it is hard to tell. I will also assume the line <code>Find first row of table (las row of sheet as data previously cleared)</code> is a typo and meant to be a comment.</p>\n\n<p>I hope the OP will understand that I mean this in the nicest way: That current set of code is a mess - a dog's breakfast of spaghetti. I say this so there are no illusions - there is much to learn from this code and I doubt I will cover it all in this post.</p>\n\n<h2>Option Explicit</h2>\n\n<p>Something I repeat quite often. <strong>Always</strong> put <code>Option Explicit</code> at the top of the module. It prevents simple spelling errors resulting in undefined variables, and makes debugging easier because the run-time code usually gives a better error description and may even highlight the bad line of code. </p>\n\n<p>In this example <code>x</code> is undeclared, even though it is assigned very early in the code.</p>\n\n<h2>Indenting</h2>\n\n<p>Always properly indent the code. This makes it easier to read and maintain. It also helps you check your code logic, because an unfinished loop or something inside a loop that should be outside will stand out because of the indenting.</p>\n\n<h2>Consistent variable use</h2>\n\n<p>Check when variables are being used. </p>\n\n<ul>\n<li>You set <code>MyRange</code> but I don't see it being used anywhere.</li>\n<li>You set <code>Company_Name = Sheets(\"General\").Range(\"A\" & x).Value</code> at\nthe beginning of the loop, but when you check\n<code>Sheets(\"General\").Range(\"A\" & x).Value <> \"\"</code> at the end of the loop\nyou don't reset the value. You could set <code>Company_Name</code> before you\nenter the loop, and then reset it when you get to the end of the\nloop, resulting in a final check of <code>Loop While Company_Name <> \"\"</code>\nwhich is easier to understand for the general reader.</li>\n</ul>\n\n<p>This concept is about using your variable names to self-comment the code. Good variable names means that the reader understands what the code is doing without any additional comments. </p>\n\n<h2>The use of <code>On Error</code></h2>\n\n<p>The spaghetti code from error handling tells me that the code logic and possible errors has not been considered. The current code is too messy to provide any specific advice. Here are some general pointers:</p>\n\n<p>If you think your code is going to fail because something does not exist, then check for its existence before you enter the code. And encapsulate that error check in a function to both isolate from your code and encourage re-use. Two examples of how to check if a Worksheet exists:</p>\n\n<pre><code>Function WSExists1(wsName as String) as Boolean\nDim result as Boolean '<-- Value set by default to False\nDim tempWS as Worksheet\n For each tempWS in ThisWorkbook.Worksheets\n result = result OR (tempWS.Name = wsName)\n Next tempWS\n WSExists1 = result\nEnd Function\n\nFunction WSExists2(wsName as String) as Boolean\nDim result as Boolean '<-- Value set by default to False\nOn Error Resume Next\n result = ThisWorkbook.Worksheets(wsName).Range(\"A1\").Address = \"A1\"\n WSExists1 = result\nEnd Function\n</code></pre>\n\n<p>Now, in your code you can use <code>If WSExists(Company_Name) Then</code> with great confidence and no requirement for spaghetti <code>GoTo</code>.</p>\n\n<p>You can create similar 'helper' functions for other areas where you check for errors.</p>\n\n<h2>Performance</h2>\n\n<p>Hard to tell in the current code, but I suspect that you could dispense with the Excel Table manipulation and use arrays to work with the data. Noting that <code>.DataRange</code> returns an array of values anyway.</p>\n\n<p>In addition, your first loop (on <code>Company_Name</code>) could be based on an array that your get from <code>Sheets(\"General\").Range(\"A4:A\" & LastRowTBD).Value</code>. This will assist with performance.</p>\n\n<p>However, how much is redundant code and where performance tweaks can be built in will have to wait until the simpler tidy up elements have been done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:12:18.473",
"Id": "432599",
"Score": "0",
"body": "I will absolutely take it in the way that it was meant! As I said I have cobbled together the code (which is my first real coding project) from Google, youtube, Macros and other answers in Stack Overflow and whilst I've tried to standardise it all, I had in some cases absolutely no idea really on how the code worked to try to re work it. I will get to updating an amending! What is the convention here as I'm a first time poster...update the code and edit the original post with amendments - subject to what I see in the next answer? Thanks again for the help. Always ways to learn :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:26:17.397",
"Id": "432607",
"Score": "0",
"body": "On some the Error GoTo handling I was actually trying to use this as a positive step. In those cases I was expecting/hoping something not to exist ie for sheet coding an action to take if the if statement was false. Ie if it doesn't exist skip out the coding that needs to happen if it does. Lesson learnt!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T20:35:49.813",
"Id": "432692",
"Score": "0",
"body": "On Code Review, the convention is to create a new review question with the updated (and working) code. In the intro you could link back to this one to help provide the continuing story."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T22:25:02.833",
"Id": "223259",
"ParentId": "223236",
"Score": "2"
}
},
{
"body": "<p>You're missing <code>Option Explicit</code> from the top of your code. From the menu at the top choose Tools>Options... to display the Options dialog>Code Settings group>Require Variable Declaration. Make sure that box is checked. Thereafter <code>Option Explicit</code> will be added to the top of all modules mandating that you do <code>Dim fooBar as Range</code> or whatever the appropriate data type is. Future-You will thank you because it'll help avoid silly errors like having <code>bananna</code> as a variable name instead of <code>banana</code>.</p>\n\n<p>Once you have option explicit at the top of a module intentionally misspell a variable and then from the menu Debug>Compile and you'll see it in affect.</p>\n\n<p>For modules that already exist you need to add this so go ahead and do that.</p>\n\n<hr>\n\n<p>For your variable names it's usually convention to have the first word lower case and the first letter of each word upper cased. <code>lastRow</code> or <code>targetTable</code> would be examples of this.</p>\n\n<p>The actual names of variables like <code>x</code>, <code>rng</code>, <code>sh</code> are, well, not helpful. The same is true for <code>lrow</code> which I'm at present assuming could be <code>lastRow</code>. If you rename it to be something more descriptive it will tell Future-You at a glance what it's used for.</p>\n\n<pre><code>Set nameArea = lookupSheet.Cells(startRow, lookupColumnIndex).Resize(rowSpan,1)\n</code></pre>\n\n<p>is much easier to understand than</p>\n\n<pre><code>Set rng = ws.Cells(x,y).Resize(z,1)\n</code></pre>\n\n<p>Underscores in variable names is used by the <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/implements-statement\" rel=\"nofollow noreferrer\">Implements statement</a> and IMO is something that should be used only for it.</p>\n\n<hr>\n\n<p>Indentation. You have <code>Do</code> then way at the end you have <code>Loop</code> that isn't on the same indentation level. This makes it hard to figure out should be indented. <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">rubberduckvba.com</a> can help you out with this and so much more. <strong>Disclosure Note</strong>: I'm a contributing member to Rubberduck.</p>\n\n<p>You have a very long Sub that's doing a whole lot. If you have smaller Subs you'll notice things you didn't before. An example of things hidden in plain view several variables that, as far as I can tell aren't being used. These include <code>MyCell</code>, <code>TargetTable</code>, <code>NumberOfAreas</code>, <code>rng</code>, <code>LastRow</code>, and <code>MyRange</code>.</p>\n\n<p>Others have already pointed out confusing nature of your if condition on the <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/ifthenelse-statement\" rel=\"nofollow noreferrer\">If...Then...Else statement</a> <code>If WorksheetsExists = Not sh Is Nothing Then</code>. Since <code>WorksheetsExists</code> is of type <code>Boolean</code> which initializes as <code>False</code> you have <code>False = Not sh Is Nothing Then</code>. When <code>sh is Nothing</code> is evaluated you'll end up with a boolean that you can use directly. You don't need, and shouldn't, compare it to a boolean. That needlessly complicates it. Leaving it out also simplifies your code so you have <code>If Not companySheet Is Nothing Then</code>.</p>\n\n<p>You have empty else blocks that should be removed.</p>\n\n<pre><code>Else\nEnd If\n</code></pre>\n\n<p>If there's nothing in them and aren't being used remove <code>Else</code> key.</p>\n\n<hr>\n\n<p>You've a <code>On Error Resume Next</code> before a conditional check in the if statement. My suggestion is to use the following instead. This turns on error handling for the single line and turns it off again after comparison. Just remember to assign it to false just before the loop restarts to avoid false positives.</p>\n\n<pre><code>On Error Resume Next\nDim firstColumnContainsNoVisibleCells As Boolean\nfirstColumnContainsNoVisibleCells = sourceTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count <= 1\nOn Error GoTo 0\n\nIf firstColumnContainsNoVisibleCells Then\n</code></pre>\n\n<hr>\n\n<p>You are doing a comparison using <code>\"\"</code>. <code>\"\"</code> can lead you to question if the string <em>might</em> have contained something but was inadvertently deleted. The better way to do this uses <code>vbNullString</code> as it lets you know that the comparison is intentional. <code>FooBar.Value <> vbNullString</code> is unambiguous.</p>\n\n<hr>\n\n<p>You're using a <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">magic number</a> <code>65535</code>. What's the significance of that number? You only know what it is because of a comment. Going back to renaming variable names you have access to the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.xlrgbcolor\" rel=\"nofollow noreferrer\">XlRgbColor enumeration</a> which has the member <code>rgbYellow</code> which <em>is</em> that number. Note how \n<code>ActiveSheet.Tab.Color = XlRgbColor.rgbYellow</code> is self documenting. If you're not familiar with the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/enum-statement\" rel=\"nofollow noreferrer\">Enum statement</a> have a read through it. Layman's explanation is it gives number a word to go along with it.</p>\n\n<hr>\n\n<p>Any time a sheet was referenced multiple times with a string argument, <code>Sheets(\"Template\")</code> I created a Worksheet object for it. This is because if the name is ever changed you only have to change it in that once location and not chase after it because of Run-Time error when you find out you missed one.</p>\n\n<p>Below is my refactoring that I got to by incorporating all my suggestions. <code>figureOutFRow</code> needs to be supplied as your orginal <code>frow</code> is never given a value and defaults to 0. </p>\n\n<pre><code>Option Explicit\n\nSub Update_Backup_Sheets()\n Dim amalgamatedDateSheet As Worksheet\n Set amalgamatedDateSheet = Sheets(\"Amalgamated Data\")\n\n Dim sourceTable As ListObject\n Set sourceTable = amalgamatedDateSheet.ListObjects(\"TableFullData\")\n\n Dim generalSheet As Worksheet\n Set generalSheet = Worksheets(\"General\")\n\n Dim templateSheet As Worksheet\n Set templateSheet = Worksheets(\"Template\")\n\n Dim balanceDownloadSheet As Worksheet\n Set balanceDownloadSheet = Worksheets(\"Balance Download\")\n\n Application.ScreenUpdating = False\n Application.DisplayAlerts = False\n\n Dim companyName As Range\n For Each companyName In generalSheet.Range(generalSheet.Range(\"A4\"), generalSheet.Range(\"A4\").End(xlDown))\n If companyName.Value2 <> vbNullString Then\n sourceTable.AutoFilter.ShowAllData\n sourceTable.DataBodyRange.AutoFilter Field:=2, Criteria1:=\"=\" & companyName.Value2\n\n Dim firstColumnContainsNoVisibleCells As Boolean\n Dim companySheet As Worksheet\n On Error Resume Next\n firstColumnContainsNoVisibleCells = sourceTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count <= 1\n Set companySheet = Sheets(companyName.Value2)\n On Error GoTo 0\n\n If firstColumnContainsNoVisibleCells Then\n If Not companySheet Is Nothing Then\n With companySheet.ListObjects(1)\n .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete\n .DataBodyRange.ClearContents\n End With\n End If\n Else\n If Not companySheet Is Nothing Then\n If templateSheet.Visible = xlSheetHidden Then\n templateSheet.Visible = xlSheetVisible\n End If\n\n templateSheet.Copy After:=Sheets(4)\n ActiveSheet.Range(\"A20\").ListObject.Name = \"Table\" & companyName.Value2\n ActiveSheet.Name = companyName.Value2\n With ActiveSheet.Tab\n .Color = XlRgbColor.rgbYellow\n .TintAndShade = 0\n End With\n\n Dim figureOutFRow As Long\n figureOutFRow = 0 '<--- need to supply correct row\n CheckBalanceDownloadRecords balanceDownloadSheet, companyName.Value2, figureOutFRow\n\n templateSheet.Visible = xlSheetHidden\n\n MsgBox \"Worksheet for \" & companyName.Value2 & \" created\"\n End If\n\n 'Clear existing data and resize table\n With companySheet.ListObjects(1)\n .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete\n .DataBodyRange.ClearContents\n End With\n\n 'Find first row of table (las row of sheet as data previously cleared)\n Dim lrow As Long\n lrow = companySheet.Range(\"B\" & Rows.Count).End(xlUp).Row\n\n With sourceTable.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy\n With companySheet\n .Range(\"A\" & lrow).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone\n Application.CutCopyMode = False\n End With\n End With\n End If\n\n Set companySheet = Nothing\n firstColumnContainsNoVisibleCells = False 'To avoid false positives\n End If\n Next\n\n Application.DisplayAlerts = True\n Application.ScreenUpdating = True\n amalgamatedDateSheet.Select\n\n sourceTable.AutoFilter.ShowAllData\n MsgBox \"All Sheets Updated\"\nEnd Sub\n\nPrivate Sub CheckBalanceDownloadRecords(ByVal balanceDownloadSheet As Worksheet, ByVal companyName As String, ByVal frow As Long)\n Dim rgfound As Range\n Set rgfound = balanceDownloadSheet.Range(\"A1\", \"A\" & frow - 1).Find(companyName)\n\n If rgfound Is Nothing Then\n Dim flrow As Long\n flrow = balanceDownloadSheet.Range(\"a\" & Rows.Count).End(xlUp).Row\n\n With balanceDownloadSheet\n .ListObjects(1).ListRows.Add\n .Rows(flrow).Copy\n .Range(\"A\" & flrow + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone\n Application.CutCopyMode = False\n .Range(\"a\" & flrow + 1).Value = companyName\n End With\n End If\nEnd Sub\n</code></pre>\n\n<p>I really can't go any farther. This should be plenty to get you started. I'm pretty confident the <code>If Not companySheet Is Nothing Then</code> can actually be removed. Without being able to test it leaves it to you to step through the code and see if it actually can be removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:19:34.157",
"Id": "432603",
"Score": "0",
"body": "Thanks for this, I was aware of the mess of spaghetti that was left with If then else, but was at a loss to figure out how to avoid this so that code that was specifically for use when things were positive didn't execute and throw errors. As I stated above this is my first time really coding so was cobbling together bits of working code from other sources. I will test out you're code later today, but it looks much neater!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:57:15.620",
"Id": "432665",
"Score": "0",
"body": "Hi Ivan thanks for this, almost works perfectly for me when I change `if not companySheet is nothing then` to `if companySheet is Nothing then`. Unfortunately I can't simply remove this line as its an integral part of the coding ie if there is data in the filtered amalgamated table but there isn't an existing companySheet then i need to create one, if there is already a sheet in that name I don't want to overwrite or create a new one as there is additional data on these sheets outside of the tables I'm pasting to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:13:11.230",
"Id": "432668",
"Score": "0",
"body": "I've also moved the End If after making the templateSheet visible after the Msgbox as otherwise it was trying to create a sheet when one already existed. I am however getting an error thrown on the next line of `With companySheet.ListObjects(1)` of: \"Object Variable or With block variable not set\". I can see this has been set higher up in a previous If statement, but adding the Set again also throws an error of \"Type mismatch\" so I'm at a loss as to how to move on. EDIT: It is also throwing the same error before those above edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:37:50.887",
"Id": "432674",
"Score": "1",
"body": "That error message is RTE91 (https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/object-variable-not-set-error-91). It sounds like the `companySheet` variable isn't being assigned. In the menu at the top click Tools>Locals to display the locals window. When it errors on that line of code click Debug then look in the Locals window. If it isn't assigned you'll need to determine why and resolve that error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:39:32.003",
"Id": "432675",
"Score": "1",
"body": "If the variable IS being assigned but there isn't a ListObject on the sheet you'd get a RTE9 (https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/subscript-out-of-range-error-9)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:33:13.067",
"Id": "432731",
"Score": "0",
"body": "I have googled and looking at the issue in the Watch tab, and am now getting a error13 - Type Mismatch on the following: Sheets(companyName) type is being set as Integer rather than WorkSheet. Per the above I have used `Dim companySheet as WorkSheet` (which is setting type as worksheet) and `Set companySheet = Sheets(companyName)`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T02:56:32.237",
"Id": "223270",
"ParentId": "223236",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223270",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T10:35:43.293",
"Id": "223236",
"Score": "2",
"Tags": [
"beginner",
"vba",
"excel"
],
"Title": "Bookkeeping Coding - Check and Create Tabs, Copy filtered Data in Loop - EDIT new/better code posted as new thread"
} | 223236 |
<p>I've recently created a tomato timer for terminal. It's hosted in <a href="https://github.com/JaDogg/pydoro" rel="nofollow noreferrer">github</a>. </p>
<p>My concerns are how Pythonic my code is? Is the way I'm handling state transitions good? Which areas of the text user interface I can improve? Also I've ordered the files in order of importance: first file is core logic, second ui and third utils.</p>
<h2>How it looks like</h2>
<p><a href="https://i.stack.imgur.com/XVZap.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XVZap.gif" alt="screenshot"></a></p>
<h2>Code</h2>
<h3>pydoro.pydoro_core.tomato.py</h3>
<p>This file is responsible for handling states</p>
<pre class="lang-py prettyprint-override"><code>import itertools
from enum import IntEnum
from timeit import default_timer
from pydoro.pydoro_core import sound
from pydoro.pydoro_core.util import in_app_path
TOMATOES_PER_SET = 4
SECONDS_PER_MIN = 60
WORK_TIME = 25 * SECONDS_PER_MIN
SMALL_BREAK_TIME = 5 * SECONDS_PER_MIN
LONG_BREAK_TIME = 15 * SECONDS_PER_MIN
ALARM_TIME = 20
TOMATO = [
("", "\n "),
("#00cc00", "/'\\/`\\"),
("", " "),
("", "task1"),
("", "\n "),
("#ff0000", ".-"),
("", " "),
("#00cc00", "|/"),
("", " "),
("#ff0000", "-."),
("", " "),
("", "task2"),
("", "\n "),
("#ff0000", "/"),
("", " "),
("#ff0000", "\\"),
("", " "),
("", "task3"),
("", "\n "),
("#ff0000", "'"),
("", " "),
("bold", "pydoro"),
("", " "),
("#ff0000", "\\"),
("", " "),
("", "task4"),
("", "\n "),
("#ff0000", ";"),
("", " "),
("#ff0000", "'"),
("", " "),
("", "status"),
("", "\n "),
("#ff0000", ";"),
("", " "),
("#ff0000", ";"),
("", " "),
("", "time"),
("", "\n "),
("#ff0000", ":"),
("", " "),
("#ff0000", "/"),
("", " "),
("#ff0000", "."),
("", "\n "),
("#ff0000", "\\"),
("", " "),
("#ff0000", ".'"),
("", " "),
("#ff0000", "/"),
("", " "),
("", "count"),
("", "\n "),
("#ff0000", "\\"),
("", " "),
("#ff0000", "____"),
("", " "),
("#ff0000", ".'"),
("", " "),
("", "sets"),
]
LOCATIONS = {
"count": 51,
"sets": 59,
"status": 31,
"task1": 3,
"task2": 11,
"task3": 17,
"task4": 25,
"time": 37,
}
TEXT_LONG_BREAK = r"""
___ LONG _
| _ )_ _ ___ __ _| |__
| _ | '_/ -_/ _` | / /
|___|_| \___\__,_|_\_\
""".strip(
"\r\n"
)
TEXT_SMALL_BREAK = TEXT_LONG_BREAK.replace("LONG", "SMALL")
TEXT_WORK = r"""
__ __ _
\ \ / ___ _ _| |__
\ \/\/ / _ | '_| / /
\_/\_/\___|_| |_\_\
""".strip(
"\r\n"
)
class Tasks(IntEnum):
WORK = 1
SMALL_BREAK = 2
LONG_BREAK = 3
NO_TASK = 4
INTERMEDIATE = 5
class TaskStatus(IntEnum):
NONE = 111
STARTED = 222
PAUSED = 555
LIMBO = 666
TEXT = {
TaskStatus.NONE.value: "",
TaskStatus.STARTED.value: "",
TaskStatus.PAUSED.value: "PAUSED",
TaskStatus.LIMBO.value: "",
Tasks.WORK.value: TEXT_WORK,
Tasks.SMALL_BREAK.value: TEXT_SMALL_BREAK,
Tasks.LONG_BREAK.value: TEXT_LONG_BREAK,
Tasks.NO_TASK.value: "",
Tasks.INTERMEDIATE.value: "",
}
PROGRESS = ["|# |", "| # |", "| #|", "| # |"]
def cur_time():
return int(default_timer())
def play_alarm():
# noinspection PyBroadException
try:
sound.play(in_app_path("b15.wav"), block=False)
except Exception:
pass
class InitialState:
name = "initial"
def __init__(self, time_period=0, tomato=None):
self._time_period = int(time_period)
self._tomato = tomato
self._task = Tasks.NO_TASK
self._status = TaskStatus.NONE
self._started_at = 0
self._remainder = 0
self._progress = itertools.cycle(PROGRESS)
def start(self):
play_alarm()
return WorkingState(tomato=self._tomato)
def pause(self):
return self
def reset(self):
return self
@property
def remainder(self):
return self._remainder
@property
def next_state(self):
return self
@property
def time_period(self):
return self._time_period
@property
def time_remaining(self):
return "Press [start]"
@property
def task(self):
return self._task
@property
def status(self):
return self._status
@property
def done(self):
return False
def _format_time(self, remainder):
minutes, seconds = divmod(int(remainder), SECONDS_PER_MIN)
if self.status == TaskStatus.STARTED:
progress = next(self._progress) + " "
else:
progress = ""
return "{}{:00}min {:00}s remaining".format(progress, minutes, seconds)
def _calc_remainder(self):
cur = cur_time()
difference = cur - self._started_at
remainder = self._remainder - difference
self._started_at = cur
if remainder <= 0:
remainder = 0
self._remainder = remainder
class IntermediateState(InitialState):
name = "waiting"
def __init__(self, time_period=0, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._task = Tasks.INTERMEDIATE
self._status = TaskStatus.LIMBO
self._next_factory = None
self._last_alarm_time = 0
self._sound()
def _sound(self):
if cur_time() - self._last_alarm_time > ALARM_TIME:
play_alarm()
self._last_alarm_time = cur_time()
def start(self):
return self._next_factory(tomato=self._tomato)
@property
def time_remaining(self):
self._sound()
return "Press [start] to continue with " + self._next_factory.name
@property
def done(self):
return False
@staticmethod
def transition_to(next_state_factory, tomato):
state = IntermediateState(tomato=tomato)
state._next_factory = next_state_factory
return state
class WorkingState(InitialState):
name = "work"
def __init__(self, time_period=WORK_TIME, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._remainder = int(self._time_period)
self._task = Tasks.WORK
self._status = TaskStatus.STARTED
self._started_at = cur_time()
def start(self):
return self
@property
def time_remaining(self):
self._calc_remainder()
return self._format_time(self._remainder)
@property
def next_state(self):
self._tomato.tomatoes += 1
if self._tomato.tomatoes % TOMATOES_PER_SET == 0:
return IntermediateState.transition_to(LongBreakState, tomato=self._tomato)
return IntermediateState.transition_to(SmallBreakState, tomato=self._tomato)
def pause(self):
return WorkPausedState.return_to(self._tomato, self)
def reset(self):
self._remainder = self.time_period
return self
@property
def done(self):
return self._remainder <= 0
class WorkPausedState(InitialState):
name = "work paused"
def __init__(self, time_period=0, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._prev = None
self._task = Tasks.WORK
self._status = TaskStatus.PAUSED
def start(self):
self._prev._started_at = cur_time()
return self._prev
def reset(self):
self._prev._remainder = self._prev.time_period
return self
@property
def time_remaining(self):
return self._format_time(self._prev.remainder)
@staticmethod
def return_to(tomato, state):
cur_state = WorkPausedState(tomato=tomato)
cur_state._prev = state
return cur_state
@property
def done(self):
return False
class SmallBreakState(InitialState):
name = "small break"
def __init__(self, time_period=SMALL_BREAK_TIME, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._remainder = int(self._time_period)
self._task = Tasks.SMALL_BREAK
self._status = TaskStatus.STARTED
self._started_at = cur_time()
def start(self):
return self
@property
def time_remaining(self):
self._calc_remainder()
return self._format_time(self._remainder)
@property
def next_state(self):
return IntermediateState.transition_to(WorkingState, tomato=self._tomato)
def pause(self):
return SmallBreakPausedState.return_to(self._tomato, self)
def reset(self):
self._remainder = self.time_period
return self
@property
def done(self):
return self._remainder <= 0
class SmallBreakPausedState(InitialState):
name = "small break paused"
def __init__(self, time_period=0, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._task = Tasks.SMALL_BREAK
self._status = TaskStatus.PAUSED
self._prev = None
def start(self):
self._prev._started_at = cur_time()
return self._prev
@property
def time_remaining(self):
return self._format_time(self._prev.remainder)
@staticmethod
def return_to(tomato, state):
cur_state = SmallBreakPausedState(tomato=tomato)
cur_state._prev = state
return cur_state
def reset(self):
self._prev._remainder = self._prev.time_period
return self
@property
def done(self):
return False
class LongBreakState(SmallBreakState):
name = "long break"
def __init__(self, time_period=LONG_BREAK_TIME, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._task = Tasks.LONG_BREAK
self._status = TaskStatus.STARTED
def pause(self):
return LongBreakPausedState.return_to(self._tomato, self)
class LongBreakPausedState(SmallBreakPausedState):
name = "long break paused"
def __init__(self, time_period=0, tomato=None):
super().__init__(time_period=time_period, tomato=tomato)
self._task = Tasks.LONG_BREAK
self._status = TaskStatus.PAUSED
@staticmethod
def return_to(tomato, state):
cur_state = LongBreakPausedState(tomato=tomato)
cur_state._prev = state
return cur_state
class Tomato:
def __init__(self):
self._state = InitialState(tomato=self)
self.tomatoes = 0
def start(self):
self._state = self._state.start()
def pause(self):
self._state = self._state.pause()
def reset(self):
self._state = self._state.reset()
def reset_all(self):
self._state = InitialState(tomato=self)
self.tomatoes = 0
def update(self):
if self._state.done:
self._state = self._state.next_state
def as_formatted_text(self):
task = TEXT[self._state.task.value]
task = task.splitlines()
if not task:
task = [""] * 4
sets = self.tomatoes // TOMATOES_PER_SET
if sets == 1:
sets = "1 set completed"
elif sets >= 2:
sets = str(sets) + " sets completed"
else:
sets = ""
status = TEXT[self._state.status.value]
time = self._state.time_remaining
count = "(`) " * (TOMATOES_PER_SET - self.tomatoes % TOMATOES_PER_SET)
ftext = TOMATO[:]
for i in range(1, 5):
ftext[LOCATIONS["task" + str(i)]] = ("", task[i - 1])
ftext[LOCATIONS["status"]] = ("", status)
ftext[LOCATIONS["time"]] = ("", time)
ftext[LOCATIONS["count"]] = ("", count)
ftext[LOCATIONS["sets"]] = ("", sets)
return ftext
</code></pre>
<h3>pydoro.pydoro_tui.py</h3>
<p>This is the main executable script file and this is responsible for creating prompt-toolkit layout.</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import threading
from prompt_toolkit.application import Application
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous
from prompt_toolkit.layout import HSplit, Layout, VSplit, FormattedTextControl, Window
from prompt_toolkit.styles import Style
from prompt_toolkit.widgets import Box, Button, Label
from pydoro.pydoro_core.tomato import Tomato
from pydoro.pydoro_core.util import every
tomato = Tomato()
def exit_clicked(_=None):
get_app().exit()
# All the widgets for the UI.
btn_start = Button("Start", handler=tomato.start)
btn_pause = Button("Pause", handler=tomato.pause)
btn_reset = Button("Reset", handler=tomato.reset)
btn_reset_all = Button("Reset All", handler=tomato.reset_all)
btn_exit = Button("Exit", handler=exit_clicked)
# text_area = TextArea(read_only=True, height=11, focusable=False)
text_area = FormattedTextControl(focusable=False, show_cursor=False)
text_window = Window(
content=text_area, dont_extend_height=True, height=11, style="bg:#ffffff #000000"
)
root_container = Box(
HSplit(
[
Label(text="Press `Tab` to move the focus."),
HSplit(
[
VSplit(
[btn_start, btn_pause, btn_reset, btn_reset_all, btn_exit],
padding=1,
style="bg:#cccccc",
),
text_window,
]
),
]
)
)
layout = Layout(container=root_container, focused_element=btn_start)
# Key bindings.
kb = KeyBindings()
kb.add("tab")(focus_next)
kb.add("s-tab")(focus_previous)
kb.add("right")(focus_next)
kb.add("left")(focus_previous)
kb.add("q")(exit_clicked)
# Styling.
style = Style(
[
("left-pane", "bg:#888800 #000000"),
("right-pane", "bg:#00aa00 #000000"),
("button", "#000000"),
("button-arrow", "#000000"),
("button focused", "bg:#ff0000"),
("red", "#ff0000"),
("green", "#00ff00"),
]
)
# Build a main application object.
application = Application(layout=layout, key_bindings=kb, style=style, full_screen=True)
def draw():
tomato.update()
text_area.text = tomato.as_formatted_text()
application.invalidate()
def main():
draw()
threading.Thread(target=lambda: every(0.4, draw), daemon=True).start()
application.run()
if __name__ == "__main__":
main()
</code></pre>
<h3>pydoro.pydoro_core.util.py</h3>
<pre class="lang-py prettyprint-override"><code>import os
import time
def every(delay, task):
next_time = time.time() + delay
while True:
time.sleep(max(0, next_time - time.time()))
task()
next_time += (time.time() - next_time) // delay * delay + delay
def in_app_path(path):
import sys
try:
wd = sys._MEIPASS
return os.path.abspath(os.path.join(wd, path))
except AttributeError:
return _from_resource(path)
def _from_resource(path):
from pkg_resources import resource_filename
res_path = resource_filename(__name__, path)
if not os.path.exists(res_path):
res_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
return res_path
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T16:34:35.047",
"Id": "432534",
"Score": "0",
"body": "There is a `sound.py` file in GitHub for handling cross-platform audio but since I didn't write it fully, I've decided not to add it here. But anything even on the GitHub is fair game. Also I'm not a beginner feel free to call out any sloppiness."
}
] | [
{
"body": "<p>Thanks for sharing this. There is a lot here, and in general it looks good. Without a LOT more thought I would not be able to provide constructive feedback to the logic here. So I will punt, and fallback to some relatively minor Pythonic (my opinion) comments.</p>\n<h3>Max is .. really cool</h3>\n<p>This method does some basic math with timestamps.</p>\n<pre><code>def _calc_remainder(self):\n cur = cur_time()\n difference = cur - self._started_at\n remainder = self._remainder - difference\n self._started_at = cur\n if remainder <= 0:\n remainder = 0\n self._remainder = remainder\n \n</code></pre>\n<p>I would take the 7 lines and reduce to 3 like.</p>\n<pre><code>def _calc_remainder(self):\n cur = cur_time()\n self._remainder = max(self._remainder - (cur - self._started_at), 0)\n self._started_at = cur\n \n</code></pre>\n<p>The big differences are using <code>max()</code> to clip to <code>0</code> and removing some of the intermediate calcs.</p>\n<h3>Be explicit about what you are calculating:</h3>\n<p>This:</p>\n<pre><code>def next_state(self):\n self._tomato.tomatoes += 1\n if self._tomato.tomatoes % TOMATOES_PER_SET == 0:\n return IntermediateState.transition_to(LongBreakState, tomato=self._tomato)\n return IntermediateState.transition_to(SmallBreakState, tomato=self._tomato)\n</code></pre>\n<p>Can be reduced a bit to:</p>\n<pre><code>def next_state(self):\n self._tomato.tomatoes += 1\n next_state = LongBreakState if self._tomato.tomatoes % TOMATOES_PER_SET == 0 else SmallBreakState\n return IntermediateState.transition_to(next_state, tomato=self._tomato)\n \n</code></pre>\n<p>The primary change I would recommend here is the explict calculation of <code>next_state</code>. This construct makes <code>next_state</code> explicit, while the previous requires the reader to figure this out.</p>\n<h3>Python does not require <code>()</code> around tuples</h3>\n<p>So this:</p>\n<pre><code>ftext = TOMATO[:]\nfor i in range(1, 5):\n ftext[LOCATIONS["task" + str(i)]] = ("", task[i - 1])\nftext[LOCATIONS["status"]] = ("", status)\n.... \n</code></pre>\n<p>Can be reduced to:</p>\n<pre><code>ftext = TOMATO[:]\nfor i in range(1, 5):\n ftext[LOCATIONS["task" + str(i)]] = "", task[i - 1]\nftext[LOCATIONS["status"]] = "", status\n....\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T04:56:59.263",
"Id": "223271",
"ParentId": "223238",
"Score": "2"
}
},
{
"body": "<h3>Comments are good.</h3>\n\n<ul>\n<li>Provide a module level doc string describe what the program does or provide a link to wikipedia</li>\n<li>What are the fields in the tuples in TOMATO (I think RGB color and a display string)</li>\n<li>Why are some fields in TOMATO empty strings or just spaces?</li>\n<li>maybe define RED = \"#ff0000\" and GREEN = \"#00cc00\" and use RED or GREEN in TOMATO</li>\n<li>same for LOCATIONS</li>\n</ul>\n\n<p>IntEnum is intended for when you need to be able to use the enums as integers. Your code doesn't use that feature. So consider just using Enum.</p>\n\n<h3>Enum</h3>\n\n<p>Enum members are hashable and can be used as dictionary keys like so:</p>\n\n<pre><code>TEXT = {\n TaskStatus.NONE: \"\",\n TaskStatus.STARTED: \"\",\n ...etc...\n}\n</code></pre>\n\n<h3>@property</h3>\n\n<p>Although @property is designed so that it can be used to make \"read-only\" attributes in Python, I don't think that is considered to be Pythonic. It is more Pythonic to just access attributes directly. Properties are more often used when you need to do some calculations when setting or getting the value of an attribute. And you don't need to create properties unless and until you need them.</p>\n\n<h3>State machine</h3>\n\n<p>Clever use of <code>itertools.cycle()</code> for the progress indicator. But does each state instance need its own?</p>\n\n<p><code>InitialState.time_remaining()</code> returns \"Press [Start]\", which doesn't seem like a remaining amount of time.</p>\n\n<p><code>IntermediateState.start()</code> calls <code>self._next_factory()</code> which is set to <code>None</code> in <code>__init__()</code>. Perhaps it would be good to check that <code>_next_factory</code> was initialized. This is in several places.</p>\n\n<p>I don't see the benefit of the <code>transition_to()</code> method. I would just use a <code>next_state</code> parameter in <code>__init__()</code>. Similarly for <code>return_to()</code>.</p>\n\n<p>I found the state transitions hard to follow, so you might want to document that somewhere for future reference.</p>\n\n<p>If you don't want to roll your own, <a href=\"https://github.com/pytransitions/transitions\" rel=\"nofollow noreferrer\">transitions</a> is a nice state machine library.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T09:18:12.103",
"Id": "433934",
"Score": "0",
"body": "I like your answer lot of useful content. Do you think I should perhaps break the tomato module to multiple files? Is tomato a good name for a module? Do you have a better idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T18:50:31.283",
"Id": "433999",
"Score": "0",
"body": "The code in the tomato module seems related, I don't see anything to split into another module. Maybe the the UI stuff in there could be split out so you use alternate UIs if you continue to develop this. Tomato is a fine name--it means something to you and to someone familiar with the Tomato Timer method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T06:45:56.467",
"Id": "223784",
"ParentId": "223238",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "223784",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T11:44:24.250",
"Id": "223238",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"console",
"animation",
"timer"
],
"Title": "pydoro - terminal tomato timer"
} | 223238 |
<p>This following code searches for <code>jpg</code> files of size larger than 500 KB. Its purpose is to move/cp files, depending on their EXIF data, into folders that correspond to the files' year and month.</p>
<pre><code>find . -type f -iname '*.jpg' -size +500k | while read file; do
yr=$(stat -f '%Sm' -t '%Y' "$file")
month=$(stat -f '%Sm' -t '%m' "$file")
folder="/path/to/backup/folder/$yr"
subFodler=$folder"/"$month
[[ -d "$folder" ]] || echo mkdir "$folder"
[[ -d "$subFodler" ]] || echo mkdir "$subFodler"
echo mv "$file" "$folder/$month"
done
</code></pre>
<p>Currently it´s a lot of duplicate lines.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T13:33:17.167",
"Id": "432525",
"Score": "1",
"body": "Trivial code typo note: subFodler is a misspelling of subFolder. Glenn Jackman's solution gets rid of this variable, but just for the record..."
}
] | [
{
"body": "<p>I see this invocation of stat is MacOS specific.</p>\n\n<p>Here's how I would shrink your code</p>\n\n<pre><code>find . -type f -iname '*.jpg' -size +500k -exec sh -c '\n for file in \"$@\"; do\n folder=\"/path/to/backup/folder/$(stat -f '%Sm' -t '%Y/%m' \"$file\")\"\n mkdir -p \"$folder\"\n echo mv \"$file\" \"$folder\"\n done\n' sh {} +\n</code></pre>\n\n<p><code>mkdir -p</code> will create all missing folders, and it will also suppress errors if the directory already exists. </p>\n\n<p>find's <code>-exec cmd {} +</code> feeds several filenames to the given command.</p>\n\n<p>And this looks odd <code>sh -c 'stuff' sh file ...</code> -- the 2nd sh will be assigned to <code>$0</code> inside the -c script, and the given files will be $1, $2, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T14:56:46.747",
"Id": "432531",
"Score": "1",
"body": "Nice! Thanks! add a \" to line 4, at the mkdir line and we are good to go!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T12:33:47.077",
"Id": "223241",
"ParentId": "223239",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223241",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T12:23:23.890",
"Id": "223239",
"Score": "2",
"Tags": [
"bash"
],
"Title": "Script to move images into year and month folder"
} | 223239 |
<p>I am attempting to create a lock free pool of resources and I need the ability to access any one that is not already accessed and then return it back when I do not need it. This will happen very very often in many threads and I felt that a locked queue would create a lot of contention.</p>
<p>My solution is a relatively simple one (lots of atomics) but that simplicity and speed is pretty important to me.</p>
<p>I am not very familiar with atomics and I was wondering if I missed a potentially unsafe use. Although I am aware of the lack of protection against unsafe use of these functions (releasing an index that has not been acquired) but for my use case this will never happen. Just assume I am going to use the class correctly, I know its not good practice to write code that can easily break but the purpose is to be quick; therefor, I can not make useless checks.</p>
<p>That being said, I would like to know if there are any ways I can improve it: <strong>are there more optimal memory orders than <em>sequential</em> that I can use for some of them? Is the array of atomic ints safe? Can I get away with a simple volatile array? Is the <em>do while</em> loop necessary in the acquire method?</strong></p>
<p>If you have any other thoughts please, let me know.</p>
<pre><code>#pragma once
#include <atomic>
template <typename T>
class LFPoolQueue {
public:
const uint16_t END = 0xffff;
LFPoolQueue(uint16_t size)
{
m_size = size;
m_pool = new T[size];
m_ptrs = new std::atomic<uint16_t>[size];
uint16_t lindex = size - 1;
for (uint16_t i = 0; i < lindex; i++)
m_ptrs[i].store(i + 1);
m_ptrs[lindex].store(END);
m_next.store(0);
m_last.store(lindex);
}
~LFPoolQueue()
{
delete[] m_pool;
delete[] m_ptrs;
}
int dequeue()
{
bool wasMaxed = false;
struct VersionRef
{
uint16_t version;
uint16_t ref;
};
uint32_t unsafePtr = m_next.load();
uint32_t newPtr = 0;
VersionRef vrOld = {};
VersionRef vrNew = {};
do
{
memcpy(&vrOld, &unsafePtr, sizeof(uint32_t));
vrNew.version = (vrOld.version + 1) & 0x7FFFU;
wasMaxed = vrOld.version & 0x8000U;
vrNew.ref = m_ptrs[vrOld.ref].load();
if (vrNew.ref == END)
{
if (wasMaxed)
return END;
else
{
vrNew.ref = vrOld.ref;
vrNew.version |= 0x8000U;
}
}
memcpy(&newPtr, &vrNew, sizeof(uint32_t));
} while (!m_next.compare_exchange_weak(unsafePtr, newPtr));
if (wasMaxed)
return dequeue();
else
return vrOld.ref;
}
void enqueue(uint16_t index)
{
m_ptrs[index].store(END);
m_ptrs[m_last.exchange(index)].store(index);
}
uint16_t size() { return m_size; }
T& operator[](const int index) { return m_pool[index]; }
private:
uint16_t m_size;
T* m_pool;
std::atomic<uint16_t>* m_ptrs;
std::atomic<uint32_t> m_next;
std::atomic<uint16_t> m_last;
};
</code></pre>
<p><strong>main.cpp test app</strong></p>
<pre><code>#include <iostream>
#include "LFPoolQueue.h"
int main()
{
LFPoolQueue<int> q(3);
q[0] = 0;
q[1] = 1;
q[2] = 2;
for (int i = 0; i < 6; i++)
{
if (i == 3)
{
q.enqueue(1);
std::cout << "returned 1" << std::endl;
}
else
{
int index = q.dequeue();
std::cout << i << ": " << index << std::endl;
}
}
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>0: 0
1: 1
2: 2
returned 1
4: 1
5: 65535
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T13:58:27.293",
"Id": "432527",
"Score": "1",
"body": "Have you tested it and is the code working? Could you provide a working example of how to use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T00:39:51.003",
"Id": "432574",
"Score": "0",
"body": "Not really, that's why I posted this code review. I can not really run tests on it because its so fundamentally unpredictable. The system I will be using it in is so complicated that if this is the part that fails it will be very difficult to discover. Therefore I am hoping, with enough skilled eyes, someone can spot a deadly error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T00:48:44.960",
"Id": "432576",
"Score": "0",
"body": "Have you done any testing of this code? Even minimal, by putting it into a small test app and exercising the basic functionality?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T00:59:47.373",
"Id": "432577",
"Score": "0",
"body": "I'll try some single threaded basic logic functionality and see what happens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:10:26.377",
"Id": "432629",
"Score": "0",
"body": "Look at the related section to the right of these comments, it might give you some ideas for testing. On Code Review we have guidelines that say we can only review working code https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:19:38.927",
"Id": "432670",
"Score": "0",
"body": "Alrighty, I have corrected a few preliminary errors and verified that the basic functionality works, my only question left and the reason I started this thread is weather or not I am handling threads safely. That is something that, I am sure you are aware, is very difficult to simply test and usually just takes many different minds to look at and analyze."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T01:33:07.263",
"Id": "433079",
"Score": "0",
"body": "Any thoughts? Is it clear what I'm trying to do?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T13:06:15.400",
"Id": "223242",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"queue",
"lock-free"
],
"Title": "Lock-free pooled queue"
} | 223242 |
<p>I'm writing a python script and do database query to get the ids of employees who are in one table but are not in another. I'm using psycopg2 module for python 2 and PostgreSQL as database. After querying from one table based on a condition, I do another query on another table to get the difference between these tables using the result of previous query. The problem is the full procedure takes a long time. I want to know is there any other method or technique which can make the entire procedure faster?
Below is the code I used for doing my feature:</p>
<pre><code>def find_difference_assignment_pls_count(self):
counter = 0
emp_ids = []
self.test_cursor.execute("""Select id,emp_id from test_test where flag=true and emp_id is not null and ver_id in(select id from test_phases where state='test')""")
matching_records = self.test_cursor.fetchall()
for match_record in matching_records:
self.test_cursor.execute("""Select id from test_table where test_emp_id=%s and state='test_state'""",(match_record['emp_id'],))
result = self.test_cursor.fetchall()
if result:
continue
else:
emp_ids.append(match_record['emp_id'])
counter +=1
print "Employees of test_test not in test_table: ", counter
return emp_ids
</code></pre>
<p>I run these queries on two tables which at least have more than 500000 records. Therefore the performance is really slow.</p>
| [] | [
{
"body": "<p><a href=\"http://www.postgresqltutorial.com/postgresql-left-join/\" rel=\"nofollow noreferrer\">LEFT JOIN</a> from <code>test_test</code> to <code>test_table</code> selecting only rows where <code>test_table.test_emp_id</code> is <code>null</code>.</p>\n\n<pre><code>select emp_id \nfrom test_test\nleft join test_table on (\n test_table.test_emp_id = test_test.emp_id and\n test_table.state = 'test_state'\n)\nwhere (\n test_test.flag = true and \n test_test.emp_id is not null and\n test_test.ver_id in (\n select id\n from test_phases\n where state = 'test'\n ) and\n test_table.test_emp_id is null\n)\n</code></pre>\n\n<p>You may also want to consider: </p>\n\n<ol>\n<li><p>Using an inner join instead of a subquery to select only rows with <code>test_phases.state = 'test'</code>. </p></li>\n<li><p>Selecting <code>distinct</code> <code>emp_id</code>s if <code>test_test.emp_id</code> does not have a unique constraint.</p></li>\n</ol>\n\n\n\n<pre><code>select distinct emp_id \nfrom test_test\ninner join test_phases on test_phases.id = test_test.ver_id\nleft join test_table on (\n test_table.test_emp_id = test_test.emp_id and\n test_table.state = 'test_state'\n)\nwhere (\n test_test.flag = true and \n test_test.emp_id is not null and\n test_phases.state = 'test' and\n test_table.test_emp_id is null\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T18:27:24.380",
"Id": "223253",
"ParentId": "223243",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223253",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T13:42:21.520",
"Id": "223243",
"Score": "3",
"Tags": [
"python",
"performance",
"postgresql",
"join"
],
"Title": "Python script to find employees who are in one PostgreSQL table but not in another"
} | 223243 |
<p>I've got a big react app (with Redux) here that has a huge bottleneck.</p>
<p>We have implemented a product search by using product number or product name and this search is extremely laggy.</p>
<blockquote>
<p>Problem: If a user types in some characters, those characters are
shown in the InputField really retarded. The UI is frozen for a couple
of seconds. In Internet Explorer 11, the search is almost unusable.</p>
</blockquote>
<p>It's a Material UI TextField that filters products.</p>
<p>What I already did for optimization:</p>
<ol>
<li>Replaced things like <strong>style={{
maxHeight: 230,
overflowY: 'scroll',
}}</strong> with <strong>const cssStyle={..}</strong></li>
<li>Changed some critical components from <strong>React.Component</strong> to <strong>React.PureComponent</strong></li>
<li>Added <strong>shouldComponentUpdate</strong> for our SearchComponent</li>
<li>Removed some unnecessary <strong>closure bindings</strong></li>
<li>Removed some unnecessary <strong>objects</strong></li>
<li>Removed all <strong>console.log()</strong></li>
<li>Added <strong>debouncing</strong> for the input field (that makes it even worse)</li>
</ol>
<p>That's how our SearchComponent looks like at the moment:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Downshift from 'downshift';
import TextField from '@material-ui/core/TextField';
import MenuItem from '@material-ui/core/MenuItem';
import Paper from '@material-ui/core/Paper';
import IconTooltip from '../helper/icon-tooltip';
import { translate } from '../../utils/translations';
const propTypes = {
values: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
legend: PropTypes.string,
helpText: PropTypes.string,
onFilter: PropTypes.func.isRequired,
selected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
isItemAvailable: PropTypes.func,
};
const defaultProps = {
legend: '',
helpText: '',
selected: '',
isItemAvailable: () => true,
};
const mapNullToDefault = selected =>
(selected === null || selected === undefined ? '' : selected);
const mapDefaultToNull = selected => (!selected.length ? null : selected);
class AutoSuggestField extends Component {
shouldComponentUpdate(nextProps) {
return this.props.selected !== nextProps.selected;
}
getLegendNode() {
const { legend, helpText } = this.props;
return (
<legend>
{legend}{' '}
{helpText && helpText.length > 0 ? (
<IconTooltip helpText={helpText} />
) : (
''
)}
</legend>
);
}
handleEvent(event) {
const { onFilter } = this.props;
const value = mapDefaultToNull(event.target.value);
onFilter(value);
}
handleOnSelect(itemId, item) {
const { onFilter } = this.props;
if (item) {
onFilter(item.label);
}
}
render() {
const { values, selected, isItemAvailable } = this.props;
const inputValue = mapNullToDefault(selected);
const paperCSSStyle = {
maxHeight: 230,
overflowY: 'scroll',
};
return (
<div>
<div>{this.getLegendNode()}</div>
<Downshift
inputValue={inputValue}
onSelect={(itemId) => {
const item = values.find(i => i.id === itemId);
this.handleOnSelect(itemId, item);
}}
>
{/* See children-function on https://github.com/downshift-js/downshift#children-function */}
{({
isOpen,
openMenu,
highlightedIndex,
getInputProps,
getMenuProps,
getItemProps,
ref,
}) => (
<div>
<TextField
className="searchFormInputField"
InputProps={{
inputRef: ref,
...getInputProps({
onFocus: () => openMenu(),
onChange: (event) => {
this.handleEvent(event);
},
}),
}}
fullWidth
value={inputValue}
placeholder={translate('filter.autosuggest.default')}
/>
<div {...getMenuProps()}>
{isOpen && values && values.length ? (
<React.Fragment>
<Paper style={paperCSSStyle}>
{values.map((suggestion, index) => {
const isHighlighted = highlightedIndex === index;
const isSelected = false;
return (
<MenuItem
{...getItemProps({ item: suggestion.id })}
key={suggestion.id}
selected={isSelected}
title={suggestion.label}
component="div"
disabled={!isItemAvailable(suggestion)}
style={{
fontWeight: isHighlighted ? 800 : 400,
}}
>
{suggestion.label}
</MenuItem>
);
})}
</Paper>
</React.Fragment>
) : (
''
)}
</div>
</div>
)}
</Downshift>
</div>
);
}
}
AutoSuggestField.propTypes = propTypes;
AutoSuggestField.defaultProps = defaultProps;
export default AutoSuggestField;</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.0/umd/react-dom.production.min.js"></script></code></pre>
</div>
</div>
</p>
<p>EDIT (added some infos here:)</p>
<ul>
<li>Downshift is this package here: <a href="https://www.npmjs.com/package/downshift" rel="nofollow noreferrer">https://www.npmjs.com/package/downshift</a></li>
<li>I need to lift the value to the store as it is needed in other components as well</li>
<li>Will change it back to React.Component and use some deep compare then, thx</li>
<li>throttle sounds well, but I am not doing any API request in the search</li>
<li>No API requests. The search only works with 'local' stuff (Redux, local Arrays, local JSON-objects).</li>
</ul>
<p>Here is some more Code, that calls our AutoSuggestField:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { removeFilter, setFilter } from '../store/filter-values/actions';
import FilterSelection from './components/FilterSelection';
import withFilterService from './service/withFilterService';
import AutoSuggestField from '../components/filter/AutoSuggestField';
import FilterService from './service/FilterService';
import { ProductCategory } from '../data/model/category';
export class TrieSearchFilterSelection extends FilterSelection {
constructor(attributeName, selected, trieResult) {
super(attributeName, selected);
this.filterResultIds = {};
trieResult.forEach((product) => {
this.filterResultIds[product.id] = true;
});
}
// eslint-disable-next-line class-methods-use-this
compareSpec() {
throw Error('Not implemented');
}
filter(product) {
if (this.isReset()) {
return true; // if this filter is reset(ed) don't do anything
}
return !!this.filterResultIds[product.id];
}
}
const propTypes = {
attributeName: PropTypes.string.isRequired,
selected: PropTypes.instanceOf(TrieSearchFilterSelection),
ignoreOwnAttributeForAvailability: PropTypes.bool,
onRemoveFilter: PropTypes.func.isRequired,
onSetFilter: PropTypes.func.isRequired,
filterService: PropTypes.instanceOf(FilterService).isRequired,
category: PropTypes.instanceOf(ProductCategory).isRequired,
};
const defaultProps = {
selected: null,
ignoreOwnAttributeForAvailability: true,
};
class CameraTitleOrdernumberFilter extends PureComponent {
constructor(props) {
super(props);
const { filterService, category } = this.props;
this.trieSearch = filterService
.getServiceForCategory(category.name)
.getTrieSearch();
}
getValues() {
const { selected, attributeName } = this.props;
const products = this.trieSearch.getSearchResultOrAllProducts(selected ? selected.getSelectedValue() : '');
const availabitlity = this.trieSearch.getProductAvailability(attributeName);
return products.map((product) => {
const { name } = product;
const ordernumber = product.specs.specMap.ordernumber.value;
return {
label: `${product.name} - ${ordernumber}`,
name,
ordernumber,
id: product.id,
available: availabitlity.includes(product.id),
};
});
}
handleFilterSelected(newValue) {
const { attributeName, onRemoveFilter, onSetFilter } = this.props;
let products = [];
if (newValue) {
products = this.trieSearch.get(newValue);
}
const selectionObj = new TrieSearchFilterSelection(
attributeName,
newValue || null,
products
);
if (selectionObj.isReset()) {
onRemoveFilter();
} else {
onSetFilter(selectionObj);
}
}
render() {
const { selected } = this.props;
const valuesToUse = this.getValues();
const selectedToUse =
!!selected && 'selected' in selected ? selected.selected : null;
return (
<AutoSuggestField
{...this.props}
values={valuesToUse}
selected={selectedToUse}
isItemAvailable={item => item.available}
onFilter={newValue => this.handleFilterSelected(newValue)}
/>
);
}
}
CameraTitleOrdernumberFilter.propTypes = propTypes;
CameraTitleOrdernumberFilter.defaultProps = defaultProps;
export {
CameraTitleOrdernumberFilter as UnconnectedCameraTitleOrdernumberFilter,
};
const stateMapper = (
{ filterValues },
{ category, attributeName, selected }
) => ({
selected:
(category.name in filterValues &&
attributeName in filterValues[category.name] &&
filterValues[category.name][attributeName]) ||
selected,
});
const mapDispatchToProps = (dispatch, { category, attributeName }) => ({
onRemoveFilter: () => dispatch(removeFilter(category.name, attributeName)),
onSetFilter: (newValue) => {
dispatch(setFilter(category.name, attributeName, newValue));
},
});
export const doConnect = component =>
connect(
stateMapper,
mapDispatchToProps
)(withFilterService(component));
export default doConnect(CameraTitleOrdernumberFilter);</code></pre>
</div>
</div>
</p>
<p>It seems, that I did not find the performance problem as it still exists. Can someone help here? </p>
| [] | [
{
"body": "<p>Difficult to fix this kind of thing without being able to run the code. That said, having a look at your comments above, and what you've got there, I would suggest a few things. </p>\n\n<p>First off, when things start to lag, the UI is freezing up, or you're r experiencing render thrashing that can also make things lag, usually I would start with:</p>\n\n<ul>\n<li>It looks like you're seting the value from the store, as you type, which is an unneccessary bit of heavy lifting. Use local state and move away from controlled components for form fields.</li>\n<li>Change PureComponent for Component and use ShouldComponentUpdate along with a deep equality check (lodash, underscore, both have _.equal or roll your own). PureComponent only does a shallow comparison, so you may still see all sorts of thrashing in your react dev tools. I've seen this often on lists, and list Items.</li>\n<li>use <code>throttle</code> rather than debounce (debounce takes the last event after a given time, where throttle will take it at a set interval but avoid hammering your API on every request) - again assuming your onFilter function triggers an API call.</li>\n<li>Maybe you're doing do much at once\n\n<ul>\n<li>if the above is triggering multiple API calls, are you cancelling, and then calling again?</li>\n<li>Are you using selectors to filter the list client side, to ensure you're not triggering additional renders unneccessarily?</li>\n<li>marshal the events in your application, so that you show a loading indicator, and then only filter your list once the results are available.</li>\n</ul></li>\n<li>Look at the libs/deps\n\n<ul>\n<li>I'm not experienced with Downshift, though it may be interacting with the DOM directly, try removing this.</li>\n<li>I've had no issues with the material-ui inputs, so I wouldn't look there</li>\n<li>have you got anything else going on at the same time? Logging in redux, bugsnag or similar, rendering images?, animations? If you watch the react tree in dev tools is anything else rendering unnecessarily? Try disabling these one by one if you can, to find the culprit.</li>\n<li>Something I have had issues with is the material-ui spinner, if you're using that anywhere in the same view, try removing that as well.</li>\n</ul></li>\n<li>Look outside the scope of your current component</li>\n</ul>\n\n<p>Thats a really hard one without being able to fiddle with the code, Hope this is helpful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T20:12:03.197",
"Id": "432558",
"Score": "1",
"body": "Thank you very much. I edited my post above (added some code as well). Can you have a look at the other code ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T17:29:22.107",
"Id": "223251",
"ParentId": "223248",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223251",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T16:26:12.813",
"Id": "223248",
"Score": "1",
"Tags": [
"performance",
"react.js",
"jsx"
],
"Title": "React - Bottleneck Textinput / Filtering"
} | 223248 |
<p>I'm working on a Phoenix/Absinthe application and I thought to expose encrypted sequential IDs instead of UUIDs since these are a bit shorter.
Encryption on Elixir/Erlang seems very hard, so I think I'll use UUIDs eventually.</p>
<p>Anyway I'd like to know how bad, from security perspective, is the solution I came up with:</p>
<pre><code>defmodule MyAppWeb.GraphQL.Types.EncId do
use Absinthe.Schema.Notation
defp secret_key(len \\ 32) do
Application.get_env(:my_app, MyAppWeb.Endpoint)
|> Keyword.get(:secret_key_base, "")
|> String.slice(0, len)
end
defp pad_bytes(binary, block \\ 16) do
padding_bits =
case rem(byte_size(binary), block) do
0 -> 0
r -> (block - r) * 8
end
<<0::size(padding_bits)>> <> binary
end
defp unpad_bytes(<<0, tail::bitstring>>), do: unpad_bytes(tail)
defp unpad_bytes(binary), do: binary
defp encrypt(raw_binary) do
padded_binary = pad_bytes(raw_binary)
:crypto.crypto_one_time(:aes_256_ecb, secret_key(), padded_binary, true)
end
defp decrypt(raw_enc) do
:crypto.crypto_one_time(:aes_256_ecb, secret_key(), raw_enc, false)
|> unpad_bytes()
|> :erlang.binary_to_term()
end
def serialize(id) do
id
|> :erlang.term_to_binary()
|> encrypt()
|> Base.url_encode64(padding: false)
end
def parse(%{value: enc_id}) do
try do
{:ok, raw_enc} = Base.url_decode64(enc_id, padding: false)
{:ok, decrypt(raw_enc)}
rescue
_ -> :error
end
end
scalar :enc_id, name: "EncId" do
serialize(&__MODULE__.serialize/1)
parse(&__MODULE__.parse/1)
end
end
</code></pre>
| [] | [
{
"body": "<p>I don't understand why encryption would be \"hard\" - the code above looks straightforward enough although I'm not sure you need the padding (never tried the new crypto APIs).</p>\n\n<p>Do note that if you want to secure your UUIDs (why?), you probably want to add a random IV to your UUIDs otherwise you'll probably expose too much information - UUIDs have some bits very static. Generally speaking, rolling your own crypto protocol is fraught with error; I would use an existing library like Hashids (<a href=\"https://hexdocs.pm/hashids/Hashids.html\" rel=\"nofollow noreferrer\">https://hexdocs.pm/hashids/Hashids.html</a>) because that protocol has been analyzed and you're probably better off with the mild known weaknesses in such a library than some huge unknown weakness lurking in roll-your-own :).</p>\n\n<p>But for all practical purposes, generating v4 UUIDs using a cryptographically strong RNG should be all you need. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T23:45:34.607",
"Id": "225224",
"ParentId": "223254",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T19:20:52.733",
"Id": "223254",
"Score": "1",
"Tags": [
"security",
"cryptography",
"elixir",
"erlang"
],
"Title": "Expose encrypted serial ID in Elixir"
} | 223254 |
<p>The code base is split between three different files odbc.py, scrape.py, and dataprocessor.py. For ODBC, the job of this file is to take scraped data and determine whether or not those results are in a database. Ultimately, I'd like to extend this script to contain more general functionality, so that the queries that are being performed are less dependent on the specifics of checking for titles; for instance, I have an idea where I'd like to check what interviews were added to the database and return back the results and sample path. The 'top 100' variable is an example of the output from <em>scrape.py</em>. </p>
<p>Here is the code for pyodc.py: </p>
<pre><code>import pyodbc
from ConfigFunc import GetConfig
#This function allows for the user to pull ODBC #
Location = 'AzureWinMedia06232019'
connectConfig = GetConfig(Location)
#Establishes Connection with Azure Database via ODBC#
conn = pyodbc.connect("""Driver={};Server={};Database={};Uid={};
Pwd={};Encrypt={};TrustServerCertificate={};
Connection Timeout={};""".format(connectConfig["Driver"], connectConfig["Server"], connectConfig["Database"],
connectConfig["User"], connectConfig["Password"], connectConfig["Encrypt"], connectConfig["TrustedServer"], connectConfig["ConnectionTimeout"]))
top100 = {1: {'artist': 'Lil Nas X Featuring Billy Ray Cyrus', 'title': 'Old Town Road'}, 2: {'artist': 'Billie Eilish', 'title': 'Bad Guy'}, 3: {'artist': 'Khalid', 'title': 'Talk'}, 4: {'artist': 'Jonas Brothers', 'title': 'Sucker'}, 5: {'artist': 'Ed Sheeran & Justin Bieber', 'title': "I Don't Care"}, 6: {'artist': 'Post Malone', 'title': 'Wow.'}, 7: {'artist': 'Post Malone & Swae Lee', 'title': 'Sunflower (Spider-Man: Into The Spider-Verse)'}, 8: {'artist': 'DaBaby', 'title': 'Suge'}, 9: {'artist': 'Chris Brown Featuring Drake', 'title': 'No Guidance'}, 10: {'artist': 'Sam Smith & Normani', 'title': 'Dancing With A Stranger'}, 11: {'artist': 'Polo G Featuring Lil Tjay', 'title': 'Pop Out'}, 12: {'artist': 'Shawn Mendes', 'title': "If I Can't Have You"}, 13: {'artist': 'Ava Max', 'title': 'Sweet But Psycho'}, 14: {'artist': 'Taylor Swift Featuring Brendon Urie', 'title': 'ME!'}, 15: {'artist': 'Halsey', 'title': 'Without Me'}, 16: {'artist': 'Ariana Grande', 'title': '7 Rings'}, 17: {'artist': 'Lizzo', 'title': 'Truth Hurts'}, 18: {'artist': 'Marshmello & Bastille', 'title': 'Happier'}, 19: {'artist': 'Blake Shelton', 'title': "God's Country"}, 20: {'artist': 'Morgan Wallen', 'title': 'Whiskey Glasses'}, 21: {'artist': 'Panic! At The Disco', 'title': 'High Hopes'}, 22: {'artist': 'Luke Combs', 'title': 'Beer Never Broke My Heart'}, 23: {'artist': 'Daddy Yankee & Katy Perry Featuring Snow', 'title': 'Con Calma'}, 24: {'artist': 'Young Thug, J. Cole & Travis Scott', 'title': 'The London'}, 25: {'artist': 'J. Cole', 'title': 'Middle Child'}, 26: {'artist': 'City Girls', 'title': 'Act Up'}, 27: {'artist': 'benny blanco, Halsey & Khalid', 'title': 'Eastside'}, 28: {'artist': 'Katy Perry', 'title': 'Never Really Over'}, 29: {'artist': 'Mustard & Migos', 'title': 'Pure Water'}, 30: {'artist': 'Tyler, The Creator', 'title': 'Earfquake'}, 31: {'artist': 'Panic! At The Disco', 'title': 'Hey Look Ma, I Made It'}, 32: {'artist': 'Meek Mill Featuring Drake', 'title': 'Going Bad'}, 33: {'artist': 'Dan + Shay', 'title': 'Speechless'}, 34: {'artist': 'Lady Gaga & Bradley Cooper', 'title': 'Shallow'}, 35: {'artist': 'Khalid', 'title': 'Better'}, 36: {'artist': 'Lee Brice', 'title': 'Rumor'}, 37: {'artist': 'Ariana Grande', 'title': "Break Up With Your Girlfriend, I'm Bored"}, 38: {'artist': 'Travis Scott', 'title': 'Sicko Mode'}, 39: {'artist': 'Thomas Rhett', 'title': 'Look What God Gave Her'}, 40: {'artist': 'A Boogie Wit da Hoodie', 'title': 'Look Back At It'}, 41: {'artist': 'Calboy', 'title': 'Envy Me'}, 42: {'artist': 'Billie Eilish', 'title': "When The Party's Over"}, 43: {'artist': 'Halsey', 'title': 'Nightmare'}, 44: {'artist': 'Jonas Brothers', 'title': 'Cool'}, 45: {'artist': 'Luke Combs', 'title': 'Beautiful Crazy'}, 46: {'artist': 'Kane Brown', 'title': 'Good As You'}, 47: {'artist': 'Cardi B', 'title': 'Press'}, 48: {'artist': 'Lil Baby', 'title': 'Close Friends'}, 49: {'artist': 'Ed Sheeran Featuring Chance The Rapper & PnB Rock', 'title': 'Cross Me'}, 50: {'artist': 'YG, Tyga & Jon Z', 'title': 'Go Loko'}, 51: {'artist': 'Cardi B & Bruno Mars', 'title': 'Please Me'}, 52: {'artist': 'Brett Eldredge', 'title': 'Love Someone'}, 53: {'artist': 'Offset Featuring Cardi B', 'title': 'Clout'}, 54: {'artist': 'YK Osiris', 'title': 'Worth It'}, 55: {'artist': 'Lewis Capaldi', 'title': 'Someone You Loved'}, 56: {'artist': 'Kelsea Ballerini', 'title': 'Miss Me More'}, 57: {'artist': 'P!nk', 'title': 'Walk Me Home'}, 58: {'artist': 'Billie Eilish', 'title': 'Bury A Friend'}, 59: {'artist': 'Maren Morris', 'title': 'GIRL'}, 60: {'artist': 'DJ Khaled Featuring SZA', 'title': 'Just Us'}, 61: {'artist': 'Luke Bryan', 'title': "Knockin' Boots"}, 62: {'artist': 'Luke Combs', 'title': "Even Though I'm Leaving"}, 63: {'artist': '5 Seconds Of Summer', 'title': 'Easier'}, 64: {'artist': 'Summer Walker X Drake', 'title': 'Girls Need Love'}, 65: {'artist': 'Lil Tecca', 'title': 'Ran$om'}, 66: {'artist': 'Blanco Brown', 'title': 'The Git Up'}, 67: {'artist': 'Meek Mill Featuring Ella Mai', 'title': '24/7'}, 68: {'artist': 'Jason Aldean', 'title': 'Rearview Town'}, 69: {'artist': 'Bad Bunny & Tainy', 'title': 'Callaita'}, 70: {'artist': 'DJ Khaled Featuring Cardi B & 21 Savage', 'title': 'Wish Wish'}, 71: {'artist': 'Dan + Shay', 'title': 'All To Myself'}, 72: {'artist': 'Chase Rice', 'title': 'Eyes On You'}, 73: {'artist': 'Beyonce', 'title': 'Before I Let Go'}, 74: {'artist': 'Eric Church', 'title': 'Some Of It'}, 75: {'artist': 'Marshmello Featuring CHVRCHES', 'title': 'Here With Me'}, 76: {'artist': 'Lil Uzi Vert', 'title': 'Sanguine Paradise'}, 77: {'artist': 'Lunay, Daddy Yankee & Bad Bunny', 'title': 'Soltera'}, 78: {'artist': 'Florida Georgia Line', 'title': 'Talk You Out Of It'}, 79: {'artist': 'Yo Gotti Featuring Lil Baby', 'title': 'Put A Date On It'}, 80: {'artist': 'Eli Young Band', 'title': "Love Ain't"}, 81: {'artist': 'NLE Choppa', 'title': 'Shotta Flow'}, 82: {'artist': 'Pedro Capo X Farruko', 'title': 'Calma'}, 83: {'artist': 'Avicii', 'title': 'Heaven'}, 84: {'artist': 'The Chainsmokers & Bebe Rexha', 'title': 'Call You Mine'}, 85: {'artist': 'Billie Eilish', 'title': 'Ocean Eyes'}, 86: {'artist': 'Megan Thee Stallion', 'title': 'Big Ole Freak'}, 87: {'artist': 'Future', 'title': 'Please Tell Me'}, 88: {'artist': 'Cody Johnson', 'title': 'On My Way To You'}, 89: {'artist': 'SHAED', 'title': 'Trampoline'}, 90: {'artist': 'Chris Young', 'title': 'Raised On Country'}, 91: {'artist': 'Nicky Jam X Ozuna', 'title': 'Te Robare'}, 92: {'artist': 'Ozuna', 'title': 'Amor Genuino'}, 93: {'artist': 'Jonas Brothers', 'title': 'Only Human'}, 94: {'artist': 'Yella Beezy, Gucci Mane & Quavo', 'title': 'Bacc At It Again'}, 95: {'artist': 'Bryce Vine Featuring YG', 'title': 'La La Land'}, 96: {'artist': 'Juice WRLD', 'title': 'Robbery'}, 97: {'artist': 'Ozuna x Daddy Yankee x J Balvin x Farruko x Anuel AA', 'title': 'Baila Baila Baila'}, 98: {'artist': 'Future', 'title': 'XanaX Damage'}, 99: {'artist': 'Future', 'title': 'Government Official'}, 100: {'artist': 'Sech Featuring Darell', 'title': 'Otro Trago'}}
def read(conn, query):
"""Executes a Query against the specified connection and query params"""
cursor = conn.cursor()
cursor.execute(query)
data = cursor.fetchall()
print(data)
return data
def top100Search(conn, top100):
"""Executes a query for the values in the top100 variable against the database specified within conn param"""
results = []
for items in top100:
topquery = "SELECT Title, Performer FROM Media WHERE Title ='" + top100[items]['title'].replace("'","''") + "'"
temp = read(conn, topquery)
if temp == []:
continue
else:
results.append(temp)
return results
def resultsparser(results):
b = []
for i in range(0, len(a)):
for j in range(0, len(a[i])):
b.append(a[i][j])
return b
</code></pre>
<p>The code is importing an external function (Get Config) which looks like this: </p>
<pre><code>import pyodbc
import ConfigParser
def GetConfig(remoteServer):
"""Needs a specified server in config and returns back the ODBC parameters Server, Driver, Database, User, Password, Encrypt, TrustedServer, ConnectionTimeout"""
Config = ConfigParser.ConfigParser()
Config.read('activeconfig.ini')
Server = Config.get(remoteServer, 'Server')
Driver = Config.get(remoteServer, 'Driver')
Database = Config.get(remoteServer, "Database")
User = Config.get(remoteServer, "User")
Password = Config.get(remoteServer, "Password")
Encrypt = Config.get(remoteServer, "Encrypt")
TrustedServer = Config.get(remoteServer, "TrustedServer")
ConnectionTimeout = Config.get(remoteServer, "ConnectionTimeout")
return {"Server": Server,"Driver": Driver, "Database": Database, "User":User, "Password": Password,
"Encrypt": Encrypt, "TrustedServer": TrustedServer, "ConnectionTimeout": ConnectionTimeout}
</code></pre>
<p>The purpose of the code above is to get the database connection string, which is stored in a config.ini file. Which is structured like so and connects to a remote Azure Database, which is a replica of a media library:</p>
<pre><code>[SomeServer]
Server:
Password:
Database:
User:
Driver:
Encrypt:
TrustedServer:
ConnectionTimeout:
</code></pre>
<p>Overall, I'm wondering if my code is over specified or if any of my functions/variables should be migrated over into classes? I haven't included the scraper or the Pandas portion of the code, as I thought it would be a bit much but could include it if it's helpful.</p>
| [] | [
{
"body": "<p>A <em>very strong</em> suggestion: <strong>Fix the <a href=\"https://www.owasp.org/index.php/SQL_Injection\" rel=\"nofollow noreferrer\">SQL injection</a></strong> in your code! This code should never ever be allowed into a production application.</p>\n\n<p>Some suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n<li>Naming is incredibly important for code maintainability. <code>data</code> is a well-known <a href=\"https://wiki.c2.com/?BadVariableNames\" rel=\"nofollow noreferrer\">offender</a> because it is completely meaningless. Every variable contains data, and unless you are handling arbitrary collections of completely unknown bytes there is a better name for the contents of that variable. <code>b</code>, for example, could at the very least be improved by calling it <code>result</code> - it's not going to conflict with the other <code>result</code> variable. It's not always easy to think of a better name, but it's time well spent.</li>\n<li><p>Your connection string could be formatted straight from the dictionary without duplicating the names (untested):</p>\n\n<pre><code>\"\".join([f\"{key}={value};\" for key, value in connection_configuration.items()])\n</code></pre></li>\n<li><code>conn</code> and <code>top100</code> are both shadowed by the <code>top100Search</code> parameters - they have the same name. This is a bug magnet.</li>\n<li><code>GetConfig</code> might as well return the entire dictionary - the code is much simpler that way, and anything that's not needed in the configuration would cause a handy error or would simply be ignored.</li>\n<li>Values like <code>Location</code> would be better off as configuration - it has no bearing on the logic of this code.</li>\n<li>You have a bug in your code - <code>resultparser</code> takes <code>results</code> but seems to think it's called <code>a</code> in the code.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:15:31.957",
"Id": "223275",
"ParentId": "223264",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223275",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T23:50:47.100",
"Id": "223264",
"Score": "0",
"Tags": [
"python",
"pandas",
"odbc"
],
"Title": "Code scrapes, queries against a database and intersects"
} | 223264 |
<p>I'm working on some legacy code which uses the singleton pattern. The problem I have with the traditional singleton is that the instance lives until the program terminates. This is messing up the order in which things need to get destroyed and makes it difficult to write independent unit tests. Unfortunately, I can't get rid of the singleton by constructing a single instance and passing it around since this would break APIs.</p>
<p>I wrote the following wrapper around a class T that hands out shared pointers to a single instance of T. When the last shared pointer goes out of scope the object gets destroyed.</p>
<pre><code>#include <memory>
#include <type_traits>
#include <mutex>
template <class T>
class refCountedSingleton
{
static_assert(!std::is_default_constructible<T>::value, "T must have a private/protected constructor to ensure it can only be constructed by refCountedSingleton");
static_assert(!std::is_copy_constructible<T>::value, "T must have a private/protected copy constructor to ensure instances handed out by refCountedSingleton cannot be copied");
static_assert(!std::is_copy_assignable<T>::value, "T must have a private/protected copy assignment operator to ensure instances handed out by refCountedSingleton cannot be copied");
static std::weak_ptr<T> p;
static std::mutex mu;
public:
static std::shared_ptr<T> getShared();
};
template <class T>
std::weak_ptr<T> refCountedSingleton<T>::p;
template <class T>
std::mutex refCountedSingleton<T>::mu;
template <class T>
std::shared_ptr<T> refCountedSingleton<T>::getShared()
{
std::lock_guard<std::mutex> lock(mu);
std::shared_ptr<T> temp = p.lock();
if (!temp) {
temp.reset(new T());
p = temp;
}
return temp;
}
</code></pre>
<p>The following class could be used as T:</p>
<pre><code>class obj {
friend class refCountedSingleton<obj>;
private:
obj() {}
obj(obj const&);
obj& operator=(obj const&);
};
</code></pre>
<p>Example use case:</p>
<pre><code>{
std::shared_ptr<obj> pm1 = refCountedSingleton<obj>::getShared();
{
// calling getShared() multiple times yields pointers to the same object
std::shared_ptr<obj> pm2 = refCountedSingleton<obj>::getShared();
}
} // instance of obj gets destroyed here
{
// a new instance of obj gets greated
std::shared_ptr<obj> pm3 = refCountedSingleton<obj>::getShared();
}
</code></pre>
<p>My singleton needs to be thread safe which is why I'm locking the mutex in <code>getShared()</code>. With the traditional singleton pattern performance can be improved by avoiding the expensive locking most of the time by leveraging <a href="https://en.wikipedia.org/wiki/Double-checked_locking" rel="nofollow noreferrer">double-checked locking</a>. I'm wondering if something similar could be done here as well.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T06:25:29.150",
"Id": "432588",
"Score": "0",
"body": "Welcome to Code Review! Correct me if I'm wrong, but as it stands the code in your question does not seem to compile (see yourself on [godbolt](https://godbolt.org/z/k_PS3h)). Seems like you're missing a `friend` declaration or something to that effect. Please verify and fix that, otherwise your question is off-topic for this site ([help/dont-ask])."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:48:41.277",
"Id": "432609",
"Score": "1",
"body": "The language guarantees (after C++11) that static storage duration objects are constructed in a thread safe manor. Which means the classic Singleton pattern works really well without any jumping through hoops: https://stackoverflow.com/a/1008289/14065"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:54:33.273",
"Id": "432610",
"Score": "0",
"body": "Solving the order of destruction is relatively simple. Since the order of destruction is guaranteed based on the order of creation you simply have to force a specific order of creation. I shouw a technique to solve it here: https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T09:01:20.300",
"Id": "432614",
"Score": "0",
"body": "The problem with this design is that across libraries (static or shared) you can potentially get multiple instances of your singleton (so its not actually a singleton any more). The problem is the standard does not specify how libraries work so link this into libA.a and libB.a where both use a singleton for `refCountedSingleton<XX>` and you will have two instances of `refCountedSingleton<XX>::p` when these are compiled into your application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:43:07.917",
"Id": "432640",
"Score": "0",
"body": "@MartinYork: I agree that the traditional lazy-initialized singleton is simpler and also thread safe. And yes, there are ways to control the order of destruction of static objects. However, the lazy-initialized singleton is asymmetric: It constructs the instance late (when requested for the first time) but the instance still lives until the program terminates. In some cases that might be too late. For example if unit tests shall be fully independent (all objects created by a test are supposed to be destroyed at the end of the test). My implementation tries to address these shortcomings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:42:25.403",
"Id": "432661",
"Score": "1",
"body": "Address things that don't work for you not shortcomings. Sure I can see that. The biggest issue with singleton is the lack of control of how it is created. Thus using the singleton pattern independently is usually an anti-pattern. It should be used in conjunction with another creator pattern so that you can adjust the behavior in non normal situations (like testing). I would suggest that you look at combining it with the factory pattern. By default you have a standard singleton but you can use the factory to install another type of singleton creator so that during testing it can create/destory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:44:01.443",
"Id": "432662",
"Score": "0",
"body": "https://softwareengineering.stackexchange.com/a/40374/12917"
}
] | [
{
"body": "<p>The problem with the above code is that it doing two things with one piece of code.</p>\n\n<p>1: Singleton Creation.\n2: Singelton LifeSpan.</p>\n\n<p>I would separate these out into two separate classes.</p>\n\n<p>The creation is done via an abstract factory (MySingletonFactory) but lifespan is controlled via explicit factory classes that are defined for the situation (so your code does not define the life span of the singleton).</p>\n\n<p>The other issue of the above code is that I have seen this not working because of the way global variables are created in libraries. When these libraries are linked together it is not required to remove duplicate variables (as all variables were already resolved as much as possible during compilation). The linking phase will only try and resolve unresolved dependencies not all linkers will try and remove duplicated global variables (though I suppose this will depend on how sophisticated the linker is).</p>\n\n<p>Here is how I would resolve the problem (by removing globals (using static storage function scope variables)).</p>\n\n<h2>Interfaces</h2>\n\n<pre><code>#include <memory>\n#include <iostream>\n#include <cstdlib>\n\nclass MySingleInterface\n{\n public:\n virtual ~MySingleInterface() {}\n\n virtual int doWork() = 0;\n};\nclass MySingleFactoryInterface\n{\n public:\n virtual ~MySingleFactoryInterface() {}\n virtual std::shared_ptr<MySingleInterface> createTheObject() = 0;\n};\n</code></pre>\n\n<h2>Abstract Factory (I think?)</h2>\n\n<pre><code>class MySingletonFactory\n{\n private:\n friend class MySingleInterface;\n static MySingleFactoryInterface& getCurrentFactory(MySingleFactoryInterface* replace)\n {\n // Do not strictly need a default factory.\n // But it is nice to have one for standard (default)\n // operations. Then you only specify one in non standard\n // situations like testing. \n static MyDefaultSingeltonFactory defaultFactory;\n\n // The current factory we are using.\n static MySingleFactoryInterface* currentFactory = &defaultFactory;\n if (replace)\n {\n std::swap(replace, currentFactory);\n }\n else\n {\n replace = currentFactory;\n }\n return *replace;\n }\n public:\n static std::shared_ptr<MySingleInterface> getInstance()\n {\n return getCurrentFactory(nullptr).createTheObject();\n }\n static MySingleFactoryInterface& setFactory(MySingleFactoryInterface& alternativeFactory)\n {\n return getCurrentFactory(&alternativeFactory);\n }\n};\n</code></pre>\n\n<h2>Example Default Singleton</h2>\n\n<pre><code>class MyDefaultSingeltonFactory;\nclass MyDefaultSingleton: public MySingleInterface\n{\n private:\n friend class MyDefaultSingeltonFactory;\n MyDefaultSingleton(){}\n public:\n virtual int doWork() override {static int value; return value++;} // Normal operation.\n};\nclass MyDefaultSingeltonFactory: public MySingleFactoryInterface\n{\n // A Normal Singleton factory.\n // The singelton lives from creation until the end of the program.\n // Note: This is the behavior of this factory does not need to\n // to be universal behavior.\n public:\n std::shared_ptr<MySingleInterface> createTheObject() override\n {\n std::shared_ptr<MySingleInterface> instance = std::shared_ptr<MySingleInterface>(new MyDefaultSingleton());\n return instance;\n }\n};\n</code></pre>\n\n<h2>Example Test Singelton</h2>\n\n<pre><code>class MyTestSingleton: public MySingleInterface\n{\n int value;\n public:\n MyTestSingleton()\n : value(rand())\n {}\n public:\n virtual int doWork() override {return value;} // Operation for testing.\n};\n\nclass MyTestSingletonFactory: public MySingleFactoryInterface\n{\n // This factory creates a new instance each time.\n // Can be useful for some types of test.\n public:\n std::shared_ptr<MySingleInterface> createTheObject() override\n {\n return std::make_shared<MyTestSingleton>();\n }\n};\n\nclass MyTestPersistantSingletonFactory: public MySingleFactoryInterface\n{\n // As long as the code holds a shared pointer it will be re-used.\n // Useful if you want to create the singleton during \"setUp()\" and\n // destroy it during \"tearDown()\" you get a brand new singleton for\n // each individual test.\n public:\n std::shared_ptr<MySingleInterface> createTheObject() override\n {\n // I leave the exercise of locking to you.\n static std::weak_ptr<MySingleInterface> persist;\n auto result = persist.lock();\n if (!result)\n {\n result = std::make_shared<MyTestSingleton>();\n persist = result;\n }\n return result;\n }\n};\n</code></pre>\n\n<h2>Test Harness</h2>\n\n<pre><code>int main()\n{\n srand(0);\n\n // Incrementing results.\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n\n // Each result indapendant.\n MyTestSingletonFactory testFactory;\n MySingletonFactory::setFactory(testFactory);\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n\n\n MyTestPersistantSingletonFactory persistantFactory;\n MySingletonFactory::setFactory(persistantFactory);\n {\n // As long as we hold a reference then\n // we should get the same result.\n std::shared_ptr<MySingleInterface> local = MySingletonFactory::getInstance();\n std::cout << \"L: \" << local->doWork() << \"\\n\";\n std::cout << \"L: \" << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n std::cout << \"L: \" << local->doWork() << \"\\n\";\n std::cout << \"L: \" << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n }\n // No local reference so we will create a new value.\n std::cout << \"N: \" << MySingletonFactory::getInstance()->doWork() << \"\\n\";\n}\n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>> ./a.out\n0\n1\n2\n3\n4\n5\n6\n7\n8\n520932930\n28925691\n822784415\n890459872\nL: 145532761\nL: 145532761\nL: 145532761\nL: 145532761\nN: 2132723841\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T19:05:06.483",
"Id": "223312",
"ParentId": "223265",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>While your code is thread-safe, it does not scale.<br>\nConsider adding a fast-path in case there is an object.</p></li>\n<li><p>There is no need for a class, a free function is enough.</p></li>\n<li><p><code>std::make_shared()</code> generally coalesces the two allocations (control-block and payload), making it significantly more efficient.<br>\nIf you want to ensure only <code>get_shared_singleton()</code> can ever construct a <code>T</code>, <a href=\"https://stackoverflow.com/questions/56356914/how-to-disable-creating-copying-obj-outside-a-factory-method/56363209#56363209\">use a key</a>.</p></li>\n</ol>\n\n<pre><code>class Key {\n Key() {}\n friend std::shared_ptr<T> get_shared_singleton();\n};\n\ntemplate <class T>\nstd::shared_ptr<T> get_shared_singleton() {\n static std::atomic<std::weak_ptr<T>> p;\n auto r = p.load(std::memory_order_consume).lock();\n if (r) return r;\n static std::mutex m;\n std::lock_guard _(m);\n r = p.load(std::memory_order_consume).lock();\n if (r) return r;\n if constexpr (std::is_constructible_v<T, Key>)\n r = std::make_shared<T>(Key());\n else\n r = std::make_shared<T>();\n p.store(r, std::std::memory_order_release);\n return r;\n}\n</code></pre>\n\n<p><sub>Be aware it needs C++2a for <code>std::atomic<std::weak_ptr<T>></code>.</sub></p>\n\n<p>Use it like:</p>\n\n<pre><code>struct X {\n X(X const&) = delete;\n X& operator=(X const&) = delete;\n X(Key /* optionally required for lockdown */) …\n …\n};\n\n…\n\nget_shared_singleton<X>()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:05:24.533",
"Id": "223315",
"ParentId": "223265",
"Score": "2"
}
},
{
"body": "<p>Although the motivation is to create independent unit tests, it only partially achieves that result.</p>\n\n<p>Because the singleton is globally accessible from while it's alive, we've constrained the tests to run sequentially, which limits our ability to run more of them in a given time.</p>\n\n<p>There may be benefit in making the singleton be thread-local for tests (this is an argument for using a suitable factory, as it can then be configured with a thread-local version for unit tests, and a global version for integration tests and production).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T08:09:56.693",
"Id": "223339",
"ParentId": "223265",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T00:01:05.933",
"Id": "223265",
"Score": "3",
"Tags": [
"c++",
"performance",
"multithreading",
"design-patterns",
"thread-safety"
],
"Title": "Thread-safe \"singleton\" that destroys object when not used anymore"
} | 223265 |
<p><a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">Readability counts</a>, but is very subjective. The following snippets are equivalent in functionality and turn a generator iterator into a chunked HTTP response in Flask. Which of those two patterns is more Pythonic, readable and convenient?</p>
<p>A) Aspect style with function decorators that change the return value:</p>
<pre><code>@app.route('/')
@flask_response_decorator
@optional_streaming_decorator
@progress_log_decorator
def index() -> Iterator:
"""Index page, optionally HTTP chunk-streamed and formatted."""
return Foo.get_instance().are_changes_locked()
</code></pre>
<p>or</p>
<p>B) explicit decorators within the function body</p>
<pre><code>@app.route('/')
def index() -> flask.Response:
"""Index page, optionally HTTP chunk-streamed and formatted."""
response = Foo.get_instance().are_changes_locked()
return flask.Response(optional_iterator_to_stream(iterator_to_progress_log(response)))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T02:20:17.747",
"Id": "432581",
"Score": "0",
"body": "Around here, we generally don't like brevity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T03:19:21.403",
"Id": "432585",
"Score": "0",
"body": "I added docstrings. The code above is now exactly as it is in my project, except from the `Foo` class, which is irrelevant for this example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T06:11:53.913",
"Id": "432587",
"Score": "0",
"body": "You say yourself that it is subjective, that IMHO means its not a good fit for the kind of \"objective\" QA-style system here. In addition, you did not provide a lot of code to judge the code/differences in a greater context, which makes this question tend even more to the [off-topic](/help/dont-ask) side of things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T06:57:45.417",
"Id": "432589",
"Score": "0",
"body": "I don't see how this question could possibly be off-topic. It is matched by the first point of on-topic examples: \"If you have a working piece of code from your project and are looking for open-ended feedback in the following areas: Application of best practices and design pattern usage (...)\". This question is about the usage of decorators for transforming the return value of a Flask view function and I provided a real piece of code I am using in production."
}
] | [
{
"body": "<blockquote>\n <p>Pythonic, readable and convenient</p>\n</blockquote>\n\n<p>are all subjective and open to debate, even though \"Pythonic\" is less so than the others. That said, a simplified version may be illustrative. Comparing</p>\n\n<pre><code>@foo\n@bar\ndef baz(value: T) -> T:\n return value\n</code></pre>\n\n<p>to</p>\n\n<pre><code>def baz(value: T) -> FooT:\n return foo(bar(value))\n</code></pre>\n\n<p>there are two issues with the former:</p>\n\n<ol>\n<li>The final return type is now hidden in <code>foo</code>.</li>\n<li>It is easy to confuse the layering - is <code>baz(value)</code> equivalent to <code>foo(bar(baz(value)))</code> or <code>bar(foo(baz(value)))</code> (or even <code>baz(foo(bar(value)))</code> in case of a novice)? Nested decorators come up so rarely that I would have to look at the documentation to be absolutely sure whether they were in the right sequence.</li>\n</ol>\n\n<p>There seems to be two situations where multi-level decorators would be fine:</p>\n\n<ol>\n<li>If they pass through the return value unchanged. A logger would be a typical example.</li>\n<li>If the decorators are <a href=\"https://en.wikipedia.org/wiki/Commutative_property\" rel=\"nofollow noreferrer\">commutative</a>, that is, their order doesn't matter for the outcome.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T07:38:34.360",
"Id": "223274",
"ParentId": "223268",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T02:07:17.440",
"Id": "223268",
"Score": "1",
"Tags": [
"python",
"comparative-review",
"aspect-oriented"
],
"Title": "Aspect-oriented vs explicit style in Python"
} | 223268 |
<p>I made a small application using <code>C#</code>, <code>SQL Database</code>, entity framework , and windows forms to manipulate users (<code>Add_User</code> , <code>Update_User</code> , <code>Delete_User</code>) and their activities (<code>Add_Activity</code> , <code>Update_Activity</code> , <code>Delete_Activity</code>). I created a database with 2 tables, the first one with users and a second one with the activities of each user. The relationship is one to many with a foreign key at the activities table which is the <code>User_ID</code> in the first table. The first Frame has the option to create a new user or to choose a user from a data grid loaded with all the users from the table and update or delete them. By double clicking at one of the users at the data grid a second Frame opens with a data grid of all the activities of that user. The code for that is: </p>
<pre><code>void updateActions()
{
using (I2SEntities1 db = new I2SEntities1())
dgActions.DataSource = db.Actions.Where(x => x.Client_ID.Equals(Main.client.Client_ID)).ToList<Action>();
}
</code></pre>
<p>Where <code>dgActions</code> is the data grid in the second frame and <code>Main.client.Client_ID</code> is the <code>ID</code> of the <code>User</code>.</p>
<ul>
<li><p>My first question: Is this a good way of doing it. In order to load all the activities of the user I have to iterate to all the members in the table activities which doesn't look so good. There is an <code>ICollection<Actions></code> in the auto generated code from entity framework , how can i make use of it?.</p></li>
<li><p>My second question: If I want to delete a user, I can't do it if it has activities because of the foreign key which is normal. How would I go about doing this?</p></li>
</ul>
<p>Is there another, better way, to check if a user still has activities and display a message? I can do it with a <code>try/catch</code> block or by checking if the count in the <code>ICollection<Action></code> of the class <code>Client</code> is zero . But is this the right away?</p>
<pre><code>private void btnDelete_Click(object sender, EventArgs e)
{
if(MessageBox.Show("Do you really want to delete this user ?" , "Delete User" , MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (I2SEntities1 db = new I2SEntities1())
{
var entry = db.Entry(client);
if (entry.State == System.Data.Entity.EntityState.Detached)
db.Clients.Attach(client);
if (client.Actions.Count == 0)
{
try
{
db.Clients.Remove(client);
db.SaveChanges();
MessageBox.Show("User: " + client.Name + " deleted successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
else
MessageBox.Show("Can't delete User " + client.Name + ". User has activities");
}
Clear();
update_Grid();
}
}
</code></pre>
<p>These are my main concerns, but I would also like to know if I have a good application design.</p>
<pre><code>namespace I2S
{
public partial class Main : Form
{
public static Client client = new Client();
public Main()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Clear();
}
void Clear()
{
txtName.Text = txtPhone.Text = txtAddress.Text = "";
btnAdd.Text = "Add";
btnDelete.Enabled = false;
client.Client_ID = 0;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if(MessageBox.Show("Do you really want to delete this user ?" , "Delete User" , MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (I2SEntities1 db = new I2SEntities1())
{
var entry = db.Entry(client);
if (entry.State == System.Data.Entity.EntityState.Detached)
db.Clients.Attach(client);
db.Clients.Remove(client);
db.SaveChanges();
MessageBox.Show("Deleted Successfully");
}
Clear();
update_Grid();
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
client.Name = txtName.Text.Trim();
client.Address = txtAddress.Text.Trim();
client.Telephone = txtPhone.Text.Trim();
using (I2SEntities1 db = new I2SEntities1())
{
if (client.Client_ID == 0)
{
db.Clients.Add(client);
db.SaveChanges();
MessageBox.Show("New user added");
}
else
{
db.Entry(client).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
MessageBox.Show("User Updated Successfully");
}
Clear();
update_Grid();
}
}
private void Main_Load(object sender, EventArgs e)
{
update_Grid();
}
void update_Grid()
{
dgClients.AutoGenerateColumns = false;
using (I2SEntities1 db = new I2SEntities1())
{
dgClients.DataSource = db.Clients.ToList<Client>();
}
}
private void dgClients_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgClients.CurrentRow.Index != -1)
{
client.Client_ID = Convert.ToInt32(dgClients.CurrentRow.Cells["Client_ID"].Value);
}
using (I2SEntities1 db = new I2SEntities1())
{
client = db.Clients.Where(x => x.Client_ID == client.Client_ID).FirstOrDefault();
txtName.Text = client.Name;
txtAddress.Text = client.Address;
txtPhone.Text = client.Telephone;
}
btnAdd.Text = "Update";
btnDelete.Enabled = true;
}
private void dgClients_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (dgClients.CurrentRow.Index != -1)
{
client.Client_ID = Convert.ToInt32(dgClients.CurrentRow.Cells["Client_ID"].Value);
}
Form2 actionsForm = new Form2();
actionsForm.Show();
}
}
}
namespace I2S
{
public partial class Form2 : Form
{
Action action = new Action();
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Clear();
txtDateStart.Format = DateTimePickerFormat.Short;
txtTimeStart.Format = DateTimePickerFormat.Time;
txtDateEnd.Format = DateTimePickerFormat.Short;
txtTimeEnd.Format = DateTimePickerFormat.Time;
btDeleteAction.Enabled = false;
updateActions();
}
private void dgActions_CellClick(object sender, DataGridViewCellEventArgs e)
{
if(dgActions.CurrentRow.Index != -1)
{
action.Action_Id = Convert.ToInt32(dgActions.CurrentRow.Cells["Action_ID"].Value);
}
using (I2SEntities1 db = new I2SEntities1())
{
action = db.Actions.Where(x => x.Action_Id == action.Action_Id).FirstOrDefault();
txtActionDescription.Text = action.Action_Desc;
txtDateStart.Text = action.Action_Beggin.Date.ToString();
txtTimeStart.Text = action.Action_Beggin.TimeOfDay.ToString();
txtDateEnd.Text = action.Action_End.Date.ToString();
txtTimeEnd.Text = action.Action_End.TimeOfDay.ToString();
}
btAddAction.Text = "Update";
btDeleteAction.Enabled = true;
}
private void btDeleteAction_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to delete this action ?", "Delete Action", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (I2SEntities1 db = new I2SEntities1())
{
var entry = db.Entry(action);
if (entry.State == System.Data.Entity.EntityState.Detached)
db.Actions.Attach(action);
db.Actions.Remove(action);
MessageBox.Show("Action Sucesfully Removed");
db.SaveChanges();
}
Clear();
updateActions();
}
}
private void btAddAction_Click(object sender, EventArgs e)
{
action.Action_Desc = txtActionDescription.Text.Trim();
action.Action_Beggin = Convert.ToDateTime(txtDateStart.Value.Date + txtTimeStart.Value.TimeOfDay);
action.Action_End = Convert.ToDateTime(txtDateEnd.Value.Date + txtTimeEnd.Value.TimeOfDay);
action.Client_ID = Main.client.Client_ID;
using (I2SEntities1 db = new I2SEntities1())
{
if (action.Action_Id == 0)
{
db.Actions.Add(action);
db.SaveChanges();
MessageBox.Show("New action added");
}
else
{
db.Entry(action).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
MessageBox.Show("Action Succesfully Updated");
}
}
Clear();
updateActions();
}
void updateActions()
{
using (I2SEntities1 db = new I2SEntities1())
dgActions.DataSource = db.Actions.Where(x => x.Client_ID.Equals(Main.client.Client_ID)).ToList<Action>();
}
private void btClear_Click(object sender, EventArgs e)
{
Clear();
}
void Clear()
{
txtActionDescription.Text = txtDateStart.Text = txtTimeStart.Text = txtDateEnd.Text = txtTimeEnd.Text= "";
btDeleteAction.Enabled = false;
btAddAction.Text = "Add";
action.Action_Id = 0;
}
}
}
</code></pre>
<p>The DTO's for <code>Client</code> and <code>Actions</code> :</p>
<pre><code> namespace I2S
{
using System;
using System.Collections.Generic;
public partial class Client
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Client()
{
this.Actions = new HashSet<Action>();
}
public int Client_ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Action> Actions { get; set; }
}
}
namespace I2S
{
using System;
using System.Collections.Generic;
public partial class Action
{
public int Action_Id { get; set; }
public string Action_Desc { get; set; }
public System.DateTime Action_Beggin { get; set; }
public System.DateTime Action_End { get; set; }
public int Client_ID { get; set; }
public virtual Client Client { get; set; }
}
}
namespace I2S
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class I2SEntities1 : DbContext
{
public I2SEntities1()
: base("name=I2SEntities1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Action> Actions { get; set; }
public virtual DbSet<Client> Clients { get; set; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T11:18:25.950",
"Id": "432621",
"Score": "0",
"body": "It would be helpful to reviewers, if you showed the DTO's for `Client` and `Action` - and the database context. Are you using code first or db first when maintaining your database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T11:32:18.750",
"Id": "432622",
"Score": "0",
"body": "@Henrik Hansen For the database context shall I printScreen it? What do you mean by code first or db first?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T11:43:34.083",
"Id": "432624",
"Score": "0",
"body": "No, I just mean the code for `I2SEntities1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T11:59:10.053",
"Id": "432626",
"Score": "1",
"body": "**Code first**:you create the data model as classes in C# and use [migrations](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/) to create the database. **db first**: You create your database - tables ect. - in SQL Server \"by hand\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:01:59.907",
"Id": "432627",
"Score": "1",
"body": "I create my database in SQL \"by hand\" and than i used entity framework for the classes."
}
] | [
{
"body": "<p>So for anyone that might find it interesting: I found how to make it more efficient. \nI used as data source for my data grid this:</p>\n\n<pre><code>dgActions.DataSource = db.Actions.Where(\n x => x.Client_ID.Equals(Main.client.Client_ID)).ToList<Action>();\n</code></pre>\n\n<p>But in my opinion that is not so efficient. \nSo I thought to use the navigation property of the class <code>Client</code> as data source.\nI pass a <code>client_ID</code> from the first form. \nCreate a new <code>Client</code> object and copy the one from the data base that has the same <code>Client_ID</code> passed from the previous form and use the navigation property of that object as data source.\nI think this is a better implementation:</p>\n\n<pre><code>void updateActions()\n{\n using (I2SEntities1 db = new I2SEntities1())\n {\n myClient = db.Clients.Where(x \n => x.Client_ID == Main.client.Client_ID).FirstOrDefault();\n dgActions.DataSource = myClient.Actions.ToList<Action>();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:51:57.023",
"Id": "432664",
"Score": "1",
"body": "_in my opinion that is not so efficient._ - efficiency doesn't care about opinions :-P this needs to be proven with a benchmark ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:13:03.417",
"Id": "432667",
"Score": "0",
"body": "@t3chb0t You are right. But in this case it looks obvious. In the first case I had to iterate over the hole table to find the data that I needed and in the other case I just use the ones at the IColection. I am not familiar with this kind of programing and with c#. But if I would compare it with the complexity of an algorithm in the first case it would be O(n) where n number of members in an array and in the second case O(k) where k size of bucket of the unordered associative container. where 1 < k < n ;"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:44:30.073",
"Id": "223304",
"ParentId": "223276",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:48:49.927",
"Id": "223276",
"Score": "3",
"Tags": [
"c#",
"sql",
"entity-framework",
"winforms"
],
"Title": "Small application for manipulating users and their activities"
} | 223276 |
<p>I came to a point while refactoring using <code>if {} else {}</code> code with Java optionals. While optimizing code it turned to a result to this:</p>
<blockquote>
<pre><code>Optional.of(myBoolean).filter(b -> b).ifPresent(b -> {/*my code if true*/});
</code></pre>
</blockquote>
<p>I recognized <code>filter(b -> b)</code> is not the way i wanted to use optionals thus i turned it to</p>
<blockquote>
<pre><code>If.is(myBoolean).then(b -> {/*my code if true*/}).orElse(b -> {/*my code if false*/});
</code></pre>
</blockquote>
<p>The code for the <code>If</code> class I wrote to handle this is:</p>
<pre><code>public class If {
private boolean isTrue;
public If(final boolean value) {
isTrue = value;
}
public If then(final Consumer s) {
if (isTrue) {
s.accept(null);
}
return this;
}
public void orElse(final Consumer s) {
if (!isTrue) {
s.accept(null);
}
}
public static If is(final boolean value) {
return new If(value);
}
}
</code></pre>
<p>Is this a good (whatever good is or should be) approach using the <code>if {} else {}</code> statement in Java?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T09:10:49.027",
"Id": "432616",
"Score": "4",
"body": "Hi Daniel, is it possible to share the code you have refactored with us? Often `if-else` branches can be replaced by polymorphism."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T11:11:08.320",
"Id": "432620",
"Score": "4",
"body": "What does this class have to do with Optionals? Which advantage does it have over a regular `if`/`else`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:03:24.793",
"Id": "432788",
"Score": "1",
"body": "I don't quite understand the need of `.filter(b -> b)` in the first code example, it would be the exact same thing without that part, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T09:08:08.923",
"Id": "433721",
"Score": "0",
"body": "Hi @SimonForsberg, I checked again the `filter` method `Optional.of(true).ifPresent(b -> System.out.println(\"1: \" + b));`\n`Optional.of(false).ifPresent(b -> System.out.println(\"2: \" + b));`\n`Optional.of(true).filter(b -> b).ifPresent(x -> System.out.println(\"3: \" + x));`\n`Optional.of(false).filter(b -> b).ifPresent(x -> System.out.println(\"4: \" + x));`\n\nThe console output was\n`1: true`\n`2: false`\n`3: true`\n\nand `2: false` should not appear (as `4: false` doesn't). Therefore `filter(b -> b)` is necessary. That led me to the `If` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T09:40:45.860",
"Id": "433727",
"Score": "1",
"body": "@DanielGschösser Oh right, you want to turn all those `false` booleans to an empty optional, I get it."
}
] | [
{
"body": "<p>My first instinct is that your code is a pretty “cool” way to rewrite if else statements, but I don’t think it gains you too much. If you have massive amounts of if trees and want to make them more readable, I would consider using polymorphism to your advantage or, when appropriate, strategy pattern. </p>\n\n<p>If you want some help refactoring a certain if tree please feel free to post the code and we can help. </p>\n\n<p>There are often, IMO, two big reasons to make a new abstraction. </p>\n\n<p>1) to decrease the mental load on the maintainers of this code or </p>\n\n<p>2) to increase the ability to add new features in the future. </p>\n\n<p>Both of these are, of course, related. My question is, and feel free to comment below, does your if abstraction decrease maintainer mental load through simplicity or brevity and/or does your if abstraction improve the ability to add new features in the future? If not then you need to consider why you are doing it in the first place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T11:32:37.490",
"Id": "433361",
"Score": "0",
"body": "Well i guess the only advantage is to write code in one line readable from left to right. That was more or less the intention for this (escalated) codereview that lead to the question here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T09:42:39.337",
"Id": "433728",
"Score": "2",
"body": "@DanielGschösser `If.is(myBoolean).then(b -> {/*my code if true*/}).orElse(b -> {/*my code if false*/});` can also be written as `if (myBoolean) { /* my code if true */ } else { /* my code if false */ }` which can also be written in one line readable from left to right. Just because it can be written in more lines doesn't mean that it has to."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:59:46.240",
"Id": "223288",
"ParentId": "223277",
"Score": "9"
}
},
{
"body": "<p><strong>There is nothing inherently wrong with if-else statements.</strong></p>\n\n<p>Please do not use Optionals as replacement for if-else statements. They were not intended for that purpose. Optional was intended to convey the <em>possibility of null-values in public interfaces</em> in code, instead of just documentation, and only that. Even using optional in a private method is against it's intention (you're supposed to know what your own code does).</p>\n\n<p>Please read this answer from one of the architects behind the Optional class: <a href=\"https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555\">https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555</a></p>\n\n<p><strong>Exercise</strong>: Calculate the number of object creations and method calls involved in a Optional-if-else compared to a regular if-else and evaluate what effect the difference, if there is one, has on the optimizations.</p>\n\n<p><strong>Implementation</strong></p>\n\n<p>The If-class is intended to replace if-else-statements, but it does not follow the same logic as it allows multiple then-statements. It also lacks support for else-if constructs. Regular if-else statements do not consume anything so the parameter type of <code>then</code> and <code>orElse</code> should be <code>Runnable</code> (the fact that you pass a <code>null</code> to the consumer is a tell tale about code smell).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T05:37:44.713",
"Id": "223329",
"ParentId": "223277",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "223288",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T08:52:18.583",
"Id": "223277",
"Score": "5",
"Tags": [
"java",
"optional"
],
"Title": "Is it worth to use if-else statement as Java optional pattern?"
} | 223277 |
<pre><code> function slice(array, startingPoint, endingPoint){
if(arguments.length === 1) {
return array;
}else if(arguments.length === 2) {
// non-int value
var numberInString = startingPoint;
if(typeof(startingPoint) !== 'number'){
var checkNumber = Number(startingPoint);
if(checkNumber.toString() === 'NaN'){
return array;
}else{
numberInString = checkNumber;
}
}
var result = [];
if(numberInString < 0) {
var posStartPoint = array.length - Math.abs(numberInString);
var updateArr = [];
for(var i = posStartPoint; i < array.length; i++){
updateArr.push(array[i]);
}
return updateArr;
}else if( numberInString > array.length) {
return [];
}
for(var i = numberInString; i < array.length; i++){
result.push(array[i]);
}
return result;
}else{
var numberInStartPoint = startingPoint;
var numberInEndPoint = endingPoint;
var updateArr = [];
if(typeof(endingPoint) !== 'number' || typeof(startingPoint) !== 'number'){
if(typeof(endingPoint) !== 'number' && typeof(startingPoint) !== 'number'){
var checkStartNumber = Number(startingPoint);
var checkEndNumber = Number(endingPoint);
if( checkEndNumber.toString() === 'NaN' || checkStartNumber.toString() === 'NaN'){
return updateArr;
}else{
numberInStartPoint = checkStartNumber;
numberInEndPoint = checkEndNumber;
}
}
}
var posEndingPoint = numberInEndPoint;
var posStartPoint = numberInStartPoint;
if(posEndingPoint < 0 || numberInStartPoint < 0 ) {
if( posEndingPoint < 0 && numberInStartPoint < 0 ) {
posEndingPoint = array.length - Math.abs(posEndingPoint);
posStartPoint = array.length - Math.abs(numberInStartPoint);
}else if( numberInStartPoint < 0 ) {
posStartPoint = array.length - Math.abs(numberInStartPoint);
}else{
posEndingPoint = array.length - Math.abs(posEndingPoint);
}
}else if( numberInStartPoint === posEndingPoint) {
return [];
}else if( numberInStartPoint >= 0 && posEndingPoint >= 0) {
posEndingPoint = posEndingPoint;
posStartPoint = numberInStartPoint;
}
for(var i = posStartPoint; i < posEndingPoint; i++){
updateArr.push(array[i]);
}
return updateArr;
}
}
</code></pre>
<p>I have these passing test cases: </p>
<pre><code> 'if no other arguments , it should return original array':function(){
var arr = [1,2,3];
eq(arr,slice(arr)); // test passed
},
'if second argument is non-integer value , return original array':function(){
var arr = [1,2,3];
eq(arr,slice(arr,'a')); // test passed
},
'if second argument is string but include number only , it should return elements from startingPoint':function(){
var arr = [1,2,3,4];
eq('2,3,4',slice(arr,'1')); // test passed
},
'if startingPoint is integer value , return elements from startingPoint to array.length':function(){
var arr = [1,2,3];
eq('3',slice(arr,2)); // test passed
},
'if startingPoint is negative value, it should count from right side':function(){
var arr = [1,2,3];
eq('2,3',slice(arr,-2)); // test passed
},
'if startingPoint is greater then array.length , return an empty array':function(){
var arr = [1,2,3];
eq('',slice(arr,5)); // test passed
},
'if endingPoint is non-integer value, it should return an empty array':function(){
var arr = [1,2,3];
eq('1,2',slice(arr,0,'2')); // test passed
},
'if endingPoint is negative value , it should start count from right side':function(){
var arr = [1,2,3,4];
eq('1,2',slice(arr,0,-2)); // test passed
},
'if both values are same , return an empty array':function(){
var arr = [1,2,3];
eq('',slice(arr,2,2)); // test passed
},
'if startingPoint and endingPoint both are positive , return element between them exluding endingPoint':function(){
var arr = [1,2,3,4];
eq('',slice(arr,3,0)); // test passed
},
'if startingPoint is negative and endingPoint is positive, it should start counting from right ':function(){
var arr = [1,2,3,4];
eq('2,3,4',slice(arr,-3,4)); // test passed
},
'if both are negative, both point need to start counting from right side ':function(){
var arr = [1,2,3,4];
eq('2,3', slice(arr, -3,-1)); // test passed
},
'if endingPoint is less then startingPoint, it should return empty array.':function(){
var arr = [1,2,3,4];
eq('', slice(arr,3,1)); // test passed
},
'if both are non-integer, it should count from right side if numbers inside string otherwise return empty arr.':function(){
var arr = [1,2,3,4];
eq('2,3', slice(arr,'1','3')); // test passed
eq('',slice(arr,'a','2')); // test passed
}
</code></pre>
<p>Have I made a correct implementation of <code>Array.prototype.slice()</code> method? Any test cases that I've missed?</p>
<p>I am using <a href="https://github.com/joewalnes/jstinytest" rel="nofollow noreferrer">tinytest.js</a> library for testing.</p>
| [] | [
{
"body": "<h2>General points</h2>\n\n<ul>\n<li><code>if</code> statements that return should not be followed by an <code>else</code>. Eg <code>if (foo) { return bar } else if (bar) {..</code> The <code>else</code> is redundant.</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\" rel=\"nofollow noreferrer\"><code>typeof</code></a> is not a function it is an operator (language token). Thus <code>typeof(foo) === \"foo\"</code> is the same as <code>typeof foo === \"foo\"</code></li>\n<li>Use the function <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\" rel=\"nofollow noreferrer\"><code>isNaN</code></a> to test if a value (number like) can not be parsed to a <code>Number</code>.</li>\n<li>Use constants <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> to define values that do not change. Eg you have <code>var updateArr = [];</code> could be <code>const updateArr = [];</code></li>\n<li>You should always keep <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\"><code>var</code></a> declarations in one place at the top of the function. If you are defining block scoped variables in the code use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a></li>\n<li><p>Do not use the <code>arguments</code> object it has some odd quirks that can catch the unwary. Use ES6+ <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters\" rel=\"nofollow noreferrer\">rest parameters</a>, or any of the new ways of defining arguments. example using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a> <code>function slice(array, start = 0, end = array.length)</code> </p></li>\n<li><p>Naming is poor and often too verbose. Keep names simple and short. Use the context of the code to add semantic meaning. </p>\n\n<p>To pick an example the arguments <code>startingPoint</code>, <code>endingPoint</code> does <code>point</code> add anything of value to the argument name?. Keep it short <code>start</code> as a noun is better than the gerund of start <code>starting</code> that implies start as a verb (General naming rule Verbs for functions, nouns for variables). </p>\n\n<p>Both arguments would best be <code>start</code> and <code>end</code> within the context of the function their meaning is very clear.</p></li>\n<li><p>You are duplicating content. eg You explicitly define 3 return arrays using two names <code>result</code>, <code>updateArr</code>. You should never do this.</p></li>\n</ul>\n\n<p>The code is very old school. Keep your skills up to date and always write using the latest language version.</p>\n\n<p>You are repeating logic. Vetting the arguments, iterating the array (there are 3 for loops in the code!!) </p>\n\n<h2>Compliance</h2>\n\n<p>Your function failed many compliance tests that I performed.</p>\n\n<p>I am not a big fan of unit testing as it is just as subject to error, omission, flawed assumptions as the code it is testing. </p>\n\n<p>In this case despite the effort you put in to test the code, the testing is of no use as the assumptions you have made are incorrect, and the tests are incomplete.</p>\n\n<p>I am surprised that you did not compare the result of your function to the result of <code>Array.slice</code> on the same array. That would be the better than testing against what you assume to be correct, would it not?</p>\n\n<h3>Compliance failure list</h3>\n\n<ol>\n<li><p>Return same array in many cases. Eg <code>a = [1,2,3]; if (splice(a) === a) { /* failed */ }</code>\nThe returned array must never be the same array. Many people use <code>slice</code> as a replacement to the old <code>[].concat(array)</code> hack. </p></li>\n<li><p>Returns incorrect length array. Eg <code>a = []; if (splice(a, 1, 2).length !== a.length) { /* failed */ }</code></p>\n\n<p>This is due to several incorrect behaviors.</p></li>\n<li>Fails to detect array like objects, or non arrays.</li>\n<li>Crashes page due to not bounds checking arguments. Eg <code>slice([],0,Infinity)</code> starts an infinite loop that eventually crashes page due to memory error.</li>\n</ol>\n\n<p>There are other fail modes but they are force edge cases that will have varying results across browsers and versions.</p>\n\n<h2>Example</h2>\n\n<p>The example implements slice as best can be without actual being a property of the <code>Array</code> being sliced. </p>\n\n<p>This forces the code to have to handle non array or array like arguments. It does its best to imitate slice if the array argument contains that method. Will throw a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError\" rel=\"nofollow noreferrer\"><code>RangeError</code></a> if first argument is not an array or a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError\" rel=\"nofollow noreferrer\"><code>ReferenceError</code></a> is first argument is missing.</p>\n\n<p>It uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof\" rel=\"nofollow noreferrer\"><code>instanceof</code></a> to vet the first argument. </p>\n\n<p>To vet the inputs it uses some helper functions at the top of the code. <code>vetPos</code> and <code>toPos</code> to convert relative position values to absolute positions as set out by the <a href=\"https://tc39.es/ecma262/#sec-array.prototype.slice\" rel=\"nofollow noreferrer\">spec</a>.</p>\n\n<pre><code>function slice(array, start, end) {\n if (array instanceof Array) {\n const len = array.length;\n const toPos = v => Math.max(0, Math.min(len, v < 0 ? len + v : v));\n const vetPos = v => toPos(isNaN(v) ? 0 : Math.floor(Math.abs(v)) * Math.sign(v));\n start = vetPos(start);\n end = vetPos(end === undefined ? len : end);\n let count = Math.max(0, end - start), idx = start, res;\n if (count === len) { res = [...array] } \n else {\n res = [];\n while (count--) { res.push(array[idx++]) }\n }\n return res;\n }\n if (array && typeof array.slice === \"function\") { return array.slice(start, end) }\n if (array) { throw new RangeError(\"First argument must be an array\") }\n throw new ReferenceError(\"Missing first argument\");\n}\n</code></pre>\n\n<h2>Notes</h2>\n\n<ul>\n<li><p>Reference for compliance from <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\" rel=\"nofollow noreferrer\">MDN <code>Array.slice</code></a> and the latest spec <a href=\"https://tc39.es/ecma262/#sec-array.prototype.slice\" rel=\"nofollow noreferrer\">ECMAScript 2020 (Draft) 'Array.prototype.slice'</a></p></li>\n<li><p>Because your code was messed up due to tabs when you pasted to CR (Good reason to use spaces rather than tabs) I auto formatted the code so I could read it and thus may have missed some related style points.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T11:17:19.980",
"Id": "432740",
"Score": "0",
"body": "+1 but I do question the first point. Also the second point could be considered stylistic consistency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T11:50:41.727",
"Id": "432748",
"Score": "0",
"body": "@morbusg Thanks. Re pts 1,2 I consider redundant code as noise, something for bugs to hide in. If it interferes with style consistency then it is a good sign that the style should be improved IMHO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:06:22.153",
"Id": "223342",
"ParentId": "223278",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T09:15:46.117",
"Id": "223278",
"Score": "3",
"Tags": [
"javascript",
"reinventing-the-wheel"
],
"Title": "An implementation of Array.prototype.slice()"
} | 223278 |
<p>How could one write in a more elegant way that if error is null, the result is true? I really need a bool as returned value.</p>
<pre><code>func existsFile(pPath string) bool {
_, errStat := os.Stat(pPath)
if errStat != nil {
return false
}
return true
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:06:41.713",
"Id": "432628",
"Score": "0",
"body": "I'm not sure what do you mean by \"more elegant\" but you can return both your value and original error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T04:32:30.963",
"Id": "432710",
"Score": "0",
"body": "One line. `return os.Stat(pPath) != nil`. But it is questionable whether you should do this at all. Usually you're about to open it for I/O, in which case you should just do that and handle the failure as it actually occurs, rather than trying to foretell the future and risk all the timing-window problems that can arise when you do so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T08:09:35.880",
"Id": "432727",
"Score": "0",
"body": "@user207421 os.Stat returns two values. you need to pick one to compare."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T11:57:13.320",
"Id": "433629",
"Score": "0",
"body": "This post and most answers ignore that fact that `ost.Stat` returning a non-nil error *does not equate to* file non-existence. There are many other possible reasons `os.Stat` might fail (e.g. permissions). The errors should be tested with [`os.IsNotExist`](https://golang.org/pkg/os#IsNotExist)."
}
] | [
{
"body": "<p>Instead of checking with an <code>if</code> statement if <code>errStat</code> is null and then returning false:</p>\n\n<blockquote>\n<pre><code>if errStat != nil {\n return false\n}\nreturn true\n</code></pre>\n</blockquote>\n\n<p>you can return a Boolean expression:</p>\n\n<pre><code>return errStat == nil\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:48:13.960",
"Id": "432641",
"Score": "0",
"body": "As per my answer, without knowing what the OP means by _elegant_, I can understand why you'd answer with a shorter version. However, I would argue idiomatic golang and human-readable code is more important than brevity. Elegance is code that only requires you to read it once, to know what it does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:06:19.230",
"Id": "432645",
"Score": "3",
"body": "@EliasVanOotegem: Using a Boolian expression as an assignment in cases like this (were one variable depends on a Boolian expression) is very common and (well, in my opinion and probably many more software programmers) is cleaner and more human readable. Some refactoring services actually offer similar changes. Shorter can be more readable. If you write this function for a \"a violent psychopath\" you may need a book..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:09:39.220",
"Id": "432646",
"Score": "1",
"body": ":D Personal preference/taste I suppose. Not trying to argue your response wasn't valid mate... relax. I know bool expressions are very common, in my experience, though, bugs caused by something like `return x >= y` where it should've been `return y >= x` or `return x < y` are also very common, hence my avoiding them."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:03:20.780",
"Id": "223289",
"ParentId": "223280",
"Score": "10"
}
},
{
"body": "<p>Elegant is hard to define, especially given the small snippet of code you've provided. I'll go down the list of different ways to write it. Note: Not all of them are what I'd call <em>\"elegant\"</em>, though:</p>\n\n<pre><code>// as short as possible (NOT ELEGANT)\nfunc fileExists(path string) (ok bool) {\n if _, err := os.Stat(path); err == nil {\n ok = true\n }\n return\n}\n</code></pre>\n\n<p>This works by creating a variable for the return value. A <code>bool</code> defaults to the <code>false</code> value. Next, I stat the path, and if <code>Stat</code> returns no errors, I set the return variable to <code>true</code>. Return and only if <code>Stat</code> returned no errors, the function will return <code>true</code>.</p>\n\n<pre><code>// boolean assignment\nif fileExists(path string) bool {\n _, err := os.Stat(path)\n return err == nil\n}\n</code></pre>\n\n<p>This is shorter, because we're returning the boolean value resulting from the comparison of <code>err</code>. If no error is returned, the function will return <code>true</code>.</p>\n\n<h3>All things considered, this is not elegant</h3>\n\n<p>It's important to remember: code is written by humans, for humans to read, and maintain. The compiler is there to translate the <em>human</em> readable code to machine instructions. If you try to write something as short as possible, it's going to be harder for others to maintain/understand. There's 2 very well known quotes about this:</p>\n\n<blockquote>\n <p>Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? -- Brian Kernighan in The Elements of Programming Style</p>\n</blockquote>\n\n<p>And</p>\n\n<blockquote>\n <p>Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. From <a href=\"http://wiki.c2.com/?CodeForTheMaintainer\" rel=\"nofollow noreferrer\">Code for the maintainer</a></p>\n</blockquote>\n\n<p>Keeping these things in mind, I'd say the code you have is easy to read, easy to maintain, and therefore elegant. There is one small change I'd suggest to have it be more <em>\"idiomatic\"</em>:</p>\n\n<pre><code>func fileExists(path string) bool {\n if _, err := os.Stat(path); err != nil {\n return false\n }\n return true\n}\n</code></pre>\n\n<p>The <code>if <err-assigning-expression>; err != nil</code> is the de facto standard way of checking error returns in golang, if you don't need the return values other than checking them. In this case, all you need the <code>err</code> for is to check whether it was a nil value of not, so assign & check in one <code>if</code> statement is what I'd recommend.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:46:22.620",
"Id": "223294",
"ParentId": "223280",
"Score": "3"
}
},
{
"body": "<p>Elegance is the wrong criterion. The key criterion is correctness, which implies readability and maintainability.</p>\n\n<p>As you read text, you notice misspelled words. Does that mean that you laboriously spell-check each word, letter-by-letter? In fact, most likely, you quickly and unconsciously scan the shape of the words. Only if the shape of a word seems odd do you pause and slowly check the spelling letter-by-letter.</p>\n\n<p>Since readablity is so important, we choose a few idiomatic, instantly recognizable code forms. For example,</p>\n\n<pre><code>if err != nil {\n // ...\n return ...\n}\n// ...\nreturn ...\n</code></pre>\n\n<p>Even if, in a particular case, we could write</p>\n\n<pre><code>return err == ...\n</code></pre>\n\n<p>The first, general form always works. The second, specialized form may not.</p>\n\n<p>The second form is less maintainable.</p>\n\n<p>If we find that </p>\n\n<pre><code>return err == ...\n</code></pre>\n\n<p>is insufficient, we probably have to replace it with the first form</p>\n\n<pre><code>if err != nil {\n // ...\n return ... \n}\n// ...\nreturn ...\n</code></pre>\n\n<p>To summarize, prefer a single, easily recognizable code form</p>\n\n<pre><code>if err != nil {\n // ...\n return ...\n}\n// ...\nreturn ...\n</code></pre>\n\n<p>in particular</p>\n\n<pre><code>if err != nil {\n return false\n}\nreturn true\n</code></pre>\n\n<hr>\n\n<p><strong>Idiomatic Go</strong></p>\n\n<blockquote>\n <p><a href=\"https://github.com/golang/go/wiki/CodeReviewComments#go-code-review-comments\" rel=\"nofollow noreferrer\">Go wiki: Go Code Review Comments</a></p>\n \n <p>This page collects common comments made during reviews of Go code, so\n that a single detailed explanation can be referred to by shorthands.</p>\n \n <p><a href=\"https://github.com/golang/go/wiki/CodeReviewComments#indent-error-flow\" rel=\"nofollow noreferrer\">Indent Error Flow</a></p>\n \n <p>Try to keep the normal code path at a minimal indentation, and indent\n the error handling, dealing with it first. This improves the\n readability of the code by permitting visually scanning the normal\n path quickly. For instance, don't write:</p>\n\n<pre><code>if err != nil {\n // error handling\n} else {\n // normal code\n}\n</code></pre>\n \n <p>Instead, write:</p>\n\n<pre><code>if err != nil {\n // error handling\n return // or continue, etc.\n}\n// normal code\n</code></pre>\n \n <p>If the if statement has an initialization statement, such as:</p>\n\n<pre><code>if x, err := f(); err != nil {\n // error handling\n return\n} else {\n // use x\n}\n</code></pre>\n \n <p>then this may require moving the short variable declaration to its own\n line:</p>\n\n<pre><code>x, err := f()\nif err != nil {\n // error handling\n return\n}\n// use x\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>For readability, don't be idiosyncratic. Conform to the familiar Go standard library <a href=\"https://golang.org/pkg/os/\" rel=\"nofollow noreferrer\"><code>os</code> package</a> names. For example,</p>\n\n<pre><code>func Stat(name string) (FileInfo, error)\n\nfunc IsExist(err error) bool\n</code></pre>\n\n<p>For your function,</p>\n\n<pre><code>func isFileExist(name string) bool {\n _, err := os.Stat(name)\n if err != nil {\n return false\n }\n return true\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T04:31:37.133",
"Id": "432709",
"Score": "2",
"body": "You start out well but your reasons for preferring five lines of code over one are entirely subjective."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:20:49.887",
"Id": "432814",
"Score": "0",
"body": "\"The first, general form always works. The second, specialized form may not.\" I'm not clear in which case the second form would not be equal to the first. Not arguing, just curious."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:47:37.930",
"Id": "223305",
"ParentId": "223280",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "223289",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T10:48:40.567",
"Id": "223280",
"Score": "3",
"Tags": [
"error-handling",
"file-system",
"go"
],
"Title": "Go function to test whether a file exists"
} | 223280 |
<p>Lets say I have simple <code>IsSomething()</code> method which checks, if object meets few requirements. Which approach is better?</p>
<pre><code>public bool IsSomething()
{
if (!MeetRequirementX()) return false;
if (!MeetRequirementY()) return false;
if (!MeetRequirementZ()) return false;
return true;
}
</code></pre>
<p>Or</p>
<pre><code>public bool IsSomething()
{
if (MeetRequirementX() &&
MeetRequirementY() &&
MeetRequirementZ())
return true;
return false;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:41:05.663",
"Id": "432631",
"Score": "1",
"body": "Which approach is more redable? btw, without context your question is off-topic on Code-Review. We require real and working code here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:52:59.413",
"Id": "432635",
"Score": "2",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)"
}
] | [
{
"body": "<p>Your second example doesn't compile; you're using too much <code>if</code>s.</p>\n\n<p>If you would be looking what the compiler would make of it, there wouldn't be too much of a difference; the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#conditional-logical-and-operator-\" rel=\"nofollow noreferrer\"><code>&&</code> operator short-circuits</a>. Therefore, you can concentrate on what's more readable for the maintainers of the code (which could be a future you).</p>\n\n<p>The shortest version would be</p>\n\n<pre><code>public bool IsSomething()\n{\n return MeetRequirementX() && MeetRequirementY() && MeetRequirementZ();\n}\n</code></pre>\n\n<p>which is fine if it's kind of obvious how these requirements combine into the desired result for <code>IsSomething()</code>. If that's not obvious, you'd better explain why each requirement is necessary with a comment, and then I'd prefer the following:</p>\n\n<pre><code>public bool IsSomething()\n{\n // comment explaining why requirement X is necessary\n if (!MeetRequirementX()) return false;\n\n // comment explaining why requirement Y is necessary\n if (!MeetRequirementY()) return false;\n\n // comment explaining why requirement Z is necessary\n return MeetRequirementZ();\n}\n</code></pre>\n\n<p>Or replace the last line with</p>\n\n<pre><code> if (!MeetRequirementZ()) return false;\n\n return true;\n</code></pre>\n\n<p>if you prefer the symmetry of that. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:48:11.450",
"Id": "432633",
"Score": "6",
"body": "You should avoid answering clearly off-topic questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:47:02.297",
"Id": "223286",
"ParentId": "223285",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223286",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:37:23.580",
"Id": "223285",
"Score": "-5",
"Tags": [
"c#"
],
"Title": "Should method return default true, or false when meeting requirements"
} | 223285 |
<p>Elm is a pure functional language for the front-end. It enforces an architecture that allows programs to stay pure in an event-based setting.</p>
<p>This simple header-only library implements a variant of the the Elm Architecture for C++17. Its small footprint and simplicity makes it easy to understand and quick to get started.</p>
<h3>Features</h3>
<p>The architecture supports running commands in parallel as asynchronous tasks, as well as in a immediate fashion.</p>
<h3>Example Program</h3>
<p>This example utilizes both direct and deferred action modes. It initializes by immediately increasing a conuter, then it manipulates the counter at a later time by deferring commands for later execution. To demonstrate the asynchronicity of the library the user can also enter a number in order to increase or decrease the counter.</p>
<pre><code>#include "elm-architecture/elm-architecture.hpp"
#include <iostream>
namespace elm = elm_architecture;
// Model
struct model_type {
int counter = 0;
};
// Msg
struct increase {};
struct decrease {};
struct user_increase {
int value;
};
using message_type = std::variant<increase, decrease, user_increase>;
std::shared_future<message_type>
delayed_increase(std::chrono::milliseconds delay) {
return std::async(
std::launch::async,
[delay]( ) -> message_type {
std::this_thread::sleep_for(delay);
return increase {};
})
.share( );
}
std::shared_future<message_type>
delayed_decrease(std::chrono::milliseconds delay) {
return std::async(
std::launch::async,
[delay]( ) -> message_type {
std::this_thread::sleep_for(delay);
return decrease {};
})
.share( );
}
std::shared_future<message_type>
ask_user( ) {
return std::async(
std::launch::async,
[]( ) -> message_type {
int amount = 0;
std::cin >> amount;
return user_increase {amount};
})
.share( );
}
// Update
struct update_fn {
using return_type = elm::return_type<model_type, message_type>;
static auto
update(const model_type& mod, const increase&) -> return_type {
auto next = mod;
next.counter += 1;
std::cout << "Increasing counter from " << mod.counter << " to " << next.counter << std::endl;
return {next, {}};
}
static auto
update(const model_type& mod, const decrease&) -> return_type {
auto next = mod;
next.counter -= 1;
std::cout << "Decreasing counter from " << mod.counter << " to " << next.counter << std::endl;
return {next, {}};
}
static auto
update(const model_type& mod, const user_increase& msg) -> return_type {
auto next = mod;
next.counter += msg.value;
std::cout << "User increasing counter from " << mod.counter << " to " << next.counter << std::endl;
return {next, {ask_user( )}};
}
};
// Event Loop
int
main( ) {
elm::start_eventloop<model_type, message_type, update_fn>({
increase {},
delayed_increase(std::chrono::milliseconds {1500}),
delayed_decrease(std::chrono::milliseconds {1000}),
delayed_increase(std::chrono::milliseconds {400}),
ask_user( ),
});
}
</code></pre>
<h3>The library</h3>
<pre><code>#pragma once
#include <deque>
#include <future>
#include <variant>
#include <vector>
namespace elm_architecture {
// A command can either be a deferred command (shared_future) or
// invoked directly.
template <typename Model, typename Msg>
using command_type = std::variant<std::shared_future<Msg>, Msg>;
// The return type for the update functions, a new model and a
// list of actions to take after.
template <typename Model, typename Msg>
using return_type = std::tuple<Model, std::vector<command_type<Model, Msg>>>;
// Start the eventloop with a given list of initial actions to take
template <typename Model, typename Msg, typename Update>
auto
start_eventloop(const std::vector<command_type<Model, Msg>>& init = {}) {
auto model = Model {};
std::deque<command_type<Model, Msg>> pending{init.begin(), init.end()};
std::vector<std::shared_future<Msg>> in_progress;
while(pending.size( ) > 0 || in_progress.size( ) > 0) {
// Step One: Apply all pending events and remove them
while(pending.size( ) > 0) {
const auto& item = pending.front( );
if(std::holds_alternative<std::shared_future<Msg>>(item)) {
in_progress.push_back(std::get<std::shared_future<Msg>>(item));
} else {
const auto& msg = std::get<Msg>(item);
const auto visitor = [&model](const auto& msg) { return Update::update(model, msg); };
auto [next_model, commands] = std::visit(visitor, msg);
std::copy(commands.begin( ), commands.end( ), std::back_inserter(pending));
model = next_model;
}
pending.pop_front( );
}
// Step Two: Pause the loop, the only way we get more events now is by polling
// until one of the pending events finishes.
{
for(auto future = in_progress.begin( ); future != in_progress.end( ); ++future) {
if(future->wait_for(std::chrono::milliseconds {1}) == std::future_status::ready) {
pending.push_back(future->get( ));
in_progress.erase(future);
break;
}
}
}
}
}
} // namespace elm_architecture
</code></pre>
<p>This project can also be found on <a href="https://github.com/simon-the-sourcerer-ab/elm-architecture-cpp" rel="nofollow noreferrer">GitHub</a>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T12:48:54.627",
"Id": "223287",
"Score": "2",
"Tags": [
"c++",
"functional-programming",
"c++17",
"elm"
],
"Title": "A tiny library implementing the Elm Architecture in C++"
} | 223287 |
<p>This is the first big project for me and I am not sure which is the correct way to structure the code yet. Is it okay to have so many classes and functions? What else should I improve?</p>
<pre class="lang-py prettyprint-override"><code>import pygame
import sys
import random
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
font = pygame.font.SysFont('Monospace', 35)
# COLORS
BLACK = (0, 0, 0)
GREEN = (32, 238, 189)
YELLOW = (255, 230, 0)
RED = (250, 25, 78)
GREEN2 = (33, 239, 33)
WHITE = (255, 255, 255)
# SCREEN
TILE_SIZE = 30
GRID_SIZE = [40, 30]
FPS = 20
WIDTH = GRID_SIZE[0] * TILE_SIZE
HEIGHT = GRID_SIZE[1] * TILE_SIZE
BACKGROUND_COLOR = BLACK
screen = pygame.display.set_mode((WIDTH, HEIGHT))
score = 0
class BodyPart:
def __init__(self, x, y, direction):
self.dir_x, self.dir_y = direction
self.x, self.y = x, y
def set_direction(self, direction):
self.dir_x = direction[0]
self.dir_y = direction[1]
class Snake:
def __init__(self):
self.color = GREEN
self.body = [BodyPart(TILE_SIZE * 3, int(HEIGHT / 2), (1, 0))]
def append_body_part(self, count):
for i in range(count):
x, y, dir_x, dir_y = self.body[-1].x, self.body[-1].y, self.body[-1].dir_x, self.body[-1].dir_y
x -= dir_x * TILE_SIZE
y -= dir_y * TILE_SIZE
self.body.append(BodyPart(x, y, (dir_x, dir_y)))
def update_position(self):
for body_part in self.body:
body_part.x += body_part.dir_x * TILE_SIZE
body_part.y += body_part.dir_y * TILE_SIZE
z = len(self.body) - 1
while z != 0:
self.body[z].dir_x = self.body[z-1].dir_x
self.body[z].dir_y = self.body[z-1].dir_y
z -= 1
def collision(self):
head_x, head_y = self.body[0].x, self.body[0].y
for body_part in snake.body[1:]:
if body_part.x == head_x and body_part.y == head_y:
return True
if head_x < 0 or head_x == WIDTH or head_y < 0 or head_y == HEIGHT:
return True
return False
class Food:
def __init__(self):
self.x = None
self.y = None
self.length_bonus = None
self.color = None
self.__random_coords()
self.__choose_random_food()
def display(self):
pygame.draw.rect(screen, self.color, (self.x, self.y, TILE_SIZE, TILE_SIZE))
def eaten(self):
return (snake.body[0].x, snake.body[0].y) == (self.x, self.y)
def __random_coords(self):
matching = True
while matching:
self.x = random.randrange(TILE_SIZE, WIDTH - TILE_SIZE + 1, TILE_SIZE)
self.y = random.randrange(TILE_SIZE, HEIGHT - TILE_SIZE + 1, TILE_SIZE)
for body_part in snake.body:
if self.x != body_part.x and self.y != body_part.y:
matching = False
def __choose_random_food(self):
self.foods = [self.__banana, self.__apple, self.__watermelon]
random.choice(self.foods)()
def __banana(self):
self.length_bonus = 1
self.color = YELLOW
def __apple(self):
self.length_bonus = 2
self.color = RED
def __watermelon(self):
self.length_bonus = 3
self.color = GREEN2
def redraw_screen():
global food_on_screen, food, score
screen.fill(BACKGROUND_COLOR)
for body_part in snake.body:
pygame.draw.rect(screen, snake.color, (body_part.x, body_part.y, TILE_SIZE, TILE_SIZE))
if not food_on_screen:
food = Food()
food_on_screen = True
food.display()
if food.eaten():
snake.append_body_part(food.length_bonus)
score += food.length_bonus
food_on_screen = False
text = font.render(f"Score: {score}", False, WHITE)
screen.blit(text, (TILE_SIZE, TILE_SIZE))
pygame.display.update()
snake = Snake()
food_on_screen = False
game_over = False
while not game_over:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and snake.body[0].dir_x != -1:
snake.body[0].set_direction([1, 0])
if event.key == pygame.K_LEFT and snake.body[0].dir_x != 1:
snake.body[0].set_direction([-1, 0])
if event.key == pygame.K_UP and snake.body[0].dir_y != 1:
snake.body[0].set_direction([0, -1])
if event.key == pygame.K_DOWN and snake.body[0].dir_y != -1:
snake.body[0].set_direction([0, 1])
snake.update_position()
if snake.collision():
game_over = True
break
redraw_screen()
print(f"Your final score: {score}")
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>First of all, from an Object-Oriented perspective, you have objects that represent real objects within the game with behaviors and attributes, so on that note, well done! There are, however, other areas that need a bit of TLC.</p>\n\n<p>You have an enumeration of colors sitting there as individually-defined constants. For a bit more type-safety, I would suggest persisting them in an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Enum</a> instead:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass Color(Enum):\n BLACK = (0, 0, 0)\n # other\n # colors\n # here\n</code></pre>\n\n<p>You can then access the enum constant for the color black as <code>Color.BLACK</code> and the tuple of RGB values as <code>Color.BLACK.value</code>.</p>\n\n<p>Moving on to something a bit more functional, it doesn't make sense that each <code>BodyPart</code> has a direction. Conceptually speaking, the only thing in the game Snake that has a direction is the head, and each body part occupies the space of the body part in front of it per game tick.</p>\n\n<p>I would suggest removing direction entirely from <code>BodyPart</code>, and storing the <code>BodyPart</code> objects within <code>Snake</code> as a <strong>linked list</strong>. Because in the end, you can still iterate through each <code>BodyPart</code>, but considering the 3 most important features:</p>\n\n<ul>\n<li>The <strong>head</strong>, and its directional movement</li>\n<li>The <strong>link between each <code>BodyPart</code> and the next</strong>, to determine movement of the <code>BodyPart</code>s</li>\n<li>The <strong>tail</strong>, for adding new <code>BodyPart</code>s to the <code>Snake</code></li>\n</ul>\n\n<p>The linked list is the most meaningful data structure to use here.</p>\n\n<p>Also, <code>Food</code> is a bit weird. Actually initializing a <code>Food</code> object is hidden behind private methods, which makes no logical sense. <code>Food</code> initialization should require parameters to define what type of food it is and where it is on the game. We can revisit the idea of enums and introduce a <code>FoodType</code> enum of tuples of form <code>(length_bonus, Color)</code> where we can once again use our <code>Color</code> enum from before, then require a <code>FoodType</code> parameter in init along with x and y. Then we can move the methods that generate a random Color and position out of that class and use those to generate the necessities for a Food object.</p>\n\n<p>Lastly, I would highly recommend encapsulating x and y in all cases into a Point object. That would make it much easier to keep track of each piece's coordinates, and subsequently movements, collisions, etc.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Point(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n # __eq__ and other important methods here\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:59:59.563",
"Id": "432736",
"Score": "0",
"body": "Thanks, this was very helpful. But there is one thing that I don't understand. Why do I need to store my color constants in a class which inherits from Enum? To access a color I now need to say Color.BLACK.value instead of just BLACK which makes it more complicated. What is the purpouse of this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T11:42:50.627",
"Id": "432745",
"Score": "0",
"body": "Several reasons, which allude to the capabilities of the Enum type. The reason I gave first was type safety: you can check if parameters are Colors since `Color` is a declared class now. Enums are also iterable, flexible, hashable, and more efficiently interpreted. Follow the link in my answer to the documentation for Enum, you'll see more advantages."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:41:07.420",
"Id": "223311",
"ParentId": "223290",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:06:53.763",
"Id": "223290",
"Score": "3",
"Tags": [
"python",
"beginner",
"pygame",
"snake-game"
],
"Title": "Beginner's snake game in pygame"
} | 223290 |
<p>Getting started:</p>
<p>For a given number <code>x</code> (say <code>-5</code>) I want to know which element of a list <code>y</code> (say <code>[2, -6]</code>), minimizes the value of distance function <code>d</code> (say the absolute value) which applied on <code>x</code> and all elements of <code>y</code>. My current solution to this problem is</p>
<pre><code>x = -5
y = [2, -6]
def d(a1, a2):
return abs(a1-a2) # more complicated in real application
min(y, key = lambda _: d(_, x)) # correctly returns -6
</code></pre>
<p>Next level: <code>x</code> is actually a list (say <code>[1, 5, -10]</code>), so I build a list comprehension on top my previous solution:</p>
<pre><code>x = [1, 5, -10]
[min(y, key = lambda _: d(_, xindex)) for xindex in x] # correctly returns [2, 2, -6]
</code></pre>
<p>As this type of problem seems quite basic to me, I expect a simple solution for this problem (like <code>argmin(list1=x, list2=y, function=d)</code>). <a href="https://stackoverflow.com/q/36422949/6256241">Here is a question</a> where it is shown how a custom distance matrix can be build. But this alone (the step from the distance matrix to the argmins would also have to be done) seems too be more complicated than my code.</p>
<p>Overall my question is: is my code fine, or is there a nicer solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:25:35.803",
"Id": "432637",
"Score": "0",
"body": "Do you want to know the index of the value or the value itself that minimizes that distance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:30:36.130",
"Id": "432639",
"Score": "1",
"body": "@AlexV I want to know the value itself (eg `[2, 2, -6]`) that minimizes the distance."
}
] | [
{
"body": "<p>The approach is fine and this is exactly the purpose of the <code>key</code> attribute of <code>min</code>.</p>\n\n<p>I’d just nitpick that the <code>_</code> variable name is usually meant to indicate unused arguments and thus, using it inside the <code>lambda</code> goes against conventions.</p>\n\n<p>Alternatively, you can make use of <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a> which may yield better performances on larger lists:</p>\n\n<pre><code>[min(y, key=partial(d, a2=xindex)) for xindex in x]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:51:56.490",
"Id": "432648",
"Score": "0",
"body": "Thank your for your insights. Your solution only works if I add `functools` before `partial` (`[min(y, key=functools.partial(d, a2=xindex)) for xindex in x]`). Is this a special issue of my system (I'm using a jupyter notebook) or more general?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:00:28.537",
"Id": "432679",
"Score": "3",
"body": "Have you tried `from functools import partial`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:10:24.370",
"Id": "223295",
"ParentId": "223291",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223295",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:10:11.810",
"Id": "223291",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "For each element in a list, finding the element in a second list, that minimizes a distance function"
} | 223291 |
<p>Please look at this working WordPress code:</p>
<pre><code>add_action('init', 'add_custom_rewrites');
function add_custom_rewrites(){
add_rewrite_rule(
'^(en|fr|es|de)/inspiration/testimonial/([^/]*)?',
'index.php?post_type=testimonial&lang=$matches[1]&name=$matches[2]',
'top'
);
add_rewrite_rule(
'^inspiration/testimonial/([^/]*)?',
'index.php?post_type=testimonial&lang=it&name=$matches[1]',
'top'
);
}
</code></pre>
<p>The first rule matches a post under an url like this:</p>
<pre><code>example.com/en/inspiration/testimonial/test-post
</code></pre>
<p>The second matches this:</p>
<pre><code>example.com/inspiration/testimonial/test-post
</code></pre>
<p>Which is for the default language (it). Since the default lang is implicit, it's not written in the url, but under the hood it's like <code>example.com/it/inspiration/testimonial/test-post</code>.</p>
<p>Well, the question: is there any better way of achieving this result? Particularly, is there any way of doing it with only one single rule?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T15:16:16.303",
"Id": "432650",
"Score": "0",
"body": "Only for the fun (don't use this absolutly not flexible stupid thing), you can do it in a single replacement with `^(?|(en|es|fr|de)()/inspiration|(i)nspira(t)ion)/testimonial/([^/]*)` and `index.php?post_type=testimonial&lang=$matches[1]$matches[2]&name=$matches[3]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T20:21:28.403",
"Id": "432691",
"Score": "0",
"body": "Does defaulting to Italian have to be hard-coded in the URL-rewriting rules? What language appears if you go to `index.php?post_type=testimonial&lang=&name=something`? (Are you using a plugin like [Polylang](https://polylang.wordpress.com/) or [Multisite Language Switcher](https://wordpress.org/plugins/multisite-language-switcher/)?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T22:27:37.643",
"Id": "432702",
"Score": "0",
"body": "@CasimiretHippolyte kindly avoid sabotaging the site design. Please post a review instead of a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:11:48.247",
"Id": "432812",
"Score": "0",
"body": "@200_success hi, I don't need to hardcode IT in url, I can omit, and it will show italian. Currently using polylang pro, but I don't think it's related to the issue."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:11:23.347",
"Id": "223292",
"Score": "0",
"Tags": [
"php",
"regex",
"url-routing",
"wordpress"
],
"Title": "WordPress hook to add URL-rewriting rules for articles with language variants"
} | 223292 |
<p>I am concerned about a few things about my heap implementation. This is in Kotlin. </p>
<p>For starters-</p>
<ul>
<li>When and when not to use expressions?</li>
<li>The use of <code>also</code> to swap numbers </li>
</ul>
<p>Other suggestions about the algorithm and the code are welcome.</p>
<pre><code>class BinaryHeap : Iterable<Int> {
private val array = mutableListOf(0)
var heapSize = 0
override fun iterator(): Iterator<Int> = array.iterator()
private fun parent(i: Int) = i.shr(1)
private fun left(i: Int) = i.shl(1)
private fun right(i: Int) = i.shl(1).plus(1)
private fun maxHeapify(i: Int) {
var largest: Int
val left = left(i)
val right = right(i)
largest = if (left <= heapSize && array[i] > array[left]) i
else if (left <= heapSize) left
else i
if (right <= heapSize && array[largest] < array[right])
largest = right
if (largest != i) {
swap(largest, i)
maxHeapify(largest)
}
}
val max = if (heapSize != 0) array[1] else -1
fun extractMax(): Int {
return if (heapSize < 1)
-1
else {
val max = array[1]
array[1] = array[heapSize]
heapSize--
maxHeapify(1)
max
}
}
private fun swap(i: Int, j: Int) {
array[i] = array[j].also { array[j] = array[i] }
}
fun insert(i: Int) {
if (array.size > heapSize + 1)
array[++heapSize] = i
else {
array.add(i)
heapSize++
}
var badNode = heapSize
var parentBadNode = parent(badNode)
while (parentBadNode != 0 && array[parentBadNode] < array[badNode]) {
swap(parentBadNode, badNode)
badNode = parentBadNode.also { parentBadNode = parent(parentBadNode) }
}
}
fun insert(i: Iterable<Int>) {
i.forEach {
insert(it)
}
}
override fun toString(): String {
return array.joinToString { "$it " }
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:35:19.177",
"Id": "433011",
"Score": "2",
"body": "I'm confused by \"*The round function has an odd behavior it rounds down x.5 to x*\". (1) There isn't any `round` in the code. (2) There's nothing odd about that. The only thing which might be considered odd is not having learnt from the previous 50 years of experience of library development that `round` methods should take a parameter indicating what to do with `x.5` (up, down, to zero, away from zero, or to even)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T16:23:38.017",
"Id": "433015",
"Score": "0",
"body": "Yea my bad. I should have mentioned that the behavior of `round` was just a general inquiry. About the parameter, I don't think one exists in Java or Kotlin."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T13:39:07.273",
"Id": "223293",
"Score": "1",
"Tags": [
"heap",
"kotlin"
],
"Title": "Max-Heap Implementation in Kotlin"
} | 223293 |
<p>I am going to simulate a particle system, the particles are infinitesimal points which apply forces on the neighbors and I need a fast way of making proximity checks, they are going to have a maximum check radius but not a minimum and will be almost evenly spaced.</p>
<p>The simulation will be very similar to this: <a href="https://youtu.be/SFf3pcE08NM" rel="nofollow noreferrer">https://youtu.be/SFf3pcE08NM</a></p>
<p>I thought a spatial grid would be the easiest approach for it and I need it to be as cost efficient as possible to matter how ugly it gets.</p>
<p>Is there any optimization I can make on this code?</p>
<p>Is there a way to compute the optimal cell size from the average distance between particles?</p>
<pre><code>_empty_set = set()
class SpatialHash:
def __init__(self, cell_size=0.1):
self.cells = {}
self.bucket_map = {}
self.cell_size = cell_size
def key(self, co):
return int(co[0] / self.cell_size), int(co[1] / self.cell_size), int(co[2] / self.cell_size)
def add_item(self, item):
co = item.co
k = int(co[0] / self.cell_size), int(co[1] / self.cell_size), int(co[2] / self.cell_size)
if k in self.cells:
c = self.cells[k]
else:
c = set()
self.cell_size[k] = c
c.add(item)
self.bucket_map[item] = c
def remove_item(self, item):
self.bucket_map[item].remove(item)
def update_item(self, item):
self.bucket_map[item].remove(item)
self.add_item(item)
def check_sphere(self, co, radius, exclude=()):
r_sqr = radius * radius
for x in range(int((co[0] - radius) / self.cell_size),
int((co[0] + radius) / self.cell_size) + 1):
for y in range(int((co[1] - radius) / self.cell_size),
int((co[1] + radius) / self.cell_size) + 1):
for z in range(int((co[2] - radius) / self.cell_size),
int((co[2] + radius) / self.cell_size) + 1):
for item in self.cells.get((x, y, z), _empty_set):
if item not in exclude and (item.co - co).length_squared <= r_sqr:
yield item
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T15:35:17.730",
"Id": "432652",
"Score": "0",
"body": "Did you consider using an [octree](https://en.wikipedia.org/wiki/Octree) for this? If so, perhaps explaining why you rejected that may help inform the reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T15:42:09.317",
"Id": "432655",
"Score": "0",
"body": "Well,The particles will be massive but well distributed, If I do it right I can fit snugly an average amount of particles on the grid, with an octree all nodes would have about athe same depth so cutting the overhead of travessing it would be equivalent to a spatial hash."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:58:21.230",
"Id": "432678",
"Score": "0",
"body": "Do you have a function to generate test data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:04:39.097",
"Id": "432680",
"Score": "0",
"body": "No, but I'm testing some \"massive\" simulations on blender with it right now and it seems to be behaving properly, edited it now, because I found a bug but its extremely slow yet https://i.postimg.cc/1tPxSh0d/image.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:07:39.093",
"Id": "432681",
"Score": "1",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:26:13.270",
"Id": "432683",
"Score": "0",
"body": "Ah, right, I'm gonna pay more attention to the rules thanks for alerting me."
}
] | [
{
"body": "<p>You could rewrite your <code>key()</code> method and use it to much greater effect, reducing repeated code.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def key(self, co, radius=0):\n return tuple((c + radius) // self.cell_size for c in co)\n</code></pre>\n\n<p>You can then call <code>key()</code> in both <code>add_item()</code> and <code>check_sphere()</code>. In <code>add_item()</code> it will replace <code>k</code>, while in <code>check_sphere()</code> you can use it to define your ranges.</p>\n\n<p>After that I would look for a way to flatten those nested <code>for</code> loops which will likely be an algorithm change. Hopefully someone else has some ideas there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:33:38.917",
"Id": "223300",
"ParentId": "223296",
"Score": "2"
}
},
{
"body": "<p>HoboProber's <a href=\"https://codereview.stackexchange.com/a/223300/92478\">answer</a> is good with regards to clean code, but more than likely slower than what you already have.</p>\n\n<p>At the moment we basically have to following variants of the key function:</p>\n\n<pre><code>from math import floor\n\n\ndef key_op(particle, cell_size):\n return int(particle[0] / cell_size), int(particle[1] / cell_size), int(particle[2] / cell_size)\n\n\ndef key_hobo(particle, cell_size):\n return tuple(coordinate // cell_size for coordinate in particle)\n\n\ndef key_op_edit(particle, cell_size):\n \"\"\"This was taken from your edit that was rolled back due to answer invalidation\"\"\"\n return floor(particle[0] / cell_size), floor(particle[1] / cell_size), floor(particle[2] / cell_size)\n</code></pre>\n\n<p>HoboProber already sneakily introduced <a href=\"https://docs.python.org/3/glossary.html#term-floor-division\" rel=\"nofollow noreferrer\">floor division</a> (think <code>\\\\</code>) to you, so the explicit version of this is also up for discussion:</p>\n\n<pre><code>def key_floor_div(particle, cell_size):\n return particle[0] // cell_size, particle[1] // cell_size, particle[2] // cell_size\n</code></pre>\n\n<p>The timings for them are as follows:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>key_op 1.28 µs ± 16.2 ns (mean ± std. dev. of 7 runs, 1000000 loops each)\nkey_op_edit 1.62 µs ± 13.8 ns (mean ± std. dev. of 7 runs, 1000000 loops each)\nkey_hobo 2.09 µs ± 34.3 ns (mean ± std. dev. of 7 runs, 100000 loops each)\nkey_floor_div 1.11 µs ± 14.3 ns (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<p>The timing was done in an IPython environment running <code>%timeit func(example, cell_size)</code> with <code>example = (23849.234, 1399283.8923, 2137842.24357)</code> and <code>cell_size = 10</code>.</p>\n\n<p>Based on these results there seems to be a narrow win for the floor div version over the original implementation.</p>\n\n<p>But can we do better? Enter <a href=\"https://numba.pydata.org/\" rel=\"nofollow noreferrer\">numba</a>, a just-in-time compiler for Python code. At this early testing stage basically all you have to do is <code>from numba import jit</code> and then</p>\n\n<pre><code>@jit(nopython=True)\ndef key_op_numba(particle, cell_size):\n return int(particle[0] / cell_size), int(particle[1] / cell_size), int(particle[2] / cell_size)\n</code></pre>\n\n<p>Act accordingly for the other versions. Now lets look at the timings:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>key_op 623 ns ± 8.42 ns (mean ± std. dev. of 7 runs, 1000000 loops each)\nkey_op_edit 618 ns ± 10.5 ns (mean ± std. dev. of 7 runs, 1000000 loops each)\nkey_hobo* N/A\nkey_floor_div 628 ns ± 7.06 ns (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<p>As you can see numba can easily double the performance of this functions, and that is with the default settings. You might be able to squeeze out a little bit more of you are really going for it.</p>\n\n<hr>\n\n<p><strong>Bug</strong>: There is likely a bug in this piece of code:</p>\n\n<pre><code>if k in self.cells:\n c = self.cells[k]\nelse:\n c = set()\n self.cell_size[k] = c\n# ^-- should likely be self.cells here\n</code></pre>\n\n<p>Note: a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>defaultdict</code></a> can help to simplify this part of the code, though I cannot really say something on how its performance compares to that of a normal dict and your member-check/if-construct.</p>\n\n<hr>\n\n<p>*numba does not seem to like to instantiate a tuple from a generator expression, transforming it into a list comprehension yields <code>1.25 µs ± 25.1 ns</code>. You then have to convert it to a tuple to make it hashable, e.g. <code>tuple(key_hobo_numba(example, cell_size)</code>, which leaves us with the final timing of <code>1.45 µs ± 14.8 ns</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T19:15:36.017",
"Id": "223313",
"ParentId": "223296",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223313",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:11:52.707",
"Id": "223296",
"Score": "4",
"Tags": [
"python",
"performance",
"simulation",
"physics"
],
"Title": "Simple spatial grid for particle system"
} | 223296 |
<p>I would like to know if I'm writing a plugin for jquery correctly. I followed the <a href="https://learn.jquery.com/plugins/basic-plugin-creation/" rel="nofollow noreferrer">official guide</a> and also added some tweaks that I've found from various sources over time.</p>
<p>While this works perfectly, I don't know if I'm doing something wrong.</p>
<p>This is the sample:</p>
<pre><code>(function($)
{
var plugin = "my_plugin_name";
var methods = {
init : function(user_settings)
{
return this.each(function(index)
{
if(!$(this).hasClass("plugin_class"))
{
$(this).addClass("plugin_class");
var $this = $(this);
var data = $this.data(plugin);
if(!data)
{
var default_settings = {
optionA: "abc",
optionB: 123,
optionB: true
};
if(user_settings)
{
$.extend(true, default_settings, user_settings);
}
$this.data(plugin,
{
"settings": default_settings
});
}
privateMethod($this);
}
});
},
exposedMethodX : function(value) //$(selector).my_plugin_name("exposedMethodX", true)
{
console.log(value)
}
};
$.fn[plugin] = function(method)
{
if(methods[method])
{
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if(typeof method === "object" || !method)
{
return methods.init.apply(this, arguments);
}
else
{
alert("Method " + method + " does not exist");
}
};
function privateMethod(obj)
{
console.log(obj.data(plugin).settings);
}
})(jQuery);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T16:25:11.627",
"Id": "433016",
"Score": "0",
"body": "Ahoy! Would you have any sample usage for this template you could add to the post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T18:25:32.033",
"Id": "433406",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ This is just a sample. Only a general structure. `$(selector).my_plugin_name()` will work, also `$(selector).my_plugin_name(\"exposedMethodX\", 123)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T02:11:34.213",
"Id": "433449",
"Score": "0",
"body": "When adding more context please [edit] instead of doing so in a comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T18:17:32.300",
"Id": "433997",
"Score": "0",
"body": "There [exists a GitHub repository with several examples of jQuery plugin boilerplate](https://github.com/jquery-boilerplate/jquery-patterns), if you're interested."
}
] | [
{
"body": "<p>In general the template looks like a good start. I noticed that the code appears to resemble the format advised in <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PHP-Fig's PSR-2</a>, namely \"<em>The opening brace MUST go on its own line</em>\"<sup><a href=\"https://www.php-fig.org/psr/psr-2/#43-methods\" rel=\"nofollow noreferrer\">1</a></sup> for functions and methods plus control structures like <code>if</code> and <code>else</code> blocks. Most of the Javascript style guides I have seen call for curly braces to exist on the same line of the block they are opening. Personally I don't even agree with this in PHP, let alone Javascript, however if that is your personal preference then keep it consistent.</p>\n\n<hr>\n\n<p>Inside the <code>init</code> method, there is an iterator:</p>\n\n<blockquote>\n<pre><code>return this.each(function(index)\n{\n if(!$(this).hasClass(\"plugin_class\"))\n {\n $(this).addClass(\"plugin_class\");\n\n var $this = $(this);\n</code></pre>\n</blockquote>\n\n<p>The reference <code>var $this = $(this);</code> could be stored before the check of the class name and/or class name addition in order to reduce DOM queries.</p>\n\n<p>Also, the name <code>$this</code> could be more descriptive - at least something like <code>$element</code> or <code>$elem</code> (as shown in the example under <a href=\"https://learn.jquery.com/plugins/advanced-plugin-concepts/#provide-public-access-to-secondary-functions-as-applicable\" rel=\"nofollow noreferrer\"><em>Provide Public Access to Secondary Functions as Applicable</em></a> from the <a href=\"https://learn.jquery.com/plugins/advanced-plugin-concepts/\" rel=\"nofollow noreferrer\">Advanced Plugin Concepts</a>).</p>\n\n<h2>Addressing Your Additional question</h2>\n\n<p>You asked in a comment:</p>\n\n<blockquote>\n <p><em>what about the <code>$.fn[plugin]</code> part? I'm not sure about the first if statement. could that function be refactored and improved?</em></p>\n</blockquote>\n\n<p>It is possible that <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> could potentially be used to simplify the call, though given that <a href=\"https://jquery.com/browser-support/\" rel=\"nofollow noreferrer\">current jQuery browser support</a> includes IE 9+ it may not be wise to utilize ES-6 features.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T20:39:21.330",
"Id": "433872",
"Score": "0",
"body": "thanks for your feedback. what about the `$.fn[plugin]` part? I'm not sure about the first if statement. could that function be refactored and improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T21:08:03.420",
"Id": "434015",
"Score": "0",
"body": "I expanded my answer to address your question"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T17:04:54.630",
"Id": "223761",
"ParentId": "223297",
"Score": "2"
}
},
{
"body": "<p>From a short review;</p>\n\n<ul>\n<li>Please follow the lowerCamelCase naming convention, <code>user_settings</code> -> <code>userSettings</code></li>\n<li>In production code, never use <code>console.log</code> or <code>alert</code></li>\n<li><p>You set <code>optionB</code> twice</p>\n\n<pre><code> var default_settings = {\n optionA: \"abc\",\n optionB: 123,\n optionB: true\n };\n</code></pre></li>\n<li><p>The cyclomatic complexity would be lower if you exit immediately after the <code>hasClass</code> check:</p>\n\n<pre><code> if($(this).hasClass(\"plugin_class\")){\n return;\n }\n</code></pre></li>\n<li><p>You could even consider using <code>filter</code> on <code>hasClass</code> instead of checking for <code>each</code> </p></li>\n<li><p><code>\"plugin_class\"</code> should be a constant right under <code>var plugin</code></p></li>\n<li><p>The following </p>\n\n<pre><code> if(user_settings)\n {\n $.extend(true, default_settings, user_settings);\n }\n</code></pre>\n\n<p>could be written as</p>\n\n<pre><code> $.extend(true, user_settings || default_settings);\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T14:52:41.227",
"Id": "223814",
"ParentId": "223297",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T14:14:23.110",
"Id": "223297",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"template",
"plugin"
],
"Title": "basic jQuery plugin template"
} | 223297 |
<p>I implemented the following class (it works) and I just want to hear your opinions about best practices and what can be improved. The idea was to do it using mostly arrays.</p>
<p>The class just finds the peak elements in an array with respect to their neighbors. The first element and the last element are ignored.</p>
<p><strong>Example</strong>: <code>{3, 15, 5, 20, 10}</code>
<strong>Answer</strong>: <code>{15, 20}</code></p>
<pre><code>package findpeak;
import java.util.ArrayList;
import java.util.List;
public class ArrayPeak
{
private final int[] ARRAY;
private final int LEN;
private static final int IGNORE_FIRST_POSITION = 0;
private final int IGNORE_LAST_POSITION;
public ArrayPeak(int[] array)
{
this.ARRAY = array;
this.LEN = this.ARRAY.length;
this.IGNORE_LAST_POSITION = this.LEN - 1;
}
public List<Integer> findPeaks()
{
List<Integer> peaks = new ArrayList<>();
for (int position = 0; position < LEN; position++)
{
int output = 0;
if (position != IGNORE_FIRST_POSITION && position != IGNORE_LAST_POSITION)
{
int[] trippleArray =
{
ARRAY[position - 1], ARRAY[position], ARRAY[position + 1]
};
output = checkPeak(trippleArray);
}
peaks.add(output);
}
return filterZeros(peaks);
}
private static int checkPeak(int[] inputArray)
{
int peak = 0;
if (inputArray[1] > inputArray[0] && inputArray[1] > inputArray[2])
{
peak = inputArray[1];
}
return peak;
}
private static List<Integer> filterZeros(List<Integer> list)
{
List<Integer> filteredList = new ArrayList<>();
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) != 0)
{
filteredList.add(list.get(i));
}
}
return filteredList;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T15:40:49.890",
"Id": "432654",
"Score": "2",
"body": "BTW, what's the expected output with test cases such as `{1}` or `{1,2}` where the first/last/only element is a local maximum? What about empty arrays? (I can infer that from the code, but it helps people if you're explicit about the edge cases.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:17:15.330",
"Id": "432658",
"Score": "0",
"body": "Another case that might fail: `{0,1,1,0}`"
}
] | [
{
"body": "<p>This shouldn't involve an instance of a class: you can (and should) implement this as a standalone static method, which takes the input array as a parameter and returns the peaks. Introducing a class to record the state is just introducing complexity which will make the code harder to maintain without providing any benefit.</p>\n\n<p>I would also like some documentation explaining exactly what the method does: for example, it doesn't return non-positive peaks, and (as Toby Speight's comment indicates) some might thing it would return plateaus. Basically you need a better specification, and that needs to appear as documentation, so that the intention of the code is completely unambiguous (for the benefit of the implementer, maintainer, and consumer). I would not expect a method like this to return the heights of peaks, rather than their position.</p>\n\n<hr />\n\n<p><code>IGNORE_FIRST_POSITION</code> sounds like the name of a <code>boolean</code>, not an int. You'd be better off, I think, changing the <code>for</code> loop to start at 1, end at <code>array.Length - 1</code>, and include a comment explaining why this is the case.</p>\n\n<hr />\n\n<p>I like that <code>CheckPeak</code> is its own method because it puts the corresponding logic 'all in one place', but I don't like that you are creating a new array every time you check for a peak: I would much prefer you pass the array and candidate position as parameters, and it checks 'in-place'. This is a simpler API (the current one lacks any specification that it takes an array of three parameters), and will reduce the overhead from calling the method.</p>\n\n<p>I also don't like that it returns the height of the peak, rather than whether or not a peak appears: this too is lacking documentation (though granted it is private, so it isn't as important as the public method). Much better to return <code>true</code> or <code>false</code> if it is a peak, then add the peak to the list of peaks if it returns <code>true</code>, otherwise do not (then you can remote the confusing <code>filterZeros</code> at the end).</p>\n\n<p>This can also remove the unpleased <code>output</code> variable, which is defined too early. It only has meaning once it is assigned, and if it isn't assigned it just has a default value you will filter anyway, so you might as well declare and assign it in one.</p>\n\n<hr />\n\n<p>Really tiny thing that is almost completely subjective: I'd prefer to write</p>\n\n<pre><code>if (inputArray[1] > inputArray[0] && inputArray[1] > inputArray[2])\n</code></pre>\n\n<p>as</p>\n\n<pre><code>if (inputArray[0] < inputArray[1] && inputArray[1] > inputArray[2])\n</code></pre>\n\n<p>It keeps them 'in order, and makes it a little easier to feel what is going on.</p>\n\n<hr />\n\n<p>Your code only works with <code>Integers</code>: if I wanted to find peaks in a <code>Double[]</code>, I would need to write a new class. You might want to make it generic on a type <code>T</code> that implements <code>Comparable<T></code>. This can create some confusion with floating point types (i.e. <code>NaN</code>s), but by depending on a basic interface, your code will be reusable and harder to 'get wrong'.</p>\n\n<p>You might also consider taking an abstract collection as a parameter; it's good that you return <code>List<T></code> rathern than <code>ArrayList<T></code>.</p>\n\n<hr />\n\n<p>Example rewrite (disclaimer: untested, and I don't know Java, and I'm running out of time...):</p>\n\n<pre><code>public class ArrayPeak\n{\n public static <T extends Comparable<T>> List<T> findPeaks(T[] array)\n {\n List<T> peaks = new ArrayList<>();\n\n // ignore first and last elements\n for (int position = 1; position < array.length - 1; position++)\n {\n if (checkPeak(array, position)\n {\n peaks.add(array[position]);\n }\n }\n\n return peaks;\n }\n\n private static <T extends Comparable<T>> int checkPeak(T[] array, int position)\n {\n if (inputArray[position - 1].compareTo(inputArray[position]) < 0 && inputArray[position].compareTo(inputArray[position + 1]) > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:51:32.340",
"Id": "432663",
"Score": "1",
"body": "minor addendum: the `checkPeak` method can be simplified to directly return the if-condition: `return inputArray[...];`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:21:52.367",
"Id": "223303",
"ParentId": "223301",
"Score": "2"
}
},
{
"body": "<p><strong>KISS</strong></p>\n\n<p><strong>K</strong>eep <strong>I</strong>t <strong>S</strong>hort <strong>S</strong>imple. Your code seems to be overly complicated compared to what you want to achieve. The invocation of a class isn't really necessary, for your use case a simple static utility method would be enough.</p>\n\n<p><strong>Memory usage and runtime</strong></p>\n\n<p>You are allocating an array just to compare three numbers:</p>\n\n<pre><code>int[] trippleArray =\n{\n ARRAY[position - 1], ARRAY[position], ARRAY[position + 1]\n};\n</code></pre>\n\n<p>This could easily be done inplace:</p>\n\n<pre><code>if (ARRAY[position - 1] < ARRAY[position] && ARRAY[position] > ARRAY[position + 1])\n{\n peaks.add(ARRAY[position]);\n}\n</code></pre>\n\n<p>In consequence <code>filterZeros()</code> is not necessary anymore and you get rid of a linear runtime method. By the way returning non-existing results with a special value, in your case returning <code>0</code> when there is no peak and removing these special values afterwards is a huge runtime issue, as you get linear runtime just for iterating over the entire input again. Instead you could return a <code>boolean</code> if a result exists or make use of <code>null</code>.</p>\n\n<p><strong>Variable naming</strong></p>\n\n<p><code>CONSTANT_CASE</code> is reserved to constants, i.e. static final fields. This is not the case for <code>ARRAY</code>, <code>LEN</code> and <code>IGNORE_LAST_POSITION</code>. By the way a constant for the first index in an array isn't really necessary as everyone knows the first index is <code>0</code> and the second is <code>1</code>. Furthermore <code>IGNORE_FIRST_POSITION</code> and <code>IGNORE_LAST_POSITION</code> sound like <code>boolean</code> variables, consider a better name.</p>\n\n<p><strong>Improved version</strong></p>\n\n<pre><code>public static List<Integer> findPeaks(int[] input) {\n List<Integer> peaks = new LinkedList<>();\n for (int i = 1; i < input.length - 1; i++) {\n if (input[i - 1] < input[i] && input[i] > input[i + 1]) {\n peaks.add(input[i]);\n }\n }\n return peaks;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:19:23.070",
"Id": "432669",
"Score": "1",
"body": "Last time I checked, KISS meant \"Keep It Simple, Stupid\", but your version does sound much better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:29:42.697",
"Id": "432673",
"Score": "0",
"body": "Yeah, that's the most common abbreviation, but as far as I know both versions exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:21:33.170",
"Id": "432697",
"Score": "0",
"body": "I'd be disinclined to use a `LinkedList` here, because it increases the complexity of lookups for the consumer (likely use-case) - and in doing so probably goes against general expectations - without changing the complexity of the method itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T18:23:22.250",
"Id": "432826",
"Score": "0",
"body": "Correct, on the other hand an `ArrayList` isn't the best solution either, as its add operation might end in linear complexity. In my opinion a `Set` would be the best solution, but the question stated a `List` return type."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:18:09.263",
"Id": "223308",
"ParentId": "223301",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T15:20:32.850",
"Id": "223301",
"Score": "3",
"Tags": [
"java",
"array"
],
"Title": "Find all local maxima in a one-dimensional array"
} | 223301 |
<p>My code is currently offloading parsed data into multiple spreadsheets, but it's pretty slow: about 110k rows and 35 columns in 3.5 minutes.
I was wondering if there were a more efficient way of looping through my collection of dictionaries.</p>
<pre><code>Sub getData(Parsed As Object, company As String, a, wb)
'Parsed contains a collection of dictionaries parsed from a JSON input'
Dim oSheet As Variant
Dim i As Long
Dim j As Long
For Each oSheet In ActiveWorkbook.Sheets
'Identify the sheet containing the name of the company'
Dim matchSheet As String
If InStr(UCase(oSheet.Name), UCase(company)) Then
matchSheet = oSheet.Name
Else
GoTo nextIteration
End If
'Create a 2d array of i number of dictionaries and j number of element in each dictionary'
Dim Values As Variant
ReDim Values(Parsed.Count, ArrayLen(a))
Dim Value As Dictionary
Dim key As Variant
i = 1
j = 0
wb.Sheets(matchSheet).Select 'macro not working without selecting the sheet'
wb.Sheets(matchSheet).Cells.Clear 'Clearing the data in the company Sheet'
'For loops populating the Values array'
For Each Value In Parsed
For Each key In a
Values(i, j) = Value(key)
j = j + 1
Next key
j = 0
i = i + 1
Next Value
'populating the needed sheet range with the parsed data'
wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(Parsed.Count, ArrayLen(a))) = Values
'populationg the headers for that data'
wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(1, ArrayLen(a))).Value = a
wb.Sheets(matchSheet).Range("D:D").NumberFormat = "General"
nextIteration:
Next oSheet
End Sub
</code></pre>
<p>Here is an exemple of what my API request returning 2 deals with 3 keys out of 37:</p>
<pre><code>[
{
"DealNo": "11111",
"DealDate": "2010-01-01",
"Quantity": "1000"
},
{
"DealNo": "11112",
"DealDate": "2010-01-02",
"Quantity": "2000"
}
]
</code></pre>
<p>And here is the structure of the data after it has been parsed in excel:
<a href="https://i.stack.imgur.com/6j3EA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6j3EA.png" alt="Collection"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T20:07:57.373",
"Id": "432690",
"Score": "0",
"body": "Do you have a (much smaller) example of your JSON for testing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:58:11.337",
"Id": "432701",
"Score": "1",
"body": "I don't understand what `a` is."
}
] | [
{
"body": "<p>A couple of review points.</p>\n\n<p><strong>Goto</strong>. Using Goto is a real bad smell. In your case, you can remove the spaghetti very easily. </p>\n\n<blockquote>\n<pre><code>Sub getData(Parsed As Object, company As String, a, wb)\n 'Parsed contains a collection of dictionaries parsed from a JSON input'\n Dim oSheet As Variant\n Dim i As Long\n Dim j As Long\n For Each oSheet In ActiveWorkbook.Sheets\n 'Identify the sheet containing the name of the company'\n Dim matchSheet As String\n If InStr(UCase(oSheet.Name), UCase(company)) Then\n matchSheet = oSheet.Name\n Else\n GoTo nextIteration\n End If\n ' [Main Code Block]\nnextIteration:\n Next oSheet\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>Becomes</p>\n\n<pre><code>Sub getData(Parsed As Object, company As String, a, wb)\n 'Parsed contains a collection of dictionaries parsed from a JSON input'\n Dim oSheet As Variant\n Dim i As Long\n Dim j As Long\n For Each oSheet In ActiveWorkbook.Sheets\n 'Identify the sheet containing the name of the company'\n Dim matchSheet As String\n If InStr(UCase(oSheet.Name), UCase(company)) Then\n matchSheet = oSheet.Name\n ' [Main Code Block]\n End If\n Next oSheet\nEnd Sub\n</code></pre>\n\n<p>Much cleaner!</p>\n\n<p><strong>Select</strong>. I can see why your code does not work without using <code>Select</code>. And you do not need it. You have unqualified references to Range objects (in this case <code>Cells</code>) that are acting on the active sheet. By selecting the sheet, you are changing the active sheet but there is no guarantee that it is going to stay that way!</p>\n\n<blockquote>\n<pre><code> wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(Parsed.Count, ArrayLen(a))) = Values\n 'populationg the headers for that data'\n wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(1, ArrayLen(a))).Value = a\n wb.Sheets(matchSheet).Range(\"D:D\").NumberFormat = \"General\"\n</code></pre>\n</blockquote>\n\n<p>Is better expressed in a <code>With</code> statement for brevity and ease of reading (note that the \".\" are also in front of the <code>Cells</code>, this is the critical change to your original code).</p>\n\n<pre><code> With wb.Sheets(matchSheet)\n .Range(.Cells(1, 1), .Cells(Parsed.Count, ArrayLen(a))) = Values\n 'populating the headers for that data'\n .Range(.Cells(1, 1), .Cells(1, ArrayLen(a))).Value = a\n .Range(\"D:D\").NumberFormat = \"General\"\n End With\n</code></pre>\n\n<p><strong>ReDim</strong>. Probably not a huge issue, but you <code>ReDim</code> every loop instance on values that are passed in at the start. Set your Values array up once before you enter the loop. By the looks of your code, you clobber the values in the array each time you go through the loop, so you don't even have to clear it.</p>\n\n<p>I would guess that your biggest performance hit is iterating through the dictionaries. If you could bring your data in in a cleaner fashion, it may help your performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:45:50.443",
"Id": "432734",
"Score": "0",
"body": "Thank you for the feedback. I realize now that the goto was completely useless in that case. Iterating through a collection of dictionaries is definitely hitting my performance especially as I was offloading the data cell by cell at first (which took an eternity). How would you suggest importing the data in a cleaner fashion? Currently, I just use Tim Hall's JSON parser [link](https://github.com/timhall/VBA-Dictionary) to get my Parsed variable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T13:50:28.507",
"Id": "432777",
"Score": "0",
"body": "It's entirely possible that you don't have to create an array of dictionaries because that structure already exists in the `Parsed` object, as returned by the JSON parser. Without seeing a JSON example of the structure, you can evaluate each section as shown in [this answer](https://stackoverflow.com/a/46245469/4717755) to see if that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:25:13.853",
"Id": "433036",
"Score": "0",
"body": "@PeterT I took a look at your link and if i understood correctly anytime you see the square brackets [] JSONConverter maps it to collection and maps {} to a dictionary. It seems that this is exactly what happens in my case. Is there therefore no other way to load the data on the spreadsheet faster? I added JSON example and the returned structure in excel"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T22:14:04.533",
"Id": "223318",
"ParentId": "223302",
"Score": "2"
}
},
{
"body": "<p>As AJD stated there is no need to recreate the array of values for each sheet. </p>\n\n<p>I don't like <code>Sub getData()</code> because <code>Get</code> implies that a value is going to be returned. <code>Sub setData()</code> isn't appropriate either because <code>Set</code> implies that a value is being set. <code>UpdateData()</code> makes sense but not in a Public Module. Using undescriptive names in Public Modules can lead to confusion down the road as a project grows. Using a name like <code>Sub UpdateCompanyJSONInformation()</code> will make it clear exactly what the macro is meant to do.</p>\n\n<p><code>ArrayLen()</code> is used in the code but never declared. I imagine that it returns <code>Ubound(Array) + Lbound(Array)</code>. I personally would throw <code>ArrayLen()</code> into the trash with <code>GetColumnLetter()</code> and similar helper functions that are floating around the internet. IMO <code>ArrayLen()</code> is obfuscating the code by masking a simple coding pattern that we should easily recognize. </p>\n\n<p><code>i = 1: j = 0</code> This was a little confusing for me. At first it looked like the <code>i</code> dimension was 1 based and the <code>j</code> dimension was 0 based. Not knowing exactly what <code>ArrayLen()</code> returned added to the confusion. I had to look over the way the values were being written to the worksheet several times before I realized the the first row was empty. You should fit the Array to your data. I can guarantee that if you come back to this project in 1 to 2 years to make a simple modification, you will not remember that you the first row of data is empty. </p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Sub UpdateCompanyJSONInformation(Parsed As Object, company As String, headers As Variant, wb)\n Application.ScreenUpdating = False\n'Parsed contains a collection of dictionaries parsed from a JSON input'\n\n Dim oSheet As Variant, Values As Variant\n For Each oSheet In ActiveWorkbook.Sheets\n With oSheet\n 'Identify the sheet containing the name of the company'\n\n If InStr(1, oSheet.Name, company, vbTextCompare) Then\n If Not IsArray(Values) Then Values = getCompanyJSONInformation(Parsed, headers)\n\n .Cells.Clear 'Clearing the data in the company Sheet'\n .Range(\"A1\").Resize(UBound(Values), UBound(Values, 2)).Value = Values\n End If\n End With\n Next oSheet\n\nEnd Sub\n\nFunction getCompanyJSONInformation(Parsed As Object, headers As Variant) As Variant\n Dim key As Variant, Values As Variant\n Dim Value As Dictionary\n ReDim Values(1 To Parsed.Count + 1, LBound(headers) + 1 To UBound(headers) + 1 - LBound(headers))\n Dim r As Long, c As Long\n\n r = 1\n For Each key In headers\n c = c + 1\n Values(r, c) = key\n Next\n\n For Each Value In Parsed\n r = r + 1\n For c = 1 To UBound(Values, 2)\n key = Values(1, c)\n Values(r, c) = Value(key)\n Next\n Next\n getCompanyJSONInformation = Values\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:27:29.187",
"Id": "433037",
"Score": "0",
"body": "Great! I implemented it and it works nice! just had to specify on which dimension I want the `For c = 1 To Ubound(Values)` to be applied, in my case `For c = 1 To Ubound(Values, 2)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T00:02:32.070",
"Id": "433074",
"Score": "0",
"body": "@John your right I forgot to set c to the 2bd dimension. Did it improve the performance? How many worksheets are you updating?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T08:22:23.227",
"Id": "223341",
"ParentId": "223302",
"Score": "1"
}
},
{
"body": "<p>Here's a very quick example of how you can simply assign a <code>Collection</code> and <code>Dictionary</code> directly from the parsed JSON object directly into your objects, then convert it into a 2-D array. </p>\n\n<pre><code>Option Explicit\n\nPublic Sub test()\n Dim jsonInput As String\n jsonInput = \"{ \"\"dataset\"\":[ { \"\"DealNo\"\":\"\"11111\"\", \"\"DealDate\"\":\"\"2010-01-01\"\", \"\"Quantity\"\":\"\"1000\"\" }, { \"\"DealNo\"\":\"\"11112\"\", \"\"DealDate\"\":\"\"2010-01-02\"\", \"\"Quantity\"\":\"\"2000\"\" } ]}\"\n\n Dim json As Object\n Set json = ParseJson(jsonInput)\n\n DataToRange json\nEnd Sub\n\n\nPrivate Sub DataToRange(ByRef parsed As Object)\n '--- extract the array of data from the JSON input\n Dim dataset As Collection\n Set dataset = parsed(\"dataset\")\n\n '--- now grab the first entry in the data set as assume all\n ' entries have the same number of fields\n Dim deal As Dictionary\n Set deal = dataset(1)\n\n '--- create an array to hold the converted data\n Dim dealData As Variant\n ReDim dealData(1 To dataset.Count, 0 To deal.Count - 1)\n\n '--- now convert the data set into an array\n Dim i As Long\n Dim j As Long\n For i = 1 To dataset.Count\n Set deal = dataset(i)\n For j = 0 To deal.Count - 1\n dealData(i, j) = deal.Items(j)\n Next j\n Next i\n\n '--- now set up the destination range and copy the deal data\n ' to that range\n Dim dealArea As Range\n Set dealArea = Sheet1.Range(\"A1\").Resize(UBound(dealData, 1), UBound(dealData, 2))\n dealArea.Value = dealData\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:54:02.260",
"Id": "223443",
"ParentId": "223302",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:00:42.280",
"Id": "223302",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Faster output to Sheet from a collection of Dictionaries"
} | 223302 |
<p>In <em>"The Joy of Clojure", 2nd edition</em>, code for quicksort is introduced on page 133 that I found hard to digest. I have <a href="https://gist.github.com/dtonhofer/47c2303703ba4ecaf3b512cc0f1dab36" rel="nofollow noreferrer">rewritten it</a> to make it clearer (at least to myself). </p>
<p>Here is the original:</p>
<pre><code>(defn sort-parts-joc [work]
(lazy-seq
(loop [[part & parts] work]
(if-let [[pivot & xs] (seq part)]
(let [smaller? #(< % pivot)]
(recur (list*
(filter smaller? xs)
pivot
(remove smaller? xs)
parts)))
(when-let [[x & parts] parts]
(cons x (sort-parts-joc parts)))))))
</code></pre>
<p>Here is the rewritten code:</p>
<pre><code>(defn sort-parts-explicit-lazy [work]
(lazy-seq
(loop [loopwork work]
(let [[ part & partz ] loopwork ]
(if-let [[pivot & valuez] (seq part)]
(let [ smaller? #(< % pivot)
smz (filter smaller? valuez)
lgz (remove smaller? valuez)
nxxt (list* smz pivot lgz partz) ]
(recur nxxt))
(if-let [[oldpivot & rightpartz] partz]
(cons oldpivot (sort-parts-explicit-lazy rightpartz))
[]))))))
</code></pre>
<p>Testing:</p>
<pre><code>(require '( clojure test ))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[1]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[1 2]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[1 2 3]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[3 2 1]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[3 3 3]])))
</code></pre>
<p>So, it works. </p>
<p>Both functions are essentially the same.</p>
<p>However I have a bad feeling about this. The simultaneous use of <code>recur</code> and full recursion, with the full recursion path "leaving" the loop in its middle in the same function feels weird, like unstructured code dropping a good, fat GOTO.</p>
<p>Here is the expression tree for reference:</p>
<p><a href="https://i.stack.imgur.com/gydnF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gydnF.png" alt="quicksort function expression tree"></a></p>
<p>We are far from from beta-reduction here. The "reduction" can only be understood using explicit instruction flow semantics. Okay, reality meets platonic ideals.</p>
<p>Is the loop-recur/full-recursion supposed to look like this? Is it a style problem that can be improved? </p>
| [] | [
{
"body": "<blockquote>\n <p>We are far from from beta-reduction here. The \"reduction\" can only be\n understood using explicit instruction flow semantics.</p>\n</blockquote>\n\n<p>No. You have chosen to interpret <code>loop</code> and <code>recur</code> in this way, but that is not how Clojure understands them. </p>\n\n<ul>\n<li><code>recur</code> is simply a flag for a tail-recursive call, functional as you like.</li>\n<li><code>loop</code> is a gloss on defining and applying a function.</li>\n</ul>\n\n<p>We could define <code>loop</code> as a macro in terms of <code>fn</code>:</p>\n\n<pre><code>(defmacro loop [bindings & expressions]\n (let [[bindees values] (->> bindings\n (partition 2)\n (apply map vector))]\n `((fn ~bindees ~@expressions) ~@values)))\n</code></pre>\n\n<p><a href=\"https://github.com/clojure/clojure/blob/clojure-1.9.0/src/clj/clojure/core.clj#L4541\" rel=\"nofollow noreferrer\">The real <code>loop</code> macro</a> checks the syntax of <code>bindings</code>. I've not bothered. And it handles destructuring explicitly. I've left it for <code>fn</code> to do. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:24:44.193",
"Id": "432671",
"Score": "0",
"body": "Ok. I have actually moved the deconstruction in `loop` further down for \"beginner's clarity\" after I printed out `work` and noticed that it never changed in the \"loop\" and that I had better use what's on the left side. And having many things happen at once that I don't really can be sure of and not having \"asserts\" makes me nervous."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T17:28:35.370",
"Id": "432672",
"Score": "0",
"body": "I get it. So maybe the glossed-over \"loop\" function should be made explicit, then we could have the recursive call tree TOPF--calls-->LOOPF--calls-->(LOOPF or TOPF). This is more verbose but more expository for beginners."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T23:29:16.693",
"Id": "432883",
"Score": "0",
"body": "@DavidTonhofer Clojure is not a pure functional language. My point is that `loop` and `recur` don't make it any less pure. The former is a piece of syntactic sugar simple enough to be expressed as a three line macro. The latter is an implementation hint/instruction. By the way, I'm sorry to say that I don't know what TOPF or LOOPF mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:25:04.040",
"Id": "433200",
"Score": "0",
"body": "Ah, soory. Just \"top function\" and \"loop function\". I should be clearer..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T16:47:06.823",
"Id": "223307",
"ParentId": "223306",
"Score": "2"
}
},
{
"body": "<p>As you have already noticed, this can be viewed as a case of mutual recursion. To demonstrate this I give the following mutually recursive definitions:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn sort-parts [work] (lazy-seq (sp-loop work)))\n\n(defn sp-loop [[part & parts]]\n (if-let [[pivot & xs] (seq part)]\n (sp-loop ;or recur for tco\n (let [smaller? #(< % pivot)]\n (list*\n (filter smaller? xs)\n pivot\n (remove smaller? xs)\n parts)))\n (when-let [[x & parts] parts]\n (cons x (sort-parts parts)))))\n</code></pre>\n\n<p>Because <code>sp-loop</code> is needed only in one place inside <code>sort-parts</code>, we can replace the previous with the following:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn sort-parts [work]\n (lazy-seq\n ((fn sp-loop [[part & parts]]\n (if-let [[pivot & xs] (seq part)]\n (sp-loop ;or recur for tco\n (let [smaller? #(< % pivot)]\n (list*\n (filter smaller? xs)\n pivot\n (remove smaller? xs)\n parts)))\n (when-let [[x & parts] parts]\n (cons x (sort-parts parts)))))\n work)))\n</code></pre>\n\n<p>Of course, if we use <code>recur</code>, <code>sp-loop</code> can be anonymous. But instead of defining and calling an anonymous function which only executes a loop, we can explicitly write a loop, arriving this way at the definition given in the book.</p>\n\n<p>Moving further, noticing that in the mutually recursive definitions there is very little code inside <code>sort-parts</code> apart from the call of <code>sp-loop</code> (this call is just being wrapped in a <code>LazySeq</code>'s thunk), we can define <code>qsort</code> using only one recursively defined function and no (explicit) loops, as shown below:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn qsort [xs]\n (lazy-seq\n ((fn sort-parts [[part & parts]]\n (if-let [[pivot & xs] (seq part)]\n (recur ;or sort-parts for no tco\n (let [smaller? #(< % pivot)]\n (list*\n (filter smaller? xs)\n pivot\n (remove smaller? xs)\n parts)))\n (when-let [[x & parts] parts]\n (cons x (lazy-seq (sort-parts parts))))))\n (list xs))))\n</code></pre>\n\n<p>And if we drop laziness, we can use just one loop:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn qsortv [xs]\n (loop [done []\n [part & parts] (list xs)]\n (if-let [[pivot & xs] (seq part)]\n (recur\n done\n (let [smaller? #(< % pivot)]\n (list*\n (filter smaller? xs)\n pivot\n (remove smaller? xs)\n parts)))\n (if-let [[x & parts] parts]\n (recur (conj done x) parts)\n done))))\n</code></pre>\n\n<p>Finally, in <a href=\"https://stackoverflow.com/q/55881144/11419548\">this question</a> you can see a similar case of mutual recursion and laziness but without tail calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:25:53.670",
"Id": "433201",
"Score": "0",
"body": "That's pretty extensive."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T23:32:17.583",
"Id": "223386",
"ParentId": "223306",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223386",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T14:36:37.520",
"Id": "223306",
"Score": "1",
"Tags": [
"recursion",
"clojure"
],
"Title": "Combined looping and recursion when implementing Quicksort, using proper Clojure style"
} | 223306 |
<p>I have been implementing a library of the PLC function blocks. One of the function blocks is the "Timer Pulse" function block which behavior is following:
<a href="https://i.stack.imgur.com/iRFAo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iRFAo.jpg" alt="enter image description here"></a> </p>
<p>I have implemented this function block in this manner</p>
<p>Tpulse.h:</p>
<pre><code>#include <stdint.h>
#include "LogicBlk.h"
namespace LogicBlocks
{
// Timer Pulse i.e. logic one at the output for specified time as soon as 0->1 at the input
class Tpulse : public LogicBlk{
public:
Tpulse(uint32_t*, uint32_t, uint32_t, uint32_t);
virtual ~Tpulse();
void Update(void);
private:
uint32_t *m_BitsArray;
uint32_t m_Input;
uint32_t m_Output;
uint32_t m_PulseTime;
uint32_t m_StartTime;
uint32_t m_ElapsedTime;
uint32_t m_CurrentTime;
};
}
</code></pre>
<p>Tpulse.cpp:</p>
<pre><code>LogicBlocks::Tpulse::Tpulse(uint32_t *bitsArray, uint32_t input, uint32_t output, uint32_t pulseTime):
m_BitsArray{bitsArray}, m_Input{input}, m_Output{output}, m_PulseTime{pulseTime}{
m_StartTime = 0;
m_ElapsedTime = 0;
m_CurrentTime = 0;
}
LogicBlocks::Tpulse::~Tpulse(){
}
void LogicBlocks::Tpulse::Update(void){
if(Utils::TestBitSet(m_BitsArray, m_Input) && Utils::TestBitClr(m_BitsArray, m_Output) && !m_ElapsedTime){
m_StartTime = GetTick();
SetBit(m_BitsArray, m_Output);
}else if(Utils::TestBitSet(m_BitsArray, m_Output)){
m_CurrentTime = GetTick();
m_ElapsedTime = m_CurrentTime - m_StartTime;
if(m_ElapsedTime >= m_PulseTime){
ClrBit(m_BitsArray, m_Output);
if(TestBitClr(m_BitsArray, m_Input)){
m_ElapsedTime = 0;
}
}
}else if(TestBitClr(m_BitsArray, m_Input) && TestBitClr(m_BitsArray, m_Output)){
m_ElapsedTime = 0;
}
}
</code></pre>
<p>LogicBlk.h</p>
<pre><code>namespace LogicBlocks
{
class LogicBlk {
public:
virtual void Update(void) = 0;
private:
};
}
</code></pre>
<p>Based on the tests which I have already done it seems to me that it works fine but I am not sure. Please can anybody assess my code from functional and programming style point of view? Thank you in advance for any suggestions.</p>
| [] | [
{
"body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Let the compiler write default functions</h2>\n\n<p>The <code>Tpulse</code> destructor literally does nothing and is what the compiler would have generated anyway. To indicate that, eliminate the function in <code>Tpulse.cpp</code> and declare it as <code>default</code> in <code>Tpulse.h</code>:</p>\n\n<pre><code>virtual ~Tpulse() = default;\n</code></pre>\n\n<h2>If you define one special member function, define them all</h2>\n\n<p>Sometimes called the \"rule of five,\" if you delete or define any of the <em>special member functions</em>, you should delete or define them all. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all\" rel=\"nofollow noreferrer\">C.21</a></p>\n\n<h2>Use <code>override</code> where appropriate</h2>\n\n<p>If you're intending to override a virtual base function, you should explicitly say so to help catch errors. In this case it's the <code>Update</code> function which should be marked <code>override</code>:</p>\n\n<pre><code>void Update() override;\n</code></pre>\n\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c128-virtual-functions-should-specify-exactly-one-of-virtual-override-or-final\" rel=\"nofollow noreferrer\">C.128</a> Also note that unlike in C, <code>Update(void)</code> and <code>Update()</code> mean the same thing in C++. I prefer the shorter form, but sometimes coding guidelines (often written by or for C programmers) require the long form.</p>\n\n<h2>Use namespaces consistently</h2>\n\n<p>In some places within <code>Tpulse::Update</code>, <code>TestBitClr()</code> is written with a <code>Utils::</code> namespace prefix and in other place not. This is inconsistent and confusing to the reader who may be left wondering if there are two versions. Instead, I'd recommend either always using the explicit namespace or putting a <code>using namespace Util;</code> <em>within</em> the <code>Update</code> function.</p>\n\n<h2>Prefer <code>std::</code> namespace versions of functions and types</h2>\n\n<p>Rather than <code>uint32_t</code>, I'd recommend using <code>std::uint32_t</code> and explicitly adding <code>#include <cstdint></code>. This makes it clear which type you mean and will be robust even if someone later introduces a local <code>uint32_t</code> which does, unfortunately, sometimes happen in embedded systems projects.</p>\n\n<h2>Use parameter names in function templates</h2>\n\n<p>It's best to make the interface clear and explicit, and with a function call like this:</p>\n\n<pre><code>Tpulse(uint32_t*, uint32_t, uint32_t, uint32_t);\n</code></pre>\n\n<p>It's not clear what the various <code>uint32_t</code> values represent. If they were written like this, it would be better:</p>\n\n<pre><code>Tpulse(std::uint32_t *bitsArray, std::uint32_t input, std::uint32_t output, std::uint32_t pulseTime):\n</code></pre>\n\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i4-make-interfaces-precisely-and-strongly-typed\" rel=\"nofollow noreferrer\">I.4</a>.</p>\n\n<h2>Think about the possible correct use of <code>volatile</code></h2>\n\n<p>In embedded systems we often encounter one of the few <em>correct</em> uses of <code>volatile</code>. In this case, I'm wondering about the <code>m_BitsArray</code> pointer. If, as I suspect, this is memory-mapped I/O, then this \"memory\" is not really solely under the control of the C++ environment since external asynchronous signals may cause those bits to change outside program control. For that reason, it may be that it should be declared as <code>volatile</code> to indicate this fact. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconc-volatile2\" rel=\"nofollow noreferrer\">CP.200</a>. On the other hand, if this array might also be use by other threads within your program, you will need to add explicit synchronization of some kind. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconc-volatile\" rel=\"nofollow noreferrer\">CP.8</a></p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>It appears to me that <code>m_Input</code> and <code>m_Output</code> should never change within the lifetime of a <code>Tpulse</code> object, so I'd suggest that both of those member data functions should be declared <code>const</code>. The same is probably true of <code>m_PulseTime</code>.</p>\n\n<h2>Minimize the interface</h2>\n\n<p>It seems to me that the <code>Tpulse</code> class could eliminate <code>m_ElapsedTime</code> and <code>m_CurrentTime</code> in favor of only using <code>m_StartTime</code> and perhaps a <code>bool running</code>. If you need other named variables within <code>Update</code> they can be local.</p>\n\n<h2>Use helper functions</h2>\n\n<p>The code could be much simpler to read and understand with the use of a few <code>private</code> helper functions:</p>\n\n<pre><code>bool LogicBlocks::Tpulse::input() const {\n return Utils::TestBitSet(m_BitsArray, m_Input);\n}\n\nbool LogicBlocks::Tpulse::output(bool value) {\n if (value) {\n Utils::SetBit(m_BitsArray, m_Output);\n } else {\n Utils::ClrBit(m_BitsArray, m_Output);\n }\n return value;\n}\n</code></pre>\n\n<h2>Simplify the code</h2>\n\n<p>The <code>Update</code> code is a little more complex than it needs to be. Essentially, either the timer is running and we do timer things, or it's not yet running, but we receive an input that tells us to start it. The only other slightly tricky thing is that we don't allow the timer to restart until it's expired <strong>and</strong> the input is low.</p>\n\n<p>So we can simplify the code, using a <code>bool running</code> member variable and the helper functions shown above:</p>\n\n<pre><code>void LogicBlocks::Tpulse::Update(){\n if (running) { \n auto elapsed = Utils::GetTick() - m_StartTime;\n if (elapsed >= m_PulseTime) {\n output(false);\n running = input();\n }\n } else if (input()) {\n m_StartTime = Utils::GetTick();\n running = output(true);\n } \n}\n</code></pre>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n\n<p>In this case I wrote this <code>main</code> to do some testing:</p>\n\n<pre><code>#include \"Tpulse.h\"\n#include \"Utils.h\"\n#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <thread>\n\nint main() {\n using namespace Utils;\n using namespace std::chrono_literals;\n uint32_t reg{0};\n constexpr uint32_t inbit{0x80};\n constexpr uint32_t outbit{0x2};\n LogicBlocks::Tpulse tp(&reg, inbit, outbit, 5);\n for (int i=0; i < 20; ++i) {\n std::this_thread::sleep_for(1s);\n if (i == 2 || i == 9) {\n SetBit(&reg, inbit);\n } else if (i == 4 || i == 16) {\n ClrBit(&reg, inbit);\n }\n std::cout << std::dec << \"t = \" << i << \", reg = 0x\" << std::hex << reg;\n tp.Update();\n std::cout << \", updated to 0x\" << reg << '\\n';\n }\n}\n</code></pre>\n\n<p>Here's the output:</p>\n\n<pre><code>t = 0, reg = 0x0, updated to 0x0\nt = 1, reg = 0x0, updated to 0x0\nt = 2, reg = 0x80, updated to 0x82\nt = 3, reg = 0x82, updated to 0x82\nt = 4, reg = 0x2, updated to 0x2\nt = 5, reg = 0x2, updated to 0x2\nt = 6, reg = 0x2, updated to 0x2\nt = 7, reg = 0x2, updated to 0x0\nt = 8, reg = 0x0, updated to 0x0\nt = 9, reg = 0x80, updated to 0x82\nt = 10, reg = 0x82, updated to 0x82\nt = 11, reg = 0x82, updated to 0x82\nt = 12, reg = 0x82, updated to 0x82\nt = 13, reg = 0x82, updated to 0x82\nt = 14, reg = 0x82, updated to 0x80\nt = 15, reg = 0x80, updated to 0x80\nt = 16, reg = 0x0, updated to 0x0\nt = 17, reg = 0x0, updated to 0x0\nt = 18, reg = 0x0, updated to 0x0\nt = 19, reg = 0x0, updated to 0x0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:20:04.637",
"Id": "223441",
"ParentId": "223309",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:13:25.327",
"Id": "223309",
"Score": "3",
"Tags": [
"c++",
"embedded",
"function-block-diagram"
],
"Title": "Implementing PLC \"Timer Pulse\" function block in C++"
} | 223309 |
<p>I'm looking for specific feedback on a major design change that I plan on making to my personal website (<a href="https://aleksandrhovhannisyan.github.io/" rel="nofollow noreferrer">https://aleksandrhovhannisyan.github.io/</a>).</p>
<p>Currently, the Projects section contains hardcoded HTML. With my current approach, each time I want to add a new project, I have to copy-paste an existing project div and customizing the information. Even worse, some of the information, like the stargazer count, must be updated with new commits each time that information changes. There's also the issue of adding icons to each project, and they're not always uniform in dimensions (noob alert).</p>
<p>My alternative approach, which I've been working on for a couple days now, is to pull data for my repositories using <a href="https://developer.github.com/v3/repos/#list-user-repositories" rel="nofollow noreferrer">the GitHub API</a> and AJAX. Don't worry—I'm not authenticating, so no client credentials have to be exposed.</p>
<p>The code (HTML, CSS, JS) is below. Please note that the JavaScript originally contains other functionality as well, like for the light/dark mode switch and the navbar hamburger icon, and so on. But those functions are not relevant for this code review, <em>so I've omitted them to make things easier.</em></p>
<p>Also, I exceeded my character limit for this post, so I stripped most of the HTML that isn't relevant.</p>
<p>Below are some specific questions I'm hoping people could answer. However, I am more than open to comments on anything else you notice!</p>
<ol>
<li><p><strong>Code style/cleanliness</strong>: If it isn't obvious, I'm sort of new to JavaScript and working with APIs. This "overhaul" is my way of getting my feet wet and learning a bit more. Is there anything that makes the JavaScript difficult to read or understand? Does the fact that I have so many functions make it more difficult to keep track of how data is passed around?</p></li>
<li><p><strong>The <code>repos</code> map</strong>: Is it okay that I have the global <code>repos</code> map up at the top? Is my approach here okay/understandable? What about the <code>get</code> convenience function I defined: is there a better approach? Again, any feedback is appreciated!</p></li>
<li><p><strong>Be honest</strong>: Which version of the site's Projects section do you prefer—the one you see here or the original linked at the top of this post? And for what reason(s)?</p></li>
</ol>
<p>Thank you in advance! Here's the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var repos = new Map();
setupRepos();
requestRepoData();
/** Defines all repositories of interest, to be displayed in the Projects section of the page in
* the precise order that they appear here. These serve as filters for when we scour through all
* repositories returned by the GitHub API. Though these are mostly hardcoded, we only have to enter
* the information within this function; the rest of the script is not hardcoded in that respect.
* Notable downside: if the name of the repo changes for whatever reason, it will need to be updated here.
*/
function setupRepos() {
addRepo("Scribe-Text-Editor", "Scribe: Text Editor", ["cpp", "qt5", "qtcreator"]);
addRepo("EmbodyGame", "Embody: Game", ["csharp", "unity", "ai"]);
addRepo("aleksandrhovhannisyan.github.io", "Personal Website", ["html5", "css", "javascript"]);
addRepo("Steering-Behaviors", "Steering Behaviors", ["csharp", "unity", "ai"]);
addRepo("MIPS-Linked-List", "ASM Linked List", ["mips", "asm", "qtspim"]);
addRepo('Dimension35', "dim35: Game", ["godot", "networking"]);
}
/** Associates the given official name of a repo with an object representing custom data about that repository.
* This hashing/association makes it easier to do lookups later on.
*
* @param {string} officialName - The unique name used to identify this repository on GitHub.
* @param {string} customName - A custom name for the repository, not necessarily the same as its official name.
* @param {string[]} topics - An array of strings denoting the topics that correspond to this repo.
*/
function addRepo(officialName, customName, topics) {
// Note 1: We define a custom name here for two reasons: 1) some repo names are quite long, such as my website's,
// and 2) multi-word repos have hyphens instead of spaces on GitHub, so we'd need to replace those (which would be wasteful)
// Note 2: We define the topics here instead of parsing them dynamically because GitHub's API returns the topics
// as a *sorted* array, which means we'll end up displaying undesired tags (since we don't show all of them).
// This approach gives us more control but sacrifices flexibility, since we have to enter topics manually for repos of interest.
repos.set(officialName, { "customName" : customName, "topics" : topics, "card" : null });
}
/** Convenience wrapper for accessing the custom data for a particular repo. Uses the given
* repo's official name (per the GitHub API) as the key into the associated Map.
*
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Object} The custom object representing the given repo.
*/
function get(repo) {
// Notice how the underlying syntax is messy; the wrapper makes it cleaner when used
return repos.get(repo.name);
}
function requestRepoData() {
let request = new XMLHttpRequest();
request.open('GET', 'https://api.github.com/users/AleksandrHovhannisyan/repos', true);
request.onload = parseRepos;
request.send();
}
function parseRepos() {
if (this.status !== 200) return;
let data = JSON.parse(this.response);
// Even though we have to loop over all repos to find the ones we want, doing so is arguably
// much faster (and easier) than making separate API requests for each repo of interest
// Also note that GitHub has a rate limit of 60 requests/hr for unauthenticated IPs
for (let repo of data) {
if (repos.has(repo.name)) {
// We cache the card here instead of publishing it immediately so we can display
// the cards in our own order, since the requests are processed out of order (b/c of async)
get(repo).card = createCardFor(repo);
}
}
publishRepoCards();
}
/** Creates a project card for the given repo. A card consists of a header, description,
* and footer, as well as an invisible link and hidden content to be displayed when the
* card is hovered over.
*
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} A DOM element representing a project card for the given repo.
*/
function createCardFor(repo) {
let card = document.createElement('section');
card.setAttribute('class', 'project');
card.appendChild(headerFor(repo));
card.appendChild(descriptionFor(repo));
card.appendChild(footerFor(repo));
card.appendChild(anchorFor(repo));
card.appendChild(createHoverContent());
return card;
}
/**
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} A header for the given repo, consisting of three key pieces:
* the repo icon, the repo name, and the repo's rating (stargazers).
*/
function headerFor(repo) {
var header = document.createElement('header');
var icon = document.createElement('span');
icon.setAttribute('class', 'project-icon');
// The emoji part of the description on GitHub
icon.textContent = repo.description.substring(0, 3);
var h4 = document.createElement('h4');
h4.appendChild(icon);
h4.appendChild(nameLabelFor(repo));
header.appendChild(h4);
header.appendChild(stargazerLabelFor(repo));
return header;
}
/**
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} A label for the name of the given repo.
*/
function nameLabelFor(repo) {
var projectName = document.createElement('span');
projectName.textContent = get(repo).customName;
return projectName;
}
/**
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} A label showing the number of stargazers for the given repo.
*/
function stargazerLabelFor(repo) {
var projectRating = document.createElement('span');
var starIcon = document.createElement('i');
starIcon.setAttribute('class', 'fas fa-star filled');
var starCount = document.createElement('span');
starCount.textContent = ' ' + repo.stargazers_count;
projectRating.setAttribute('class', 'project-rating');
projectRating.appendChild(starIcon);
projectRating.appendChild(starCount);
return projectRating;
}
/**
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} An element containing the description of the given repo.
*/
function descriptionFor(repo) {
var description = document.createElement('p');
description.setAttribute('class', 'description');
// Non-emoji part of the description on GitHub
description.textContent = repo.description.substring(3);
return description;
}
/**
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} A footer for the name of the given repo, consisting of at most
* three paragraphs denoting the topics associated with that repo.
*/
function footerFor(repo) {
var footer = document.createElement('footer');
footer.setAttribute('class', 'topics');
for(let topic of get(repo).topics) {
let p = document.createElement('p');
p.textContent = topic;
footer.appendChild(p);
}
return footer;
}
/**
* @param {Object} repo - The JSON-parsed object containing a repository's data.
* @returns {Element} An anchor element whose href is set to the given repo's "real" URL.
*/
function anchorFor(repo) {
var anchor = document.createElement('a');
anchor.setAttribute('class', 'container-link');
anchor.setAttribute('href', repo.html_url);
anchor.setAttribute('target', '_blank');
return anchor;
}
function createHoverContent() {
var hoverContent = document.createElement('div');
hoverContent.setAttribute('class', 'hover-content');
var boldText = document.createElement('strong');
boldText.textContent = 'View on GitHub';
var externalLinkIcon = document.createElement('i');
externalLinkIcon.setAttribute('class', 'fas fa-external-link-alt');
hoverContent.appendChild(boldText);
hoverContent.appendChild(externalLinkIcon);
return hoverContent;
}
function publishRepoCards() {
const projects = document.getElementById('projects');
const placeholder = document.getElementById('project-placeholder');
for (let repo of repos.values()) {
projects.insertBefore(repo.card, placeholder);
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* ============================================
General top-level styling
============================================
*/
* {
box-sizing: border-box;
}
:root {
--main-bg-color: white;
--nav-bg-color: rgb(44, 44, 44);
--nav-text-color: rgb(179, 177, 177);
--nav-min-height: 50px;
--topic-label-bg-color: #e7e7e7;
--hr-color: rgba(143, 142, 142, 0.2);
--text-color-normal: black;
--text-color-emphasis: black;
--link-color: rgb(39, 83, 133);
--button-bg-color: rgb(39, 83, 133);
--button-bg-hover-color: rgb(83, 129, 182);
--button-text-color: white;
--button-text-hover-color: white;
--skill-hover-bg-color: whitesmoke;
--project-card-bg-color: rgb(253, 253, 253);
--project-card-shadow: 0px 0px 4px 2px rgba(50, 50, 50, 0.4);
--project-card-shadow-hover: 0px 1px 6px 2px rgba(10, 10, 10, 0.6);
--project-card-margin: 30px;
--form-bg-color: rgb(255, 255, 255);
--form-input-margins: 10px;
--form-max-width: 475px;
--page-center-percentage: 80%;
--global-transition-duration: 0.5s;
--institution-info-border-width: 3px;
}
.night {
--main-bg-color: rgb(44, 44, 44);
--nav-bg-color: rgb(10, 10, 10);
--topic-label-bg-color: #222222;
--hr-color: rgba(255, 255, 255, 0.2);
--text-color-normal: rgb(179, 177, 177);
--text-color-emphasis: rgb(202, 202, 202);
--link-color: rgb(202, 183, 143);
--button-bg-color: rgb(90, 90, 66);
--button-bg-hover-color: rgb(141, 141, 114);
--button-text-color: var(--text-color-emphasis);
--button-text-hover-color: rgb(24, 24, 24);
--skill-hover-bg-color: rgb(66, 66, 66);
--project-card-bg-color: rgb(54, 54, 54);
/* The shadows need to be a bit more prominent so they contrast well in dark mode,
hence the larger values for blur and spread */
--project-card-shadow: 0 2px 6px 4px rgba(31, 31, 31, 0.9);
--project-card-shadow-hover: 0px 2px 10px 5px rgba(10, 10, 10, 0.6);
--form-bg-color: var(--skill-hover-bg-color);
}
#intro {
margin-bottom: 40px;
}
#about-me, #projects, #skills, #education, #contact {
/* So the fixed navbar doesn't cover up any content we scroll to */
margin-top: calc((var(--nav-min-height) + 20px) * -1);
padding-top: calc(var(--nav-min-height) + 20px);
}
#about-me, #projects, #skills, #education {
margin-bottom: 120px;
}
body {
font-family: Nunito, sans-serif;
color: var(--text-color-normal);
background-color: var(--main-bg-color);
transition: background-color var(--global-transition-duration);
width: var(--page-center-percentage);
margin-left: auto;
margin-right: auto;
}
i, h1, h2, h4, strong, em {
color: var(--text-color-emphasis);
}
.institution-info h4 {
margin-left: 10px;
font-weight: normal;
color: var(--text-color-normal);
}
h1 {
font-size: 2em;
margin-block-start: 0.67em;
margin-block-end: 0.67em;
}
h1, h2 {
margin-top: 0;
}
a {
color: var(--link-color);
}
p {
color: var(--text-color-normal);
}
/* Links an entire parent container, but the parent must be set to relative position */
.container-link {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-decoration: none;
z-index: 1;
}
/* ============================================
Buttons, collapsibles, etc.
============================================
*/
/* Note: this is an anchor with a class of button */
.button {
width: 100%;
height: 40px;
line-height: 40px;
text-align: center;
display: block;
margin-bottom: 10px;
margin-right: 15px;
border-radius: 10px;
font-size: 1em;
font-weight: bold;
text-decoration: none;
}
.collapsible {
font-family: Nunito, sans-serif;
font-size: 1em;
display: flex;
align-items: center;
border: none;
outline: none;
width: 100%;
}
.collapsible span {
text-align: left;
padding-left: 10px;
margin-top: 20px;
margin-bottom: 20px;
}
.button, .collapsible {
cursor: pointer;
border: none;
background-color: var(--button-bg-color);
transition: var(--global-transition-duration);
}
.button, .button *, .collapsible * {
color: var(--button-text-color);
}
.button:hover, .collapsible:hover {
background-color: var(--button-bg-hover-color);
}
/* To get rid of Firefox's dotted lines when these are clicked */
.button::-moz-focus-inner, .collapsible::-moz-focus-inner {
border: 0;
}
.button:hover, .button:hover *, .collapsible:hover * {
color: var(--button-text-hover-color);
}
button:focus {
outline: none;
}
.fa-angle-right, .fa-angle-down {
margin-left: 10px;
margin-right: 20px;
font-size: 1em;
}
@media only screen and (min-width: 400px) {
.main-buttons {
display: flex;
}
.button {
max-width: 200px;
}
}
/* ============================================
Navigation (+ night mode nightmode-switch)
============================================
*/
#topnav .centered-content {
width: var(--page-center-percentage);
margin-left: auto;
margin-right: auto;
height: var(--nav-min-height);
display: flex;
justify-content: space-between;
align-items: center;
}
#topnav {
width: 100%;
min-height: var(--nav-min-height);
position: fixed;
left: 0;
right: 100%;
top: 0;
background-color: var(--nav-bg-color);
/* This is to ensure that it always appears above everything. */
z-index: 100;
}
#topnav * {
color: var(--nav-text-color);
}
.nav-links {
padding: 0;
list-style-type: none;
display: none;
margin-left: 0;
margin-right: 0;
}
.nav-links li {
text-align: center;
margin: 20px auto;
}
.nav-links a {
text-decoration: none;
vertical-align: middle;
transition: var(--global-transition-duration);
}
#topnav .nav-links a:hover {
text-decoration: underline;
color: white;
}
.navbar-hamburger {
font-size: 1.5em;
}
.nightmode-switch-container, .nightmode-switch-container * {
display: inline-block;
}
.nightmode-switch {
width: 40px;
height: 20px;
line-height: 15px;
margin-right: 5px;
background-color: var(--nav-bg-color);
border: 3px solid var(--nav-text-color);
border-radius: 100px;
cursor: pointer;
transition: var(--global-transition-duration);
}
.nightmode-switch::before {
content: "";
display: inline-block;
vertical-align: middle;
line-height: normal;
margin-left: 2px;
margin-bottom: 2px;
width: 12px;
height: 10px;
background-color: var(--nav-text-color);
border-radius: 50%;
transition: var(--global-transition-duration);
}
.night .nightmode-switch::before {
margin-left: 20px;
}
.nav-links.active {
display: block;
background-color: var(--nav-bg-color);
color: var(--nav-text-color);
/* Make the dropdown take up 100% of the viewport width */
position: absolute;
left: 0;
right: 0;
top: 20px;
}
@media only screen and (min-width: 820px) {
/* This is the most important part: shows the links next to each other
Note: .nav-links.active accounts for an edge case where you open the hamburger
on a small view and then resize the browser so it's larger.
*/
.nav-links, .nav-links.active {
margin: 0;
position: static;
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: center;
font-size: 1.1em;
}
.nav-links li {
margin: 0;
}
.nav-links a {
margin-left: 40px;
transition: var(--global-transition-duration);
}
.navbar-hamburger {
display: none;
}
}
/* ============================================
Page header (intro, about me)
============================================
*/
#page-header {
margin-top: 100px;
display: grid;
column-gap: 50px;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
#main-cta {
margin-bottom: 30px;
font-size: 1.1em;
}
/* ============================================
Projects/portfolio cards
============================================
*/
#projects {
display: grid;
column-gap: 50px;
row-gap: 50px;
/* Fill up space as it's made available, with each card being a minimum of 250px */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
/* Don't treat the project header as an item/card, keep it on the top row */
#projects h2 {
grid-row: 1;
grid-column: 1 / -1;
}
.project {
/* To ensure that .project-link (see below) is absolute relative to us and not the page */
position: relative;
display: grid;
grid-template-columns: 1;
/* Header, description, footer, respectively */
grid-template-rows: max-content 1fr max-content;
row-gap: 20px;
}
/* All project cards except the placeholder get a background and box shadow */
.project:not(#project-placeholder) {
background-color: var(--project-card-bg-color);
box-shadow: var(--project-card-shadow);
border-radius: 5px;
transition: all var(--global-transition-duration);
}
/* Apply margins to all project headers except the placeholder's */
.project:not(#project-placeholder) header {
margin-top: var(--project-card-margin);
margin-bottom: 0px;
margin-left: var(--project-card-margin);
margin-right: var(--project-card-margin);
display: grid;
grid-template-areas: "heading heading rating";
}
.project-icon * {
width: 24px;
margin-right: 3px;
display: inline-block;
vertical-align: middle;
}
.project h4 {
margin: 0px;
align-self: center;
grid-area: heading;
}
.project-rating {
font-size: 0.85em;
justify-self: center;
align-self: center;
grid-area: rating;
}
.project .description {
margin-top: 0px;
margin-bottom: 0px;
margin-left: var(--project-card-margin);
margin-right: var(--project-card-margin);
}
/* Displayed when a user hovers over a project card */
.hover-content {
font-size: 1.2em;
/* Again, note that .project has position: relative */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* Center the content for the hover layer */
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
/* Opacity = 0 means it's hidden by default */
opacity: 0;
background-color: var(--skill-hover-bg-color);
transition: var(--global-transition-duration) ease;
}
/* Make it clearer which card is hovered over */
.project:hover:not(#project-placeholder) {
box-shadow: var(--project-card-shadow-hover);
}
/* Transition for the hover content changes its opacity */
.project:hover .hover-content {
cursor: pointer;
opacity: 0.92;
}
.fa-external-link-alt {
margin-top: 20px;
}
.project-name {
color: var(--link-color);
text-decoration: none;
}
.topics {
display: flex;
flex-wrap: wrap;
grid-row: 3;
margin-top: 0px;
margin-bottom: var(--project-card-margin);
margin-left: var(--project-card-margin);
margin-right: var(--project-card-margin);
}
.topics p {
font-size: 0.9em;
padding: 5px;
margin-top: 10px;
margin-bottom: 0px;
margin-right: 10px;
border-radius: 2px;
background-color: var(--topic-label-bg-color);
box-shadow: 0 0 2px black;
transition: background-color var(--global-transition-duration);
}
#project-placeholder {
display: flex;
flex-direction: column;
text-align: center;
justify-content: center;
}
.github-cta {
display: inline-block;
font-size: 3em;
margin-top: 20px;
text-decoration: none;
color: black;
}
/* ============================================
Skills (responsive columns)
============================================
*/
#skills {
display: grid;
column-gap: 50px;
row-gap: 20px;
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
}
#skills h2 {
grid-row: 1;
grid-column: 1 / -1;
}
.skill-category h4 {
margin-bottom: 5px;
}
.skill-item {
margin-top: 10px;
display: grid;
column-gap: 10px;
grid-template-columns: 1fr 1fr;
}
.skill-item:hover {
background-color: var(--skill-hover-bg-color);
}
.skill-name {
grid-column: 1;
}
.skill-rating {
grid-column: 2;
display: inline;
text-align: right;
}
.fa-star.filled {
color: var(--button-bg-color);
}
.fa-star.empty {
color: var(--nav-text-color);
}
.night .fa-star.filled {
color: rgb(145, 145, 145);
}
.night .fa-star.empty {
color: var(--button-bg-color);
}
/* ============================================
Education (institutions, coursework, etc.)
============================================
*/
.institution {
margin-top: 20px;
}
/* Course and award container */
.institution-info {
display: grid;
/* Mobile first: only one column. Changes to two columns on bigger screens. See media query below. */
grid-template-columns: 1fr;
/* Will be set to a sufficiently large max-height by corresponding click handler for .collapsible */
max-height: 0px;
transition: max-height var(--global-transition-duration);
overflow: hidden;
border: solid var(--institution-info-border-width) var(--button-bg-color);
border-top: none;
}
.institution-info .awards {
/* Only matters on mobile, where the awards are stacked underneath courses */
border-top: solid var(--institution-info-border-width) var(--button-bg-color);
}
.institution-info ul {
padding-right: 10px;
}
.institution-info p {
padding-left: 10px;
}
/* Line up courses and awards side by side on larger screens */
@media only screen and (min-width: 800px) {
.institution-info {
grid-template-rows: 1fr;
grid-template-columns: auto auto;
}
.institution-info .awards {
/* Now that it's lined up to the right of the courses, there's no need for a top border */
border-top: none;
/* But there is for a left border */
border-left: solid var(--institution-info-border-width) var(--button-bg-color);
}
}
/* ============================================
Contact form
============================================
*/
#contact {
display: grid;
grid-template-areas: "form"
"socials";
grid-template-rows: auto;
column-gap: 50px;
}
#contact-form {
grid-area: form;
}
#social-networks {
grid-area: socials;
}
@media only screen and (min-width: 700px) {
#contact {
grid-template-areas: "form form form socials";
}
}
form {
margin-bottom: 50px;
margin-top: 30px;
max-width: var(--form-max-width);
}
form * {
color: var(--text-color-normal);
font-family: Nunito, sans-serif;
font-size: 1em;
}
form input:not([class="button"]), form textarea {
height: 30px;
width: 100%;
margin-bottom: 15px;
padding: 10px;
background-color: var(--form-bg-color);
border: 0px solid;
box-shadow: 0 0 3px 1px rgb(172, 172, 172);
border-radius: 3px;
transition: var(--global-transition-duration);
}
form label {
margin-bottom: 5px;
display: block;
}
form input:focus, form textarea:focus {
outline: none;
box-shadow: 0 0 5px 2px rgb(155, 155, 155);
}
form textarea {
max-width: var(--form-max-width);
min-height: 200px;
transition: height 0s;
transition: background-color var(--global-transition-duration);
}
form .button {
max-width: 100%;
width: 100%;
height: 45px;
}
/* Yum, honey */
input.honeypot {
display: none;
}
/* ============================================
Social networks
============================================
*/
#social-networks {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
grid-template-rows: min-content;
grid-auto-rows: min-content;
row-gap: 50px;
column-gap: 30px;
margin-bottom: 50px;
}
#social-networks h3 {
grid-row: 1;
grid-column: 1 / -1;
}
.social-network {
/* Position relative because we have an absolutely
positioned .container-link as a child */
position: relative;
display: grid;
grid-template-columns: auto 1fr;
column-gap: 20px;
}
.social-network:hover {
cursor: pointer;
background-color: var(--skill-hover-bg-color);
}
.social-network .fa-stack {
grid-column: 1;
display: grid;
}
.fa-stack i {
align-self: center;
justify-self: center;
}
/* Whatever icon is being used as the background one */
.fa-stack-2x {
opacity: 0;
font-size: 1.5em;
color: white;
}
.night .fa-stack-2x {
opacity: 1;
}
.social-network .network-name {
grid-column: 2;
align-self: center;
}
#social-networks .fa-linkedin {
color: #0077B5;
}
#social-networks .fa-github {
color: black;
}
#social-networks .fa-stack-exchange {
color: #195398;
}
#social-networks .fa-address-book {
color: #37A000;
}
#page-footer {
position: absolute;
left: 0;
height: 50px;
width: 100%;
background: var(--nav-bg-color);
color: var(--nav-text-color);
display: flex;
justify-content: center;
align-items: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Nunito font looks amazing :) -->
<link href="https://fonts.googleapis.com/css?family=Nunito&display=swap" rel="stylesheet">
<!-- Font Awesome icons -->
<script src="https://kit.fontawesome.com/7d7dc6ad85.js"></script>
<!-- Custom stylesheet -->
<link rel="stylesheet" href="style.css">
<!-- Favicon -->
<link rel="icon" href="favicon.ico" type='image/x-icon'>
<!-- Preview image (e.g., for LinkedIn or Facebook) -->
<meta property="og:image" content="https://avatars2.githubusercontent.com/u/19352442?s=400&amp;v=4">
<title>Aleksandr Hovhannisyan</title>
<!-- Contact form -->
<meta name="referrer" content="origin">
</head>
<body>
<nav id="topnav">
<div class="centered-content">
<div class="nightmode-switch-container">
<div class="nightmode-switch"></div><span>Light mode</span>
</div>
<i class="navbar-hamburger fas fa-bars"></i>
<ul class="nav-links">
<li><a href="#about-me">About Me</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#education">Education</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<article id="content">
<section id="projects">
<h2>Projects &#128193;</h2>
<aside id="project-placeholder" class="project">
<header>
<h4>Want to see more of my work?</h4>
</header>
<div>
<p>Check out my other repos:</p>
<a class="github-cta" href="https://github.com/AleksandrHovhannisyan?tab=repositories" target="_blank"><i class="fab fa-github"></i></a>
</div>
</aside>
</section>
</article>
<!-- Custom javascript -->
<script src="index.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T18:10:32.123",
"Id": "433526",
"Score": "0",
"body": "Note to anyone viewing this late: I have since then updated the repo, so the original link is outdated. I also changed my approach slightly, so what you see here for the repo icons will actually end up being text."
}
] | [
{
"body": "<h2>Addressing your questions</h2>\n\n<blockquote>\n <ol>\n <li><strong>Code style/cleanliness</strong> Does the fact that I have so many functions make it more difficult to keep track of how data is passed around?</li>\n </ol>\n</blockquote>\n\n<p>I wouldn't say it makes it more difficult to keep track of how data is passed around...</p>\n\n<blockquote>\n <ol start=\"2\">\n <li><strong>The repos map</strong>: Is it okay that I have the global repos map up at the top? Is my approach here okay/understandable? What about the get convenience function I defined: is there a better approach? </li>\n </ol>\n</blockquote>\n\n<p>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">class</a> could be used to store the <em>repos</em> as a field declaration, however if you wanted it to be <em>private</em> such a feature is currently experimental<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations\" rel=\"nofollow noreferrer\">1</a></sup>, though <a href=\"https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript\" rel=\"nofollow noreferrer\">the revealing module pattern</a> could be used for that.</p>\n\n<p>You could also use a plain-old Javascript Object (i.e. POJO) instead of a set as long as the keys are only going to be string literals but then iteration of the items would not be in the same order they were inserted. Refer to answers to <a href=\"https://stackoverflow.com/q/18541940/1575353\">Map vs Object in JavaScript\n</a> for more information.</p>\n\n<h2>Other feedback</h2>\n\n<p>Many variable are declared with <code>let</code> but never re-assigned (e.g. <code>let request = new XMLHttpRequest();</code> in <code>requestRepoData</code>). It is recommended that you default to using <code>const</code> to avoid accidental re-assignment and then use <code>let</code> when you deem it necessary. </p>\n\n<hr>\n\n<p>I see <code>setAttribute()</code> is used in certain places to add class names to elements - for example:</p>\n\n<blockquote>\n<pre><code>let card = document.createElement('section');\ncard.setAttribute('class', 'project');\n</code></pre>\n</blockquote>\n\n<p>There is a method: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods\" rel=\"nofollow noreferrer\"><code>classList.add()</code></a> that can be used instead:</p>\n\n<pre><code>card.classList.add('project');\n</code></pre>\n\n<hr>\n\n<p>For this line in <code>addRepo()</code>:</p>\n\n<blockquote>\n<pre><code>repos.set(officialName, { \"customName\" : customName, \"topics\" : topics, \"card\" : null });\n</code></pre>\n</blockquote>\n\n<p>The key names don't need to be in double quotes unless the names contain special characters like hyphens.</p>\n\n<pre><code>repos.set(officialName, { customName : customName, topics : topics, card : null });\n</code></pre>\n\n<p>Additionally, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">the shorthand property definition notation</a> could be used to simplify this code to this:</p>\n\n<pre><code>repos.set(officialName, { customName, topics, \"card\" : null });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:50:24.640",
"Id": "433029",
"Score": "0",
"body": "I guess I should've mentioned that I also want the repo cards to appear in a specific order—namely, the order in which their records were inserted into the map. If I use an object instead of a map, wouldn't I lose the ability to traverse the cards in that custom order?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:56:13.607",
"Id": "433030",
"Score": "0",
"body": "Yes that ability would be lost."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:24:24.653",
"Id": "433035",
"Score": "0",
"body": "Thanks for all the feedback! I didn't ask this originally, but I wonder: Would it be better to hardcode the repo icons (the emoji) alongside all the other info instead of getting those from the GitHub repo description (using substrings)? I currently use `icon.textContent = repo.description.substring(0, 3);`, which seems a bit hacky/unclean to me. Just curious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T18:35:41.003",
"Id": "433860",
"Score": "0",
"body": "oh, hmm... neither approach seems very clean... perhaps an ideal scenario would be that the repo would have a meta field to store such information... I considered suggesting a regex to look for emoji chars and conditionally strip them out when displaying the non-emoji description"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T23:32:46.410",
"Id": "433889",
"Score": "0",
"body": "Yeah I just went with the hardcoded approach so my repos don't look too noisy. Good enough for me :D"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T16:18:43.107",
"Id": "223429",
"ParentId": "223310",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223429",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T18:35:35.340",
"Id": "223310",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"api",
"ajax"
],
"Title": "Pulling data from the GitHub API for user repositories"
} | 223310 |
<p>I have already done many of the Project Euler questions in other languages before, but whenever learning a new language, I like to do the problems again in that language. </p>
<p>Here is my elixir version of </p>
<blockquote>
<p>Find the sum of all Fibonacci numbers below 4,000,000.</p>
</blockquote>
<pre><code>stream = Stream.unfold({0,1}, fn {a, b} -> {a, {b, a + b}} end)
Enum.reduce_while(stream, 0, &(
cond do
&1 < 4000000 and rem(&1, 2) == 0 ->
{:cont, &2 + &1}
&1 < 4000000 ->
{:cont, &2}
true ->
{:halt, &2}
end
))
</code></pre>
<p>Can anyone spot a way to make my code fit the elixir paradigm more? Are there things I could improve?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:23:44.543",
"Id": "432698",
"Score": "0",
"body": "Not sure why the downvote, if this isn't the purpose of this site then what is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:44:06.337",
"Id": "432699",
"Score": "1",
"body": "Someone has voted to close it as \"Unclear what you're asking\". I don't see why this would be considered unclear though, and this looks very much ontopic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:45:09.990",
"Id": "432700",
"Score": "0",
"body": "Someone seems to have raised a \"Unclear what you're asking\" close vote. But you have added that to your question since then, so your question should be good to go."
}
] | [
{
"body": "<p>I'd improve two things:</p>\n\n<ul>\n<li>take advantage of <a href=\"https://github.com/elixir-lang/elixir/blob/13b5e53efadd2b6b66d05fcb4aa526fa74672762/lib/elixir/lib/kernel/special_forms.ex#L1559\" rel=\"nofollow noreferrer\">ability</a> to specify multiple clauses for anonymous function,</li>\n<li>use <a href=\"https://github.com/elixir-lang/elixir/blob/3c001a569d0c63843b3791859147e01658759843/lib/elixir/pages/Syntax%20Reference.md#numbers\" rel=\"nofollow noreferrer\">underscore</a> for big numbers to improve code readability.</li>\n</ul>\n\n<p>My take on your code:</p>\n\n<pre><code>{0, 1}\n|> Stream.unfold(fn {a, b} -> {a, {b, a + b}} end)\n|> Enum.reduce_while(0, fn\n value, acc when value < 4_000_000 and rem(value, 2) == 0 -> {:cont, acc + value}\n value, acc when value < 4_000_000 -> {:cont, acc}\n _value, acc -> {:halt, acc}\nend)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T23:30:59.793",
"Id": "437215",
"Score": "1",
"body": "Also, I like your use of an explicit `fn` over the submitters `&`- the latter is often hard to read and usually I will only use it for very short stuff, probably just the `&function/arity` construct and nothing else."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T14:38:10.667",
"Id": "223750",
"ParentId": "223316",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:18:57.893",
"Id": "223316",
"Score": "1",
"Tags": [
"programming-challenge",
"elixir"
],
"Title": "Find the sum of Fibonacci sequence"
} | 223316 |
<p>I'm trying to follow <a href="https://software.intel.com/en-us/articles/api-without-secrets-introduction-to-vulkan-part-1" rel="nofollow noreferrer">this Vulkan API tutorial</a> and have come up with an implementation that I don't completely loathe. The <code>VkUtf8StringArray</code> class is my least favorite thing and would like to know if there are better ways I structure things and/or make them safer...</p>
<p><em>Note: Depends on <a href="https://gist.github.com/Kittoes0124/0e936d97a0bc57c8d8a0ce16406231cb" rel="nofollow noreferrer">a helper file</a> to load the dll at run-time.</em></p>
<p><strong>Full Code:</strong></p>
<pre><code>using ByteTerrace.Windows.Api;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace ByteTerrace.Vulkan.Api
{
public sealed class VkAccessor : IDisposable
{
private static bool TryGetProcAddrDelegate<TDelegate>(IntPtr procAddress, out TDelegate @delegate) {
if (IntPtr.Zero == procAddress) {
@delegate = default;
return false;
}
else {
@delegate = Marshal.GetDelegateForFunctionPointer<TDelegate>(procAddress);
}
return true;
}
public static int MakeVersion(int major, int minor, int patch) => (((major) << 22) | ((minor) << 12) | (patch));
public static VkAccessor New(string dllName) => new VkAccessor(dllName);
private delegate IntPtr vkGetInstanceProcAddr(IntPtr instance, IntPtr pName);
private readonly vkGetInstanceProcAddr m_vkGetInstanceProcAddr;
private readonly IntPtr m_vkHandle;
private bool m_isDisposed;
private VkAccessor(string dllName) {
m_isDisposed = false;
if (!Module.TryGetModule(dllName, out m_vkHandle)) {
throw new Exception(message: "unable to load the specified Vulkan DLL module");
}
if (!Module.TryGetDelegateForFunctionPointer(m_vkHandle, nameof(vkGetInstanceProcAddr), out m_vkGetInstanceProcAddr)) {
throw new Exception(message: "unable to find an entry point for the vkGetInstanceProcAddr procedure");
}
}
~VkAccessor() => Dispose(false);
private void Dispose(bool disposing) {
if (m_isDisposed) {
return;
}
else {
if (disposing) {
// no managed resources to free...
}
if (!Module.FreeLibrary(m_vkHandle)) {
throw new Exception(message: "unable to free the Vulkan DLL module handle");
}
m_isDisposed = true;
}
}
private IntPtr GetInstanceProcAddr(IntPtr instance, string procedureName) {
if (string.IsNullOrEmpty(procedureName)) {
throw new ArgumentException(message: "name cannot be null or empty", paramName: nameof(procedureName));
}
using (var vkProcedureName = VkUtf8String.New(procedureName)) {
return m_vkGetInstanceProcAddr(instance, vkProcedureName.Handle);
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public bool TryGetGlobalProcDelegate<TDelegate>(string procedureName, out TDelegate @delegate) => TryGetProcAddrDelegate(GetInstanceProcAddr(IntPtr.Zero, procedureName), out @delegate);
public bool TryGetInstanceProcDelegate<TDelegate>(IntPtr instance, string procedureName, out TDelegate @delegate) => TryGetProcAddrDelegate(GetInstanceProcAddr(instance, procedureName), out @delegate);
}
public sealed class VkInstance : IDisposable
{
public static VkInstance New(VkAccessor vkAccessor, ref VkInstanceCreateInfo vkInstanceCreateInfo) => new VkInstance(vkAccessor, ref vkInstanceCreateInfo);
private delegate VkResult vkCreateInstance(ref VkInstanceCreateInfo pCreateInfo, IntPtr pAllocator, out IntPtr pInstance);
private delegate void vkDestroyInstance(IntPtr instance, IntPtr pAllocator);
private readonly vkDestroyInstance m_vkDestroyInstanceDelegate;
private readonly IntPtr m_vkInstanceHandle;
private bool m_isDisposed;
private VkInstance(VkAccessor vkAccessor, ref VkInstanceCreateInfo vkInstanceCreateInfo) {
if (!vkAccessor.TryGetGlobalProcDelegate(nameof(vkCreateInstance), out vkCreateInstance vkCreateInstanceDelegate)) {
throw new Exception(message: "unable to create a global Vulkan delegate for the vkCreateInstance procedure"); // TODO: Refactor to use a custom exception.
}
if (VkResult.VK_SUCCESS != vkCreateInstanceDelegate(ref vkInstanceCreateInfo, IntPtr.Zero, out IntPtr vkInstanceHandle)) {
throw new Exception(message: "unable to create a Vulkan intance using the specified information"); // TODO: Refactor to use a custom exception.
}
if (!vkAccessor.TryGetInstanceProcDelegate(vkInstanceHandle, nameof(vkDestroyInstance), out vkDestroyInstance vkDestroyInstanceDelegate)) {
throw new Exception(message: "unable to create an instance Vulkan delegate for the vkDestroyInstance procedure"); // TODO: Refactor to use a custom exception.
}
m_vkDestroyInstanceDelegate = vkDestroyInstanceDelegate;
m_vkInstanceHandle = vkInstanceHandle;
}
~VkInstance() => Dispose(false);
private void Dispose(bool disposing) {
if (m_isDisposed) {
return;
}
else {
if (disposing) {
// no managed resources to free...
}
m_vkDestroyInstanceDelegate(m_vkInstanceHandle, IntPtr.Zero);
m_isDisposed = true;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
public sealed class VkUtf8String : IDisposable
{
public static VkUtf8String New(string value) => new VkUtf8String(value);
private readonly IntPtr m_handle;
#if (DEBUG)
private readonly string m_value;
#endif
private bool m_isDisposed;
public IntPtr Handle {
get {
if (m_isDisposed) {
return IntPtr.Zero;
}
else {
return m_handle;
}
}
}
#if (DEBUG)
public string Value {
get {
if (m_isDisposed) {
return null;
}
else {
return m_value;
}
}
}
#endif
private unsafe VkUtf8String(string value) {
if (value == null) {
m_handle = IntPtr.Zero;
}
else {
value = (value + char.MinValue);
var length = value.Length;
var maxByteCount = Encoding.UTF8.GetMaxByteCount(length);
var valueCopyHandle = Marshal.AllocHGlobal(maxByteCount);
var valueCopySpan = new Span<byte>(valueCopyHandle.ToPointer(), maxByteCount);
Encoding.UTF8.GetBytes(value, valueCopySpan);
m_handle = valueCopyHandle;
}
m_isDisposed = false;
#if (DEBUG)
m_value = value;
#endif
}
~VkUtf8String() => Dispose(false);
private void Dispose(bool disposing) {
if (m_isDisposed) {
return;
}
else {
if (disposing) {
// no managed resources to free...
}
Marshal.FreeHGlobal(m_handle);
m_isDisposed = true;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#if (DEBUG)
public override string ToString() => Value?.Substring(0, (Value.Length - 1));
#endif
}
public sealed class VkUtf8StringArray : IDisposable
{
public static VkUtf8StringArray New(params string[] values) => new VkUtf8StringArray(values);
private readonly int m_count;
private unsafe readonly IntPtr* m_handle;
private bool m_isDisposed;
public int Count => m_count;
public unsafe IntPtr* Handle {
get {
if (m_isDisposed) {
return null;
}
else {
return m_handle;
}
}
}
private unsafe VkUtf8StringArray(string[] values) {
if ((null == values) || (0 == values.Length)) {
m_count = 0;
m_handle = null;
}
else {
var count = values.Length;
var handle = ((IntPtr*)Marshal.AllocHGlobal(Unsafe.SizeOf<IntPtr>() * count));
for (var i = 0; (i < count); i++) {
handle[i] = VkUtf8String.New(values[i]).Handle;
}
m_count = count;
m_handle = handle;
}
m_isDisposed = false;
}
~VkUtf8StringArray() => Dispose(false);
private unsafe void Dispose(bool disposing) {
if (m_isDisposed) {
return;
}
else {
if (disposing) {
// no managed resources to free...
}
if (null != m_handle) {
for (int i = 0; (i < m_count); i++) {
Marshal.FreeHGlobal(m_handle[i]);
}
Marshal.FreeHGlobal(new IntPtr(m_handle));
}
m_isDisposed = true;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
public enum VkInstanceCreateFlags
{
VK_NONE = 0,
}
public enum VkResult
{
VK_SUCCESS = 0,
}
public enum VkStructureType
{
VK_STRUCTURE_TYPE_APPLICATION_INFO = 0,
VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1,
}
[StructLayout(LayoutKind.Sequential)]
public struct VkApplicationInfo
{
public static VkApplicationInfo New(VkUtf8String applicationName, VkUtf8String engineName) => new VkApplicationInfo(applicationName.Handle, engineName.Handle);
public VkStructureType sType;
public IntPtr pNext;
public IntPtr pApplicationName;
public int applicationVersion;
public IntPtr pEngineName;
public int engineVersion;
public int apiVersion;
private VkApplicationInfo(IntPtr applicationName, IntPtr engineName) {
sType = VkStructureType.VK_STRUCTURE_TYPE_APPLICATION_INFO;
pNext = IntPtr.Zero;
pApplicationName = applicationName;
applicationVersion = VkAccessor.MakeVersion(1, 1, 0);
pEngineName = engineName;
engineVersion = VkAccessor.MakeVersion(1, 1, 0);
apiVersion = VkAccessor.MakeVersion(1, 1, 0);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct VkInstanceCreateInfo
{
public unsafe static VkInstanceCreateInfo New(VkApplicationInfo* applicationInfo, VkUtf8StringArray enabledLayerNames, VkUtf8StringArray enabledExtensionNames) => new VkInstanceCreateInfo(
applicationInfo,
enabledLayerNames.Count,
enabledLayerNames.Handle,
enabledExtensionNames.Count,
enabledExtensionNames.Handle
);
public VkStructureType sType;
public IntPtr pNext;
public VkInstanceCreateFlags flags;
public unsafe VkApplicationInfo* pApplicationInfo;
public int enabledLayerCount;
public unsafe IntPtr* ppEnabledLayerNames;
public int enabledExtensionCount;
public unsafe IntPtr* ppEnabledExtensionNames;
public unsafe VkInstanceCreateInfo(VkApplicationInfo* applicationInfo, int enabledLayerCount, IntPtr* enabledLayerNames, int enabledExtensionCount, IntPtr* enabledExtensionNames) {
sType = VkStructureType.VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
pNext = IntPtr.Zero;
flags = VkInstanceCreateFlags.VK_NONE;
pApplicationInfo = applicationInfo;
this.enabledLayerCount = enabledLayerCount;
ppEnabledLayerNames = enabledLayerNames;
this.enabledExtensionCount = enabledExtensionCount;
ppEnabledExtensionNames = enabledExtensionNames;
}
}
}
</code></pre>
<p><strong>Example Usage:</strong></p>
<pre><code>using ByteTerrace.Vulkan.Api;
using System;
namespace TestBench
{
unsafe class Program
{
static void Main(string[] args) {
using (var applicationName = VkUtf8String.New("ByteTerrace Vulkan API"))
using (var engineName = VkUtf8String.New("N/A"))
using (var enabledLayers = VkUtf8StringArray.New(null))
using (var enabledExtensions = VkUtf8StringArray.New("VK_KHR_surface", "VK_KHR_win32_surface")) {
var applicationInfo = VkApplicationInfo.New(applicationName, engineName);
var instanceCreateInfo = VkInstanceCreateInfo.New(&applicationInfo, enabledLayers, enabledExtensions);
using (var vkAccessor = VkAccessor.New("vulkan-1.dll"))
using (var vkInstance = VkInstance.New(vkAccessor, ref instanceCreateInfo)) {
// TODO: Something useful once I bind more structures and methods...
}
}
Console.WriteLine("Done.");
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T21:34:54.553",
"Id": "223317",
"Score": "2",
"Tags": [
"c#",
"pointers",
"wrapper"
],
"Title": "Managed Vulkan API Wrapper (create/destroy an instance)"
} | 223317 |
<p>I have recently added a subroutine, CleanUpComments, to be called from multiple other subroutines to clean up comment positions and sizes. It works, but it is extremely slow taking about 10 seconds to run through ~200 comments. I have indicated the code section that accounts for the delay. (<code>wsPlan</code> is the code name of the sheet I'm working with and all of the <code>UF_***</code> variables are global.) I have tried it with comments visible and hidden with no apparent difference.</p>
<pre><code>Public Sub CleanUpComments()
' v8b1: Added to modify all comments to:
' (1) move and size with cells
' (2) be physically positioned near the cell to which they correspond
' (3) be optimally sized appropriate to the text within
' This was created by combining code posted on the following website:
' http://www.contextures.com/xlcomments03.html
Dim CellComments As Comment
Dim lngArea As Long
Dim varReply As Variant
'''vv This accounts for the 10 second delay *******************************************
For Each CellComments In wsPlan.Comments
With CellComments.Shape
.Placement = xlMoveAndSize
.Top = CellComments.Parent.Top + 5
.Left = CellComments.Parent.Offset(0, 1).Left + 5
.TextFrame.Characters.Font.Name = "Tahoma"
.TextFrame.Characters.Font.Size = 8
.TextFrame.AutoSize = True
End With
If CellComments.Shape.Width > 200 Then
lngArea = CellComments.Shape.Width * CellComments.Shape.Height
CellComments.Shape.Width = 150
CellComments.Shape.Height = (lngArea / 150) * 1.1
End If
Next CellComments
'''^^ This accounts for the 10 second delay *******************************************
UF_Caption = "SHOW COMMENTS"
UF_Label1Caption = "Do you wish to leave comments showing?"
UF_Height = 105
UF_TopOffset = 70
Call Updates_On
UF_QuestionYN.Show
varReply = UF_QuestionYN.Q_Reply
Unload UF_QuestionYN
Call Updates_Off
If varReply Then
Application.DisplayCommentIndicator = xlCommentAndIndicator
Else
Application.DisplayCommentIndicator = xlCommentIndicatorOnly
End If
End Sub
</code></pre>
<p>Is there a better (faster) approach to reset the comment positions and sizes? </p>
<p>(I tried this approach, checking if the values needed to be changed before I changed them, but it added another second!)</p>
<pre><code>'''vv
For Each CellComments In wsPlan.Comments
With CellComments.Shape
.Placement = xlMoveAndSize
If .Top - CellComments.Parent.Top <> 5 _
Then .Top = CellComments.Parent.Top + 5
If .Left - CellComments.Parent.Offset(0, 1).Left <> 5 _
Then .Left = CellComments.Parent.Offset(0, 1).Left + 5
If .TextFrame.Characters.Font.Name <> "Tahoma" _
Then .TextFrame.Characters.Font.Name = "Tahoma"
If .TextFrame.Characters.Font.Size <> 8 _
Then .TextFrame.Characters.Font.Size = 8
If .TextFrame.AutoSize <> True Then .TextFrame.AutoSize = True
If .Width > 200 Then
lngArea = .Width * .Height
.Width = 150
.Height = (lngArea / 150) * 1.1
End If
End With
Next CellComments
'''^^
</code></pre>
<p>I also have included my subroutine, Updates_Off, that I use to turn off updates and it is invoked in the calling routine so they are already off when CleanUpComments is called. (OBTW, the variables in this are all globals declared somewhere else.) I have also included my Updates_On to answer any questions about that.</p>
<p>Am I missing anything that I should be turning off that would speed this up?</p>
<p>Thanks.</p>
<pre><code>Public Sub Updates_Off()
' Turn off Screen updating
Application.ScreenUpdating = False
' Turn off Event tracking
Application.EnableEvents = False
' Check what calculation mode is in effect and set current to manual
CalcMode = Application.Calculation
If CalcMode = xlCalculationManual Then _
MsgBox "Starting mode is manual"
IterationMode = Application.Iteration
Iterations = Application.MaxIterations
Application.Calculation = xlCalculationManual
End Sub
Public Sub Updates_On()
' Turn on Screen updating
Application.ScreenUpdating = True
' Turn on Event tracking
Application.EnableEvents = True
' Reset Calculation mode
Application.Calculation = CalcMode
Application.Iteration = IterationMode
Application.MaxIterations = Iterations
If CalcMode = xlCalculationManual Then _
MsgBox "Reset to manual mode"
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T01:22:31.857",
"Id": "432706",
"Score": "0",
"body": "Since you need to iterate all comments, autosize them, re-adjust sizing, ...I'm not sure I'd call *slow* taking 50 milliseconds to do all that though.. Although if the comments are visible...do you get similar performance if `Updates_Off` is invoked before the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:38:31.013",
"Id": "432841",
"Score": "0",
"body": "@MathieuGuindon, I forgot to indicate that updates are already turned off before this is called. Clarified that in the OP. And comments are not visible, although I tried it both ways with no discernable difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:43:21.517",
"Id": "432845",
"Score": "0",
"body": "I'd be curious to see the code for `Updates_On`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:46:37.503",
"Id": "432849",
"Score": "0",
"body": "@MathieuGuindon, it's just the inverse of the Updates_Off. However, I can add it to the OP. These two are called multiple times in the master program to keep updates off except when I need for things like user form display."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:48:56.367",
"Id": "432854",
"Score": "0",
"body": "That's exactly what I thought. Having them in the OP would make feedback on these two procedures less speculative. Also `UF_***` variables are all globals as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:56:01.673",
"Id": "432860",
"Score": "0",
"body": "@MathieuGuindon, yes the UF_*** variables are global. (I've been working some parts of the code for years and my mind just skips over them!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:56:44.890",
"Id": "432862",
"Score": "0",
"body": "I can assure you that these variables literally jump at my face, screaming \"WHAT AM I DOING HERE?!\" ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:58:49.263",
"Id": "432868",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95644/discussion-between-rey-juna-and-mathieu-guindon)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T00:50:23.270",
"Id": "223320",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Speeding up formatting of all comments in a worksheet"
} | 223320 |
<p>I have a mapping application which takes string arguments in the form of string arrays. I parse these and then perform an action on the map. One of these is <code>MoveVertex</code> which lets the user pass in the name of an existing shape/feature on the map, the index of the vertex to move, and a new x,y location to move that vertex to. </p>
<p>I'm currently getting thousands of these in a row, all for the same shape. It takes anywhere from 3-10ish seconds to parse them all and complete the action. I'm looking for any improvements I could make.</p>
<p>One thing I did so far was stop the map from refreshing every time a vertex is moved. This helped a bit, but it's still slow.</p>
<p>Example of the string[] commands being sent:</p>
<pre><code>command[0] = "move" //command type
command[1] = "vertex" //what to move
command[2] = "testLine[10]" //move the vertex at index 10 in testLine's list of vertices
command[3] = "x" //new x value for the vertex
command[4] = "y" //new y value for the vertex
</code></pre>
<p>Here's the function that does the work:</p>
<pre><code>public static void MoveVertex(string[] command, Layer inMemoryFeatureLayer, Map map)
{
int index; //this will be the index of the vertex in the collection of vertices of the shape
string featureName; //name of the shape/feature that has the vertex to move
if (command.Length < 5) //can't be more than 5 parameters
{
return;
}
try
{
if (!command[2].Contains('[')) //if it doesn't contain brackets which contain an index of the vertices
{
return;
}
const string pattern = @"\[(.*?)\]";
var query = command[2];
var matches = Regex.Matches(query, pattern); //Gets anything inside the brackets
index = Convert.ToInt32(matches[0].Groups[1].Value); //should be an int
featureName = command[2].Substring(0, command[2].IndexOf('[')).ToUpper(); //everything before the bracket is the name of the object
}
catch (Exception ex)
{
return;
}
if (!double.TryParse(command[3], out double longitude) || !double.TryParse(command[4], out double latitude))
{
return;
}
try
{
BaseShape shape;
inMemoryFeatureLayer.Open(); //make sure the layer is open
if (inMemoryFeatureLayer.Name.Contains(GlobalVars.LineType)) if it's the layer holding line shapes
{
shape = (LineShape)inMemoryFeatureLayer.FeatureSource.GetFeatureById(featureName, ReturningColumnsType.NoColumns).GetShape();
((LineShape)shape).Vertices[index] = new Vertex(longitude, latitude); //set the vertex to a new location
}
else //it's the layer holdilng polygone shapes
{
shape = (PolygonShape)inMemoryFeatureLayer.FeatureSource.GetFeatureById(featureName, ReturningColumnsType.NoColumns).GetShape();
((PolygonShape)shape).OuterRing.Vertices[index] = new Vertex(longitude, latitude); //set the vertex to a new location
}
inMemoryFeatureLayer.EditTools.BeginTransaction();
inMemoryFeatureLayer.EditTools.Update(shape);
inMemoryFeatureLayer.EditTools.CommitTransaction();
map.Refresh(); //this won't happen because I suspend refreshes beforehand
}
catch (Exception ex)
{
//log it
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T05:48:10.687",
"Id": "432713",
"Score": "9",
"body": "_if (command.Length < 5) //can't be more than 5 parameters_ - you mean **less**?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:05:17.960",
"Id": "432720",
"Score": "16",
"body": "Have you tried profiling your code? Executing the parsing part of the code a thousand times takes about 1-2 ms on my system, and while the suggestions here make that roughly 20% faster, that's not going to make much of a difference overall."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:39:48.373",
"Id": "432733",
"Score": "5",
"body": "Pieter's sugestion is good. Maybe GetFeatureById is a bottleneck, or maybe it's really fast; we can't tell from this snippet, but you can tell by using Visual Studio's code profiling tools."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:28:02.443",
"Id": "432791",
"Score": "2",
"body": "@t3chb0t yup good catch thanks. I did profile my code after the suggestions here and found out all the third party map control's function calls were taking the longest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:00:55.593",
"Id": "432799",
"Score": "7",
"body": "This is another good example of how you should not optimize your code ;-) First measure, than optimize when you know exactly what needs to be optimized. All these reviews are virtually in vain because they do not signifficantly improve your code but a little bit of its readability and as far as performance is concerned, irrelevant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T22:01:11.603",
"Id": "432879",
"Score": "4",
"body": "You might see an improvement if you use compiled regular expressions instead of interpreted. Check out this article https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices#interpreted-vs-compiled-regular-expressions which shows how to use the `RegexOptions.Compiled` option"
}
] | [
{
"body": "<p>One possible place you can improve performance is here:</p>\n\n<pre><code>const string pattern = @\"\\[(.*?)\\]\";\nvar query = command[2];\nvar matches = Regex.Matches(query, pattern); //Gets anything inside the brackets\nindex = Convert.ToInt32(matches[0].Groups[1].Value); //should be an int\n\nfeatureName = command[2].Substring(0, command[2].IndexOf('[')).ToUpper(); \n</code></pre>\n\n<p>You're parsing the same string twice. Using the <code>Split</code> method for such a simple parsing would probably improve that:</p>\n\n<pre><code>var separators = new char[] { '[', ']' };\nvar parts = command[2].Split(separators,StringSplitOptions.RemoveEmptyEntries);\nindex = Convert.ToInt32(parts[1]);\nfeatureName = parts[0].ToUpper(); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T02:44:08.697",
"Id": "223325",
"ParentId": "223321",
"Score": "12"
}
},
{
"body": "<p>You should take a look at the possibility to name groups in regex patterns; your match pattern can then be a oneliner:</p>\n\n<pre><code> const string pattern = @\"^(?<name>\\w+)\\[(?<index>\\d+)\\]$\";\n\n Match match = Regex.Match(command[2], pattern);\n\n if (match.Success)\n {\n string featureName = match.Groups[\"name\"].Value;\n int index = int.Parse(match.Groups[\"index\"].Value);\n\n try\n {\n // TODO: use the information\n }\n catch (Exception ex)\n {\n // TODO: Notify consumer\n }\n }\n else\n {\n // TODO: notify consumer\n }\n</code></pre>\n\n<p>As shown, the pattern for the index is changed from <code>.*?</code> to <code>\\d+</code> which is more precise and hence more efficient because it doesn't need the non-greedy operator <code>?</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>if (command.Length < 5) //can't be more than 5 parameters\n{\n return;\n}\n</code></pre>\n</blockquote>\n\n<p>When meeting an error you just return from the method without doing anything. Shouldn't you notify the consumer/log the situation/condition?</p>\n\n<hr>\n\n<p>You don't write from where the <code>command</code> information comes from, but if you read it from a text file, I think I would parse the string information while reading the file and then create a set of command objects defined as something like:</p>\n\n<pre><code>public class CommandInfo\n{\n public string Action { get; set; }\n public string Type { get; set; }\n public string ListName { get; set; }\n public int Index { get; set; }\n public Point Vertex { get; set; }\n}\n</code></pre>\n\n<p>Or whatever is suitable for your needs</p>\n\n<p>This may not improve performance but it is more \"type safe\" than just dispatching an array of strings around.</p>\n\n<hr>\n\n<p>According to efficiency:</p>\n\n<p>You write, that you have thousands of commands for the same shape, but it seems that you requery a set of shapes <code>inMemoryFeatureLayer.FeatureSource</code> for every command. Whouldn't it be more efficient if you group the commands for each shape, so that you only have to query for the shape once and then can execute all the related commands?</p>\n\n<hr>\n\n<p><strong>TIP:</strong> If you are using Visual Studio 2019, you get help from intellisense and color coding if you compose the regex pattern directly in the call to <code>Match</code> or <code>Matches</code>:</p>\n\n<pre><code>Match match = Regex.Match(command[2], @\"^(?<name>\\w+)\\[(?<index>\\d+)\\]$\");\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>FYI: there has been some discussion in the comments to various answers about which approach is the most efficient, when extracting the name of the list of vertices and the index from a string like <code>command[2] = \"testLine[10]\"</code> => <code>\"testLine\" and 10</code>. So I ran some comparison tests for the following methods:</p>\n\n<pre><code>const string pattern = @\"^(?<name>\\w+)\\[(?<index>\\d+)\\]$\";\n\nRegex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.Singleline);\nvoid DoRegex()\n{\n foreach (string item in data)\n {\n Match match = regex.Match(item);\n if (match.Success)\n {\n string featureName = match.Groups[\"name\"].Value;\n int index = int.Parse(match.Groups[\"index\"].Value);\n testResult += index ^ featureName.GetHashCode();\n }\n else\n {\n throw new InvalidOperationException(\"DoRegex match\");\n }\n }\n}\n\nvoid DoSplitString()\n{\n foreach (string item in data)\n {\n string[] split = item.Split('[', ']');\n string featureName = split[0];\n if (int.TryParse(split[1], out int index))\n testResult += index ^ featureName.GetHashCode();\n else\n throw new InvalidOperationException(\"DoSplitString TryParse\");\n }\n}\n\nvoid DoIndexOf()\n{\n foreach (string item in data)\n {\n int endIndex = item.IndexOf('[');\n string featureName = item.Substring(0, endIndex);\n if (int.TryParse(item.Substring(endIndex + 1, item.Length - endIndex - 2), out int index))\n testResult += index ^ featureName.GetHashCode(); \n else\n throw new InvalidOperationException(\"DoIndexOf TryParse\");\n }\n}\n\nvoid DoStringBuilder()\n{\n foreach (string item in data)\n {\n string featureName = \"\";\n int index = 0;\n char stop = '[';\n\n StringBuilder builder = new StringBuilder();\n foreach (char ch in item)\n {\n if (ch == stop)\n {\n if (stop == '[')\n {\n featureName = builder.ToString();\n stop = ']';\n }\n else\n {\n if (int.TryParse(builder.ToString(), out index))\n testResult += index ^ featureName.GetHashCode();\n else\n throw new InvalidOperationException(\"DoStringBuilder TryParse\");\n break;\n }\n builder.Clear();\n }\n else\n {\n builder.Append(ch);\n }\n }\n }\n}\n</code></pre>\n\n<p>I use a compiled instance for <code>Regex</code>, which reduces the duration for this test with about 600 ms compared to an uncompiled version - when it is compiled once and the same instance is reused for all tests. <code>testResult</code> serves as a simple validation.</p>\n\n<p>The dataset is generated as (the data creation is not part of the measures):</p>\n\n<pre><code>const int testCount = 2000;\nconst int randSeed = 5;\nRandom rand = new Random(randSeed);\nIList<string> data;\nint testResult = 0;\n\nIEnumerable<string> CreateData(int count)\n{\n string chars = \"abcdefghijklmnopqrstuwxyz\";\n\n for (int i = 0; i < count; i++)\n {\n yield return $\"{(string.Join(\"\", Enumerable.Range(1, rand.Next(10, 30)).Select(n => chars[rand.Next(0, chars.Length)])))}[{rand.Next(0, 100)}]\";\n }\n}\n\n\npublic void Run()\n{\n data = CreateData(1000).ToList();\n ...\n</code></pre>\n\n<p>I ran each method 2000 times in order to measure some realistic averages with the same dataset with 1000 strings for all measures. The result is rather disappointing for the <code>Regex</code> approach:</p>\n\n<pre><code>testResult: 2052366768\nResult for test DoSplitString:\nIterations: 2000\nAverage: 0,34116 Milliseconds\nMin: 0,29660 Milliseconds\nMax: 1,17520 Milliseconds\nTotal: 682,31420 Milliseconds\n\n\ntestResult: 2052366768\nResult for test DoRegex:\nIterations: 2000\nAverage: 1,69160 Milliseconds\nMin: 1,48380 Milliseconds\nMax: 6,16170 Milliseconds\nTotal: 3383,19930 Milliseconds\n\n\ntestResult: 2052366768\nResult for test DoIndexOf:\nIterations: 2000\nAverage: 0,22634 Milliseconds\nMin: 0,19200 Milliseconds\nMax: 0,93010 Milliseconds\nTotal: 452,68460 Milliseconds\n\ntestResult: 2052366768\nResult for test DoStringBuilder:\nIterations: 2000\nAverage: 0,36898 Milliseconds\nMin: 0,33100 Milliseconds\nMax: 1,36560 Milliseconds\nTotal: 737,96910 Milliseconds\n</code></pre>\n\n<p><code>IndexOf</code> is by far the most efficient</p>\n\n<hr>\n\n<p>As t3chb0t writes in his comments, the regex pattern can be optimized significantly to </p>\n\n<pre><code>const string pattern = @\"^(?<name>.+)\\[(?<index>.+)\\]$\";\n\nstatic readonly Regex regex = new Regex(pattern, RegexOptions.Compiled);\n</code></pre>\n\n<p>Running the test with this pattern gives this result:</p>\n\n<pre><code>testResult: 2052366768\nResult for test DoRegex:\nIterations: 2000\nAverage: 0,97967 Milliseconds\nTruncated Average: 0,97777 Milliseconds\nMin: 0,84020 Milliseconds\nMax: 4,91550 Milliseconds\nTotal: 1959,33570 Milliseconds\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T06:41:37.310",
"Id": "432719",
"Score": "1",
"body": "I see you've changed the evil wildcard match `.*?` to `\\d+` - it'd be good to mention that this is more efficient and also more exact. I believe this is the [catastrophic backtracking](https://stackoverflow.com/questions/29751230/regex-pattern-catastrophic-backtracking) or [here](https://community.appway.com/screen/kb/article/checking-strings-avoiding-catastrophic-backtracking-1482810891360)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:45:31.777",
"Id": "432723",
"Score": "1",
"body": "About regex coloring; this is also possible for any string when you comment it with jetbrains helpers; see [Regular Expressions Assistance](https://www.jetbrains.com/help/resharper/Regular_Expressions_Assistance.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:37:22.467",
"Id": "432896",
"Score": "1",
"body": "Your `DoIndexOf` is cheating because `DoRegex` must do more work as you put such constraints on it as `\\w+` which the former does not do. When you use `(.+)` the regex becomes rougly 300ms faster for 1mln strings. Alternatively add a validation loop that would work the same as `\\w+` basically in every other method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:44:58.433",
"Id": "432899",
"Score": "1",
"body": "The fastest and most fair regex is `@\"^(.+)\\[(.+)\\]\"` created like this `new Regex(pattern, RegexOptions.Compiled);` which additionaly improves its performance by another 300ms as `SingleLine` adds a check agianst `\\n`. Removing the `match.Success` improves the regex method by another 30-50ms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:49:46.720",
"Id": "432900",
"Score": "0",
"body": "You also should remove any additional code like `Parse` or `TryParse` (which are by the way inconsistent accross the tests). We know they are numbers and we only want to measure their extraction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:58:59.507",
"Id": "432901",
"Score": "0",
"body": "Nice, I copied your pattern and it turns out that adding named groups improves regex but another 100ms on my machine ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:59:07.073",
"Id": "432902",
"Score": "0",
"body": "@t3chb0t: I think it's interesting to measure the entire process from `string` to `string * int`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T07:04:53.887",
"Id": "432903",
"Score": "1",
"body": "If you made a second answer with the comparative review, you would have gotten 2 +1's from me :p"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T06:01:55.857",
"Id": "223330",
"ParentId": "223321",
"Score": "18"
}
},
{
"body": "<p>Why would you want to use Regular Expressions anyway if the base format of the string is always the same?</p>\n\n<p><code>Name[Number]</code> seems like an easy pattern. Just iterate through the characters one by one and store all characters in the first string until you reach the first bracket. Then store the numbers in the second string (until you reach the closing bracket). Getting rid of the Regular Expression should make it faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T11:44:56.080",
"Id": "223350",
"ParentId": "223321",
"Score": "7"
}
},
{
"body": "<h3>Hash all string constants</h3>\n\n<p>I'm presuming you only have a limited number of keywords (\"move\", \"vertex\" etc.). Hash all of those with something fast - CRC32 is perfectly adequate.</p>\n\n<p>Split the string into space-separated tokens, as usual, and calculate the hash of the first and second tokens. Then you just need to compare the calculated hash with the hashes of the available commands. If you have a large number of keywords, this can yield very significant improvements.</p>\n\n<h3>Ditch the \"Contains\" and the regex</h3>\n\n<p>To check whether it contains a bracket, the code has to scan over the entire variable name. It then scans the entire string again to find the start and end of the brackets. And the processing necessary for the regex pattern-matching is not fast.</p>\n\n<p>All you actually need is \"IndexOf\". If there's no bracket, IndexOf returns -1. If there's a bracket, you've found the start of the number. A second \"IndexOf\" to look for the closing bracket, starting at that index, will give you the end (or -1 if there isn't a closing bracket). Then all you need to do is copy the substring.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:51:45.797",
"Id": "432794",
"Score": "1",
"body": "Don't ditch one thing to replace it with a another similar, albeit improved thing. Go with Florian's approach of parsing in a single pass instead. https://en.wikipedia.org/wiki/Out_of_the_frying_pan_into_the_fire"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:59:25.300",
"Id": "432798",
"Score": "1",
"body": "@dfhwze I'd disagree: I expect making a readable and efficient version of Florian's suggestion will be much more effort than throwing together a pair of `IndexOf` and `Substring` calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:01:29.123",
"Id": "432800",
"Score": "0",
"body": "@VisualMelon it all boils down how crucial performance is. I figured the OP holds performance very high, so Florian's approach is the superior one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:05:41.847",
"Id": "432805",
"Score": "0",
"body": "@dfhwze I don't think that is a given: I'd personally expect this one to be faster, because of the added overheads of dealing with a `StringBuilder` (or similar) implied in Florin's approach, and substring and indexof have dodgy implementations underneath with special support for ASCII and such. If I can be bothered, I might put a benchmark together later (of course anyone else would be welcome to do so before me) since that's as close to an answer as we'll get without the rest of the OP's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:08:29.617",
"Id": "432806",
"Score": "0",
"body": "(Of course, no-one would do that, because it is silly; they would loop through to find the brackets and then use `SubString`, at which point the question is whether a loop is more efficient than `IndexOf` or not (which I'd expect depends on a few things))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:16:29.313",
"Id": "432813",
"Score": "0",
"body": "@VisualMelon It seems combining IndexOf and Substring is a microsoft best practice indeed: similar example https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/ColorConverter.cs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:57:39.527",
"Id": "432818",
"Score": "0",
"body": "@dfhwze well, it's a practice, whether it's the _best_ one is an entirely different topic. asp.net-core has different _best_ practices and there regex is a friend [asp.net-core search regex](https://github.com/aspnet/AspNetCore/search?l=C%23&q=regex)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T17:00:40.110",
"Id": "432820",
"Score": "0",
"body": "@t3chb0t Well, perhaps we are throwing ourselves into the rabbit hole here. I am sure all answers here are fine :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T23:08:43.893",
"Id": "432882",
"Score": "0",
"body": "@dfhwze Florian's approach makes the slightly naive assumption that copying N characters takes the same time as N copies of a single character. This is not true for almost any architecture, especially if your architecture can do DMA copies. Of course you'd need to check with profiling, but it's not clear-cut"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:46:48.497",
"Id": "223360",
"ParentId": "223321",
"Score": "4"
}
},
{
"body": "<p>The first obvious optimization would be to not call <code>Regex.Matches(string, string)</code> which compiles the regular expression <strong>every single time</strong>. Compiling the regex is an expensive operation.</p>\n\n<p>Instead, create a <code>Regex</code> (which compiles the expression exactly once) and keep it around during your several thousand invocations. That should by itself do the trick (because, well, a few <em>thousand</em> matches is really no challenge to a modern computer).</p>\n\n<p>Also, if you are desperate, you could do without regex. You could switch by string length, which only leaves you to distinguish between <code>x</code> and <code>y</code> (all others have distinct string lengths).<br>\nOr, you could look at the first character (or the first, and another one, if you maybe have more keywords). Some minimal perfect hash generators (I forgot which one, gperf maybe?) apply that trick for very quickly matching a known set of keywords. Brackets are only possible in a particular context, so you don't really need to match for them all the time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:14:04.397",
"Id": "223404",
"ParentId": "223321",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223330",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T01:03:45.833",
"Id": "223321",
"Score": "18",
"Tags": [
"c#",
"performance",
"parsing",
"regex"
],
"Title": "Speeding up thousands of string parses"
} | 223321 |
<p>I am learning about OOP so it would be great if you can give me feedback on how to improve my code and OOP design.</p>
<p>This is a currency converter. Firstly, it will call a method to add 2 currencies and commission information and then it converts to another currency whose input is source currency and amount:</p>
<pre><code>import pytest
class Bank:
def addRate(self,first, second, rate):
self.first_currency = first
self.second_currency = second
self.rate = rate
def addCommission(self,commision):
self.commission = commision
def convert(self, currency, amount):
if currency == self.first_currency:
return (amount / self.rate) * (1-self.commission)
else:
return (amount * self.rate) * (1-self.commission)
@pytest.fixture()
def bank():
return Bank()
def test_Bank_addRate(bank):
bank.addRate("USD","GBP",2)
assert bank.first_currency == "USD"
assert bank.second_currency == "GBP"
assert bank.rate == 2
def test_Bank_addCommision(bank):
bank.addCommission(0.015)
assert bank.commission == 0.015
def test_Bank_convert(bank):
bank.addRate("USD", "GBP", 2)
bank.addCommission(0.015)
assert bank.convert("USD", 100) == 49.25
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T13:12:47.990",
"Id": "432773",
"Score": "6",
"body": "Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T13:14:05.347",
"Id": "432775",
"Score": "1",
"body": "Your code defines a `Currency` class but it doesn’t seem to be using it — what is its purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:02:49.210",
"Id": "432802",
"Score": "0",
"body": "@KonradRudolph, thank you. I removed it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:04:42.257",
"Id": "432804",
"Score": "0",
"body": "@juhist Thank you for your advice. I agree but now I am learning about OOP so I want to focus on it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:08:37.743",
"Id": "432808",
"Score": "2",
"body": "Welcome to Code Review! It appears you have modified the code slightly, mostly in response to Konrad's comment above. After getting an answer you should not change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:09:06.493",
"Id": "432809",
"Score": "0",
"body": "@Nguyen You should consider creating a class for storing currency amounts. I mean, surely you don't want to use inaccurate floating-point numbers to store monetary amounts! That would be a good starting point for learning OOP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T23:43:09.127",
"Id": "432884",
"Score": "0",
"body": "@juhist Thank you. I will consider your advice as I am re-implement the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:24:10.253",
"Id": "432950",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thank you for giving information :) I will create new question and linking back to this one as reference"
}
] | [
{
"body": "<p>First: welcome to CodeReview! I hope that you get good feedback.</p>\n\n<p>About your code. Your usage of Python is not terrible; most of your problems are conceptual, about the decisions you've made about your class. Looking at the method signatures from the outside, one would guess that <code>addRate()</code> can be called multiple times per single <code>Bank</code> instance, and that <code>convert</code> would then allow for any currency to be converted. That isn't the case; instead, your \"Bank\" class is actually closer to an \"ExchangeRate\" class.</p>\n\n<p>There are two ways to go, here. Either make your class an ExchangeRate, in which case</p>\n\n<ul>\n<li>you need to rename the class</li>\n<li><code>convert</code>, rather than accepting the name of a currency, should perhaps accept a <code>forward</code> boolean. Or, if you want to keep passing the name of a currency, it's important to make the argument name more clear, i.e. <code>dest_currency</code>.</li>\n<li>Rename your addCommission to setCommission. \"add\" implies having more than one.</li>\n<li>Rename your addRate to setRate. \"add\" implies having more than one.</li>\n</ul>\n\n<p>Or, keep a \"Bank\" class, in which case:</p>\n\n<ul>\n<li>you need to change the way that you store your exchange rates, probably to a dictionary-based system instead of a single float member</li>\n<li>convert would accept both a source and destination currency</li>\n<li>addRate's signature would stay the same, but its contents would change to use your dict.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:19:30.597",
"Id": "432962",
"Score": "0",
"body": "Hi, I re-implement my code and created follow-up question here. Can you take a look ? https://codereview.stackexchange.com/questions/223411/simple-python-oop-currency-converter"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T02:44:04.150",
"Id": "223324",
"ParentId": "223322",
"Score": "11"
}
},
{
"body": "<p>There are a few <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smells</a> in your code.</p>\n\n<ol>\n<li><p>Currency exchange rates are usually not inverses of each other. Your code assumes that GBP / USD is one number, and that number is a property of your Bank object. That is a smell, because a. banks don't own exchange rates, and b. there should at least be a GBP->USD rate as well as the USD->GBP rate.</p></li>\n<li><p>What if you want to do GBP->EUR? do you create another bank?</p></li>\n<li>In real life, currency exchange rates change over time. How will your bank object reflect that?</li>\n<li>Your bank is mutable (this could be part of the answer to the question above, but then the next question is Who will change the bank if the exchange rates change?). Mutable means: when a method takes a bank as parameter, there is nothing to stop it from saying bank.addRate(\"RUB\", \"YEN\", 1.71), and that would change the original object, which is a. bad, and b. in any case not what you'd expect an addRate method to do.</li>\n<li>Your code is striving for symmetry. Is that a good thing? You might have an Amount(amount, currency) class one day, and then your bank would probably be asked to bank.convertTo(amout, targetCurrency) which is distinctly not symmetric.</li>\n</ol>\n\n<p>A typical mistake programmers new to oop often make is to model structures instead of behaviours. The tendency is to look at the bones of what you want to model, not at the muscles. Hence you come up with a Bank class, because a bank is a thing, and a Currency class, because a currency is a thing, and then it's quickly unclear what these classes actually are supposed to do. Try to think more in terms of What is being done, and less in terms of Who is doing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T00:17:29.090",
"Id": "432885",
"Score": "0",
"body": "Thank you for anwering me. Let me answer your question:\n\n1. I will change Bank class to ExchangeRate.\n I will create a dictionary rate = {\"GBPUSD\": 2, \"USDGBP: 0.5}\n\n2. So you mean I should create a dictionary for rate ?\nSo I don't have to call another ExchangeRate everytime ?\n\n3. I think I should add method: changeRate\n\n4. I should raise exception as soon as addRate was called 2nd time for same pair currency \nand add new method: changeRate() which can be called multiple time\n\n5. I don't quite understand the point. I think I should create a class for storing currency amounts"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:19:42.030",
"Id": "432963",
"Score": "0",
"body": "Hi, I re-implement my code and created follow-up question here. Can you take a look ? https://codereview.stackexchange.com/questions/223411/simple-python-oop-currency-converter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:50:16.680",
"Id": "433003",
"Score": "0",
"body": "4. My point is that rates change over time, so you don't want them to be constant, but clients should not be allowed to change them, so you want them to be immutable. Think about how to solve this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:29:12.143",
"Id": "223363",
"ParentId": "223322",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "223324",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T01:31:47.820",
"Id": "223322",
"Score": "7",
"Tags": [
"python",
"beginner",
"object-oriented",
"unit-conversion"
],
"Title": "Simple OOP currency converter"
} | 223322 |
<p>I created a wordsearch puzzle generator in C#. It's not a playable game, and it doesn't solve puzzles.</p>
<p>Find the entire codebase here: <a href="https://repl.it/@blonkm/wordsearch" rel="nofollow noreferrer">https://repl.it/@blonkm/wordsearch</a></p>
<p>I would like to optimize it so the puzzles can be as small as possible, with as much overlapping words as possible.</p>
<p>Currently I just move around words at random until they fit:</p>
<pre><code> public void Solve() {
foreach (Word w in candidate.words) {
int n = 0;
bool done = false;
while (!done) {
double f = board.Fitness(w);
if (w.errors == 0) {
done = true;
Log.Post(w + " can be placed");
this.score += f;
this.percentageSolved++;
board.PlaceWord(w);
}
else
board.Reposition(w);
if (n > maxIterations) {
Log.Post(w + " cannot be placed");
this.score = 0.0;
done = true;
}
n++;
}
}
this.percentageSolved /= candidate.words.Count;
}
</code></pre>
<p>What would be an efficient and effective method? </p>
<p>Also, any improvements on code quality, organization and performance are welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T12:37:22.703",
"Id": "432763",
"Score": "0",
"body": "Word search puzzle generation is NP-hard in general, so there's likely no elegant algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T13:12:00.320",
"Id": "432771",
"Score": "2",
"body": "Where is the random part in the code you've posted? You should also add the problem description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:47:46.370",
"Id": "443568",
"Score": "0",
"body": "@t3chb0t The random is happening inside board.Reposition(w) which finds a new position and direction for the word. I don't know what you mean by problem description. This is not a school assignment or something like that, just something I wanted to try. So, my problem description=\"make a word search puzzle\"."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T02:06:54.097",
"Id": "223323",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Wordsearch puzzle generator"
} | 223323 |
<p>I have incoming data from an absolute rotary encoder. It is 24 bits wide. 12 bits are the number of turns and 12 bits are the angle.</p>
<p>I'm reading the data with an Arduino and sending it to the computer over a serial port. The most natural thing to do would be to combine all of the bits and send it as 3 bytes.</p>
<p>Splitting up the 3 bytes into 12 bits/12 bits at the computer in Python 3 feels unpythonic to me. Here is what I have so far:</p>
<pre><code>import struct
# fake message, H is header last 3 bytes are data
msg = b'H\x90\xfc\xf9'
header, bytes3 = struct.unpack('>c3s', msg)
print('bytes3 ', bytes3)
val = int.from_bytes(bytes3, 'big')
print('val ', val)
print('bin(val) ', bin(val))
upper12 = val >> 12
print('bin(upper12)', bin(upper12))
lower12 = val & 0b000000000000111111111111
print('bin(lower12)', bin(lower12))
</code></pre>
<p>which gives console output of</p>
<pre><code>bytes3 b'\x90\xfc\xf9'
val 9501945
bin(val) 0b100100001111110011111001
bin(upper12) 0b100100001111
bin(lower12) 0b110011111001
</code></pre>
<p>This code seems to work fine, but bitshifting (<code>val >> 12</code>) and bitwise anding (<code>val & 0b000...</code>) are a little wonky. Also it feels funny to specify Big Endian twice: first in the <code>struct.unpack</code> format string and second in <code>int.from_bytes</code>. </p>
<p>Is there a more elegant way to achieve this? </p>
<h1>Update: timing</h1>
<p>I'm still on the fence on which technique is most Pythonic. But I did time 3 techniques: </p>
<ol>
<li>original technique above</li>
<li>technique by AlexV with overlapping unsigned 16 bit integers</li>
<li>change comms protocol to send a padded 4 byte unsigned integer that <code>struct</code> can convert directly to integer</li>
</ol>
<p></p>
<pre><code>import struct
import time
import random
import timeit
def gen_random_msg(nbyte = 3):
# make a n byte message with header 'H' prepended
data = random.randint(0, 2**12-1)
data = data.to_bytes(nbyte, 'big')
msg = b'H' + data
return msg
def original_recipe():
msg = gen_random_msg(3)
header, bytes3 = struct.unpack('>c3s', msg)
val = int.from_bytes(bytes3, 'big')
upper12 = val >> 12
lower12 = val & 4095 # 4095 = 2**12-1
def overlap16bits():
msg = gen_random_msg(3)
header, val = struct.unpack('>cH', msg[0:-1])
upper12 = val >> 4
lower12 = struct.unpack('>H', msg[2:])[0] & 0xfff
def fourbyte():
msg = gen_random_msg(4)
header, val = struct.unpack('>cI', msg)
upper12 = val >> 12
lower12 = val & 4095 # 4095 = 2**12-1
niter = int(1e6)
t0 = time.time()
for i in range(niter): gen_random_msg(3)
t1 = time.time()
for i in range(niter): gen_random_msg(4)
t2 = time.time()
for i in range(niter): original_recipe()
t3 = time.time()
for i in range(niter): overlap16bits()
t4 = time.time()
for i in range(niter): fourbyte()
t5 = time.time()
gentime3 = t1-t0
gentime4 = t2-t1
original_time = t3-t2
overlap_time = t4-t3
fourbyte_time = t5-t4
print('gentime3: ', gentime3, '. gentime4: ', gentime4)
print ('original recipe: ', original_time - gentime3)
print ('overlap 16 bits: ', overlap_time - gentime3)
print ('four bytes: ', fourbyte_time - gentime4)
</code></pre>
<p>this has console output:</p>
<pre><code>gentime3: 3.478888988494873 . gentime4: 3.4476888179779053
original recipe: 1.3416340351104736
overlap 16 bits: 1.435237169265747
four bytes: 0.7956202030181885
</code></pre>
<p>It takes more time to generate 1M dummy msg than it does to process the bytes. The fastest technique was to change the comms spec and pad the 3 bytes to make a 4 byte unsigned integer. The speed up was good (approx 2x) for "fourbytes", but requires changing the communications specification. At this point I think it comes down to personal preference as to which algorithm is the best.</p>
| [] | [
{
"body": "<p>You could unpack them twice into (overlapping) unsigned shorts of 16bit and shift/mask them accordingly.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>upper12 = struct.unpack(\">H\", msg[1:-1])[0] >> 4\nlower12 = struct.unpack(\">H\", msg[2:])[0] & 0xFFF\n</code></pre>\n\n<p>Telling Python to interpret them as short integers helps you to get rid of <code>int.from_bytes</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T06:05:54.063",
"Id": "223331",
"ParentId": "223327",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223331",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T04:54:39.213",
"Id": "223327",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"bitwise"
],
"Title": "pythonic way to split bytes"
} | 223327 |
<p>I have been trying to write the md5 hashes for all files in a directory and its subdirectories to a file. Ideally, replicating the output of the Unix command <code>find . -type f -exec md5sum {} +</code> (i.e. two columns: lowercase hashes and relative file paths [with forward slashes] separated by a space and terminated only by a line feed).</p>
<p>With a lot of help from Mark Wragg, LotPings and others on stackoverflow, the following command appears to compute md5 hashes for all files in a directory and its subdirectories (including those files without file extensions and those with square brackets in the filename).</p>
<pre><code>(Get-FileHash -Algorithm MD5 -LiteralPath (Get-ChildItem -Recurse -File).fullname | ForEach-Object{"{0} {1}" -f $_.Hash.ToLower(),(Resolve-Path -LiteralPath $_.Path -Relative)} | Out-String) -replace '\r(?=\n)' -replace '\\','/' | Set-Content -NoNewline -Encoding ascii $ENV:USERPROFILE\Desktop\hashes.txt
</code></pre>
<p>The two uses of <code>-LiteralPath</code> seems to help with filenames containing square brackets and <code>(Get-ChildItem -Recurse -File).fullname</code> gets the full path of all nested files, including those without file extensions. The rest is just formatting.</p>
<p>Can any one tell me where I can find more information about <code>.fullname</code>? I've tried searching for it on Google but without any luck.</p>
<p>I had used <code>Get-ChildItem "*.*" -Recurse</code>, which gives full file paths but only for files with dots in the filename. Whereas, <code>Get-ChildItem "*" -Recurse</code> doesn't always give the full path for some reason (and returns both files and folders). Compare:</p>
<pre><code>Get-ChildItem "*.*" -Recurse | foreach-object { "$_" }
Get-ChildItem "*" -Recurse | foreach-object { "$_" }
</code></pre>
<p>The order of entries in the hashes file won't be the same as those from the Unix command but <code>compare-object</code> in PowerShell appears to ignore the order of lines, e.g. (<a href="https://serverfault.com/questions/5598/how-do-i-diff-two-text-files-in-windows-powershell">https://serverfault.com/questions/5598/how-do-i-diff-two-text-files-in-windows-powershell</a>)</p>
<pre><code>compare-object (get-content oldHashes.txt) (get-content newHashes.txt)
</code></pre>
<p>or </p>
<pre><code>diff (cat oldHashes.txt) (cat newHashes.txt)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T07:06:29.457",
"Id": "437479",
"Score": "1",
"body": "Why MD5 instead of SHA-256?"
}
] | [
{
"body": "<p>I rewrote your code from scratch how I would have written it myself. Maybe it can give you some ideas.</p>\n\n<pre><code>$lines = gci -Recurse -File | \n Get-FileHash -Algorithm MD5 | % { \n $unixPath = $_.Path -replace '\\\\','/'\n $hash = $_.Hash.ToLower()\n \"$hash $unixPath\" }\n\n$lines -join \"`n\" | \n Out-File -Encoding ascii -NoNewline $ENV:USERPROFILE\\Desktop\\hashes.txt\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><code>gci</code> is an alias for <code>Get-ChildItem</code>.</li>\n<li>I used <code>gci -File</code> to get files only.</li>\n<li><code>%</code> is an alias for <code>ForEach-Object</code>.</li>\n<li>I didn't use it, but here is the help for <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.filesysteminfo.fullname?view=netframework-4.8\" rel=\"nofollow noreferrer\">FileSystemInfo.FullName</a></li>\n<li><code>cat</code> is an alias for <code>Get-Content</code>.</li>\n</ul>\n\n<p>Feel free to ask any questions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T06:42:33.287",
"Id": "223333",
"ParentId": "223328",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T04:57:30.493",
"Id": "223328",
"Score": "4",
"Tags": [
"file-system",
"powershell"
],
"Title": "Creating a file of md5 hashes for all files in a directory in PowerShell"
} | 223328 |
<p>How to improve this code? In C++ we use templates to write function for all data types. How to write such code in python?</p>
<pre><code>def get_input(): #to get input from user
input_str = input("Enter elements to be sorted: ")
try:
lst = list(map(int, input_str.split())) #make a list of integers from input string
except:
raise TypeError("Please enter a list of integers only, seperated by a space!!")
return lst
def partition(thelist, start_idx, end_idx): #partition list according to pivot and return index of pivot
pivot = thelist[end_idx] #select last element as the pivot
idx = start_idx - 1
for curr_idx in range(start_idx, end_idx):
if thelist[curr_idx] <= pivot:
idx += 1
thelist[idx], thelist[curr_idx] = thelist[curr_idx], thelist[idx] #swapping
thelist[idx+1], thelist[end_idx] = thelist[end_idx], thelist[idx+1] #swapping
return idx+1 #returning pivot index
def quick_sort(thelist, start_idx, end_idx):
if len(thelist) == 0:
print("Empty list!!")
elif len(thelist) == 1:
print("Only one element!!")
elif start_idx < end_idx:
pivot_idx = partition(thelist, start_idx, end_idx) #get pivot index
quick_sort(thelist, start_idx, pivot_idx - 1) #apply algorithm for smaller list
quick_sort(thelist, pivot_idx + 1, end_idx) #apply algorithm for smaller list
if __name__ == '__main__':
input_list = get_input()
quick_sort(input_list, 0, len(input_list) - 1)
print(*input_list, sep = ", ")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:36:25.107",
"Id": "432721",
"Score": "1",
"body": "Why would you want to have typed versions of your sorting algorithm in the first place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T08:38:07.197",
"Id": "432729",
"Score": "0",
"body": "I am learning python and I think this is best to practice algorithms and to learn new language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:39:13.623",
"Id": "432732",
"Score": "0",
"body": "I don't know that much, I thought writing such programs will help me to learn python syntax and other functions available in Python. Should I not learn by writing such(Algorithms and Data Structures) programs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:47:35.450",
"Id": "433073",
"Score": "0",
"body": "@coder you can try PE or CodeAbbey or other sites to improve your skills. But it seems you are already good at it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T04:41:30.603",
"Id": "442726",
"Score": "0",
"body": "What @Linny said. Also, I know it's a technicality, but a list with one or no elements is still technically sorted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:35:11.940",
"Id": "442741",
"Score": "0",
"body": "Note that your `partition()` picks the pivot."
}
] | [
{
"body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every function, class, and module you write. This will allow documentation to determine what your code is supposed to do.7</p>\n\n<h1>Variable Naming</h1>\n\n<p>Here is a list of variables/parameters that I would change. This increases readability, and makes the variables easier to understand.</p>\n\n<pre><code>input_str -> elements\nthelist -> the_list\nstart_idx -> start_index\nend_idx -> end_index\nidx -> index\ncurr_idx -> current_index\n</code></pre>\n\n<p>A quick sentence about <code>thelist</code>. You have been pretty consistent throughout your program, but remember <em>all</em> variables and parameter names are <code>snake_case</code>.</p>\n\n<h1>Constants Naming</h1>\n\n<p>All constants in your program should be UPPER_CASE.</p>\n\n<h1>Operator Spacing</h1>\n\n<p>In python, and many other languages, we like to have our operators spaced out cleanly. They make the code easier to read and easier to comprehend. So when I see something like <code>1+1</code>, that's an instance red flag. You should separate this by having a space on either side of the operator, like <code>1 + 1</code>.</p>\n\n<h1><code>len(...) == 0</code> vs <code>not ...</code></h1>\n\n<blockquote>\n <p>For sequences, (strings, lists, tuples), use the fact that empty\n sequences are false.</p>\n\n<pre><code>Yes: if not seq:\n if seq:\n\nNo: if len(seq):\n if not len(seq):\n</code></pre>\n</blockquote>\n\n<h1>print() vs quit()</h1>\n\n<p>You have a structure like so:</p>\n\n<pre><code>if len(thelist) == 0:\n print(\"Empty list!!\")\n\nelif len(thelist) == 1:\n print(\"Only one element!!\")\n\nelif start_idx < end_idx:\n ... run quick sort program ...\n</code></pre>\n\n<p>Instead of restricting running the quick sort program to an <code>elif</code>, the first two checks should be separate <code>if</code>s. Then, instead of using print(), use <a href=\"https://docs.python.org/2/library/constants.html#quit\" rel=\"nofollow noreferrer\">quit()</a>. This will allow you to safely stop a program with a provided error message. Now, you can have the quick sort code run if the first two checks are false, like so:</p>\n\n<pre><code>if not the_list:\n quit(\"Empty List!\")\n\nif len(the_list) == 1:\n quit(\"Only one element!\")\n\nif start_idx < end_idx:\n ... run quick sort program ...\n</code></pre>\n\n<h1>Parameter spacing</h1>\n\n<p>There should <em>not</em> be spaces separating an operator and a parameter name / value. Change this:</p>\n\n<pre><code>print(*input_list, sep = \", \")\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>print(*input_list, sep=\", \")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T04:10:47.217",
"Id": "227444",
"ParentId": "223332",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T06:30:19.620",
"Id": "223332",
"Score": "3",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"sorting"
],
"Title": "Python: Quick Sort"
} | 223332 |
<p>I made a little gambling batch file and wanted to know if there was a better way to do the randomization and the checker.</p>
<pre><code>:num1
cls
echo Getting results! Please wait.
set /A g11=%random% %% 10
goto num2
:num2
cls
echo Getting results! Please wait..
set /A g22=%random% %% 10
goto num3
:num3
cls
echo Getting results! Please wait...
set /A g33=%random% %% 10
goto results
:results
if %g1%==%g11% if %g2%==%g22% if %g3%==%g33% goto w3
if not %g1%==%g11% if %g2%==%g22% if %g3%==%g33% goto w2
if %g1%==%g11% if not %g2%==%g22% if %g3%==%g33% goto w2
if %g1%==%g11% if %g2%==%g22% if not %g3%==%g33% goto w2
if not %g1%==%g11% if not %g2%==%g22% if %g3%==%g33% goto w1
if not %g1%==%g11% if %g2%==%g22% if not %g3%==%g33% goto w1
if %g1%==%g11% if not %g2%==%g22% if not %g3%==%g33% goto w1
if not %g1%==%g11% if not %g2%==%g22% if not %g3%==%g33% goto Lose
</code></pre>
<p>The above is the aforementioned code below is the whole code its pretty small
I'm also open to any constructive criticism or suggestions for it!</p>
<pre><code> @echo off
cls
:menu
echo Hello. Welcome to Gamblebot 2000!
echo You will start off with 100 credits. As you climb,
echo you can start to place larger and better bets!
echo Do your best to not run out of money, or you will
echo have to start over.
echo Have fun :)
echo .
echo Version alpha 1.4.9
echo .
pause
:start
cls
set bal=100
echo The game is simple. Guess a number between 0 and 9
echo for 3 instances. (For example: 123, 456, 789, 111)
echo A dice will be rolled. If you guess the number, you get a
echo winning based on the amount of numbers guessed correctly.
echo .
echo 1 numbers gives you a 2x win.
echo 2 numbers gives you a 3x win.
echo 3 numbers gives you a 4x win.
echo No numbers means you lost.
pause
goto curr
:curr
cls
echo First, start by naming the currency.
echo Name it whatever you like. Then press enter.
set /p curr=
goto g1
:currchange
cls
echo Enter name of new currency.
set /p curr=
goto g1
:g1
cls
if %bal% == 0 goto Bankrupt
echo Please make your first number selection!!!
set /p g1=
goto g2
:g2
cls
echo Please make your second number selection!!!
set /p g2=
goto g3
:g3
cls
echo Please make your third number selection!!!
set /p g3=
goto bet
:bet
cls
echo Your balance is %bal% %curr%
echo Place your bet.
set /p bet=
if %bet% GTR %bal% (
goto inf )
goto num1
:inf
cls
echo You do not have enough credits for that bet. Please choose another bet!
echo
pause
goto bet
:num1
cls
echo Getting results! Please wait.
set /A g11=%random% %% 10
goto num2
:num2
cls
echo Getting results! Please wait..
set /A g22=%random% %% 10
goto num3
:num3
cls
echo Getting results! Please wait...
set /A g33=%random% %% 10
goto results
:results
if %g1%==%g11% if %g2%==%g22% if %g3%==%g33% goto w3
if not %g1%==%g11% if %g2%==%g22% if %g3%==%g33% goto w2
if %g1%==%g11% if not %g2%==%g22% if %g3%==%g33% goto w2
if %g1%==%g11% if %g2%==%g22% if not %g3%==%g33% goto w2
if not %g1%==%g11% if not %g2%==%g22% if %g3%==%g33% goto w1
if not %g1%==%g11% if %g2%==%g22% if not %g3%==%g33% goto w1
if %g1%==%g11% if not %g2%==%g22% if not %g3%==%g33% goto w1
if not %g1%==%g11% if not %g2%==%g22% if not %g3%==%g33% goto Lose
:w3
cls
set /a win=%bet%*4
set /a bal=%bal%+%win%
echo Congratulations you have guessed all three numbers correctly!
echo the numbers were: %g11%%g22%%g33%!
echo .
echo You have won "%win%" %curr%!
echo .
echo Your new credit balance is %bal% %curr%.
echo .
echo Would you like to make another bet?
echo (Y/N)
set /p ha=
if %ha% == y goto g1
if %ha% == Y goto g1
if %ha% == n goto save
if %ha% == N goto save
:w2
cls
set /a win=%bet%*3
set /a bal=%bal%+%win%
echo Congratulations you have guessed two numbers correctly!
echo the numbers were: %g11% %g22% %g33%!
echo Your numbers were %g1% %g2% %g3%
echo .
echo You have won "%win%" %curr%!
echo .
echo Your new credit balance is %bal% %curr%.
echo .
echo Would you like to make another bet?
echo (Y/N)
set /p ha=
if %ha% == y goto g1
if %ha% == Y goto g1
if %ha% == n goto save
if %ha% == N goto save
:w1
cls
set /a win=%bet%*2
set /a bal=%bal%+%win%
echo Congratulations you have guessed one correctly!
echo the numbers were: %g11% %g22% %g33%!
echo Your numbers were %g1% %g2% %g3%
echo .
echo You have won "%win%" %curr%!
echo .
echo Your new credit balance is %bal% %curr%.
echo .
echo Would you like to make another bet?
echo (Y/N)
set /p ha=
if %ha% == y goto g1
if %ha% == Y goto g1
if %ha% == n goto save
if %ha% == N goto save
:lose
cls
set /a bal=%bal%-%bet%
echo I am sorry but you did not guess any of the numbers correctly.
echo .
echo The numbers were: %g11% %g22% %g33%!
echo Your numbers were %g1% %g2% %g3%
echo .
echo You have lost %bet% %curr%.
echo .
echo Your new credit balance is %bal% %curr%.
echo Would you like to make another bet?
echo (Y/N)
set /p ha=
if %ha% == y goto g1
if %ha% == Y goto g1
if %ha% == n goto save
if %ha% == N goto save
:change
cls
echo Would you like to change or keep the name of your currency?
echo Type k for keep or c for change.
set /p ha=
if %ha% == k goto g1
if %ha% == K goto g1
if %ha% == c goto currchange
if %ha% == C goto currchange
:Bankrupt
cls
Echo Im sorry but you have no more money ;-;
Echo Would you like to add more credits?
Echo (Y/N)
set /p ha=
if %ha% == y goto Purchase
if %ha% == Y goto Purchase
if %ha% == n Exit
if %ha% == N Exit
:Purchase
cls
Echo Please select your purchase amount!
echo .
echo .
echo 1) 100 credits $0.99
echo 2) 500 credits $4.99
echo 3) 1000 credits $8.99
echo 4) 5000 credits $18.99
set /p pur=
if %pur% == 1 goto p
if %pur% == 2 goto p
if %pur% == 3 goto p
if %pur% == 4 goto p
:p
cls
echo you have chosen Option %pur%!
echo please send an email with funds attached to buisness@fakemail.dum
echo and your credits will be applied instantly!
pause
Goto con
:con
cls
echo thank you for your support goodbye!
pause
Exit
:save
cls
echo Sorry. The save mechanic is not yet set up. It will be coming
echo in a future update Thanks for playing. I hope you had fun!
Exit
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:54:37.360",
"Id": "432726",
"Score": "2",
"body": "Welcome to Code Review! Please change your title to describe what you code does in a way that might draw interest of users skimming the question list, not your concerns about it (see [ask])."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T13:13:29.903",
"Id": "432774",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.StackExchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-18T21:08:59.507",
"Id": "475952",
"Score": "0",
"body": "Wouldn't it be better to put each section in functions instead of `goto`ing to random labels? See `Call /?`"
}
] | [
{
"body": "<p>The core logic of Number generation and comparison can be greatly simplified by using <code>For /L</code> and <code>For /F</code> loops in conjunction with indexed arrays:</p>\n<pre class=\"lang-bat prettyprint-override\"><code>@Echo Off\nSetlocal EnableDelayedExpansion\n:Gameloop\n CLS\n Set /A Matches=0,R1=!Random! %%9+1,R2=!Random! %%9+1,R3=!Random! %%9+1\n For /L %%i in (1 1 3)Do (\nrem Prompt For Selection of Guesses N%%i [ 1 2 3 ]\n <Nul Set /P "=[E]xit or Pick Number %%i [0-9]: "\nrem Capture Input of guess %%i into For Metavariable %%G\n For /F "Delims=" %%G in ('Choice /N /C:0123456789E')Do (\nrem append input to current line, output newline.\n <Nul Set /P "=[%%G]"& Echo(\nrem Exit Batch on Input of 'E'\n If "%%G" == "E" (Endlocal & Exit /B)\nrem Assign Input to Guess N%%i 'E'\n Set "N%%i=%%G" \nrem Compare Input to Rolled Number of same %%i index; Assign M%%i Display Value; Increment Matches count If EQU\n If "%%G" == "!R%%i!" (\n Set "M%%i=%%G"\n Set /A Matches+=1\n )Else Set "M%%i=-"\n ))\n Echo( Rolled: [!R1!][!R2!][!R3!]\n Echo(Matched: [!M1!][!M2!][!M3!]\nrem Calculate Score * Matches. 1M=100 2M=400 3M=900 ; Add to total Score ; Display\n For /F "Delims=" %%G in ('Set /A "Matches * 100 * Matches + 0" 2^> nul')Do (\n Set /A "Score+=%%G + 0"\n Echo(Points Earned this Round: %%G Score: !Score!\n )\nPause\nGoto :Gameloop\n</code></pre>\n<p>'rolled' numbers get assigned to R#<br />\n'Selected' numbers ~ to N#<br />\nM# Array is used to Display Matched characters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T11:30:03.087",
"Id": "256467",
"ParentId": "223334",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:21:42.053",
"Id": "223334",
"Score": "0",
"Tags": [
"game",
"number-guessing-game",
"batch"
],
"Title": "Random-number-guessing game as a batch script"
} | 223334 |
<p>I am using the following query to search for the nearest city to my location from the cities table using latitude and longitude. The query also checks whether the nearest cities to my location have more than 1 shops of a given category. Only then a city is selected.</p>
<p>The query works fine but it takes more than 5 seconds to execute. Is there any way this query can be optimised to consume less time.</p>
<pre><code>SELECT id,city,city_url,
(SELECT count(shop) FROM shops JOIN
shop_categories ON shop_categories.shop_id = shops.id WHERE
city_id=cities.id && shop_categories.category_id = :catId LIMIT 1) as
totalshops,
(6371 * 2 * ASIN(SQRT( POWER(SIN(( :latitude - latitude) *
pi()/180 / 2), 2) +COS( :latitude * pi()/180) * COS( :latitude *
pi()/180) * POWER(SIN(( :longitude - longitude) * pi()/180 / 2), 2) )))
as distance
from cities
having totalshops > 1
order by distance ASC
LIMIT 1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:41:48.333",
"Id": "432722",
"Score": "0",
"body": "Welcome to Code Review! I changed your title so that it actually describes what you are trying to accomplish (see [ask]). Please verify that I have not misunderstood your intent."
}
] | [
{
"body": "<p>MySQL surely has some tools to help you profile the query, and you should try using those to at least identify the bottleneck. But there are three things which jump out at me.</p>\n\n<ol>\n<li>The formatting is not at all conducive to reading the query. Using indentation would go a long way; breaking the line before rather than after the keyword which introduces a clause (<code>FROM</code>, <code>WHERE</code>, etc.) would also help.</li>\n<li><code>totalshops</code> does a <code>count</code> solely for <code>having totalshops > 1</code>. Can that be rewritten as a <code>WHERE EXISTS</code>?</li>\n<li>The distance calculation is serious overkill. You don't actually need the distance for the query: any strictly monotonic function of it would do. If you denormalise slightly and store Cartesian coordinates in addition to the latitude and longitude then a simple dot product with <code>DESC</code> sorting would work. If you need the distance in the presentation layer, calculate it there.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:51:44.640",
"Id": "223337",
"ParentId": "223335",
"Score": "2"
}
},
{
"body": "<p>I think there's three big things you might be able to do to improve the performance of this.</p>\n\n<ol>\n<li><p>Write your query such that it doesn't need to execute the subquery for each line and/or have a <code>HAVING</code> clause by using an inner join which will automatically exclude those with no match.</p></li>\n<li><p>Use <code>ST_Distance_Sphere(POINT(:longitude, :latitude), POINT(cities.longitude, cities.latitude)</code> to get the distance using a built in function that'll probably be faster than anything you can calculate outside of one.</p></li>\n<li><p>If you're looking for the singular closest entry it may be worth using half of the maximum distance between two points as a cut off and excluding anything by default where the long or lat is outside of the given range and would thus never be the closest entry.<br>\nFor example if the largest distance between two cities is 1,600 km you know for sure that no city outside of 800 km in any direction can ever be the closest; At 70N about the north end of Canada that equates to ~21 points of longitude anything outside of your passed in longitude +- 22 can be immediately ignored. The same rule can be applied to latitude to ignore everything outside of +/- 7.</p>\n\n<p>You'll still have to check everything in those ranges, but it'll be very quick to run and if it reduces the amount of slow work required to be run it's worth it.</p></li>\n</ol>\n\n<pre class=\"lang-sql prettyprint-override\"><code>\nSELECT\n cities.id,\n cities.city,\n cities.city_url,\n COUNT(DISTINCT shops.id) AS totalshops,\n ST_Distance_Sphere(POINT(:longitude, :latitude), POINT(cities.longitude, cities.latitude) AS distance\nFROM cities\nJOIN shops\n ON\n shops.city_id = cities.id\nJOIN shop_categories\n ON\n shop_categories.shop_id = shops.id\nWHERE\n shop_categories.category_id = :catId\n AND\n cities.longitude BETWEEN :longitude - :max_long_distance AND :longitude + :max_long_distance\n AND\n cities.latitude BETWEEN :latitude - :max_lat_distance AND :latitude + :max_lat_distance\nGROUP BY\n cities.id\nORDER BY\n distance ASC\nLIMIT 1\n;\n</code></pre>\n\n<p>PS: I assumed for the <code>GROUP BY</code> clause you're not running with the strict grouping mode enabled. If that's not the case you'll need to add the other columns from <code>cities</code> that are references like the <code>cities.city</code>, <code>cities.city_url</code>, <code>cities.longitude</code> and <code>cities.latitude</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:30:05.403",
"Id": "235682",
"ParentId": "223335",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T07:21:44.317",
"Id": "223335",
"Score": "2",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Querying nearest city with a given shop using latitude and longitude is slow"
} | 223335 |
<p>I have a review request about this part of the code:</p>
<pre><code>let private startReading (client:TcpClient) (bus:IBus) =
//TODO check if that can be changed to rec parameter
let frameNumber = ref 0
let rec StartReading (client:TcpClient) =
async{
match client with
| null -> async { return 0 } |> Async.StartAsTask |> ignore
| _ ->
match (client.IsConnectionEstablished()) with
| true ->
incr frameNumber
DeployService.DeployCabninetService
let! messange = MessagingHandler.ReadMessage client
match(messange) with
| Some data ->
let frameNumber = uint32 frameNumber.Value
logger.Info(sprintf "Received message with Frame Number: %i" frameNumber)
| None ->
_logger.Info(sprintf "Client disconnected : %O" client.Client.RemoteEndPoint)
return! DisconnectClient client None
return! StartReading client
| false ->
_logger.Info(sprintf "Client disconnected : %O" client.Client.RemoteEndPoint)
return! DisconnectClient client None
}
StartReading client |> Async.StartAsTask
</code></pre>
<p>It is simple reading message procedure from tcp client in f#, but I feel this can be written more gracefully, especially todo part with frame number incrementation using ref in f# feels wrong. </p>
<p>Any suggestions?</p>
| [] | [
{
"body": "<p>Why do you make this call <code>Async.StartAsTask</code> instead of just return the <code>Async<T></code> to let the client handle that as needed?</p>\n\n<hr>\n\n<blockquote>\n <p><code>let rec StartReading (client:TcpClient) =</code></p>\n</blockquote>\n\n<p>I would call it <code>reader</code> and then give it the signature of:</p>\n\n<pre><code>let rec reader frameNo (client:TcpClient) =\n</code></pre>\n\n<p>in order to get rid of <code>ref</code>for <code>frameNumber</code>.</p>\n\n<p>You can then initially call it:</p>\n\n<pre><code>reader 0 client |> Async.StartAsTask\n</code></pre>\n\n<p>and recursively:</p>\n\n<pre><code>return! reader (frameNo + 1) client\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:46:01.420",
"Id": "223345",
"ParentId": "223338",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223345",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T08:00:59.690",
"Id": "223338",
"Score": "1",
"Tags": [
"f#",
"tcp"
],
"Title": "F# Simple message reader using TCP"
} | 223338 |
<p>I have been creating a small library to copy parts of deeply nested objects through path strings that supports wildcards. For that I list all paths and values actually found as <code>ObjectPartial</code>s and <code>merge-partials</code> these are merged while avoiding path collisions and ordering array indexes. This review is only about this part.</p>
<p>The whole <code>merge-partials.js</code> seems too contrived and confusing. I wanted to have smaller, clearer functions that don't rely so much on side-effects, as here the <code>ObjectPartial</code>s passed to the functions are being changed. Maybe there is even a way simpler solution that I am not seeing. </p>
<p><code>object-partial.js</code></p>
<pre class="lang-js prettyprint-override"><code>const set = require('lodash.set');
const InvalidArgError = require('./errors/invalid-arg-error');
const { isUndefined } = require('./utils');
module.exports = class ObjectPartial {
/**
* Creates a new ObjectPartial with the given path and its value
* @param {Array} path
* @param {any} value
*/
constructor(path, value) {
if (!Array.isArray(path) || !path.length || isUndefined(value)) {
throw new InvalidArgError(
'No valid path or missing value for ObjectPartial'
);
}
this.path = path.slice();
this.value = value;
}
getPath() {
return this.path;
}
getValue() {
return this.value;
}
/**
* Merge the partial into a new or an existing object
* @param {*} object Optional object to merge the partial into
* @returns Resulting object
*/
mergeToObject(object = {}) {
return set(object, this.path, this.value);
}
static createFromObject(object, path) {
if (!path || !Array.isArray(path) || isUndefined(object)) {
throw new InvalidArgError(
'Missing path or object for ObjectPartial.createFromObject'
);
}
let curValue = object;
for (let i = 0; i < path.length; i++) {
if (isUndefined(curValue[path[i]])) {
return null;
}
curValue = curValue[path[i]];
}
return new ObjectPartial(path, curValue);
}
};
</code></pre>
<hr>
<p><code>merge-partials.js</code></p>
<pre class="lang-js prettyprint-override"><code>const { isUndefined, pushAllUnique } = require('./utils');
const InvalidArgError = require('./errors/invalid-arg-error');
/**
* Creates a map of all the keys on current partials level and its subsequent keys
* @param {ObjectPartial[]} partials
* @param {Number} pathIndex
* @returns Map of each key occurance (*key* (key, indices[], nextKeys[])) to the partials and next keys
*/
function createPossibleCollisionsKeyMap(partials, pathIndex) {
const result = { possibleColisionKeys: {}, hasNextLevel: false };
for (let i = 0; i < partials.length; i++) {
const partialPath = partials[i].getPath() || [];
const key = partialPath[pathIndex];
const nextKey = partialPath[pathIndex + 1];
if (!isUndefined(key)) {
if (isUndefined(result.possibleColisionKeys[key])) {
result.possibleColisionKeys[key] = { key, indices: [], nextKeys: [] };
}
result.possibleColisionKeys[key].indices.push(i);
result.possibleColisionKeys[key].nextKeys.push(nextKey);
}
if (!isUndefined(nextKey)) {
result.hasNextLevel = true;
}
}
return result;
}
function hasPossibleKeyCollision(indices, nextKeys) {
const hasMultiple = indices.length > 1;
const hasNextUndefined = nextKeys.findIndex(isUndefined) > -1;
const hasNextNonZeroIndices =
nextKeys.filter(nextKey => Number.isInteger(nextKey) && nextKey != 0)
.length > 0;
return (hasNextUndefined && hasMultiple) || hasNextNonZeroIndices;
}
/**
* Solves possible key collisions and normalizes array indices (order from 0)
* @hasSideEffects
* @param {ObjectPartial[]} partials
* @param {Array} pathIndex
* @param {Object} indices.nextKeys possible colision key map
*/
function solveKeyCollision(partials, pathIndex, { indices, nextKeys }) {
if (!hasPossibleKeyCollision(indices, nextKeys)) {
return;
}
const indicesTransform = [];
let curNextIndex = 0;
for (let i = 0; i < indices.length; i++) {
const partialIndex = indices[i];
const partialNextKey = nextKeys[i];
const partialPath = partials[partialIndex].getPath();
if (isUndefined(partialNextKey)) {
partialPath.splice(pathIndex + 1, 0, curNextIndex);
curNextIndex += 1;
} else if (Number.isInteger(partialNextKey)) {
let newIndex = indicesTransform[partialNextKey];
if (isUndefined(newIndex)) {
newIndex = curNextIndex;
curNextIndex += 1;
indicesTransform[partialNextKey] = newIndex;
}
partialPath[pathIndex + 1] = newIndex;
}
}
}
/**
* Handles the possible collisions in current section of the object partials
* @param {ObjectPartial[]} partials
* @param {*} scanMaps (curLevel, partialIndices[])
* @returns (hasNextLevel, uniqueKeys)
*/
function handlePathColisions(partials, { curLevel, partialIndices = [] }) {
const thesePartials = partials.filter((_partial, index) =>
partialIndices.includes(index)
);
const { possibleColisionKeys, hasNextLevel } = createPossibleCollisionsKeyMap(
thesePartials,
curLevel
);
const uniqueKeys = [];
Object.keys(possibleColisionKeys).forEach(key => {
solveKeyCollision(thesePartials, curLevel, possibleColisionKeys[key]);
uniqueKeys.push(possibleColisionKeys[key].key);
});
return { hasNextLevel, uniqueKeys };
}
function createDummyScanMap(partials, level) {
return {
curLevel: level,
partialIndices: partials.map((partial, index) => {
return {
path: partial.getPath(),
index
};
})
};
}
/**
* Gets a part of the ObjectPartials to be checked for possible path collisions
* @param {ObjectPartial[]} partials
* @param {Number} level
* @param {string} parentKey
* @returns {Object} Object composed of (curLevel,parentKey,partialIndices[] (path,index))
*/
function getScanMap(partials, level, parentKey) {
const result = createDummyScanMap(partials, level);
if (isUndefined(parentKey)) {
result.partialIndices = result.partialIndices
.filter(value => !isUndefined(value.path[0]))
.map(value => value.index);
} else {
result.partialIndices = result.partialIndices
.filter(
value =>
value.path[level - 1] === parentKey && !isUndefined(value.path[level])
)
.map(value => value.index);
}
return result;
}
/**
* Prepares object partials to merge contents and normalize array indexes
* @hasSideEffects
* @param {ObjectPartial[]} partials
*/
/* eslint-disable no-loop-func */
function mergePartials(partials) {
if (!partials || !Array.isArray(partials) || !partials.length) {
throw new InvalidArgError('Missing ObjectPartial list for mergePartials()');
}
let hasNextLevel = true;
let curLevel = 0;
let parentKeys;
let scanMaps;
let tempResult;
while (hasNextLevel) {
if (curLevel === 0) {
scanMaps = [getScanMap(partials, 0)];
} else {
scanMaps = parentKeys.map(pKey => getScanMap(partials, curLevel, pKey));
}
parentKeys = [];
for (let i = 0; i < scanMaps.length; i++) {
tempResult = handlePathColisions(partials, scanMaps[i]);
pushAllUnique(parentKeys, tempResult.uniqueKeys);
hasNextLevel = false || tempResult.hasNextLevel;
}
curLevel += 1;
}
}
module.exports = mergePartials;
</code></pre>
<p>I did do some tests for this that are passing and here is an example of input and output ObjectPartials. Hope the purpose of the whole thing is clear, let me know if I missed something.</p>
<pre class="lang-js prettyprint-override"><code> mergePartials([
new ObjectPartial(['A', 3, 'BA'], 'example'),
new ObjectPartial(['A', 3, 'B'], 123),
new ObjectPartial(['A', 4, 'B'], 456),
new ObjectPartial(['D'], 'yay'),
new ObjectPartial(['D', 0], 'nay')
]);
/* --> [
new ObjectPartial(['A', 0, 'BA'], 'example'),
new ObjectPartial(['A', 0, 'B'], 123),
new ObjectPartial(['A', 1, 'B'], 456),
new ObjectPartial(['D', 0], 'yay'),
new ObjectPartial(['D', 1], 'nay')
] */
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:42:08.043",
"Id": "223344",
"Score": "1",
"Tags": [
"javascript",
"performance",
"node.js"
],
"Title": "Merging partial objects while avoiding path collisions and ordering array indexes"
} | 223344 |
<p>I wrote a code to create a regression tree for a synthetic train data of size <code>Np</code>. The idea is, first I have the source node (which consists of all set of points) represented as a dictionary <code>{'points':..., 'avg':..., 'left_node':..., 'right_node', 'split_point': }</code>. The left and right nodes are the leafs after the splitting process of the whole data (source). <code>split_point</code> is for information about the best split. Then I loop to get deeper tree with maximum number of nodes specified before, also I set that a node must have more than 5 points in order it can be split. </p>
<p>This way, If I want to predict a point <code>(x',y')</code>, I can just start from source node <code>source</code> and check which region the point lies (<code>left_node</code> or <code>right_node</code>), ..and then continuing down the tree. Because all <code>left_node</code>s and <code>right_node</code>s values have the same structure as <code>source</code>....</p>
<p>Also, the <code>form</code> function is used to find the best split, the best split is the one with the smallest <code>form(reg_1, avg1, reg_2, avg2)</code>. This is a greedy algorithm to find the best split.</p>
<hr>
<p>I would like to know better ways to perform it..without external modules. But this is intended to be taught to high school students.</p>
<hr>
<p><strong>Full code:</strong></p>
<pre><code>import random
import matplotlib.pyplot as plt
def form(region_1, av1, region_2, av2):
return sum([(i[1]-av1)**2 for i in region_1]) \
+ sum([(i[1]-av2)**2 for i in region_2])
Np = 400
x_data = [abs(random.gauss(5, 0.2) + random.gauss(8, 0.5)) for i in range(Np)]
y_data = [abs(random.gauss(10, 0.2) + random.uniform(0, 10)) for i in range(Np)]
value = [abs(random.gauss(4, 0.5)) for i in range(Np)]
data = [((i,j), k) for i,j,k in zip(x_data, y_data, value)]
fig, ax = plt.subplots()
ax.plot(x_data, y_data, 'o')
fig.show()
###### Splitting from the source node (all data)
source = {'points': data, 'avg': sum([i[1] for i in data])/Np, \
'split_point': None, 'left_node': None, 'right_node': None}
forms = []
for x in x_data:
var = x
region_1 = [j for j in data if j[0][0] <= var]
region_2 = [j for j in data if j not in region_1]
if len(region_1) > 0 and len(region_2) > 0:
av1 = sum([i[1] for i in region_1])/len(region_1)
av2 = sum([i[1] for i in region_2])/len(region_2)
f = form(region_1, av1, region_2, av2)
leaf_1 = {'points': region_1, 'avg': av1}
leaf_2 = {'points': region_2, 'avg': av2}
forms.append( (leaf_1, leaf_2, ('x', var), f) )
for y in y_data:
var = y
region_1 = [j for j in data if j[0][1] <= var]
region_2 = [j for j in data if j not in region_1]
if len(region_1) > 0 and len(region_2) > 0:
av1 = sum([i[1] for i in region_1])/len(region_1)
av2 = sum([i[1] for i in region_2])/len(region_2)
f = form(region_1, av1, region_2, av2)
leaf_1 = {'points': region_1, 'avg': av1}
leaf_2 = {'points': region_2, 'avg': av2}
forms.append( (leaf_1, leaf_2, ('y', var), f) )
sorted_f = sorted(forms, key = lambda x: x[3])
best_split = sorted_f[0]
source['split_point'] = best_split[2]
source['left_node'] = best_split[0]
source['right_node'] = best_split[1]
##### Splitting from the 2 leafs and so on..
leafs = [source['left_node'], source['right_node']]
all_nodes = [leafs[0], leafs[1]]
max_nodes = 1000
while len(all_nodes) <= max_nodes:
next_leafs = []
for leaf in leafs:
if (len(leaf['points']) > 5):
xx = [i[0][0] for i in leaf['points']]
yy = [i[0][1] for i in leaf['points']]
rr = [i[1] for i in leaf['points']]
vv = [((i,j), k) for i,j,k in zip(xx, yy, rr)]
forms = []
for x in xx:
var = x
region_1 = [j for j in vv if j[0][0] <= var]
region_2 = [j for j in vv if j not in region_1]
if len(region_1) > 0 and len(region_2) > 0:
av1 = sum([i[1] for i in region_1])/len(region_1)
av2 = sum([i[1] for i in region_2])/len(region_2)
f = form(region_1, av1, region_2, av2)
leaf_1 = {'points': region_1, 'avg': av1}
leaf_2 = {'points': region_2, 'avg': av2}
forms.append( (leaf_1, leaf_2, ('x', var), f) )
for y in yy:
var = y
region_1 = [j for j in vv if j[0][1] <= var]
region_2 = [j for j in vv if j not in region_1]
if len(region_1) > 0 and len(region_2) > 0:
av1 = sum([i[1] for i in region_1])/len(region_1)
av2 = sum([i[1] for i in region_2])/len(region_2)
f = form(region_1, av1, region_2, av2)
leaf_1 = {'points': region_1, 'avg': av1}
leaf_2 = {'points': region_2, 'avg': av2}
forms.append( (leaf_1, leaf_2, ('y', var), f) )
sorted_f = sorted(forms, key = lambda x: x[3])
best_split = sorted_f[0]
leaf['split_point'] = best_split[2]
leaf['left_node'] = best_split[0]
leaf['right_node'] = best_split[1]
print(leaf['split_point'])
next_leafs.append(leaf['left_node'])
next_leafs.append(leaf['right_node'])
print("\n")
leafs = next_leafs
all_nodes.extend(leafs)
if len(leafs) == 0:
break
</code></pre>
| [] | [
{
"body": "<p>Here is my updated version, It looks simpler and better by creating a class, <code>Node</code>.</p>\n\n<pre><code>import random\n\n\ndef formula(region_1, av1, region_2, av2):\n return sum([(i[1]-av1)**2 for i in region_1]) \\\n + sum([(i[1]-av2)**2 for i in region_2])\n\ndef average(data):\n return sum([d[2] for d in data])/len(data)\n\nNp = 400\nx_data = [abs(random.gauss(5, 0.2) + random.gauss(8, 0.5)) for i in range(Np)]\ny_data = [abs(random.gauss(10, 0.2) + random.uniform(0, 10)) for i in range(Np)]\nz_data = [abs(random.gauss(4, 0.5)) for i in range(Np)]\n\n\nclass Node:\n def __init__(self, x_data, y_data, z_data):\n self.x_data = x_data\n self.y_data = y_data\n self.z_data = z_data\n self.points = [(i, j, k) for i, j, k in zip(x_data, y_data, z_data)]\n self.avg = average(self.points)\n\n def split(self):\n #Finding the best split:\n candidates = []\n for x in self.x_data:\n split_point = x\n region_1 = [i for i in self.points if i[0] <= split_point]\n region_2 = [i for i in self.points if i not in region_1]\n if (region_1 != []) and (region_2 != []):\n leaf_1 = Node([i[0] for i in region_1], \\\n [i[1] for i in region_1], \\\n [i[2] for i in region_1])\n leaf_2 = Node([i[0] for i in region_2], \\\n [i[1] for i in region_2], \\\n [i[2] for i in region_2])\n f = formula(region_1, leaf_1.avg, region_2, leaf_2.avg)\n candidates.append( (leaf_1, leaf_2, ('x', split_point), f) )\n for y in self.y_data:\n split_point = y\n region_1 = [i for i in self.points if i[1] <= split_point]\n region_2 = [i for i in self.points if i not in region_1]\n if (region_1 != []) and (region_2 != []):\n leaf_1 = Node([i[0] for i in region_1], \\\n [i[1] for i in region_1], \\\n [i[2] for i in region_1])\n leaf_2 = Node([i[0] for i in region_2], \\\n [i[1] for i in region_2], \\\n [i[2] for i in region_2])\n f = formula(region_1, leaf_1.avg, region_2, leaf_2.avg)\n candidates.append( (leaf_1, leaf_2, ('y', split_point), f) )\n\n sorted_f = sorted(candidates, key = lambda x: x[3])\n best_split = sorted_f[0]\n\n #The result:\n self.split_point = best_split[2]\n self.left_node = best_split[0]\n self.right_node = best_split[1]\n\n\n#Source node and 1st split\nsource = Node(x_data, y_data, z_data)\nsource.split()\n\n#Generate Binary Tree\nresult_nodes = [source.left_node, source.right_node]\nall_nodes = [source.left_node, source.right_node]\n\nmin_nodes = 1000\nmin_points = 5\n\nwhile len(all_nodes) <= min_nodes:\n next_nodes = []\n for node in result_nodes:\n if (len(node.points) > min_points):\n node.split()\n next_nodes.append(node.left_node)\n next_nodes.append(node.right_node)\n result_nodes = next_nodes\n all_nodes.extend(result_nodes)\n if len(result_nodes) == 0:\n break\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T04:42:41.930",
"Id": "223392",
"ParentId": "223346",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T09:48:31.443",
"Id": "223346",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"statistics",
"machine-learning"
],
"Title": "Manual Regression Tree using Python"
} | 223346 |
<p>I've written a simple asynchronous logger (<a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a1d177bd924eb759615cc1b01f9aefa5" rel="nofollow noreferrer">playground</a>):</p>
<pre><code>mod logger {
use std::sync::mpsc::{channel, Sender};
use time::now;
pub type LogError = std::sync::mpsc::SendError<String>;
/// Runs a function that can logs asynchronously.
pub fn log<F, T>(f: F) -> T
where
F: FnOnce(Logger) -> T,
{
let (sender, receiver) = channel();
let handle = std::thread::spawn(move || {
while let Ok(msg) = receiver.recv() {
println!("{}", msg);
}
println!("LOG FINISHED");
});
let result = f(Logger { sender });
handle.join().unwrap(); // Error handling?
result
}
/// The actual logger.
#[derive(Clone)]
pub struct Logger {
sender: Sender<String>,
}
impl Logger {
/// Logs an information.
pub fn info(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
let s = format!("[{}] [INFO ] {}", now().rfc3339(), s);
self.sender.send(s)
}
/// Logs an error.
pub fn error(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
let s = format!("[{}] [ERROR] {}", now().rfc3339(), s);
self.sender.send(s)
}
}
}
// Demontration:
fn main() -> Result<(), logger::LogError> {
logger::log(|logger| {
logger.info("Hello world")?;
// Cloning without overhead:
logger.clone().error("Oops, error")
})
}
</code></pre>
<p>The concept is simple: I spawn a thread with a receiver, and the logger sends the text to it.</p>
<p>To make this work, I was forced to use a callback to correctly join the thread when the user's code is done. Is there a better/prettier way to do that?</p>
<p>And also, is that pattern efficient? I know that I can buffer the lines inside the spawned thread, but I am talking about the whole pattern.</p>
| [] | [
{
"body": "<p>I have found a way to use a runtime struct instead of a closure. <code>Logger</code> needs to borrow the runtime, and it must implement <code>Drop</code> so that <code>Runtime::drop</code> is not called before <code>Logger::drop</code>.</p>\n\n<pre><code>mod logger {\n\n use std::marker::PhantomData;\n use std::sync::mpsc::{channel, Sender};\n use std::thread::JoinHandle;\n use time::now;\n\n pub type LogError = std::sync::mpsc::SendError<String>;\n\n pub struct Runtime {\n sender: Option<Sender<String>>,\n thread_handle: Option<JoinHandle<()>>,\n }\n\n impl Runtime {\n pub fn new() -> Self {\n let (sender, receiver) = channel();\n let thread_handle = std::thread::spawn(move || {\n while let Ok(msg) = receiver.recv() {\n println!(\"{}\", msg);\n }\n println!(\"LOG FINISHED\");\n });\n\n Runtime {\n sender: Some(sender),\n thread_handle: Some(thread_handle),\n }\n }\n\n pub fn logger(&self) -> Logger {\n Logger {\n sender: self.sender.clone().unwrap(),\n _marker: PhantomData,\n }\n }\n }\n\n impl Drop for Runtime {\n fn drop(&mut self) {\n // Removes the last sender alive, so that the thread quits.\n let _ = self.sender.take();\n\n if let Some(handle) = self.thread_handle.take() {\n if let Err(e) = handle.join() {\n eprintln!(\"Error while exiting the logger manager: {:?}\", e);\n }\n }\n }\n }\n\n /// The actual logger.\n #[derive(Clone)]\n pub struct Logger<'a> {\n sender: Sender<String>,\n _marker: PhantomData<&'a ()>,\n }\n\n impl Logger<'_> {\n /// Logs an information.\n pub fn info(&self, s: impl std::fmt::Display) -> Result<(), LogError> {\n let s = format!(\"[{}] [INFO ] {}\", now().rfc3339(), s);\n\n self.sender.send(s)\n }\n\n /// Logs an error.\n pub fn error(&self, s: impl std::fmt::Display) -> Result<(), LogError> {\n let s = format!(\"[{}] [ERROR] {}\", now().rfc3339(), s);\n\n self.sender.send(s)\n }\n }\n\n impl Drop for Logger<'_> {\n fn drop(&mut self) {\n // The non-trivial drop prevents the logger to outlives the manager.\n }\n }\n}\n\n// Demontration:\nfn main() -> Result<(), logger::LogError> {\n let log_manager = logger::Runtime::new();\n let logger = log_manager.logger();\n\n logger.info(\"Hello world\")?;\n // Cloning without overhead:\n logger.clone().error(\"Oops, error\")?;\n\n Ok(())\n}\n</code></pre>\n\n<p>If one try to make a logger outlive the runtime, it will not compile:</p>\n\n<pre><code>fn main() -> Result<(), logger::LogError> {\n let log_manager = logger::Runtime::new();\n let logger = log_manager.logger();\n\n logger.clone().info(\"Hello world\")\n}\n</code></pre>\n\n<p>Gives:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>error[E0597]: `log_manager` does not live long enough\n --> src/main.rs:85:18\n |\n85 | let logger = log_manager.logger();\n | ^^^^^^^^^^^ borrowed value does not live long enough\n86 | \n87 | logger.clone().info(\"Hello world\")\n | -------------- a temporary with access to the borrow is created here ...\n88 | }\n | -\n | |\n | `log_manager` dropped here while still borrowed\n | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `logger::Logger`\n |\n = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T13:50:31.323",
"Id": "223808",
"ParentId": "223355",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T14:42:47.430",
"Id": "223355",
"Score": "3",
"Tags": [
"asynchronous",
"rust",
"logging"
],
"Title": "An asynchronous logger"
} | 223355 |
<p>The exact link to the question : <a href="https://www.spoj.com/problems/DIVSUM2/" rel="nofollow noreferrer">https://www.spoj.com/problems/DIVSUM2/</a></p>
<blockquote>
<p><strong>Input:</strong> An integer stating the number of test cases (equal to 500), and that many lines follow, each containing one integer between <span class="math-container">\$1\$</span>
and <span class="math-container">\$10^{16}\$</span> inclusive.</p>
<p><strong>Output:</strong> Print one integer, the sum of the proper divisors of the number.</p>
</blockquote>
<p>An <a href="https://www.spoj.com/problems/DIVSUM/" rel="nofollow noreferrer">easier version</a> of this question exists in which the constraints are relaxed.</p>
<p>My code works for the easier version , but exceeds the time limit for the harder one.</p>
<p>Example of approach: <span class="math-container">\$36=2^2 \times 3^2\$</span>. So sum of proper factors = <span class="math-container">$$(2^0+2^1+2^2)\times(3^0+3^1+3^2)-36=55$$</span></p>
<h2>My code:</h2>
<pre><code>#include<iostream>
long long sum_proper_divisors(long long n)
{
long long sum=1,x=n;
for(long long i=2;i*i<=n;i++)
{
long long current_sum=1,current_term=1;
while(n%i==0)
{
n/=i;
current_term*=i;
current_sum+=current_term;
}
sum*=current_sum;
}
if(n>=2){
sum*=(n+1);
}
return (sum-x);
}
int main()
{
long long q;
std::cin>>q;
while(q--)
{
long long n;
std::cin>>n;
std::cout<<sum_proper_divisors(n)<<std::endl;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:14:42.297",
"Id": "432789",
"Score": "0",
"body": "Questions should be self-contained: i.e. the spec shouldn't be hidden behind a link. By all means leave the link for detail, but please summarise the requirements directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:22:29.163",
"Id": "432790",
"Score": "0",
"body": "@PeterTaylor Done ."
}
] | [
{
"body": "<p>What's going on with the indentation?</p>\n\n<hr>\n\n<blockquote>\n <p><code>long long</code></p>\n</blockquote>\n\n<p>No. We're not in the 1970s. Use <code><cstdint></code>. Here you probably want <code>std::uint_fast64_t</code>.</p>\n\n<hr>\n\n<p>IMO <code>n</code> should be <code>const</code> and the copy (<code>x</code>) should be the variable which is modified in the loop.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for(long long i=2;i*i<=n;i++)\n</code></pre>\n</blockquote>\n\n<p>The first step to optimising prime divisor searches is to use a wheel. If you special-case <code>i=2</code> then you can search <code>for(i=3;i*i<=x;i+=2)</code>, which is already a speedup by about a factor of 2.</p>\n\n<p>On some architectures, multiplication is expensive and it's faster to maintain a variable <code>ii</code> or <code>iSquared</code> which is updated using the identity <span class=\"math-container\">\\$(i+a)^2 - i^2 = 2ai + a^2\\$</span>: e.g. (untested, may be buggy): <code>for(i=3,ii=9;ii<=x;ii+=(i+1)<<2,i+=2)</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> long long current_sum=1,current_term=1;\n while(n%i==0)\n { \n n/=i; \n current_term*=i;\n current_sum+=current_term;\n }\n</code></pre>\n</blockquote>\n\n<p>This can be simplified:</p>\n\n<pre><code> std::uint_fast64_t current_sum=1;\n while(x%i==0)\n {\n x/=i;\n current_sum=current_sum*i+1;\n }\n</code></pre>\n\n<hr>\n\n<p>The first big step to improving the algorithm would be to exploit the fact that up to 500 test cases are passed at a time. If you read them all and find the largest, you can do a variant of Eratosthenes' sieve once to set up an array which allows you to factor all numbers up to that largest one very fast.</p>\n\n<p>If that's not enough, it's probably necessary to switch factorisation approach, starting with Pollard's rho algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T18:51:13.057",
"Id": "432829",
"Score": "0",
"body": "`<< 2` should give the same exact code as `* 4`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T16:17:54.867",
"Id": "223362",
"ParentId": "223357",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "223362",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:06:24.683",
"Id": "223357",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Finding sum of divisors of numbers between the range (1 to 1e16)"
} | 223357 |
<p>I am working on an API to return all the possible flight route between point <strong>A</strong> and <strong>B</strong>. I have a set of data which includes the flight number, airline, departure airport, destination airport, departure time, and arrival time. Keep in mind I am also catering connecting flights. But the connections can only happen between hubs.</p>
<p>I have 5 Hubs and 5 Airlines. Each hub is the base for an airline e.g. Dubai for Emirates, Istanbul for Turkish. The API needs to calculate all possible routes based on all the flights of these 5 airlines. The sample result could be (assuming Istanbul, London & Nairobi are hubs):</p>
<p>User wants to go from Dubai to New York:</p>
<ul>
<li>Route 1: Dubai to New York (EK203)</li>
<li>Route 2: Connecting Dubai to Istanbul to New York (EK123 , TK3)</li>
<li>Route 3: Dubai to Istanbul to London to Nairobi to New York</li>
</ul>
<p>Currently, this system is build on SQL DB and .NET API. We are able to do all above, and it works fine for direct flights but it takes up to 30 seconds when the connections are more than 2.</p>
<p>The data set we are running this on includes all the flights for all 5 airlines so the data set is huge. I was suggested to use GraphQL. </p>
<p>I am looking for suggestions on how to bring this to under 2 seconds of response.</p>
<p>Below is a chunk of SQL Query:</p>
<pre><code>WITH RoutesCTE AS
(
select
( dgl_city . Title + ', ' + dgl_country . Title + '|' + agl_city . Title + ', ' + agl_country . Title ) as [Route]
, 0 as TransfersCount
, CAST (( '[{' +
'"RosterID":"' + CAST ( ISNULL ( rtt . RosterID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"FlightNumber":"' + CAST ( ISNULL ( rtt . FlightNumber , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ReoccuranceCode":"' + ISNULL ( rtt . Code , '' ) + '",' +
'"TravelerAspNetUserID":"' + CAST ( ISNULL ( rtt . TravelerAspNetUserID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"TravelerUserCode":"' + ISNULL ( t_asp . Code , '' ) + '",' +
'"SortOrder":"' + Cast (( 0 ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureAirportIATA":"' + ISNULL ( rtt . DepartureAirportIATA , '' ) + '",' +
'"DepartureAirportTitle":"' + ISNULL ( da . Title , '' ) + '",' +
'"DepartureGeoLocationCityID":"' + CAST ( ISNULL ( dgl_city . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityTitle":"' + CAST ( ISNULL ( dgl_city . Title , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityIsHub":"' + CAST ( ISNULL ( dgl_city . IsHub , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityIsExceptionEnabledAtPickup":"' + CAST ( ISNULL ( dgl_city . IsExceptionEnabledAtPickup , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityIsExceptionEnabledAtDropoff":"' + CAST ( ISNULL ( dgl_city . IsExceptionEnabledAtDropoff , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityISOCode":"' + CAST ( ISNULL ( dgl_city . ISOCode , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCountryID":"' + CAST ( ISNULL ( dgl_country . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCountryTitle":"' + CAST ( ISNULL ( dgl_country . Title , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCountryISOCode":"' + CAST ( ISNULL ( dgl_country . ISOCode , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureDateTime":"' + CAST ( ISNULL ( rtt . DepartureDateTime , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureAirportTerminal":"' + CAST ( ISNULL ( rtt . DepartureTerminal , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureAirportGate":"' + ISNULL ( rtt . DepartureGate , '' ) + '",' +
'"ArrivalAirportIATA":"' + ISNULL ( rtt . ArrivalAirportIATA , '' ) + '",' +
'"ArrivalAirportTitle":"' + ISNULL ( aa . Title , '' ) + '",' +
'"ArrivalGeoLocationCityID":"' + CAST ( ISNULL ( agl_city . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityTitle":"' + ISNULL ( agl_city . Title , '' ) + '",' +
'"ArrivalGeoLocationCityIsHub":"' + CAST ( ISNULL ( agl_city . IsHub , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityIsExceptionEnabledAtPickup":"' + CAST ( ISNULL ( agl_city . IsExceptionEnabledAtPickup , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityIsExceptionEnabledAtDropoff":"' + CAST ( ISNULL ( agl_city . IsExceptionEnabledAtDropoff , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityISOCode":"' + CAST ( ISNULL ( agl_city . ISOCOde , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCountryID":"' + CAST ( ISNULL ( agl_country . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCountryTitle":"' + ISNULL ( agl_country . Title , '' ) + '",' +
'"ArrivalGeoLocationCountryISOCode":"' + ISNULL ( agl_country . ISOCode , '' ) + '",' +
'"ArrivalDateTime":"' + CAST ( ISNULL ( rtt . ArrivalDateTime , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalAirportTerminal":"' + ISNULL ( rtt . ArrivalTerminal , '' ) + '",' +
'"ArrivalAirportGate":"' + ISNULL ( rtt . ArrivalGate , '' ) + '",' +
'"AirlineIATA":"' + ISNULL ( rtt . AirlineIATA , '' ) + '",' +
'"AirlineTitle":"' + ISNULL ( air . Title , '' ) + '"' +
'}' + ( case
when agl_city . GeoLocationID = @ArrivalGeoLocationID then ']'
WHEN rtt . ArrivalAirportIATA IN ( SELECT a . IATA FROM @ArrivalAirportExceptions a ) THEN ']'
else ''
end )
) AS NVARCHAR ( MAX )) as JsonObj ,
rtt . DepartureAirportIATA ,
rtt . ArrivalAirportIATA ,
rtt . DepartureDateTime ,
rtt . ArrivalDateTime ,
da . OriginGeoLocationID as DepartureGeoLocationID ,
dgl_city . Title as DepartureCityTitle ,
dgl_city . UTCOffset as DepartureCityUTCOffset ,
dgl_city . IsHub as DepartureCityIsHub ,
dgl_city . ISOCode as DepartureCityISOCode ,
dgl_city . IsExceptionEnabledAtPickup as DepartureCityIsExceptionEnabledAtPickup ,
dgl_city . IsExceptionEnabledAtDropoff as DepartureCityIsExceptionEnabledAtDropoff ,
dgl_city . IsDSTEnabled as DepartureCityIsDSTEnabled ,
dgl_country . Title as DepartureCountryTitle ,
dgl_country . ISOCOde as DepartureCountryISOCode ,
dgl_country . VAT as DepartureCountryVATInPercentage ,
dgl_country . NFSTaxRegisteration as DepartureCountryNFSTaxRegisteration ,
aa . OriginGeoLocationID as ArrivalGeoLocationID ,
agl_city . Title as ArrivalCityTitle ,
agl_city . IsHub as ArrivalCityIsHub ,
agl_city . ISOCode as ArrivalCityISOCOde ,
agl_city . IsExceptionEnabledAtPickup as ArrivalCityIsExceptionEnabledAtPickup ,
agl_city . IsExceptionEnabledAtDropoff as ArrivalCityIsExceptionEnabledAtDropoff ,
agl_city . IsDSTEnabled as ArrivalCityIsDSTEnabled ,
agl_city . UTCOffset as ArrivalCityUTCOffset ,
agl_country . Title as ArrivalCountryTitle ,
agl_country . ISOCode as ArrivalCountryISOCode ,
agl_country . VAT as ArrivalCountryVATInPercentage ,
agl_country . NFSTaxRegisteration as ArrivalCountryNFSTaxRegisteration ,
rtt . TravelerAspNetUserID
, rtt . AirlineIATA
FROM @RosterTempTable rtt
INNER JOIN dbo . Airlines air
ON rtt . AirlineIATA = air . IATA
INNER JOIN dbo . Airports da
ON rtt . DepartureAirportIATA = da . IATA
INNER JOIN dbo . GeoLocations dgl_city
ON da . OriginGeoLocationID = dgl_city . GeoLocationID
INNER JOIN dbo . GeoLocations dgl_country
ON dgl_city . GeoLocationCountryID = dgl_country . GeoLocationID
INNER JOIN dbo . Airports aa
ON rtt . ArrivalAirportIATA = aa . IATA
INNER JOIN dbo . GeoLocations agl_city
ON aa . OriginGeoLocationID = agl_city . GeoLocationID
INNER JOIN dbo . GeoLocations agl_country
ON agl_city . GeoLocationCountryID = agl_country . GeoLocationID
INNER JOIN dbo . AspNetUsers t_asp
ON rtt . TravelerAspNetUserID = t_asp . Id
INNER JOIN dbo . Tiers tier
ON t_asp . TierID = tier . TierID
AND ( t_asp . KycApproval IS NOT NULL AND t_asp . KycApproval = 'true' )
AND tier . IsBarded = 'false'
UNION ALL
SELECT
r . [Route] + '|' + ( r1_agl_city . Title + ', ' + r1_agl_country . Title )
, TransfersCount + 1
, r . JsonObj + CAST (( ',{' +
'"RosterID":"' + CAST ( ISNULL ( r1 . RosterID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"FlightNumber":"' + CAST ( ISNULL ( r1 . FlightNumber , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ReoccuranceCode":"' + ISNULL ( r1 . Code , '' ) + '",' +
'"TravelerAspNetUserID":"' + CAST ( ISNULL ( r1 . TravelerAspNetUserID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"TravelerUserCode":"' + ISNULL ( t_asp . Code , '' ) + '",' +
'"DepartureAirportIATA":"' + ISNULL ( r1 . DepartureAirportIATA , '' ) + '",' +
'"DepartureAirportTitle":"' + ISNULL ( r1_da . Title , '' ) + '",' +
'"SortOrder":"' + Cast (( TransfersCount + 1 ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityID":"' + CAST ( ISNULL ( r1_dgl_city . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityTitle":"' + CAST ( ISNULL ( r1_dgl_city . Title , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityIsHub":"' + CAST ( ISNULL ( r1_dgl_city . IsHub , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityIsExceptionEnabledAtPickup":"' + CAST ( ISNULL ( r1_dgl_city . IsExceptionEnabledAtPickup , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityIsExceptionEnabledAtDropoff":"' + CAST ( ISNULL ( r1_dgl_city . IsExceptionEnabledAtDropoff , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCityISOCode":"' + CAST ( ISNULL ( r1_dgl_city . ISOCode , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCountryID":"' + CAST ( ISNULL ( r1_dgl_country . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCountryTitle":"' + CAST ( ISNULL ( r1_dgl_country . Title , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureGeoLocationCountryISOCode":"' + CAST ( ISNULL ( r1_dgl_country . ISOCode , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureDateTime":"' + CAST ( ISNULL ( r1 . DepartureDateTime , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureAirportTerminal":"' + CAST ( ISNULL ( r1 . DepartureTerminal , '' ) AS NVARCHAR ( MAX )) + '",' +
'"DepartureAirportGate":"' + ISNULL ( r1 . DepartureGate , '' ) + '",' +
'"ArrivalAirportIATA":"' + ISNULL ( r1 . ArrivalAirportIATA , '' ) + '",' +
'"ArrivalAirportTitle":"' + ISNULL ( r1_aa . Title , '' ) + '",' +
'"ArrivalCityID":"' + CAST ( ISNULL ( r1_agl_city . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityTitle":"' + ISNULL ( r1_agl_city . Title , '' ) + '",' +
'"ArrivalGeoLocationCityIsHub":"' + CAST ( ISNULL ( r1_agl_city . IsHub , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityIsExceptionEnabledAtPickup":"' + CAST ( ISNULL ( r1_agl_city . IsExceptionEnabledAtPickup , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityIsExceptionEnabledAtDropoff":"' + CAST ( ISNULL ( r1_agl_city . IsExceptionEnabledAtDropoff , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCityISOCode":"' + CAST ( ISNULL ( r1_agl_city . ISOCode , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCountryID":"' + CAST ( ISNULL ( r1_agl_country . GeoLocationID , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalGeoLocationCountryTitle":"' + ISNULL ( r1_agl_country . Title , '' ) + '",' +
'"ArrivalGeoLocationCountryISOCode":"' + ISNULL ( r1_agl_country . ISOCode , '' ) + '",' +
'"ArrivalDateTime":"' + CAST ( ISNULL ( r1 . ArrivalDateTime , '' ) AS NVARCHAR ( MAX )) + '",' +
'"ArrivalAirportTerminal":"' + ISNULL ( r1 . ArrivalTerminal , '' ) + '",' +
'"ArrivalAirportGate":"' + ISNULL ( r1 . ArrivalGate , '' ) + '",' +
'"AirlineIATA":"' + ISNULL ( r1 . AirlineIATA , '' ) + '",' +
'"AirlineTitle":"' + ISNULL ( air . Title , '' ) + '"' +
'}' + ( case
when r1_agl_city . GeoLocationID = @ArrivalGeoLocationID then ']'
WHEN r1 . ArrivalAirportIATA IN ( SELECT a . IATA FROM @ArrivalAirportExceptions a ) THEN ']'
else ''
end )
) AS NVARCHAR ( MAX )),
r . DepartureAirportIATA ,
r1 . ArrivalAirportIATA ,
r . DepartureDateTime ,
r1 . ArrivalDateTime ,
r . DepartureGeoLocationID ,
r . DepartureCityTitle ,
r . DepartureCityUTCOffset ,
r . DepartureCityIsHub ,
r . DepartureCityISOCode ,
r . DepartureCityIsExceptionEnabledAtPickup ,
r . DepartureCityIsExceptionEnabledAtDropoff ,
r . DepartureCityIsDSTEnabled ,
r . DepartureCountryTitle ,
r . DepartureCountryISOCode ,
r . DepartureCountryVATInPercentage ,
r . DepartureCountryNFSTaxRegisteration ,
r1_aa . OriginGeoLocationID as ArrivalGeoLocationID ,
r1_agl_city . Title as ArrivalCityTitle ,
r1_agl_City . IsHub AS ArrivalCityIsHub ,
r1_agl_City . ISOCode AS ArrivalCityISOCode ,
r1_agl_City . IsExceptionEnabledAtPickup AS ArrivalCityIsExceptionEnabledAtPickup ,
r1_agl_City . IsExceptionEnabledAtDropoff AS ArrivalCityIsExceptionEnabledAtDropoff ,
r1_agl_City . IsDSTEnabled AS ArrivalCityIsDSTEnabled ,
r1_agl_City . UTCOffset AS ArrivalCityUTCOffset ,
r1_agl_country . Title as ArrivalCountryTitle ,
r1_agl_country . ISOCode as ArrivalCountryISOCode ,
r1_agl_country . VAT as ArrivalCountryVATInPercentage ,
r1_agl_country . NFSTaxRegisteration as ArrivalCountryNFSTaxRegisteration ,
r1 . TravelerAspNetUserID ,
r1 . AirlineIATA
FROM RoutesCTE r
JOIN @RosterTempTable r1
INNER JOIN dbo . Airlines air
ON r1 . AirlineIATA = air . IATA
INNER JOIN dbo . Airports r1_da
ON r1 . DepartureAirportIATA = r1_da . IATA
INNER JOIN dbo . GeoLocations r1_dgl_city
ON r1_da . OriginGeoLocationID = r1_dgl_city . GeoLocationID
INNER JOIN dbo . GeoLocations r1_dgl_country
ON r1_dgl_city . GeoLocationCountryID = r1_dgl_country . GeoLocationID
INNER JOIN dbo . Airports r1_aa
ON r1 . ArrivalAirportIATA = r1_aa . IATA
INNER JOIN dbo . GeoLocations r1_agl_city
ON r1_aa . OriginGeoLocationID = r1_agl_city . GeoLocationID
INNER JOIN dbo . GeoLocations r1_agl_country
ON r1_agl_city . GeoLocationCountryID = r1_agl_country . GeoLocationID
INNER JOIN dbo . AspNetUsers t_asp
ON r1 . TravelerAspNetUserID = t_asp . Id
INNER JOIN dbo . Tiers tier
ON t_asp . TierID = tier . TierID
--ON (r.ArrivalAirportIATA = r1.DepartureAirportIATA OR (r.ArrivalCityTitle + ', ' + r.ArrivalCountryTitle) = (r1_dgl_city.Title + ', ' + r1_dgl_country.Title))
--ON (((r.AirlineIATA IN ('ey', 'ek') AND r1.AirlineIATA IN ('ey', 'ek')) AND ((r.ArrivalAirportIATA <> r1.DepartureAirportIATA) OR (r.ArrivalAirportIATA <> r1.DepartureAirportIATA))) OR (r.ArrivalAirportIATA = r1.DepartureAirportIATA))
ON (( r . ArrivalAirportIATA <> r1 . DepartureAirportIATA ) OR ( r . ArrivalAirportIATA = r1 . DepartureAirportIATA ))
AND r1 . ArrivalAirportIATA <> r . DepartureAirportIATA
AND (( DATEDIFF ( HOUR , r . ArrivalDateTime , r1 . DepartureDateTime ) > 0 ) AND ( DATEDIFF ( HOUR , r . ArrivalDateTime , r1 . DepartureDateTime ) >= ( @PickupCuttoffTimeInHours + @DeliveryCuttoffTimeInHours + @HandlerCuttoffTimeInHours )) AND ( DATEDIFF ( DAY , r . ArrivalDateTime , r1 . DepartureDateTime ) <= 5 ))
AND PATINDEX ( '%' + ( r1_agl_city . Title + ', ' + r1_agl_country . Title ) + '%' , r . [Route] ) = 0
AND ( r . ArrivalCityIsHub = 'true' OR r . TravelerAspNetUserID = r1 . TravelerAspNetUserID )
AND t_asp . KycApproval = 'true'
AND tier . IsBarded = 'false'
)
SELECT
TOP 500
[Route] ,
TransfersCount AS TotalNumberOfConnectingFlights
, JsonObj , DepartureDateTime , ArrivalDateTime , DATEDIFF ( MILLISECOND , DepartureDateTime , ArrivalDateTime ) as CalculatedTime ,
DepartureGeoLocationID ,
DepartureCityTitle ,
DepartureCityUTCOffset ,
DepartureCityIsHub ,
DepartureCityIsExceptionEnabledAtPickup ,
DepartureCityIsExceptionEnabledAtDropoff ,
DepartureCityIsDSTEnabled ,
DepartureCountryVATInPercentage ,
DepartureCountryNFSTaxRegisteration ,
DepartureCityISOCode ,
DepartureCountryTitle ,
DepartureCountryISOCode ,
ArrivalGeoLocationID ,
ArrivalCityTitle ,
ArrivalCityUTCOffset ,
ArrivalCityIsHub ,
ArrivalCityIsExceptionEnabledAtPickup ,
ArrivalCityIsExceptionEnabledAtDropoff ,
ArrivalCityISOCode ,
ArrivalCountryTitle ,
ArrivalCountryISOCode ,
ArrivalCityIsDSTEnabled ,
ArrivalCountryVATInPercentage ,
ArrivalCountryNFSTaxRegisteration
FROM RoutesCTE
WHERE TransfersCount <= 4
AND ( DepartureGeoLocationID = @DepartureGeoLocationID AND ArrivalGeoLocationID = @ArrivalGeoLocationID )
ORDER BY DepartureDateTime ASC , DATEDIFF ( MILLISECOND , DepartureDateTime , ArrivalDateTime ) ASC
</code></pre>
| [] | [
{
"body": "<p>Without same table and data scripts it is very hard to identify performance issues. However, here are a few observations that might help:</p>\n\n<ol>\n<li><p>Unless I'm reading this wrong, this seems pointless, just adding overhead:</p>\n\n<pre><code>ON ((r.ArrivalAirportIATA <> r1.DepartureAirportIATA)\n OR (r.ArrivalAirportIATA = r1.DepartureAirportIATA))\n</code></pre></li>\n<li><p>When using expressions, try to always leave one indexed field unmodified. This allows the optimizer to leverage indexes as much as possible. For example, change:</p>\n\n<pre><code>(DATEDIFF(HOUR, r.ArrivalDateTime, r1.DepartureDateTime) > 0)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>(r1.DepartureDatetime > DATEADD(HOUR,1,r.ArrivalDateTime)\n</code></pre>\n\n<p>That will allow an index on the DepartureDateTime to be used.<br>\nOn a separate note, I think you have a small logic bug here. <code>DATEDIFF(HOUR...</code> compares the specific time component referenced. If comparing 10:59 AM & 11:01 AM, the difference is 1 hour unit. I assume you're actually looking for at least 1 hour between the arrival and next departure. My recommendation will cover this as well, otherwise switch to <code>DATEDIFF(MINUTE... > 60</code></p></li>\n<li><p>Using a MAX datatype can slow things down, sometimes significantly. I'd recommend avoiding until it is really needed. On a related note, try using <code>CONCAT('\"RosterID\":\"',r1.RosterID,'\",')</code> to simplify reading your code. That will also automatically handle null as empty string.</p></li>\n<li><p>Recursive CTEs can be problematic for performance, especially when the recursion has unnecessary stuff in it. If at all possible, build your JSON after you've finished the recursion, once you've identified the routes that meet your criteria.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T08:45:19.367",
"Id": "435119",
"Score": "0",
"body": "Appreciate your detailed answer , we decided to take a completely different approach. But appreciate you taking the time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T20:34:11.463",
"Id": "224245",
"ParentId": "223358",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "224245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T15:09:09.003",
"Id": "223358",
"Score": "3",
"Tags": [
"performance",
"algorithm",
"sql",
".net",
"sql-server"
],
"Title": "Calculating all flight connections"
} | 223358 |
<p>I have a typing log in which rows are grouped by consecutive <code>package_name</code>, and within those groups rows are grouped if they are logged within 180,000 ms from each other. This is working but is there a cleaner way to achieve it? An edge case would be when more than <code>1000</code> consecutive episodes are logged for the same <code>package_name</code> (though I think it is unlikely).</p>
<pre><code>library(dplyr)
metrics <- data.frame(timestamp = c(seq(100000, 100200, by=100), seq(200000, 200200, by=100), seq(400300, 400304, by=1), seq(600400, 600600, by=100), seq(800700, 800900, by=100)),
package_name = c(rep("package1", 3), rep("package2", 3), rep("package2", 5), rep("package2", 3), rep("package1", 3)))
metrics <- metrics %>%
mutate(typing_episode = ifelse(package_name != lag(package_name), 1, 0),
typing_episode = ifelse(is.na(typing_episode), 0, typing_episode),
typing_episode = cumsum(typing_episode) + 1) %>%
group_by(typing_episode) %>%
mutate(time_diff2 = timestamp - lag(timestamp),
time_diff2 = ifelse(is.na(time_diff2), 0, time_diff2),
second_group = ifelse(time_diff2 > (1000 * 60 * 3), 1, 0),
second_group = cumsum(second_group) + 1,
typing_episode2 = typing_episode * 1000 + second_group)
print(metrics)
</code></pre>
| [] | [
{
"body": "<p>In your code, you are checking for changes in a vector or for the differences between consecutive elements of a vector by using <code>lag</code> and then cleaning up the introduced <code>NA</code> value. When looking for changes, I would find it cleaner to handle the first element separately, which enables you to do the operation in a single line of code. For differences in timestamp, <code>diff</code> would make everything a lot cleaner:</p>\n\n<pre><code>metrics <- metrics %>%\n mutate(typing_episode = cumsum(c(1, head(package_name, -1) != tail(package_name, -1)))) %>%\n group_by(typing_episode) %>%\n mutate(second_group = cumsum(c(1, diff(timestamp) > 1000 * 60 * 3)),\n typing_episode2 = typing_episode * 1000 + second_group)\nprint(metrics)\n</code></pre>\n\n<p>As you note, <code>typing_episode2</code> might have repeats if <code>second_group</code> can exceed 1000. A reasonable alternative might be to do something like <code>typing_episode2 = paste0(typing_episode, \"_\", second_group)</code>. Then you won't need to worry about non-unique <code>typing_episode2</code> values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:14:48.357",
"Id": "432982",
"Score": "0",
"body": "Thanks, I'll also concatenate `typing_episode2`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T18:12:50.943",
"Id": "223371",
"ParentId": "223367",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T17:41:20.427",
"Id": "223367",
"Score": "2",
"Tags": [
"r"
],
"Title": "Group by consecutive values in first column and second column value"
} | 223367 |
<p>I have a list of ~27000 objects. Each object represents a line from a file where each line is one record of a measurement from some instrument. </p>
<p>The most import aspects of the object are:</p>
<ul>
<li>Instrument name: int (49099, 89, …)</li>
<li>Station Name: string (K-900, MK-45, …)</li>
<li>Time: datetime object (13:34:17 01/02/2017)</li>
</ul>
<p>All these objects are going to be used in creating a <a href="http://www.hdfgroup.org/HDF5/" rel="nofollow noreferrer">Hierarchical Data Format file</a> where the top most "layer" is a measurement. Each measurement contains multiple line objects which have the same name and have a difference in time within some duration (30 minutes).<br>
One major problem is that the data files I read to create the line objects are very unstructured. I cannot assume that subsequent lines in one file have anything to do with each other, so I cannot compare each line to the previous line to have some filtering logic in the reading part. Even files that have been generated on the same date SHOULD look similar, just with different instrument name, but this is not the case for this problem.<br>
That is why I am reading them all in and THEN comparing all lines to each other. But it is taking a very long time and is not scalable at all. </p>
<p>The code provided is what I am currently doing and I would love to hear any improvements I could make or different ways to tackle my problem. </p>
<pre><code>new = []
for i, r in enumerate(self.records):
x = (y for y in self.records if y.compare_record_same_name(r))
if any(r in x for x in new):
continue
else:
new.append(x)
class Record():
def compare_record_same_name(self, other):
duration = abs(self.date_time - other.date_time)
duration = duration.total_seconds()
return (self.name == other.name and duration < TIME_SEPERATOR
and duration > 0)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T18:09:59.547",
"Id": "432825",
"Score": "0",
"body": "How exactly does the time factor into your classification? Because it sounds like you'll need some means of normalization in order to group things cleanly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T18:45:28.037",
"Id": "432828",
"Score": "0",
"body": "Why don't you sort the records?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:00:10.283",
"Id": "432831",
"Score": "0",
"body": "Is this your real code? At the moment it does not look like valid Python code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T07:27:31.177",
"Id": "432909",
"Score": "0",
"body": "@vnp, that is a pretty good suggestion, will try it thanks. Didn't think abou that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T07:30:44.943",
"Id": "432910",
"Score": "0",
"body": "@EdwardMinnix, Not sure I follow. The time is when they did a measurement and saved it to file, so all measurements within the same timeframe (30 mins) and same name should be grouped together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:43:58.560",
"Id": "432938",
"Score": "0",
"body": "@Megaloming I'm asking how you determine what the half hour blocks are. Like, is all records from 09:00-09:30 share a group, or if the first record is at 09:18 is it all records up to 9:48? The simpler your categorization, the easier it would be to do the tasks you mentioned."
}
] | [
{
"body": "<p>I find the problem you are trying to solve to be as hard to grasp from the code presented as from the description:<br>\n- <a href=\"https://www.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow noreferrer\">document your code</a>, using the conventions of the language (&environment) of choice.<br>\n- use telling names</p>\n\n<ul>\n<li>In the <code>for</code>-loop, you don't use <code>i</code>: don't use <code>enumerate()</code>.</li>\n<li>I think the first comprehension easier to understand with <code>reading</code> (? \"<code>r</code>\") mentioned first:<br>\n<code>measurement = (y for y in self.records if reading.<predicate>(y))</code></li>\n<li>I think it confusing to use the same identifier for unrelated objects in one and the same statement - suggesting <code>if not any(reading in n for n in new):</code></li>\n<li>instead of <code>if <condition>: <pass> else: <act></code> do<br>\n<code>if not <condition>: <act></code></li>\n<li><code>compare_record_same_name()</code> is a horrible name, as it mentions only half of what the function checks. It seems it is there to check whether the other record belongs to the same \"measurement\" - name it for that: <code>same_measurement()</code>.</li>\n<li>instead of converting <code>duration</code> to seconds each and very time, make <code>TIME_SEPARATOR</code> a <code>timedelta</code></li>\n</ul>\n\n<p>I'd try a different approach:</p>\n\n<ul>\n<li>readings with different instrument names do not belong to the same measurement, anyway:<br>\nuse a separate collection for each name</li>\n<li>sort each collection by time (hoping the method used makes good use of what order is bound to exist in input)</li>\n<li>any gaps exceeding <code>TIME_SEPARATOR</code> separate measurements</li>\n<li>if the time covered by any group <em>g</em> is too big for one measurement, split at large internal gaps or evenly by number of readings or time range or …</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:13:00.093",
"Id": "433139",
"Score": "0",
"body": "thanks for the feedback. I been messing around with these algorithms for so long, changing this and that, forgetting about style and not removing stuff I dont use anymore. Appreciate it.\nI will try out your last two suggestions also. As for the two first suggestions, I managed to improve it, by sorting the full collection by name and date and comparing each line to their previous line. Seems to be working"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:10:20.727",
"Id": "223483",
"ParentId": "223369",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T17:54:51.340",
"Id": "223369",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm"
],
"Title": "Comparing objects in a list against each other"
} | 223369 |
<p>After writing <code>swnprintf</code>and <code>sbprintf</code> in C (<a href="https://codereview.stackexchange.com/q/223112/200418">Encapsulating snprintf to avoid repetition of sizeof</a>), I've written a C++ version of them:</p>
<hr>
<p><code>swnprintf</code>:</p>
<p>Similar to <code>snprintf</code>. Properties: (properties not mentioned shall be the same as <code>snprintf</code>)</p>
<ul>
<li>It writes the actual value of characters written (excluding the NUL terminator) through a pointer, instead of returning it.</li>
<li>The user can explicitly discard that value by passing <code>NULL</code>.</li>
<li>If a NUL character has been written in the middle of the string (eg.: <code>swnprintf(buf, &w, sizeof(buf), "%c%c%c", 'a', 0, 'b');</code>), the last NUL written is not counted, but any other characters until that one, including NULs are counted. In this example, <code>w == 3</code> after the function call.</li>
<li>If the string is truncated, the value written is the actual number of characters written, and not the value that would have been written had <code>n</code> been sufficiently large.</li>
<li>If there's an error in the internal call to snprintf, the resulting string is unreliable (<code>written</code> is also unreliable) and the <code>return</code> value is negative. If there's truncation, the string is valid and the <code>return</code> value is positive. If there's no error, the <code>return</code> value is 0.</li>
<li><code>errno</code> is set on any error. Truncation: <code>ENOMEM</code>. The absolute value of the return value is the same as errno.</li>
</ul>
<p>Usage:</p>
<ul>
<li>Example where the user doesn't care about truncation:</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>char buf[BUFSIZ];
ptrdiff_t tmp;
ptrdiff_t len;
if (alx::swnprintf(buf, &tmp, sizeof(buf), "text, num=%i", 7) < 0)
goto err;
len = tmp;
if (alx::swnprintf(&buf[len], &tmp, sizeof(buf) - len, "2nd part") < 0)
goto err;
len += tmp;
</code></pre>
<ul>
<li>Example where the user cares about truncation and doesn't about len:</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>char cmd[_POSIX_ARG_MAX];
ptrdiff_t tmp;
if (alx::swnprintf(cmd, &tmp, sizeof(cmd), "%s ", "cat"))
goto err;
if (alx::swnprintf(&cmd[tmp], NULL, sizeof(cmd) - tmp, " %s ", "main.c"))
goto err;
system(cmd);
</code></pre>
<hr>
<p><code>sbprintf</code>:</p>
<p>This is a higher abstraction than <code>swnprintf</code>. It is designed to only accept arrays as input. It is safer because it calculates internally the size of the buffer, so the user has less chance of writing buggy code. The down side is that it is less flexible (it can only write at the beginning of a buffer). Apart from that, the behaviour is the same as in <code>swnprintf</code>.</p>
<p>Properties: (properties not mentioned shall be the same as <code>swnprintf</code>)</p>
<ul>
<li>It shall only compile if the string is a <code>char []</code> and not a <code>char *</code>.</li>
<li>It is impossible to write past the buffer, because the user doesn't input its size.</li>
</ul>
<p>Usage:</p>
<ul>
<li>Example where the user doesn't care about truncation:</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>char buf[BUFSIZ];
ptrdiff_t len;
if (alx_sbprintf(buf, &len, "text, num=%i", 7) < 0)
goto err;
</code></pre>
<ul>
<li>Example where the user cares about truncation and doesn't about len:</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>char cmd[_POSIX_ARG_MAX];
if (alx_sbprintf(cmd, NULL, "%s %s", "cat", "main.c"))
goto err;
system(cmd);
</code></pre>
<hr>
<hr>
<p>Implementation:</p>
<p><strong><code>swnprintf</code>:</strong></p>
<p><code>swnprintf.hpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef ALX_STDIO_PRINTF_SWNPRINTF_HPP
#define ALX_STDIO_PRINTF_SWNPRINTF_HPP
#include <cstdarg>
#include <cstddef>
namespace alx {
int swnprintf(char *__restrict__ str, ptrdiff_t *__restrict__ written,
ptrdiff_t nmemb, const char *__restrict__ format, ...);
} /* namespace alx */
#endif /* libalx/base/stdio/printf/swnprintf.hpp */
</code></pre>
<p><code>swnprintf.cpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "libalx/base/stdio/printf/swnprintf.hpp"
#include <cerrno>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
namespace alx {
int swnprintf(char *__restrict__ str, ptrdiff_t *__restrict__ written,
ptrdiff_t nmemb, const char *__restrict__ format, ...)
{
va_list ap;
int len;
if (nmemb < 0)
goto neg;
va_start(ap, format);
len = vsnprintf(str, nmemb, format, ap);
va_end(ap);
if (written != NULL)
*written = len;
if (len < 0)
goto err;
if ((unsigned)len >= nmemb)
goto trunc;
return 0;
err:
return -errno;
trunc:
if (written)
*written = nmemb - 1;
errno = ENOMEM;
return ENOMEM;
neg:
errno = EOVERFLOW;
return -EOVERFLOW;
}
} /* namespace alx */
</code></pre>
<hr>
<p><strong><code>sbprintf</code>:</strong></p>
<p><code>sbprintf.hpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef ALX_STDIO_PRINTF_SBPRINTF_HPP
#define ALX_STDIO_PRINTF_SBPRINTF_HPP
#include "libalx/base/assert/assert.hpp"
#include "libalx/base/stdio/printf/swnprintf.hpp"
namespace alx {
/*
* int alx_sbprintf(char buff[__restrict__], ptrdiff_t *__restrict__ written,
* const char *__restrict__ fmt, ...);
*/
#define alx_sbprintf(buff, written, fmt, ...) ( \
{ \
\
alx_static_assert_char_array(buff); \
alx::swnprintf(buff, written, sizeof(buff), fmt, ##__VA_ARGS__);\
} \
)
} /* namespace alx */
#endif /* libalx/base/stdio/printf/sbprintf.hpp */
</code></pre>
<hr>
<p>Macros used by the code above:</p>
<p><code>assert.hpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef ALX_ASSERT_ASSERT_HPP
#define ALX_ASSERT_ASSERT_HPP
#include <cassert>
#include <type_traits>
namespace alx {
#define alx_static_assert_array(a) do \
{ \
\
static_assert(std::is_array <typeof(a)>::value, "Not a `[]`!"); \
} while (0)
#define alx_static_assert_char_array(a) do \
{ \
\
alx_static_assert_array(a); \
static_assert(std::is_same <char, typeof((a)[0])>::value, \
"Not a `char[]`!"); \
} while (0)
} /* namespace alx */
#endif /* libalx/base/assert/assert.hpp */
</code></pre>
<p>Is there anything that can be improved in these two functions? I'm starting with C++ (I'm used to C), so I don't know if there are more efficient/safe methods to do this.</p>
<p>Improvements in the usage (interface) are very welcome.</p>
<p>Is <code>ENOMEM</code> adecuate when the string has been truncated? My other candidate was <code>EOVERFLOW</code>, but it was already being used by <code>snprintf</code> so I thought it might be better to choose a different one.</p>
<hr>
<p><strong>Edit</strong></p>
<p>The reasons behind so many <code>goto</code>s are:</p>
<ul>
<li><p>Unconditional statements are easier to understand and follow: The error-free path has the minimum conditional statements possible, and they are as short as possible, and therefore, the main code is more compact vertically. When you only want to know what the function does, you can read the first part of the body, and assume the <code>goto</code>s will do some cleanup job. Given that eye movement is easier horizontally than vertically, that makes the code easier for the eyes.</p></li>
<li><p>Nesting is reduced: Those <code>if</code>s after the <code>goto</code> would be nested to the <code>if</code> that reports the error. With 8-char tabs, that lets you have more characters per line. Also less eye movement (in this case horizontal).</p></li>
<li><p>Use of braces is reduced: That's a lot of almost-empty lines saved, and therefore, again less vertical movement for the eyes.</p></li>
<li><p>Errors by not updating individual exit points when making modifications are prevented: I said that when you want to know what the function does, you read the first part; when you want to know how the function handles error conditions, you read the last part. All error handling is together, so again, less vertical movement. When reading this part you can know where the <code>goto</code>s come from by their labels (I hope they are meaningful enough), and focus only on the error handling itself.</p></li>
<li><p>Although it can help the optimizer to remove duplicated code some times, that's a secondary reason for me; and sometimes I've seen it the other way (less efficient code). When the function is not critical, I just don't care; when it is, I do whatever is best.</p></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:28:22.827",
"Id": "433093",
"Score": "1",
"body": "I'm sorry, but this does not look like C++ at all. It looks like C with a few C++ features."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T17:46:57.493",
"Id": "433244",
"Score": "1",
"body": "So many bad usages of `goto`. It was show in the `60's` that nearly all uses of `goto` can be replaced with a better higher level structure. It was then shown in the `70's` that goto produces hard to read and hard to maintain spaghetti code. Even in C the usage of `goto` is rare (there was a thing about single exit point for a while) but in C++ we don't mind multiple exit points as RAII cleans up things so usage of `goto` is practically non existent. In my 40 years of development I have used it twice in production both (in hindsight) were wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:31:49.117",
"Id": "433259",
"Score": "0",
"body": "@MartinYork That's subjective. I recommend reading this: https://koblents.com/Ches/Links/Month-Mar-2013/20-Using-Goto-in-Linux-Kernel-Code/ and this: https://www.kernel.org/doc/html/v4.10/process/coding-style.html#centralized-exiting-of-functions . A couple of months ago I measured the density of `goto` in my code, and it is more or less the same as in the kernel. Basically I move error handling with a `goto` so that it is after the main `return` of the function. I avoid deep nesting with that. However, if there is a better C++ way, I'd like to know; I have to say I don't know much C++ yet"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:38:39.657",
"Id": "433260",
"Score": "0",
"body": "@CacahueteFrito Well set up false dichotomy. You are comparing your application level code with kernal level code. The difference here is resource management (and a lot of other stuff). The good reason mentioned by `CHES KOBLENTS` are well though out and documented. If you have a reason then you should document your reasons, then we would be able to tell if your usage is justified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:18:51.063",
"Id": "433267",
"Score": "0",
"body": "@MartinYork Edited the question to add the reasons behind `goto`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:37:16.727",
"Id": "433276",
"Score": "0",
"body": "I leave you with: `The goto statement comes in handy when a function exits from multiple locations and some common work such as cleanup has to be done. If there is no cleanup needed then just return directly.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:43:12.633",
"Id": "433277",
"Score": "0",
"body": "`Nesting is reduced`: Not in your code it makes no difference. `Use of braces is reduced`: Not sure how this is considered a good thing. `Errors by not updating individual exit points when making modifications are prevented`: This is done using RAII automatically without needing the programer to make mistakes. `optimizer to remove duplicated code some times`: Which can be done by using inline functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:48:54.677",
"Id": "433278",
"Score": "0",
"body": "Forgot to quote my source: The statament above comes from the kernel coding standard: https://www.kernel.org/doc/html/v4.10/process/coding-style.html?highlight=goto Just like you seem to rip your justifications and retroactively say they apply to your code when they obviously don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:50:15.543",
"Id": "433279",
"Score": "0",
"body": "@MartinYork By cleanup I consider not only things like `free()`, but also setting the error codes, and clearing variables like `written`. `if (written) *written = ...;` would add a level of indentation. `inline` is for functions which are very very short (that's 3 lines for me), or for functions that are long but do things optimizable at compile-time; this isn't the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:56:52.007",
"Id": "433280",
"Score": "0",
"body": "@MartinYork There is only one `goto` (`err`) where I could `return` directly, and I give that to you, but it is because I removed some cleanup code and didn't remove the `goto`. The rest is still with the rules"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T21:39:28.507",
"Id": "433555",
"Score": "0",
"body": "@L.F. I don't think you need to write code that a C programmer couldn't understand to say that a program is C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T23:39:34.720",
"Id": "433570",
"Score": "0",
"body": "C and C++ are very different languages with very different programming practices and idioms. If your code cannot be differentiated from C code at a glance, you are probably writing low-level or obsolete C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T23:50:36.350",
"Id": "433571",
"Score": "0",
"body": "What's more, your `goto`s don't even reduce the number of `if`s (there are still 4 or them in `swnprintf`), so how?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T03:17:10.290",
"Id": "433585",
"Score": "0",
"body": "@L.F. There's one `if` hidden in the gotos, but the main goal was to reduce the size of the ifs to just one line each"
}
] | [
{
"body": "<p><code><cstddef></code> defines <strong><code>std::ptrdiff_t</code></strong> - the implementation is allowed to also define it in the global namespace, but it's not required to - so always qualify the type.</p>\n\n<p>I was expecting to see <code>sbprintf()</code> defined as a template, rather than as a macro (as an aside, macros work at the preprocessor level, and the <code>namespace</code> definition in that file is empty and useless). Here's how the template looks:</p>\n\n<pre><code>namespace alx {\n\n template<std::size_t N, typename... Args>\n int sbprintf(char(&buff)[N], std::ptrdiff_t *written,\n const char *fmt, Args... args)\n {\n return swnprintf(buff, written, sizeof buff, fmt, args...);\n }\n\n}\n</code></pre>\n\n<p>Not only is this much neater than a macro, it's standard C++ (no GNU extensions), and automatically type-safe with no need for static asserts.</p>\n\n<p>We can enable extra type checking on GCC using the <code>format</code> attribute, but we'd need to use <code><cstdarg></code> variable argument list rather than a template parameter pack for that.</p>\n\n<p>I don't see the advantage of giving the functions different names; this is a situation where operator overloading allows us to use one name regardless of arguments (and allows natural extension to write wide character strings, for instance). We might choose to provide overloads for providing the <code>written</code> argument or not (by reference), as I can't see any need for this to be a run-time thing.</p>\n\n<p>When <code>std::vsnprintf()</code> returns a negative result, we shouldn't be storing that in <code>written</code> - it makes more sense to store zero instead, and ensure we write an empty string.</p>\n\n<p>I think the use of <code>goto</code> for error handling is less clear than simply putting the error return inline - each label has only one entry point, and there's no common cleanup to do.</p>\n\n<p>The cast of <code>len</code> to <code>unsigned</code> is pointless and possibly harmful, given that <code>std::ptrdiff_t</code> is a signed type.</p>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<p>With some of the improvements suggested above, I get the following.</p>\n\n<h3>Header</h3>\n\n<pre><code>#include <cstdarg>\n#include <cstddef>\n\n#ifdef __GNUC__\n#define attribute(x) __attribute__(x)\n#else\n#define attribute(x)\n#endif\n\nnamespace alx {\n\n // va_list version\n int sprintf(char *str, std::ptrdiff_t *written,\n std::ptrdiff_t buf_size, const char *format, va_list ap)\n attribute((format (printf, 4, 0)));\n\n // general version\n int sprintf(char *str, std::ptrdiff_t *written,\n std::ptrdiff_t buf_size, const char *format, ...)\n attribute((format (printf, 4, 5)));\n\n // deduce size from buffer argument\n template<std::size_t N>\n int sprintf(char(&buff)[N], std::ptrdiff_t *written,\n const char *fmt, ...)\n attribute((format (printf, 3, 4)));\n}\n\n#undef attribute\n\n// template definition\ntemplate<std::size_t N>\nint alx::sprintf(char(&buff)[N], std::ptrdiff_t *written,\n const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n int result = alx::sprintf(buff, written, N, fmt, ap);\n va_end(ap);\n return result;\n}\n</code></pre>\n\n<h3>Implementation</h3>\n\n<pre><code>#include <cerrno>\n#include <cstdarg>\n#include <cstddef>\n#include <cstdio>\n\nint alx::sprintf(char *str, std::ptrdiff_t *written,\n std::ptrdiff_t buf_size, const char *format, va_list ap)\n{\n if (buf_size <= 0) {\n return - (errno = EOVERFLOW);\n }\n\n int len = std::vsnprintf(str, buf_size, format, ap);\n\n if (len < 0) {\n *str = '\\0';\n if (written) {\n *written = 0;\n }\n return -errno;\n }\n\n if (len >= buf_size) {\n if (written) {\n *written = buf_size - 1;\n }\n return - (errno = EOVERFLOW);\n }\n\n if (written) {\n *written = len;\n }\n\n return 0;\n}\n\nint alx::sprintf(char *str, std::ptrdiff_t *written,\n std::ptrdiff_t buf_size, const char *format, ...)\n{\n va_list ap;\n va_start(ap, format);\n int result = alx::sprintf(str, written, buf_size, format, ap);\n va_end(ap);\n return result;\n}\n</code></pre>\n\n<p>Look Ma, no macros!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:10:05.613",
"Id": "432919",
"Score": "0",
"body": "About the two different names, given that they have different usage, and that they also will be in C, it makes some sense. If these entered the standard C library some day that would be unbelievably amazing for me :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:14:50.133",
"Id": "432922",
"Score": "0",
"body": "About written: yes, good ideas. About the cast to `(unsigned)`: that was a bug; I had it because I first used `size_t` instead of `ptrdiff_t`, so it was needed, but I should have removed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:18:53.930",
"Id": "432927",
"Score": "1",
"body": "I used the `format` attribute in the modified code. You can demo it by changing the integer `7` in your first example to a float `7.`, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:20:45.607",
"Id": "432928",
"Score": "0",
"body": "About `goto`: I prefer to see cleanly the error-free path. Error handling one-liners get inlined; everything that requires braces goes to a `goto`. Rationale: (partially) Linux: https://www.kernel.org/doc/html/v4.10/process/coding-style.html#centralized-exiting-of-functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:28:48.620",
"Id": "432930",
"Score": "0",
"body": "The `goto` is an opinion point, of course. You have my opinion, but you're not obliged to act on it. I do recommend including \"unnecessary\" braces for one-line conditionals, rather than blindly trusting the tools to help. BTW, I always forget the correct syntax for inferring array size in a template, so don't beat yourself up for struggling with that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:01:34.703",
"Id": "432980",
"Score": "0",
"body": "Is there any reason why in your first snippet the template passes the `...`, but in **\"*Header*\"** it uses `va_list`? Can you choose any? And why only in the first case the `...` is between `<>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:27:52.510",
"Id": "432989",
"Score": "0",
"body": "-Wuninitialized `*written` when `buf_size < 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:41:23.180",
"Id": "432998",
"Score": "1",
"body": "*\"and ensure we write an empty string.\"*: Make sure that `buf_size > 0` :). I think that's a good reason not to trust the string ever on negative errors. The user cannot know 100% sure if the function wrote a starting NUL, so it's better to leave it as unreliable always (when return < 0), at least in the documentation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:58:50.263",
"Id": "433004",
"Score": "0",
"body": "Are you mixing up `...` for the varargs argument list and `...` for a template parameter pack? They are quite different beasts. The reason is stated soon after my first code block - GCC format checking only works with the varargs, and not with a parameter pack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:05:22.720",
"Id": "433006",
"Score": "0",
"body": "Ohh ok. I come from C, so that was a bit of Chinese to me :). I'll Google that."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T08:54:36.470",
"Id": "223400",
"ParentId": "223372",
"Score": "2"
}
},
{
"body": "<p>The error handling can be simplified to three <code>return</code> points instead of four: (removes one line)</p>\n\n<pre class=\"lang-c prettyprint-override\"><code> return 0;\ntrunc:\n if (written)\n *written = nmemb - 1;\n errno = ENOMEM;\n return ENOMEM;\nneg:\n errno = EOVERFLOW;\nerr:\n if (written)\n *written = 0;\n return -errno;\n</code></pre>\n\n<p>Note: This includes <strong>Toby Speight</strong>'s suggestion of clearing <code>written</code></p>\n\n<hr>\n\n<p>A better name for <code>swnprintf</code> would be <code>snprintfs</code>, given that it can replace every use case of <code>snprintf</code> with added safety.</p>\n\n<hr>\n\n<p>The return value should <strong>always</strong> be used. Failure to do so shall be diagnosed:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>__attribute__ ((warn_unused_result))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:01:01.397",
"Id": "223415",
"ParentId": "223372",
"Score": "0"
}
},
{
"body": "<p>Welcome to the world of modern C++!</p>\n\n<p>The OP has stated that \"I don't think you need to write code that a C programmer couldn't understand to say that a program is C++.\" That's partially right — high-level, modern C++ techniques are easy to understand. What is wrong is that C++ programs don't have to be understood by C programmers in particular — C++ and C are different languages. If you are programming in the common subset of C and C++ (plus a few C++ features), you are not programming in C++.</p>\n\n<p>As such, this answer focuses exclusively on how to convert your code to C++ code. It seems that the OP is not very familiar with modern C++ programming, so some of the points may not make much sense to the OP. As they get more familiar with C++ programming, hopefully they will understand.</p>\n\n<hr>\n\n<blockquote>\n <p>After writing <code>swnprintf</code> and <code>sbprintf</code> in C (<a href=\"https://codereview.stackexchange.com/q/223112\">Encapsulating snprintf\n to avoid repetition of\n sizeof</a>), I've written\n a C++ version of them:</p>\n</blockquote>\n\n<p>Oh that's nice. Don't have to deal with low-level programming details anymore. Finally we have a C++ wrapper on top of <code>snprintf</code>.</p>\n\n<blockquote>\n <p><code>swnprintf</code>:</p>\n \n <p>Similar to <code>snprintf</code>. Properties: (properties not mentioned shall be\n the same as <code>snprintf</code>)</p>\n \n <ul>\n <li>It writes the actual value of characters written (excluding the NUL terminator) through a pointer, instead of returning it.</li>\n </ul>\n</blockquote>\n\n<p>Huh? I was expecting a C++-style function. Why are we using output parameters?</p>\n\n<blockquote>\n <p>The user can explicitly discard that value by passing NULL.</p>\n</blockquote>\n\n<p>Why not just return it then? Let's read on.</p>\n\n<blockquote>\n <p>If a NUL character has been written in the middle of the string (eg.:\n <code>swnprintf(buf, &w, sizeof(buf), \"%c%c%c\", 'a', 0, 'b');</code>), the last\n NUL written is not counted, but any other characters until that one,\n including NULs are counted. In this example, <code>w == 3</code> after the\n function call.</p>\n</blockquote>\n\n<p>This makes sense. The NUL character is not included in the length of a string anyway.</p>\n\n<blockquote>\n <p>If the string is truncated, the value written is the actual number of\n characters written, and not the value that would have been written had\n <code>n</code> been sufficiently large.</p>\n</blockquote>\n\n<p>The phrase \"the string is truncated\" caught my eyes. Why do we have to care about that in C++?</p>\n\n<blockquote>\n <p>If there's an error in the internal call to snprintf, the resulting\n string is unreliable (<code>written</code> is also unreliable) and the return\n value is negative. If there's truncation, the string is valid and the\n return value is positive. If there's no error, the return value is 0.</p>\n</blockquote>\n\n<p>The reason for using an output parameter is revealed — you are using the return value to report errors. In C++, the usual way is to use the return value for output, and <em>exceptions</em> to report errors.</p>\n\n<blockquote>\n <p><code>errno</code> is set on any error. Truncation: <code>ENOMEM</code>. The absolute value\n of the return value is the same as <code>errno</code>.</p>\n</blockquote>\n\n<p>Good old <code>errno</code> ... C++ programs are expected to stay a few meters away from it.</p>\n\n<blockquote>\n <p>Usage:</p>\n \n <ul>\n <li><p>Example where the user doesn't care about truncation:</p>\n\n<pre><code>char buf[BUFSIZ];\nptrdiff_t tmp;\nptrdiff_t len;\n\nif (alx::swnprintf(buf, &tmp, sizeof(buf), \"text, num=%i\", 7) < 0)\n goto err;\nlen = tmp;\nif (alx::swnprintf(&buf[len], &tmp, sizeof(buf) - len, \"2nd part\") < 0)\n goto err;\nlen += tmp;\n</code></pre></li>\n </ul>\n</blockquote>\n\n<p>Wait, this is C — well, not really, we have <code>::</code>. But this isn't the kind of C++ I am expecting — in C++ I expect this:</p>\n\n<pre><code>std::string result = alx::swnprintf(\"text, num=%i\", 7) + alx::swnprintf(\"2nd part\");\n</code></pre>\n\n<p>Notice:</p>\n\n<ul>\n<li><p>the conciseness and readability; (I doubt a C programmer has trouble <em>understanding</em> it)</p></li>\n<li><p>the reduced opportunity for errors to kick in;</p></li>\n<li><p>the lack of explicit memory management (<code>std::string</code> does them under the hood) and error checking (exceptions do them under the hood).</p></li>\n</ul>\n\n<blockquote>\n <ul>\n <li><p>Example where the user cares about truncation and doesn't about len:</p>\n\n<pre><code>char cmd[_POSIX_ARG_MAX];\nptrdiff_t tmp;\n\nif (alx::swnprintf(cmd, &tmp, sizeof(cmd), \"%s \", \"cat\"))\n goto err;\nif (alx::swnprintf(&cmd[tmp], NULL, sizeof(cmd) - tmp, \" %s \", \"main.c\"))\n goto err;\nsystem(cmd);\n</code></pre></li>\n </ul>\n</blockquote>\n\n<p>Corresponding example in a C++ program:</p>\n\n<pre><code>system(alx::swnprintf(\"%s %s\", \"cat\", \"main.c\"));\n</code></pre>\n\n<p>Where <code>system</code> has been wrapped to take <code>std::string</code>:</p>\n\n<pre><code>int system(const std::string& command)\n{\n return std::system(command.c_str());\n}\n</code></pre>\n\n<blockquote>\n <p><code>sbprintf</code>:</p>\n \n <p>This is a higher abstraction than <code>swnprintf</code>. It is designed to only\n accept arrays as input. It is safer because it calculates internally\n the size of the buffer, so the user has less chance of writing buggy\n code. The down side is that it is less flexible (it can only write at\n the beginning of a buffer). Apart from that, the behaviour is the same\n as in <code>swnprintf</code>.</p>\n</blockquote>\n\n<p>I would expect a \"higher abstraction\" to behave as in the above examples.</p>\n\n<hr>\n\n<p>It is always easier said than done. Now let's convert your code step by step.</p>\n\n<p>I am very glad to see that you used a namespace. This avoids name clashes.</p>\n\n<p>Here's your <code>swnprintf</code> declaration:</p>\n\n<pre><code>int swnprintf(char *__restrict__ str, ptrdiff_t *__restrict__ written,\n ptrdiff_t nmemb, const char *__restrict__ format, ...);\n</code></pre>\n\n<p>I would separate it to two functions. One receives a length argument:</p>\n\n<pre><code>template <typename... Args>\nstd::string swnprintf(const char* format, std::size_t length, Args&&... args);\n</code></pre>\n\n<p>The other does not, and calls <code>snprintf</code> twice to determine the length: (I have no idea how to name it)</p>\n\n<pre><code>template <typename... Args>\nstd::string swprintf(const char* format, Args&&... args);\n</code></pre>\n\n<p>Notice that the output is stored in the returned <code>std::string</code>. <code>length</code> is of type <code>std::size_t</code> to prevent negative length in the first place. The <code>str</code> is allocated internally by <code>std::string</code>, <code>written</code> is available via <code>str.size()</code>, <code>nmemb</code> is no longer needed, and the return value is converted to exceptions. And we use a template parameter pack to pass the arguments to <code>snprintf</code>.</p>\n\n<p>You need to define templates in the header. Here's my implementation:</p>\n\n<pre><code>namespace alx {\n\n struct Internal_error :std::exception {};\n struct Truncation_error :std::exception {};\n\n template <typename... Args>\n std::string swnprintf(const char* format, std::size_t length,\n Args&&... args)\n {\n std::string buffer(length, '\\0');\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wformat\"\n int len = std::snprintf(buffer.data(), length + 1, format,\n std::forward<Args>(args)...);\n#pragma GCC diagnostic pop\n if (len < 0)\n throw Internal_error{};\n else if (static_cast<std::size_t>(len) <= length)\n return buffer;\n else\n throw Truncation_error{};\n }\n\n template <typename... Args>\n std::string swprintf(const char* format, Args&&... args)\n {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wformat\"\n int len = std::snprintf(nullptr, 0, format, args...);\n#pragma GCC diagnostic pop\n return swnprintf(format, len, args...);\n }\n\n}\n</code></pre>\n\n<p><code>Internal_error</code> and <code>Truncation_error</code> are exception types to denote errors. (I had to add the pragmas to suppress the warning; in practice some kind of wrapping is expected.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T03:35:02.640",
"Id": "433587",
"Score": "0",
"body": "I got the concept, although as expected, I lost myself a little bit. I hope to understand it soon, though. Only concern might be performance; it doesn't look like a light function call. Thank you very much :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T01:27:46.133",
"Id": "223653",
"ParentId": "223372",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223400",
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T18:31:09.463",
"Id": "223372",
"Score": "4",
"Tags": [
"c++",
"gcc"
],
"Title": "Encapsulating snprintf to simplify usage: sbprintf & swnprintf"
} | 223372 |
<p>For <a href="https://github.com/Joelius300/ChartJSBlazor" rel="nofollow noreferrer">my blazor library</a> which is a modification of <a href="https://github.com/mariusmuntean/ChartJs.Blazor" rel="nofollow noreferrer">this awesome library</a> I have to convert an <code>ExpandoObject</code> into a <code>Dictionary<string, object></code> since <code>ExpandoObject</code>s aren't serialized properly in the newest preview versions of dotnet-core. See <a href="https://stackoverflow.com/questions/56693103/invoke-javascript-method-from-c-sharp-with-dynamic-parameter">my question related to this</a> for more details.</p>
<p>My current approach goes as follows: </p>
<pre><code>Dictionary<string, object> ConvertDynamicToDictonary(IDictionary<string, object> value)
{
return value.ToDictionary(
p => p.Key,
p =>
{
// if it's another IDict (might be a ExpandoObject or could also be an actual Dict containing ExpandoObjects) just go through it recursively
if (p.Value is IDictionary<string, object> dict)
{
return ConvertDynamicToDictonary(dict);
}
// if it's an IEnumerable, it might have ExpandoObjects inside, so check for that
if (p.Value is IEnumerable<object> list)
{
if (list.Any(o => o is ExpandoObject))
{
// if it does contain ExpandoObjects, take all of those and also go through them recursively
return list
.Where(o => o is ExpandoObject)
.Select(o => ConvertDynamicToDictonary((ExpandoObject)o));
}
}
// neither an IDict nor an IEnumerable -> it's probably fine to just return the value it has
return p.Value;
}
);
}
</code></pre>
<p>This works fine but I'm not sure about the <code>IEnumerable</code> part. If I omit the <code>list.Any</code> check it still works fine. New version (only write the <code>IEnumerable</code> part changed):</p>
<pre><code>// if it's an IEnumerable, it might have ExpandoObjects inside, so check for that
if (p.Value is IEnumerable<object> list)
{
// take all ExpandoObjects and go through them recursively
return list
.Where(o => o is ExpandoObject)
.Select(o => ConvertDynamicToDictonary((ExpandoObject)o));
}
</code></pre>
<p>I have also tried using <code>IEnumerable<ExpandoObject></code> instead of just <code>IEnumerable<object></code> to see if that would work and maybe be cleaner and I can confirm that that does <strong>not</strong> work (throws error). </p>
<p>What I would like to know now is, if it's a good idea to omit the <code>Any</code> check and which option is more performant (and why) and/or cleaner.<br>
Also please mention every small thing that bugs you, I always want to make it as perfect as possible :) </p>
<p>I first wanted to post this on StackOverflow but I think it fits better on here - correct me if I'm wrong. </p>
<p>EDIT 1:</p>
<p>Because I feel like I have not made clear how I will use this function, I have some demo-code for you. This will of course not compile, it's just to show how and why I need this method.<br>
If this edit is problematic because I'm adding new code, I will post a new, more complete question later on (I sadly don't have anymore time today).</p>
<pre><code>// this class (like all the others) are of course much more complicated than this.
// There's also a lot of abstraction etc (you can see the actual code on the github I've linked at the start).
SomeConfig config = new SomeConfig
{
Options = new SomeOptions
{
SomeInt = 2,
SomeString = null, // any trace of this property will not be present in the expando object
Axes = new List<Axis>
{
new Axis() // this axis will also be an expandoObject after being extracted from the json
}
},
Data = new SomeData
{
Data = new List<int> { 1, 2, 3, 4, 5 },
SomeString = "asdf"
}
};
dynamic expando = /* ParseConfigToJsonWithoutNulls -> ParseJsonToExpandoObject */
IJSRuntime jsRT = GetTheRuntime();
jsRT.InvokeAsync("blabla", expando); // this would NOT work because ExpandoObject cannot be serialized to json correctly and throws a runtime error
// this method is what we need in the best way possible without missing something :)
Dictionary<string, object> dictFromExpando = ConvertExpandoToDictonary(expando);
// so the only purpose of the ConvertExpandoToDictonary is to recursively convert all the ExpandoObjects to Dictionaries as they are serializable
// I have to do this recursively since there are nested ExpandoObjects that were created when parsing the huge json to the ExpandoObject with Json.Net
// I have decided to go with Dictionaries because it works and ExpandoObject implements the interface IDictionary<string, object>
jsRT.InvokeAsync("blabla", dictFromExpando); // this now works perfectly fine
</code></pre>
<h3>EDIT 2:</h3>
<p><strong>I have asked <a href="https://codereview.stackexchange.com/questions/223410/recursive-conversion-from-expandoobject-to-dictionarystring-object-rework">a new, much more detailed question</a>. Please have a look at it if you have the time :)</strong> </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:42:00.247",
"Id": "432844",
"Score": "2",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:45:03.603",
"Id": "432848",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ Sorry I did not know. I feel like this was just a small mistake I made which may have caused some misunderstandings. Do I really have to ask a new question just for that (becaues I feel like my main concern didn't have to do with that at all) or how would you recommend me clearing that misunderstanding up to the concerned question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:47:12.837",
"Id": "432850",
"Score": "3",
"body": "I would await sufficient answers and comments. Then you could self-answer or accept if you please, and perhaps also ask a follow-up question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T21:10:06.007",
"Id": "432873",
"Score": "2",
"body": "[The rollback is being discussed on meta](https://codereview.meta.stackexchange.com/q/9225/120114)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:59:53.917",
"Id": "432956",
"Score": "1",
"body": "Okay, will do that. It's fine if I just accept the most helpful one right? Because all of the answers were good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:02:30.283",
"Id": "432957",
"Score": "2",
"body": "Sure, it happens often enough you receive multiple very good answers making the decision which to pick a bit harder :-)"
}
] | [
{
"body": "<p>Inconsistent definition of <code>ExpandoObject</code>. It's <code>IDictionary<string, object></code> here:</p>\n\n<blockquote>\n<pre><code>if (p.Value is IDictionary<string, object> dict)\n{\n return ConvertDynamicToDictonary(dict); // <- possibly already visited?\n}\n</code></pre>\n</blockquote>\n\n<p>and <code>ExpandoObject</code> here:</p>\n\n<blockquote>\n<pre><code>if (list.Any(o => o is ExpandoObject))\n{\n // ..\n}\n</code></pre>\n</blockquote>\n\n<p>I would opt to use <code>IDictionary<string, object></code> both to improve consistency and flexibility of handling instances in the hierarchy.</p>\n\n<hr>\n\n<p>It is not clear whether the structure of the hierarchical data is a <em>tree</em> or a <em>cyclic graph</em>. This has impact on a possible infinite recursion. In case of a cyclic graph, I would keep track of visited references.</p>\n\n<hr>\n\n<p>Not all sequences are generic classes. </p>\n\n<p>This condition..</p>\n\n<blockquote>\n <p><code>if (p.Value is IEnumerable<object> list)</code></p>\n</blockquote>\n\n<p>..does not cover when <code>p.Value</code> is <code>IEnumerable</code> but not <code>IEnumerable<object></code>. As note in another answer, be careful with false positives (like <code>string</code>). </p>\n\n<hr>\n\n<p>What if <code>value</code> is null? Try avoiding null reference exceptions in your code.</p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:55:08.423",
"Id": "432859",
"Score": "1",
"body": "Thanks for the ideas. The ExpandoObject should always be a tree since it is just an instance of a class with all traces of null properties removed. This is necessary for correctly invoking some Javascript."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:17:06.407",
"Id": "223378",
"ParentId": "223375",
"Score": "4"
}
},
{
"body": "<p>A few minor stylistic bits that may increase its utility:</p>\n\n<ul>\n<li>since you take in an <code>IDictionary</code>, return an <code>IDictionary</code>.</li>\n<li>make it <code>static</code> as it accesses no instance data or methods.</li>\n<li>since it's now <code>static</code>, make it an extension method.</li>\n<li>validate the parameter passed in.</li>\n</ul>\n\n<p>Also:</p>\n\n<ul>\n<li>since it's a single <code>return</code> statement, make it an expression body.</li>\n</ul>\n\n<p>Further:</p>\n\n<ul>\n<li>yeah, the <code>.Any()</code> is redundant (and less performant if there is an <code>ExpandoObject</code> in the collection) with the <code>.Where()</code> criteria, so no need for it.</li>\n<li>allowed for non-generic <code>IEnumerable</code>.</li>\n<li>renamed some of the locals to be clearer as to their meaning.</li>\n</ul>\n\n<p>Giving:</p>\n\n<pre><code>static IDictionary<string, object> ConvertDynamicToDictionary(this IDictionary<string, object> source) => source?.ToDictionary(\n keySelector => keySelector.Key,\n elementSelector =>\n {\n object value = elementSelector.Value;\n\n // if it's another IDict (might be a ExpandoObject or could also be an actual Dict containing ExpandoObjects) just go through it recursively\n if (value is IDictionary<string, object> dictionary)\n {\n return dictionary.ConvertDynamicToDictionary();\n }\n\n // A special case since string implements IEnumerable.\n if (value is string stringValue)\n {\n return stringValue;\n }\n\n // if it's an IEnumerable, it might have ExpandoObjects inside, so check for that\n if (value is IEnumerable enumerable)\n {\n // if it does contain ExpandoObjects, take all of those and also go through them recursively\n return enumerable\n .Cast<object>()\n .Select(element => element is IDictionary<string, object> expando\n ? expando.ConvertDynamicToDictionary()\n : element);\n }\n\n // neither an IDict nor an IEnumerable -> it's probably fine to just return the value it has\n return value;\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:36:22.763",
"Id": "432839",
"Score": "0",
"body": "Ugh, `string` implements `IEnumerable`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:39:46.167",
"Id": "432842",
"Score": "0",
"body": "Clear points, thank you. Yes I already wanted to point out that IEnumerable is used seemingly everywhere and ask if that would cause issues (it would just decrease the performance right?). Also I have edited my question regarding the signature because the method is already `private` and `static` I just forgot to write that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:44:19.460",
"Id": "432846",
"Score": "0",
"body": "It's not that `IEnumerable` decreases performance, it's that the `.Any()` followed by `.Where()` with the same lambda does the same checking, and therefore `.Any()` is redundant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:47:16.490",
"Id": "432851",
"Score": "0",
"body": "I see. My edit has now been rolled back because I edited the code which you're not supposed to do. My method is actually `private static` - would you still recommend me converting it into an extension method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:47:49.083",
"Id": "432852",
"Score": "0",
"body": "I mean, *I* like them. Especially when the parameter is an interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:47:56.103",
"Id": "432853",
"Score": "1",
"body": "@JesseC.Slicer are you okay with [this revision to the question](https://codereview.stackexchange.com/revisions/223375/3) which would affect your answer? If so, we could re-apply it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:51:57.557",
"Id": "432857",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ I think the revision is minor enough, I could remove a single line from my answer to keep it salient."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:21:48.263",
"Id": "223379",
"ParentId": "223375",
"Score": "2"
}
},
{
"body": "<p>Your method is meant to handle <code>ExpandoObjects</code> explicitly, so it would be better named <code>ConvertExpandoObjectToDictonary</code>, and would probably be less confusing if it actually took an <code>ExpandoObject</code> as the parameter:</p>\n\n<pre><code>Dictionary<string, object> ConvertExpandoObjectToDictonary(ExpandoObject expandoObject);\n</code></pre>\n\n<p>This is what the public API should look like; you can keep the current method as it is (since you need to call it recursively) but make it private and hide it behind the clearer public API.</p>\n\n<hr />\n\n<p>This doesn't really make sense:</p>\n\n<pre><code>if (list.Any(o => o is ExpandoObject))\n{\n // if it does contain ExpandoObjects, take all of those and also go through them recursively\n return list\n .Where(o => o is ExpandoObject)\n .Select(o => ConvertDynamicToDictonary((ExpandoObject)o));\n}\n</code></pre>\n\n<p>You are looking for a single <code>ExpandoObject</code>, and then assuming everything you might need is an expando object and ignoring everything else. I think you want something like this instead, which keeps non-expando entries:</p>\n\n<pre><code>return list\n .Select(o => o is ExpandoObject\n ? ConvertDynamicToDictonary((ExpandoObject)o)\n : o\n );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:37:02.090",
"Id": "432840",
"Score": "0",
"body": "You are enforcing a signature and flow based on a strict interpretation of the spec. Since the spec is lacking some context, I find this approach OK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:40:42.070",
"Id": "432843",
"Score": "1",
"body": "@dfhwze sorry; I'm not sure what you mean? (I'm mostly going by the title, which suggests the purpose of this method is exactly to process `ExpandoObjects`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:44:58.520",
"Id": "432847",
"Score": "0",
"body": "The OP uses a _dict_ both to process dictionaries and expando's. You took the ambiguity away. This has an impact on the algorithm, if there really are dictionaries to be processed that aren't expando's. The OP should perhaps make clear the usage of _dict_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:50:51.740",
"Id": "432855",
"Score": "1",
"body": "@dfhwze I think I see what you mean. I'd maintain that if the _intention_ is to convert `ExpandoObjects` (which is how I read the OP) then the API should reflect that; the work can be referred to a method that processes dictionaries (per the OP): it needn't have any influence on the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:51:37.387",
"Id": "432856",
"Score": "0",
"body": "This method is only used internally and not exposed publicly (I forgot to add the `private static` and cannot edit the code now). The reason I even have this method is because I am parsing a class with lots of (complex and simple) properties to JSON without the null values. This JSON string is then parsed back to a ExpandoObject to get rid of all the null properties (it works and is necessary). The ExpandoObject is in the case of this method just an instance of this class but every trace of null properties are removed. It should also never be a Cycle graph but always a tree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:57:37.577",
"Id": "432865",
"Score": "0",
"body": "@dfhwze I can do that. In what format would that be most practical (those instances are huge with a ton of properites)? I can add a simplified version of the model I have with maybe one or two subclasses, would that be sufficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:58:34.730",
"Id": "432866",
"Score": "1",
"body": "yes :) that would be OK. Let's stop hijacking the comments of this answer now :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:55:05.557",
"Id": "432953",
"Score": "0",
"body": "I have asked [a new question](https://codereview.stackexchange.com/questions/223410/recursive-conversion-from-expandoobject-to-dictionarystring-object-rework) containing json-examples and more. Have a look at it :). Btw you're completely right about the second part, I'd just gotten very lucky that there were no IEnumerables that had objects inside which were not `ExpandoObject`s."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:23:03.147",
"Id": "223380",
"ParentId": "223375",
"Score": "7"
}
},
{
"body": "<p>The root of the problem lies in this line:</p>\n\n<blockquote>\n<pre><code>dynamic expando = /* ParseConfigToJsonWithoutNulls -> ParseJsonToExpandoObject */\n</code></pre>\n</blockquote>\n\n<p>where you decided to parse <code>*.json</code> files into an <code>ExpandoObject</code> and not directly into a <code>Dictionary</code> or some other strong type.</p>\n\n<p>I bet you are using <code>Json.Net</code> for the job and there are <em>countless</em> possibilities to deserialize <code>JSON</code> in such a way that <code>ExpandoObject</code> is not necessary.</p>\n\n<p>This means that the conversion should take place during deserialization and not after that.</p>\n\n<hr>\n\n<p>I suggest posting another question where you show us how you read your <code>*.json</code>. Maybe then we can help you to get rid of the <code>ExpandoObject</code> altogether.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:54:21.773",
"Id": "432952",
"Score": "1",
"body": "I have asked [a new question](https://codereview.stackexchange.com/questions/223410/recursive-conversion-from-expandoobject-to-dictionarystring-object-rework) containing json-examples and more. Have a look at it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T03:31:07.120",
"Id": "504339",
"Score": "1",
"body": "I think `JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonstring)` will only do top level conversion to Dictionary also it does not convert array item."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T04:56:21.933",
"Id": "223393",
"ParentId": "223375",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "223380",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T19:35:52.860",
"Id": "223375",
"Score": "5",
"Tags": [
"c#",
"recursion",
"hash-map"
],
"Title": "Recursive conversion from ExpandoObject to Dictionary<string, object>"
} | 223375 |
<p>As said, this is take 2 (see linked for Take 1 for my massively beginner code: <a href="https://codereview.stackexchange.com/questions/223236/copy-data-from-filtered-table-to-defined-tabs-and-loop-through-defined-list-fix">https://codereview.stackexchange.com/questions/223236/</a>)</p>
<p>As an overview:</p>
<p>I manage the bookkeeping for 40+ companies in an excel workbook. All data is added to a central sheet "Amalgamated Data" and from there data for all transactions for each Company has to be transferred to a sheet for each Company. The single company sheets are then sent to various people at various periods.</p>
<p>All references to the company throught the workbpook are to them as they appear as companyName.</p>
<p>The Code (tested and working - time scale for 40 companies on 400 rows approx 1 min) will be used at least once a day every day. It does the following: </p>
<ol>
<li>Checks if there have been any transactions for that Company since
the start of the financial year (list of Company’s is held in a
separate continuous Column)</li>
<li><p>If there have been no transactions </p></li>
<li><p>If there is an existing tab, clear any transactions from it (clears
out any misbookkept entries)</p></li>
<li><p>If there are no transactions, check the next company.</p></li>
<li>If there have been transactions: </li>
<li>Check if a sheet exists for the Company</li>
<li>If no Sheet, set up new tab by copying veryhidden Template
preformatted and formula’d</li>
<li>If a sheet exists (including if set up in previous Step)</li>
<li><p>Check that a Balance Download Record Exists, if not create one </p></li>
<li><p>Check that an Overview Record exists, if not create one </p></li>
<li><p>Copy all transactions for that Company to the Company Sheet</p></li>
</ol>
<p>I have set this in a loop as the recommendation from Iven Bach of a <code>Dim companyName as Range For Each companyName</code> created an error13 mismatch in the Worksheet(companyName) type with the Watch window show this as integer instead of Worksheet. I have used loop as this allows me to <code>Dim companyName as String</code></p>
<pre><code>Option Explicit
SUB UPDATE_BACKUP_SHEETSFIXED()
'This Sub does the following:
' Filter Amalgamated Data by companyName from table list on General Sheet
' Then
' 1. If no data:
' a. Check if a company Tab exists
' i. If not, move on to next company
' ii. If so:
' 1. If there is existing data clear and move to next company
' 2. If no existing data move to next company
' 2. Check if Company tab exists
' a. If tab does not exist, create:
' i. Tab
' ii. Balance Download Record
' iii. Overview Record
' b. If tab does exist (or has just been created above)
' i. If there is data, Clear existing
' ii. Copy transactions from Amalgamated Data Filter
Dim amalgamatedDateSheet As Worksheet
Set amalgamatedDateSheet = Sheets("Total Data")
Dim sourceTable As ListObject
Set sourceTable = amalgamatedDateSheet.ListObjects("TableFullData")
Dim generalSheet As Worksheet
Set generalSheet = Sheets("General")
Dim templateSheet As Worksheet
Set templateSheet = Sheets("Template")
Dim balanceDownloadSheet As Worksheet
Set balanceDownloadSheet = Sheets("Balance Download")
Dim overviewSheet As Worksheet
Set overviewSheet = Sheets("Overview")
Dim X As Long
X = 4
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Get the Company name from the Company Tab
Do
Dim companyName As String
With generalSheet
companyName = .Range("A" & X).Value
End With
'Clear all filter from table
sourceTable.AutoFilter.ShowAllData
'Filter by Company Name
sourceTable.DataBodyRange.AutoFilter Field:=2, Criteria1:="=" & companyName
'Check if transactions exist
Dim firstColumnContainsNoVisibleCells As Boolean
Dim companySheet As Worksheet
On Error Resume Next
Set companySheet = Sheets(companyName)
On Error Resume Next
firstColumnContainsNoVisibleCells = sourceTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count <= 1
On Error GoTo 0
If firstColumnContainsNoVisibleCells Then
'If no transactions
If Not companySheet Is Nothing = True Then
'If no transactions but Tab exists for Company
Dim targetTable As ListObject
Set targetTable = companySheet.ListObjects(1)
Dim firstTargetColumnContainsVisibleCells As Boolean
On Error Resume Next
firstTargetColumnContainsVisibleCells = targetTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count > 1
'If Data present, clear it
If firstTargetColumnContainsVisibleCells Then
With targetTable
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.count - 1, .DataBodyRange.Columns.count).Rows.Delete
.DataBodyRange.ClearContents
End With
End If
Call CheckRecordsPresent(balanceDownloadSheet, companyName, overviewSheet)
'If no data present move to next company
End If
Else
'If transactions exist
If Not companySheet Is Nothing = False Then
'If tab for Company does not exist
If templateSheet.Visible = xlSheetVeryHidden Then templateSheet.Visible = xlSheetVisible
'Create and rename sheet highlight it yellow
templateSheet.Copy After:=Sheets(5)
ActiveSheet.Range("A20").ListObject.Name = "Table" & (companyName)
ActiveSheet.Name = (companyName)
With ActiveSheet.Tab
.Color = XlRgbColor.rgbYellow
.TintAndShade = 0
End With
Set companySheet = Sheets(companyName)
'Hide template
templateSheet.Visible = xlSheetVeryHidden
'Confirmation Message
MsgBox "Worksheet for " & (companyName) & " created"
End If
'If tab and data exist
Call CheckRecordsPresent(balanceDownloadSheet, companyName, overviewSheet)
'Clear existing data and resize table
Set targetTable = companySheet.ListObjects(1)
On Error Resume Next
firstTargetColumnContainsVisibleCells = targetTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count > 1
If firstTargetColumnContainsVisibleCells Then
With targetTable
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.count - 1, .DataBodyRange.Columns.count).Rows.Delete
.DataBodyRange.ClearContents
End With
End If
'Find first row of table (last row of sheet as data previously cleared)
Dim lastTargetRow As Long
lastTargetRow = companySheet.Range("B" & Rows.count).End(xlUp).Row
With sourceTable.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy
With companySheet
.ListObjects(1).AutoFilter.ShowAllData
.Range("A" & lastTargetRow).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone
Application.CutCopyMode = False
End With
End With
End If
'Loop back to get a new Company's name in Company Table
Set companySheet = Nothing
X = X + 1
'Loop back to get a new Company's name in Employee Roster
Loop While generalSheet.Range("A" & X).Value <> vbNullString
'At end of loop turn screen refresh etc back on
Application.DisplayAlerts = True
Application.ScreenUpdating = True
amalgamatedDateSheet.Select
'Clear all filter from table
sourceTable.AutoFilter.ShowAllData
MsgBox "All Sheets Updated"
End Sub
Private Sub CheckRecordsPresent(ByVal balanceDownloadSheet As Worksheet, ByVal companyName As String, ByVal overviewSheet As Worksheet)
'Check Balance Download Records - create if there isn't one
Dim lastBalanceRow As Long
lastBalanceRow = balanceDownloadSheet.Range("a" & Rows.count).End(xlUp).Row
Dim rangeBalanceDownloadFound As Range
Set rangeBalanceDownloadFound = balanceDownloadSheet.Range(balanceDownloadSheet.Range("A4"), balanceDownloadSheet.Range("A" & lastBalanceRow)).Find(companyName)
If rangeBalanceDownloadFound Is Nothing Then
With balanceDownloadSheet
.ListObjects(1).ListRows.Add
.Rows(lRow).Copy
.Range("A" & lastBalanceRow + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone
Application.CutCopyMode = False
.Range("a" & lRow + 1).Value = companyName
End With
End If
'Check if front page record exists
Dim lastOverviewRow As Long
lastOverviewRow = overviewSheet.Range("a" & Rows.count).End(xlUp).Row
Dim rangeOverviewFound As Range
Set rangeOverviewFound = overviewSheet.Range(overviewSheet.Range("A6"), overviewSheet.Range("A" & lastOverviewRow)).Find(companyName)
If rangeOverviewFound Is Nothing Then
With overviewSheet
.Range("A53:E53").Copy
.Range("A53:E53").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
.Range("A53").Value = companyName
End With
End If
End Sub
</code></pre>
<p>Massive thanks to IvenBack, AJD and Mathieu Guindon for unravelling my (miraculously working) ridiculously messy previous code attempt, below is take 2 that I hope is much more streamlined and removes all (?!) of the redundant lines. Hopefully this is much improved and not too much of a bastardisation of the brilliant recommendations and codes you wrote.</p>
<p>All help gratefully received as I still have a long way to go.</p>
<p>Thanks</p>
<p>R</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:27:30.830",
"Id": "432837",
"Score": "0",
"body": "Kudos for the massive improvements, but I'd advise you stop self-flagellating: we are *all* constantly learning and improving."
}
] | [
{
"body": "<p>This code is much easier to read and understand than the last version. This is a massive leap in attaining clean code in a short amount of time. </p>\n\n<h2>On Errors</h2>\n\n<p>You have the following code:</p>\n\n<pre><code> On Error Resume Next\n Set companySheet = Sheets(companyName)\n On Error Resume Next\n firstColumnContainsNoVisibleCells = sourceTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count <= 1\n\n On Error GoTo 0\n</code></pre>\n\n<p>Well done on removing the error trap as early as possible. You don't need the second <code>On Error Resume Next</code> because the first has already set the relevant conditions. </p>\n\n<p>However, later in the code you set the error trap again, but do not turn it off.</p>\n\n<pre><code> On Error Resume Next\n firstTargetColumnContainsVisibleCells = targetTable.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).count > 1\n</code></pre>\n\n<p>Add an <code>On Error Goto 0</code> statement in there somewhere otherwise you might hide some coding error that is relatively easy to fix <strong>and</strong> you could be hiding an error that gives you false data. </p>\n\n<h2>X</h2>\n\n<p>What is <code>X</code>? You have used descriptive variable names throughout the code, but one mystery remains!</p>\n\n<h2><code>If</code> conditions</h2>\n\n<p>You have two lines of code which have a redundant pattern:</p>\n\n<pre><code>If Not companySheet Is Nothing = True Then\nIf Not companySheet Is Nothing = False Then\n</code></pre>\n\n<p>Later on you use a form that is cleaner:</p>\n\n<pre><code>If rangeOverviewFound Is Nothing Then\n</code></pre>\n\n<p>The earlier statements can be recast into a more natural form:</p>\n\n<pre><code>If Not companySheet Is Nothing Then\nIf companySheet Is Nothing Then\n</code></pre>\n\n<h2>Use of Parenthesis (implicit versus explicit values)</h2>\n\n<p>Mathieu Guindon (@MathieuGuindon) can explain this much better than I. Using the following code line as an example:</p>\n\n<pre><code> MsgBox \"Worksheet for \" & (companyName) & \" created\"\n</code></pre>\n\n<p>The '()' forces an evaluation with some side effects. It creates a value item that is passed by value (<code>ByVal</code>) to the routine/function. This could also bypass the intended passing by reference.</p>\n\n<p>If the object in '()' is an object, then the evaluation will try to get the default value (e.g. for a Range object, it would pass the Range.Value because it is the <strong>implicit</strong> default). This, of course means that the function could get something it is not expecting thus causing errors!</p>\n\n<p>In this case, <code>companyName</code> is a String, and the string evaluates to a string without any real issues. But develop good habits from the start.</p>\n\n<p>Some additional reading:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/46959921/byval-vs-byref-vba\">https://stackoverflow.com/questions/46959921/byval-vs-byref-vba</a></li>\n<li><a href=\"https://stackoverflow.com/questions/22186853/unexpected-results-from-typename\">https://stackoverflow.com/questions/22186853/unexpected-results-from-typename</a></li>\n<li><a href=\"https://stackoverflow.com/questions/5413765/what-are-the-rules-governing-usage-of-brackets-in-vba-function-calls\">https://stackoverflow.com/questions/5413765/what-are-the-rules-governing-usage-of-brackets-in-vba-function-calls</a></li>\n</ul>\n\n<p>Related - At one stage, Microsoft deprecated the <code>Call</code> keyword as it is a hangover from very early days of BASIC. But this is currently a matter of hot debate: <a href=\"https://stackoverflow.com/questions/56504639/call-statement-deprecated-or-not\">https://stackoverflow.com/questions/56504639/call-statement-deprecated-or-not</a></p>\n\n<h2>Incomplete logic paths</h2>\n\n<p>You have <code>If firstColumnContainsNoVisibleCells Then</code> and then do a block of code. IF this is not true, you then do a different block of code. Which is good.</p>\n\n<p>However, within the blocks of code, you check the status of <code>companySheet</code>. In one block you check to see if it is <code>Nothing</code> and in the other you check to see if is <code>Not</code> <code>Nothing</code>.</p>\n\n<p>The potential issue comes if that conditional fails - what does it mean? From a coding sense, you just do nothing and that could be fine. But from a business sense, does it meant that your input is malformed. Could these blocks of code benefit from having an <code>Else</code> statement?</p>\n\n<p>Whenever setting up a range of conditions, have a thought towards all the possibilities of the conditions. That may allow you to find inconsistent data, potential new uses for your code, or possible errors or exceptions that you can trap and fix early. </p>\n\n<p>For me, an <code>If</code> without and <code>Else</code> is a sign that I must carefully review what I have done. A simple variable assignment (<code>If X then Y=Z</code>) is easily explained, but checking conditions for larger blocks of code means something more complex is happening.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:46:34.130",
"Id": "433269",
"Score": "0",
"body": "Sorry for the delay in responding. Thanks for picking those bits up. And I quite like my 'x', hang over from formula building but I take your point! no changed to `firstCompanyRecord = 4` ie first companyName is in row 4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:59:49.410",
"Id": "433271",
"Score": "0",
"body": "Noted on us of parenthesis, hadn't realised it was issue, but now fixed! On the If Else issue, I'm not sure how I can redo it. As many times I'm executing a code block on if the answer is true or false only, moving on to the next step is a positive action rather than being indecisive. I think in most cases I'm using it to create records that don't exist, if it does exist then I don't need to recreate it, if that makes sense. If there is an alternative to the If Im happy to be told about it and put it to use, but as a beginner I know what I know and don't know what I haven't seen before!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:00:17.650",
"Id": "433272",
"Score": "0",
"body": "The above was the reason for my previous GoTo nightmare!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T21:39:09.763",
"Id": "433284",
"Score": "0",
"body": "No problems - another brick in the learning wall. As you explain it, you work out if record exists then create record (which in itself can be used draft the coding logic). The important thing is that a reviewer can look at your logic and understand why things have been done - and if this is not obvious through the code/variable names then comments can be added. In terms of 'seeing' things - won't hurt to look through previous reviews here and read the comments - you might get a few ideas. Some of them may appear complex and confusing at first!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T22:14:43.860",
"Id": "223384",
"ParentId": "223377",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223384",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:16:21.330",
"Id": "223377",
"Score": "1",
"Tags": [
"beginner",
"vba",
"excel"
],
"Title": "Bookkeeping Coding - Check and Create Tabs, Copy filtered Data in Loop"
} | 223377 |
<p>I'm trying to optimally solve <a href="https://codeforces.com/problemset/problem/763/A" rel="nofollow noreferrer">codeforces problem 763A</a>:</p>
<blockquote>
<p>Each New Year Timofey and his friends cut down a tree of <em>n</em> vertices
and bring it home. After that they paint all the <em>n</em> its vertices, so
that the <em>i</em>-th vertex gets color <em>c<sub>i</sub></em>.</p>
<p>Now it's time for Timofey birthday, and his mother asked him to remove
the tree. Timofey removes the tree in the following way: he takes some
vertex in hands, while all the other vertices move down so that the
tree becomes rooted at the chosen vertex. After that Timofey brings
the tree to a trash can.</p>
<p>Timofey doesn't like it when many colors are mixing together. A
subtree annoys him if there are vertices of different color in it.
Timofey wants to find a vertex which he should take in hands so that
there are no subtrees that annoy him. He doesn't consider the whole
tree as a subtree since he can't see the color of the root vertex.</p>
<p>A subtree of some vertex is a subgraph containing that vertex and all
its descendants.</p>
<p>Your task is to determine if there is a vertex, taking which in hands
Timofey wouldn't be annoyed.</p>
<p><strong>Input</strong><br>
The first line contains single integer <em>n</em> (<em>2 ≤ n ≤</em> 10⁵) — the
number of vertices in the tree.</p>
<p>Each of the next <em>n</em> - 1 lines contains two integers <em>u</em> and <em>v</em>
(1 ≤ <em>u, v ≤ n, u ≠ v</em>), denoting there is an edge between vertices <em>u</em>
and v. It is guaranteed that the given graph is a tree.</p>
<p>The next line contains <em>n</em> integers <em>c<sub>1</sub></em>, <em>c<sub>2</sub></em>, ..., <em>c<sub>n</sub></em> (1 ≤ <em>c<sub>i</sub></em> ≤ 10⁵),
denoting the colors of the vertices.</p>
<p><strong>Output</strong><br>
Print "<code>NO</code>" in a single line, if Timofey can't take the tree in
such a way that it doesn't annoy him.</p>
<p>Otherwise print "<code>YES</code>" in the first line. In the second line print the
index of the vertex which Timofey should take in hands. If there are
multiple answers, print any of them.</p>
</blockquote>
<p>I have come up with a solution that works but times out on large inputs. </p>
<pre><code>from collections import defaultdict
n = int(input())
graph = defaultdict(list)
colors = defaultdict(lambda: -1)
for i in range(n-1):
(u, v) = [int(i) for i in input().split()]
graph[u].append(v)
graph[v].append(u)
c = [int(i) for i in input().strip().split()]
colors = {i+1: v for (i, v) in enumerate(c)}
bad = set()
def start(start):
nebs = graph[start]
return all(dfs(n, set([start]), colors[n]) for n in nebs)
def dfs(start, visited, want):
visited.add(start)
if colors[start] != want:
return False
for neb in graph[start]:
if neb not in visited:
if not dfs(neb, visited, want):
return False
return True
found = False
ans = -1
for i in range(1, n+1):
if start(i):
found = True
ans = i
break
else:
bad.add(i)
if not found:
print("NO")
else:
print("YES")
print(ans)
</code></pre>
<p>I'd love some guidance on how I can make this faster -- thank you!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T21:00:46.507",
"Id": "432870",
"Score": "1",
"body": "@dfhwzw edited to reflect I'm trying to get an optimal solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:15:09.207",
"Id": "433127",
"Score": "0",
"body": "Any inclination to interpret `while all the other vertices move down`? The original root becomes one of the children of the new root, the edge to the new root removed? All edges from the original root to the new root get reversed?"
}
] | [
{
"body": "<p>Some comments on the code:</p>\n\n<pre><code>for i in range(n-1):\n (u, v) = [int(i) for i in input().split()]\n</code></pre>\n\n<p>You are using <code>i</code> as the outer loop index, and <code>i</code> as the inner (list comprehension) loop index. This is confusing, and should be discouraged.</p>\n\n<p>The second line may be written more simply as:</p>\n\n<pre><code> u, v = map(int, input().split())\n</code></pre>\n\n<p>The assignment:</p>\n\n<pre><code>colors = defaultdict(lambda: -1)\n</code></pre>\n\n<p>is overwritten by the code that creates the <code>colors</code> dictionary (below), and so can be removed.</p>\n\n<p>You are changing the variable meaning in the following lines:</p>\n\n<pre><code>c = [int(i) for i in input().strip().split()]\ncolors = {i+1: v for (i, v) in enumerate(c)}\n</code></pre>\n\n<p>In the first line, <code>i</code> is a colour value; in the second line, <code>v</code> is the colour value and <code>i</code> is the index of the colour value. For consistency, I'd used <code>v</code> instead of <code>i</code> in the first line. Or get rid of the list comprehension index altogether:</p>\n\n<pre><code>c = map(int, input().strip().split())\ncolors = { i: v for i, v in enumerate(c, 1) }\n</code></pre>\n\n<p>Using <code>enumerate(c, 1)</code> eliminates the need to use <code>i+1</code> as the key expression.</p>\n\n<p>Is the <code>.strip()</code> necessary?</p>\n\n<hr>\n\n<p>I'm not certain what the point of maintaining your <code>visited</code> set is. Each time you <code>start()</code> a search from a new point, you are resetting the the <code>visited</code> set, and during any <code>dfs()</code>, you won't encounter a node you've already visited because the graph is guaranteed to be be a tree. You just need to pass the <code>start</code> node for each <code>dfs()</code> step as a <code>previous</code> node (instead of a <code>visited</code> set) to prevent back-tracking. </p>\n\n<hr>\n\n<p>Use better variable names. I just figured out the <code>nebs</code> is an abbreviation for neighbours. </p>\n\n<hr>\n\n<p>Faster solution hint:</p>\n\n<p>I don’t believe a DFS is necessary.</p>\n\n<ul>\n<li>Ignore all edges between vertices of the same colour</li>\n<li>All other edges must share a common vertex (or Timofey will be annoyed)</li>\n<li>Examine first two edges between different coloured vertices. Continue with a linear search of remaining edges</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T21:36:02.100",
"Id": "432875",
"Score": "0",
"body": "you're absolutely correct on all counts! Thanks -- I'll make the edits"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T21:40:49.883",
"Id": "432877",
"Score": "2",
"body": "@nz_21: Please be aware that you are not allowed to change the original code in the question after receiving an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T21:43:08.203",
"Id": "432878",
"Score": "1",
"body": "Ah, I see - understood!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T21:32:35.963",
"Id": "223383",
"ParentId": "223381",
"Score": "1"
}
},
{
"body": "<p>The approach outlined in the question is brute-force: for each vertex, we do a DFS on all its subtrees, checking if they're all monochromatic. <code>O(N^2)</code></p>\n\n<p>Instead of running dfs on <em>every</em> vertex, we can selectively <em>choose</em> vertices that would conclusively tell us if it was possible to split up the graph as desired. </p>\n\n<p>Consider a path: <code>111112111111</code>. It doesn't feel right to run dfs on each of the vertices. It makes more sense to run it on JUST 2, as it it colored differently than than the vertex it is connected to. </p>\n\n<p>Concretely: If we see a an edge that connects two vertices of different color, run a dfs on both of the them. </p>\n\n<ul>\n<li><p>If either of them can split up the graph the way we want, all good - just return any of them.</p></li>\n<li><p>If none of them can, we're screwed: if we try to root the graph on any other vertex, one of its subtrees WILL have this pair of different colored vertices. Why is this guaranteed? Because it's a tree.</p></li>\n</ul>\n\n<p>Thus, at most, you'll have to make 2 <code>dfs()</code> calls, while scanning through all edges. </p>\n\n<p><code>O(N)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:29:31.203",
"Id": "223489",
"ParentId": "223381",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223489",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T20:49:20.670",
"Id": "223381",
"Score": "4",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"depth-first-search"
],
"Title": "Finding a vertex of a tree such that every subtree rooted at that vertex is of a uniform color"
} | 223381 |
<p>This is a piece of test code made for the Angular application. </p>
<p>The router object is a mock provided by the RouterTestingModule dependency. I wonder if such a test <strong>can be considered a unit test</strong> (because it actually tests only one element and the fact that it calls some method - without checking its result), <strong>or should it be called an integration test</strong> (due to the fact that it still call external dependence)?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>it('should trigger the navigation to `/home`', async(() => {
const link = fixture.debugElement.nativeElement.querySelector('.home-link');
link.click();
expect(router.navigateByUrl).toHaveBeenCalled();
}))</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T22:55:12.843",
"Id": "432881",
"Score": "0",
"body": "Welcome to Code Review! Did you create this code or do you maintain it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T07:10:49.057",
"Id": "432905",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T07:53:35.787",
"Id": "432911",
"Score": "2",
"body": "I'm voting to close this question as off-topic because it isn't asking for code review"
}
] | [
{
"body": "<p>Since</p>\n\n<blockquote>\n <ul>\n <li><code>router</code> object is a mock, and</li>\n <li>the fact that it calls some method - without checking its result</li>\n </ul>\n</blockquote>\n\n<p>You have a <em>unit test</em>, more specifically a <a href=\"https://en.wikipedia.org/wiki/White-box_testing\" rel=\"nofollow noreferrer\">whitebox test</a>, as opposed to a <em>blackbox test</em> that tests the output of some method.</p>\n\n<p>For it to become an <em>integration test</em>, you would have use a router instead of a mock.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T04:29:10.390",
"Id": "223391",
"ParentId": "223385",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223391",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T22:36:20.347",
"Id": "223385",
"Score": "1",
"Tags": [
"javascript",
"unit-testing",
"angular-2+",
"integration-testing",
"jasmine"
],
"Title": "Creating a real unit test in Karma for Angular code"
} | 223385 |
<p>I have this code ready and it works just fine. But what are the ways by which I can improve this code? I have no CS background and this is my first coding project. I could not paste my entire code so I'm posting my github project link. Any recommendations on that would also be appreciated.</p>
<pre class="lang-py prettyprint-override"><code>import pygame
pygame.init()
window = pygame.display.set_mode((600,600))
pygame.display.set_caption("Tic Tac Toe")
white = (255,255,255)
Circle = pygame.image.load('Cross.png')
Cross = pygame.image.load('Circle.png')
clicks = []
load1 = False
load2 = False
load3 = False
load4 = False
load5 = False
load6 = False
load7 = False
load8 = False
load9 = False
load10 = False
load11 = False
load12 = False
load13 = False
load14 = False
load15 = False
load16 = False
load17 = False
load18 = False
def Background():
window.fill(white)
pygame.draw.rect(window, (0,0,0),( 198,0,4,600))
pygame.draw.rect(window, (0,0,0),( 398,0,4,600))
pygame.draw.rect(window, (0,0,0),( 0,198,600,4))
pygame.draw.rect(window, (0,0,0),( 0,398,600,4))
pygame.display.flip()
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
mouse = pygame.mouse.get_pressed()[0]
mouse_x,mouse_y = pygame.mouse.get_pos()
if len(clicks)%2 != 0:
if mouse:
if mouse_x > 0 and mouse_x < 198 and mouse_y > 0 and mouse_y < 198:
clicks.append(mouse)
load1 = True
elif mouse_x > 0 and mouse_x < 198 and mouse_y > 202 and mouse_y < 398:
clicks.append(mouse)
load2 = True
elif mouse_x > 0 and mouse_x < 198 and mouse_y > 402 and mouse_y < 600:
clicks.append(mouse)
load3 = True
elif mouse_x > 202 and mouse_x < 398 and mouse_y > 0 and mouse_y < 198:
clicks.append(mouse)
load4 = True
elif mouse_x > 202 and mouse_x < 398 and mouse_y > 202 and mouse_y < 398:
clicks.append(mouse)
load5 = True
elif mouse_x > 202 and mouse_x < 398 and mouse_y > 402 and mouse_y < 600:
clicks.append(mouse)
load6 = True
elif mouse_x > 402 and mouse_x < 600 and mouse_y > 0 and mouse_y < 198:
clicks.append(mouse)
load7 = True
elif mouse_x > 402 and mouse_x < 600 and mouse_y > 202 and mouse_y < 398:
clicks.append(mouse)
load8 = True
elif mouse_x > 402 and mouse_x < 600 and mouse_y > 402 and mouse_y < 600:
clicks.append(mouse)
load9 = True
elif len(clicks)%2 == 0:
if mouse:
if mouse_x > 0 and mouse_x < 198 and mouse_y > 0 and mouse_y < 198:
clicks.append(mouse)
load10 = True
elif mouse_x > 0 and mouse_x < 198 and mouse_y > 202 and mouse_y < 398:
clicks.append(mouse)
load11 = True
elif mouse_x > 0 and mouse_x < 198 and mouse_y > 402 and mouse_y < 600:
clicks.append(mouse)
load12 = True
elif mouse_x > 202 and mouse_x < 398 and mouse_y > 0 and mouse_y < 198:
clicks.append(mouse)
load13 = True
elif mouse_x > 202 and mouse_x < 398 and mouse_y > 202 and mouse_y < 398:
clicks.append(mouse)
load14 = True
elif mouse_x > 202 and mouse_x < 398 and mouse_y > 402 and mouse_y < 600:
clicks.append(mouse)
load15 = True
elif mouse_x > 402 and mouse_x < 600 and mouse_y > 0 and mouse_y < 198:
clicks.append(mouse)
load16 = True
elif mouse_x > 402 and mouse_x < 600 and mouse_y > 202 and mouse_y < 398:
clicks.append(mouse)
load17 = True
elif mouse_x > 402 and mouse_x < 600 and mouse_y > 402 and mouse_y < 600:
clicks.append(mouse)
load18 = True
if load1:
window.blit(Circle, (0,0))
if load2:
window.blit(Circle, (0,201))
if load3:
window.blit(Circle, (0,401))
if load4:
window.blit(Circle, (201,0))
if load5:
window.blit(Circle, (201,201))
if load6:
window.blit(Circle, (201,401))
if load7:
window.blit(Circle, (401,0))
if load8:
window.blit(Circle, (401,201))
if load9:
window.blit(Circle, (401,401))
if load10:
window.blit(Cross, (0,0))
if load11:
window.blit(Cross, (0,201))
if load12:
window.blit(Cross, (0,401))
if load13:
window.blit(Cross, (201,0))
if load14:
window.blit(Cross, (201,201))
if load15:
window.blit(Cross, (201,401))
if load16:
window.blit(Cross, (401,0))
if load17:
window.blit(Cross, (401,201))
if load18:
window.blit(Cross, (401,401))
if ((load1 and load2 and load3) or (load2 and load5 and load8) or (load3 and load6 and load9) or (load1 and load4 and load7) or (load4 and load5 and load6) or
(load7 and load8 and load9) or (load1 and load5 and load9) or (load3 and load5 and load7)):
print("Circle Wins")
elif ((load10 and load11 and load12) or (load13 and load14 and load15) or (load16 and load17 and load18) or (load10 and load13 and load16) or
(load11 and load14 and load17) or(load12 and load15 and load18) or (load10 and load14 and load18) or (load13 and load14 and load16)):
print("Cross Wins")
pygame.display.update()
Background()
pygame.quit()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T04:31:03.463",
"Id": "432888",
"Score": "0",
"body": "We cannot make recommendations or reviews of code behind a link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T05:36:22.940",
"Id": "432891",
"Score": "0",
"body": "If you create variables `var1`, `var2`, and `var3`, it is about time to ask if you should do something different. In this case, you can consider using a list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T05:37:30.917",
"Id": "432892",
"Score": "0",
"body": "Try to keep all functions (and `while` loops, `for` loops, `if` blocks, etc) to at most 30-50 lines. This is not a hard limit, but it makes life much easier if a block fits easily on screen."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T04:22:29.383",
"Id": "223390",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"tic-tac-toe",
"pygame"
],
"Title": "How can I make my Pygame Tic Tac Toe game better?"
} | 223390 |
<p>I have solved a previous year question of 2018 codevita (<a href="https://www.programminggeek.in/2018/08/codevita-2018-round-1-question-string-rotation.html" rel="nofollow noreferrer">link</a>) in Python.</p>
<p><strong>Problem Description:</strong></p>
<blockquote>
<p>Rotate a given String in the specified direction by specified magnitude.<br>
After each rotation make a note of the first character of the rotated String, After all rotation are performed the accumulated first character as noted previously will form another string, say <code>FIRSTCHARSTRING</code>.<br>
Check If <code>FIRSTCHARSTRING</code> is an Anagram of any substring of the Original string.<br>
If yes print "YES" otherwise "NO". </p>
</blockquote>
<p>Here is the code:</p>
<pre><code>from collections import Counter
def lrotate(input,d):
Lfirst = input[0 : d]
Lsecond = input[d :]
return (Lsecond + Lfirst)
def rrotate(input,d):
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
return (Rsecond + Rfirst)
s=input()
n=int(input())
c='FIRSTCHARSTRING'
l=[]
for _ in range(n):
w,v=input().split()
v=int(v)
if w == 'L':
p=lrotate(c,v)
if w == 'R':
p=rrotate(c,v)
l.append(p[0])
if Counter(l) == Counter(s) :
print("Yes")
else:
print("No")
</code></pre>
<p>What can I do to optimize my code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:04:53.010",
"Id": "432893",
"Score": "1",
"body": "What is/are your goal/s in `optimize my code`? Your implementation tries to stick to the letter of the task description (which is a good thing at least for a reference for correctness) - you might go for *readability*, *maintainability*, *acceptable result using least resources* (including coder time) or *exact result using least machine resources* or…"
}
] | [
{
"body": "<p>You can use python <code>deque</code> function to rotate string.</p>\n\n<pre><code>word = 'FIRSTCHARSTRING'\ncommands = [\n ('L', 2),\n ('R', 3),\n ('L', 1),\n]\n\nfrom collections import deque\n\nq = deque(word)\n\nfor direction, magnitude in commands:\n if direction == 'L':\n q.rotate(-magnitude)\n else:\n q.rotate(magnitude)\n\nif ''.join(q) == word:\n print('Yes')\nelse:\n print('No')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:09:34.887",
"Id": "223459",
"ParentId": "223394",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T05:48:21.457",
"Id": "223394",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"strings"
],
"Title": "String Rotation"
} | 223394 |
<p>So for my class, I have to design a game that will deal out one card to for each player. I also need to use functions to accomplish this one for the high card game, and another for the face value of the card.</p>
<pre><code>import random
def high_card():
print("\n High Card")
print("-----------")
# Read each player's name
player1 = input("What is your name player one? ")
player2 = input("What is your name player two? ")
# Deal two cards
print("Card for", player1, ": ", end=' ')
card1 = face_value()
print("Card for", player2, ": ", end=' ')
card2 = face_value()
# Determine who won and display a message
if card1 > card2:
print("Contratulations ", player1, ", YOU WON!", sep='')
elif card2 > card1:
print("Contratulations ", player2, ", YOU WON!", sep='')
else:
print("The game is a draw; both cards are the same")
def face_value():
player_card = random.randint(1,13)
# Display face value of card for player
if player_card == 1:
print("Ace")
elif player_card == 2:
print("Two")
elif player_card == 3:
print("Three")
elif player_card == 4:
print("Four")
elif player_card == 5:
print("Five")
elif player_card == 6:
print("Six")
elif player_card == 7:
print("Seven")
elif player_card == 8:
print("Eight")
elif player_card == 9:
print("Nine")
elif player_card == 10:
print("Ten")
elif player_card == 11:
print("Jack")
elif player_card == 12:
print("Queen")
elif player_card == 13:
print("King")
else:
# This will catch any
# invalid card value
print("Invalid card")
high_card()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:39:46.393",
"Id": "432897",
"Score": "0",
"body": "Does this code actually work as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:40:18.463",
"Id": "432997",
"Score": "0",
"body": "Your code does not work correctly because you did not return card value from `face_value`, you just print them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T07:33:13.487",
"Id": "433123",
"Score": "0",
"body": "What exactly are you looking for feedback on? The way you have phrased the question just sounds like you want people to improve your homework, could you point out specific bits of the code you aren't sure about or something you would like to change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T00:49:18.007",
"Id": "433305",
"Score": "0",
"body": "Well, my code crashes when I try the high card function, and I can't seem to figure out why. I'm looking at what I'm doing wrong, and possibly hoping someone can flip the switch in my head so I can understand how to perform it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T14:44:06.807",
"Id": "433805",
"Score": "0",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
}
] | [
{
"body": "<p>First of all: the code does not work, so this is not the appropiate place for your question (code review is to improve code which works). Having said that, I proceed to give you some help (next time, ask your question where appropiate).</p>\n\n<p>card1 and card2 are taking values which are not numbers (look at what face_value() has as an output; it only prints strings which cannot be compared with '>' but does not return any comparable values).</p>\n\n<p>The code can be improved by adding a 'return player_card' at the end of face_value(). That way you ensure card1 and card2 will take the value of the numbers generated by random and you will be able to compare them.</p>\n\n<pre><code>import random\ndef high_card():\n print(\"\\n High Card\")\n print(\"-----------\")\n\n # Read each player's name\n player1 = input(\"What is your name player one? \")\n player2 = input(\"What is your name player two? \")\n\n # Deal two cards\n\n print(\"Card for\", player1, \": \", end=' ')\n card1 = face_value()\n print(\"Card for\", player2, \": \", end=' ')\n card2 = face_value()\n\n # Determine who won and display a message\n if card1 > card2:\n print(\"Contratulations \", player1, \", YOU WON!\", sep='')\n elif card2 > card1:\n print(\"Contratulations \", player2, \", YOU WON!\", sep='')\n else:\n print(\"The game is a draw; both cards are the same\")\n\ndef face_value():\n player_card = random.randint(1,13)\n\n # Display face value of card for player \n if player_card == 1:\n print(\"Ace\")\n elif player_card == 2:\n print(\"Two\")\n elif player_card == 3:\n print(\"Three\")\n elif player_card == 4:\n print(\"Four\")\n elif player_card == 5:\n print(\"Five\")\n elif player_card == 6:\n print(\"Six\")\n elif player_card == 7:\n print(\"Seven\")\n elif player_card == 8:\n print(\"Eight\")\n elif player_card == 9:\n print(\"Nine\")\n elif player_card == 10:\n print(\"Ten\")\n elif player_card == 11:\n print(\"Jack\")\n elif player_card == 12:\n print(\"Queen\")\n elif player_card == 13:\n print(\"King\")\n else:\n print(\"Invalid card\")\n return player_card\n\nhigh_card()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T18:31:40.957",
"Id": "223693",
"ParentId": "223395",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T06:19:33.323",
"Id": "223395",
"Score": "-2",
"Tags": [
"python",
"python-3.x",
"game",
"functional-programming",
"homework"
],
"Title": "A game that deals a high card to one of two players"
} | 223395 |
<p>I was asked this in an interview yesterday:</p>
<p>You get an array of segments (segment contains 2 numbers, representing days count (say in a month, but could be in a year, etc.): start, end). You need to find the minimum number of days where you can meet as many of your friends.</p>
<p>For example, if you get [2, 5], [4, 8], [6, 10] - then one possible answer would be 4 and 6. If you get [1,10], [2,9], [3,7] one possible answer would be 5, as in day 5 everyone is available and you can meet them all. </p>
<p>My way of solving was to order the segments by start, and then look for the biggest intersection. Though I was told this is not the most optimal solution. So I wonder - what is the optimal solution (i.e. more efficient)?</p>
<p>Here's my code:</p>
<pre><code>def optimal_dates(segments):
# sort the segments
sorted_segments = sorted(segments_list, key=lambda var: var[0])
# perform actual algorithm
final_intersections = set() # stores the final return result
working_intersection = set() # stores the working accumulative intersections
for i in range(len(sorted_segments) - 1):
seg_b = set(range(sorted_segments[i + 1][0], sorted_segments[i + 1][1] + 1))
if not working_intersection:
seg_a = set(range(sorted_segments[i][0], sorted_segments[i][1] + 1))
working_intersection = seg_a.intersection(seg_b)
# if empty, seg_a doesn't intersects forward, so add any element from it
if not working_intersection:
final_intersections.add(seg_a.pop())
else:
temp = working_intersection.intersection(seg_b)
# if empty, this was end of intersection, so add any element from the previous accumulative intersections
if not temp:
final_intersections.add(working_intersection.pop())
working_intersection = temp
# add the final element
if working_intersection:
final_intersections.add(working_intersection.pop())
else:
final_intersections.add(sorted_segments[-1][0])
return final_intersections
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:16:42.873",
"Id": "432923",
"Score": "0",
"body": "You want to meet _all_ your friends? In the minimum number of days? And those days need to be contiguous?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:18:03.100",
"Id": "432924",
"Score": "0",
"body": "yeah, but you could meet 4 friends on one day, and another 3 friends on another day, etc. The segments of availability is continuous. But not the meeting days. you could meet 2 friends on 13, and 6 friends on 23, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:00:43.340",
"Id": "433018",
"Score": "0",
"body": "In your first example, why day 4 instead of 5? Is the end of the days range exclusive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:16:08.327",
"Id": "433019",
"Score": "0",
"body": "What does a segment represent? Is it when a particular friend is available?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:29:31.760",
"Id": "433022",
"Score": "1",
"body": "@IEatBagels it could also be 5. There can be different solutions. What important is the number of days - in that example - you cannot meet all of them in 1 day, but you can meet all of them in 2 days. Segments are inclusive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:29:51.253",
"Id": "433023",
"Score": "0",
"body": "@vnp yes. exactly."
}
] | [
{
"body": "<p>Making the <code>set</code> out of an interval is an immediate red flag. <code>set</code> is a heavyweight data structure, and making it is a heavyweight operation. It is also much easier to compute an intersection of two intervals, than of two sets.</p>\n\n<p>Making the same <code>set</code> twice is another red flag.</p>\n\n<hr>\n\n<p>All that said, it seems that you really overthink the problem. It admits a much simpler solution. Consider the friend whose window of opportunity closes the earliest. You want to meet him anyway, so make the most of it: select every friend whose window opens prior to it, schedule a party, and discard all the participants from further consideration; rinse and repeat.</p>\n\n<p>Hint: do not sort the list of intervals. Sort the list of events (interval openings and closings).</p>\n\n<p>Two things I intentionally don't want to spell out:</p>\n\n<ol>\n<li>Prove that this algorithm does produce an optimal solution, and</li>\n<li>How to efficiently discard the friends you've already met.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:19:31.337",
"Id": "223479",
"ParentId": "223398",
"Score": "3"
}
},
{
"body": "<p>You can find the minimal amounts by segregating each key:value where the key is days and values are people:</p>\n\n<pre><code>ls = [[2,4], [3, 9], [4,9], [9, 3]] # your data\nprint(ls)\nns = {days: people-days for days, people in ls if days < people} \nprint(ns)\n</code></pre>\n\n<p>This returns:</p>\n\n<pre><code>[[2, 4], [3, 9], [4, 9], [9, 3]]\n{2: 2, 3: 6, 4: 5} # value is now the difference between days and people\n</code></pre>\n\n<p>From here you can see the largest difference which will be your minimal and maximum.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T09:50:36.613",
"Id": "233221",
"ParentId": "223398",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T08:19:19.387",
"Id": "223398",
"Score": "5",
"Tags": [
"python",
"algorithm",
"python-3.x",
"interview-questions"
],
"Title": "Find minimal number of days to meet all your friends"
} | 223398 |
<p>Was asked this in an interview yesterday:</p>
<p>You are given an array of numbers (not digits, but numbers: e.g. 9, 23, 184, 102, etc.) - you need to construct the largest number from it. For example: you get 21, 2, 10 - the largest number is 22110. </p>
<p>This is my solution, I wonder if you can improve this?</p>
<pre><code>def maximum_number(a):
work_dict = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
9: 0
}
for ai in a:
# if ai is a single digit number, just add it
if ai in work_dict:
work_dict[ai] += 1
continue
# otherwise, decompose it to it's digits
while ai > 0:
number = ai % 10
work_dict[number] = work_dict[number] + 1
ai = int(ai/10)
max_num = int('9'*work_dict[9] + '8'*work_dict[8] + '7'*work_dict[7] + '6'*work_dict[6] +
'5'*work_dict[5] + '4'*work_dict[4] + '3'*work_dict[3] + '2'*work_dict[2] +
'1'* work_dict[1] + '0'*work_dict[0])
return max_num
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T08:43:21.967",
"Id": "432916",
"Score": "0",
"body": "So the task basically was to decompose the numbers into digits and then rearrange those digits to form the largest possible value that could be represented by these digits?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T08:56:33.580",
"Id": "432917",
"Score": "0",
"body": "yeah... as I understood it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:44:53.950",
"Id": "433045",
"Score": "3",
"body": "You're probably *not* allowed to decompose the numbers into digits. Why would they specify `not digits, but numbers` otherwise?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:00:45.647",
"Id": "433047",
"Score": "0",
"body": "see https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T12:24:19.203",
"Id": "433368",
"Score": "0",
"body": "Firstly, you could use a list instead of a dictionary for `work_dict` if I'm not mistaken"
}
] | [
{
"body": "<h2>Your code</h2>\n\n<p>Your code as such seems to be functional, but not really elegant or concise. </p>\n\n<p>First, the variable names don't speak for themselves. Nobody would be hurt if the function input was named <code>numbers</code> instead of <code>a</code> and <code>number</code> instead of <code>ai</code>. <code>work_dict</code> is also not a particularly good name since it's very generic. How about <code>digit_histogram</code>?</p>\n\n<p>Handling single digit numbers separately seems unnecessary. The algorithm you implemented can handle them without special treatment.</p>\n\n<p>When constructing <code>max_num</code>, there is a lot of repeated code. You could simplify this using a list comprehension and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join</code></a> (more on that soon).</p>\n\n<h2>How I would have tackled this</h2>\n\n<p>Since we have the luxury that combination of these numbers should be maximized in base 10, we can get their digits simply by looking at their <code>str</code> representation (which coincidentally happens to be in base 10 ;-) )<sup>1</sup>.</p>\n\n<p>If you include the other recommendations from above you end up with:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def maximum_number_str(arr):\n digit_histogram = {\n \"0\": 0, \"1\": 0, \"2\": 0, \"3\": 0, \"4\": 0,\n \"5\": 0, \"6\": 0, \"7\": 0, \"8\": 0, \"9\": 0\n }\n # or: digit_histogram = {str(i): 0 for i in range(10)}\n\n for number in arr:\n for digit in str(number):\n digit_histogram[digit] += 1\n\n max_num = \"\".join(str(i)*digit_histogram[str(i)] for i in reversed(range(10)))\n\n return int(max_num)\n</code></pre>\n\n<p>Depending on how familiar you are with Python and if other modules are allowed, you could come up with a solution using <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>, or at least skip the dict initialization all-together if you use <code>.get(...)</code> instead of <code>[...]</code> when accessing the dictionary as presented by <a href=\"https://codereview.stackexchange.com/a/223403/92478\">Pål GD in is answer</a>.</p>\n\n<p>Just for reference, this is how it could look like using a <code>Counter</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\ndef maximum_number_counter(arr):\n digit_histogram = Counter()\n\n for number in arr:\n digit_histogram.update(str(number))\n\n max_num = \"\".join(\n str(i) * digit_histogram[str(i)] for i in reversed(range(10)))\n\n return int(max_num)\n</code></pre>\n\n<hr>\n\n<h2>Edit: The other way to think about that task</h2>\n\n<p>There seems to be a vivid discussion here if you understood the task correctly. If you follow the arguments that speak against your and my former interpretation, this actually leads to another interesting problem.</p>\n\n<p>I came up with the solution below, though I highly doubt that I could have come up with this in an interview situation.</p>\n\n<pre><code>from functools import cmp_to_key\n\n\ndef maximize_joint_number(number1, number2):\n joined12 = int(str(number1)+str(number2))\n joined21 = int(str(number2)+str(number1))\n return joined21 - joined12\n\n\ndef maximum_number(numbers):\n \"\"\"\n Generate the largest possible number that can be generated rearanging the\n *numbers*, not the digits of the input sequence\n \"\"\"\n return int(\"\".join(str(i) for i in sorted(numbers, key=cmp_to_key(maximize_joint_number))))\n</code></pre>\n\n<p>The idea to this is actually from <a href=\"https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/\" rel=\"nofollow noreferrer\">this blog post</a> that was given in a comment by <a href=\"https://codereview.stackexchange.com/users/139491\">Eric Duminil</a>. The <a href=\"https://docs.python.org/3/library/functools.html#functools.cmp_to_key\" rel=\"nofollow noreferrer\"><code>cmp_to_key</code></a> trickery is needed because the <code>cmp</code> keyword was removed from sort in Python 3. You could also use <code>cmp_to_key</code> as a decorator, which makes it a little bit nicer:</p>\n\n<pre><code>from functools import cmp_to_key\n\n@cmp_to_key\ndef maximize_joint_number(number1, number2):\n ...\n\ndef maximum_number(numbers):\n return int(\"\".join(str(i) for i in sorted(numbers, key=maximize_joint_number)))\n</code></pre>\n\n<p>A quick test seems to fulfill all the presented example outputs:</p>\n\n<pre><code>\nif __name__ == \"__main__\":\n assert maximum_number([0, 12]) == 120\n assert maximum_number([2, 21, 10]) == 22110\n assert maximum_number([9, 2, 5, 51]) == 95512\n assert maximum_number([20, 210, 32]) == 3221020\n assert maximum_number([1, 19, 93, 44, 2885, 83, 379, 3928]) == 93834439283792885191\n</code></pre>\n\n<p>The second and third test case break implementations that would try to use something like <code>sorted(numbers, key=str, reverse=True)</code> (lexicographical sort) directly.</p>\n\n<hr>\n\n<p><sup>1</sup> Thanks to <a href=\"https://codereview.stackexchange.com/users/50567\">Peter Cordes</a> for <a href=\"https://codereview.stackexchange.com/questions/223399/find-max-number-you-can-create-from-an-array-of-numbers/223402#comment433088_223402\">pointing out</a> the inaccurate wording here in earlier revisions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:10:30.260",
"Id": "432920",
"Score": "0",
"body": "Consider initializing (if necessary) the dict using dict comprehension `{ str(x) : x for x in range(10)}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:25:45.360",
"Id": "433049",
"Score": "0",
"body": "@EricDuminil: I specifically ask the OP for this aspect, and he affirmed it. So technically at the time of writing the answer was valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:39:39.950",
"Id": "433056",
"Score": "1",
"body": "@EricDuminil: I also included my take on that \"alternative\" (maybe correct) interpretation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:46:48.233",
"Id": "433057",
"Score": "1",
"body": "Perfect. I haven't seen an example for which `cmp=` is needed in a long time. Too bad it's been removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:51:47.933",
"Id": "433059",
"Score": "0",
"body": "@EricDuminil: I haven't either. But it firmly stuck somewhere in the back of my head that it existed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:05:38.093",
"Id": "433088",
"Score": "1",
"body": "Already in base 10?? Huh? The OP has binary integers, not strings. Your own solution uses `str(number)` so you're already actively / explicitly converting from number to ASCII decimal string. Maybe what you meant to say is that Python has an efficient int->string function built-in which happens to use base 10 :P."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:45:01.163",
"Id": "433099",
"Score": "0",
"body": "@PeterCordes: Reworded that section."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:02:52.693",
"Id": "223402",
"ParentId": "223399",
"Score": "7"
}
},
{
"body": "<p>First of all, whenever you see this ... this is a big no-no:</p>\n\n<pre><code>'9'*work_dict[9] + '8'*work_dict[8] + '7'*work_dict[7] +\n'6'*work_dict[6] + '5'*work_dict[5] + '4'*work_dict[4] +\n'3'*work_dict[3] + '2'*work_dict[2] + '1'* work_dict[1] +\n'0'*work_dict[0]\n</code></pre>\n\n<p>it could be replaced by a simple </p>\n\n<pre><code>''.join(str(i) * work_dict[i] for i in reversed(range(10)))\n</code></pre>\n\n<p>Of course, the initialization of the <code>work_dict</code> is similar. And in fact, you don't need to initialize it if you take care to use <code>dict.get</code> instead of <code>dict[]</code>:</p>\n\n<pre><code>work_dict[number] = work_dict[number] + 1\n# is equivalent to\nwork_dict[number] = work_dict.get(number, 0) + 1 # default to 0 if not in dict\n</code></pre>\n\n<p>Ps., whenever you are <em>counting</em> something, consider using <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\">collections.Counter</a>.</p>\n\n<hr>\n\n<p><em>Warning:</em> The rest of this answer tries to address the problem that OP <em>say</em> they are solving in the comments to the question. However, it is not certain that the understanding of the problem by the OP is correct. From here on, we assume that you are allowed to shuffle all the input digits, whereas the original problem probably only allows shuffling around the numbers.</p>\n\n<hr>\n\n<p>If you want to have it as compact and \"functional\" as possible, it would be much easier to just sort the entire input and output it:</p>\n\n<pre><code>def maximum_number(lst):\n return int(''.join(sorted(''.join(str(x) for x in lst), reverse=True)))\n</code></pre>\n\n<p>However, note that this doesn't work on the empty list (which might be okay, depending on the specification of the function).</p>\n\n<p>It should also be mentioned that</p>\n\n<ol>\n<li>it is harder to write than the \"manual loop\" variant, which can be important in an interview</li>\n<li>it might be harder to read and thus to debug, but I believe that this is up to the eye of the beholder to determine</li>\n</ol>\n\n<hr>\n\n<p>For complexity, this is <em>O(n log n)</em> whereas the optimal algorithm has running time <em>O(n)</em>. We again see the trade-off between running time and readability.</p>\n\n<p>Here is an <em>O(n)</em> algorithm using <code>Counter</code>:</p>\n\n<pre><code>from collections import Counter\ndef maximum_number(lst):\n counter = Counter()\n for elt in lst:\n counter += Counter(str(elt))\n return int(\"\".join(str(i) * counter[str(i)] for i in range(9, -1, -1)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T10:24:45.623",
"Id": "432942",
"Score": "0",
"body": "This is very compact indeed. But is it in any way more performant than my code? I mean, both will find it in a magnitude of the sorting algorithm, which is on average O(n*log(n)), correct? You do get some optimization, from treating the num as a string though, so you save the deconstruction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T10:27:09.773",
"Id": "432943",
"Score": "1",
"body": "[`sorted`](https://docs.python.org/3/library/functions.html#sorted) also accepts `reverse=True` as argument, so you could get rid of the outer `reversed`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T10:38:17.870",
"Id": "432944",
"Score": "0",
"body": "Thanks, @AlexV, updated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T10:51:07.370",
"Id": "432946",
"Score": "1",
"body": "@DavidRefaeli Updated in answer. Added an O(n) algorithm using Counter instead of the manual dict approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:00:48.447",
"Id": "432947",
"Score": "1",
"body": "No need to use `.get(...)` for the counter as per the [doc](https://docs.python.org/3/library/collections.html#collections.Counter), missing elements have a count of `0`. You can also see this in the counter implementation that was already contained in my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:02:03.323",
"Id": "432948",
"Score": "0",
"body": "very nice! I was mistaken in my first comment - I don't have a sorting algorithm, so I think actually both mine and your updated is O(n), though yours is cleaner. I assume Counter does something very similar to what I did, only on strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:34:58.967",
"Id": "432951",
"Score": "0",
"body": "Thanks @AlexV , updated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:07:28.797",
"Id": "433168",
"Score": "0",
"body": "@EricDuminil Thanks for the comment, I believe that I do answer the question as specified in the comment: _\"into digits and then rearrange those digits to form the largest possible value that could be represented by these digits?\"_ to which the OP answered in the affirmative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:05:05.483",
"Id": "433190",
"Score": "1",
"body": "@EricDuminil I added a note before the section where I start sorting and counting."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:03:37.670",
"Id": "223403",
"ParentId": "223399",
"Score": "7"
}
},
{
"body": "<p>The question reads : </p>\n\n<blockquote>\n <p>You are given an array of numbers (<strong>not digits</strong>, but numbers: e.g. 9, 23, 184, 102, etc.) - you need to construct the largest number from it. For example: you get 21, 2, 10 - the largest number is 22110. (<em>Emphasis mine</em>)</p>\n</blockquote>\n\n<p>In a comment it was stated : </p>\n\n<blockquote>\n <p>The task basically was to decompose the numbers into digits and then rearrange those digits to form the largest possible value that could be represented by these digits</p>\n</blockquote>\n\n<p>Those two statements are very different and I'd tend to believe you either misunderstood the interview question or you didn't explain it properly. The example you gave, 22110 isn't constructed by the digits <code>[2,2,1,1,0]</code>, but by the numbers <code>[2,21,10]</code>. This fits much more with how you worded your question. </p>\n\n<p>With your code, getting an input of <code>[20,210,32]</code> would yield the result <code>3222100</code>, but the actual answer should be <code>3221020</code> because of <code>[32,210,20]</code>.</p>\n\n<p>At least, this is all assuming that the requirements that you put in your questions are specifically the one you received in the interview, meaning you misunderstood the question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:33:28.160",
"Id": "433025",
"Score": "0",
"body": "3222100 is the correct max number, at least I think, as I don't have the question in front of me anymore - but there were enough examples from which I understood this. I emphasized the not digits to stress that you need to break the number into digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:38:09.900",
"Id": "433026",
"Score": "4",
"body": "@DavidRefaeli It's hard to tell from the statement you gave in your question and it really feels like it's wrong. Are you sure didn't just see it this way? Because as I wrote, for the example you gave both explanations work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:56:35.413",
"Id": "433046",
"Score": "1",
"body": "You're 100% correct. The question is completely boring otherwise. See https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:39:37.490",
"Id": "433055",
"Score": "0",
"body": "well, now I can't be sure... but could be. Who knows..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:05:45.880",
"Id": "433246",
"Score": "0",
"body": "@EricDuminil Thanks I changed it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:18:52.653",
"Id": "433253",
"Score": "1",
"body": "@EricDuminil oh god.. Ahah. It looks good now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:27:02.027",
"Id": "433256",
"Score": "0",
"body": "All good. I already upvoted yesterday."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T16:56:18.757",
"Id": "223432",
"ParentId": "223399",
"Score": "7"
}
},
{
"body": "<p>Here's what I came up with. It runs in O(n) because of the for each loop, and seems to be a nice readable option to me.</p>\n\n<pre><code>numberList = [1, 19, 93, 44, 2885, 83, 379, 3928]\n\ndef largestNumber(value):\n string = ''\n for number in value:\n string = string + str(number)\n result = ''.join(sorted(string, reverse=True))\n return(int(result))\n\n\nprint(largestNumber(numberList))\n\n\nOutput: 99998888754433332211\n</code></pre>\n\n<p>Your solution works in the same time complexity, so they are both on the same page in that regard, but stringing the values together and using python's built in sorting function saves some space and complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:25:56.810",
"Id": "433050",
"Score": "0",
"body": "The answer should be `93834439283792885191`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:09:17.040",
"Id": "433089",
"Score": "0",
"body": "Doesn't `sorted(string, reverse=True)` use an O(digits log digits)` sorting algorithm? Or does Python use CountingSort for sorting the characters of an ASCII or UTF-8 strings to get `O(char)` complexity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:24:15.617",
"Id": "433140",
"Score": "1",
"body": "@PeterCordes There's not much difference between O(n.log n) and O(n) anyway, but I'm pretty sure the complexity will be O(n. log n) here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T19:52:04.073",
"Id": "433864",
"Score": "0",
"body": "@PeterCordes, I know the time complexity of the sort is O(n log n) because Python uses Timsort, but the overall time complexity should still be O(n) since the for each loop iterates over every item of the input numberList, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T20:15:20.913",
"Id": "433869",
"Score": "0",
"body": "`N * log(N)` grows more quickly than `N`, by an extra factor of `log(N)`. So it dominates the for-loop's time. You have `O(N + N*log(N) )` which simplifies to `O( N*log(N) )`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T14:14:29.253",
"Id": "433976",
"Score": "0",
"body": "@PeterCordes Yep, my bad. I think I got it confused with just O(log n), and forgot which one grows faster. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T14:41:55.807",
"Id": "433980",
"Score": "0",
"body": "IDK how you can forget that `N * log(N) > N` for large N. You can tell just by looking at it, or thinking of a simple number like `100`. With base-10 logarithms, `log10 (100) = 2`, so N log N has already grown twice as large as just N. (In general for any `N` larger than `e` or `10` or whatever base you choose, `log(N)` is greater than 1). Maybe that method will help you avoid making the same mistake in the future by thinking about the expressions you're writing instead of only trying to memorize facts."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:19:46.843",
"Id": "223440",
"ParentId": "223399",
"Score": "-1"
}
},
{
"body": "<p>As mentioned by @IEatBagels, it seems that you didn't understand the question. You're not allowed to split numbers into digits. You're only allowed to reorder whole numbers in order to get the maximum joined number. The output for <code>[0, 12]</code> should be <code>120</code>, not <code>210</code>!</p>\n\n<p>Others answers are proud to be O(n) or O(n log n), but well, they're probably wrong.</p>\n\n<p>So I'm proud to present this O(n!) solution:</p>\n\n<pre><code>from itertools import permutations\n\ndef joined_number(numbers):\n return int(''.join(str(number) for number in numbers))\n\nmax(permutations([20,210,32]), key= joined_number)\n# (32, 210, 20)\n\nmax(permutations([1, 19, 93, 44, 2885, 83, 379, 3928]), key= joined_number)\n# (93, 83, 44, 3928, 379, 2885, 19, 1)\n</code></pre>\n\n<p>The performance is horrible and it will fail for lists longer than ~10 elements, but at least you can play with it in order to understand what the <em>real</em> question was.</p>\n\n<p>You can then try to look for the sort which could give you the correct answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:47:14.723",
"Id": "433058",
"Score": "1",
"body": "Downvoter: constructive criticism is welcome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:12:22.400",
"Id": "433090",
"Score": "0",
"body": "I think the right algorithm / sort-order for this version of the problem is lexical sort according to the decimal string representations of the numbers. The largest leading digit goes first. The total number of digits is fixed, and a larger early digit trumps anything you can do later. IDK if you left that out to avoid spoiling the problem for the OP; if so I can delete this comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:54:25.713",
"Id": "433102",
"Score": "3",
"body": "@PeterCordes: If I understood your proposal correctly, the most straightforward implementation would be using `sorted(numbers, key=str, reverse=True)`. However, this does yield the wrong result for inputs like `[9, 2, 5, 51]` -> `[9, 51, 5, 2]` where it should be `[9, 5, 51, 2]` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:56:44.207",
"Id": "433104",
"Score": "1",
"body": "@AlexV: Ah, well spotted. You're right, it's not as simple as I thought. And it's not just leading digit then shortest, either. Because `59` should sort ahead of `5`, but `51` should sort behind `5`. But grouping by leading digit lets you cut down the brute-force search space by an order of magnitude until we think of something better than trying every possibility."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:11:32.823",
"Id": "433107",
"Score": "2",
"body": "@PeterCordes: The simplest counter-example I could find is `[0, 1, 10]`. The problem is solved with \"sorting by comparator\" (see https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/ and AlexV's answer, which are basically the same) but it would be interesting to see if there's any simple \"sort by key\" solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:15:48.530",
"Id": "433109",
"Score": "1",
"body": "@EricDuminil: oh cool, until seeing the solution, it wasn't clear to me there was a transitive or whatever it's called property here that would allow a comparison sort, where `a < b` and `b < c` implies `a < c`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:22:44.693",
"Id": "433111",
"Score": "0",
"body": "@PeterCordes: It's still not completely clear to me either. It seems to work fine but I've not seen any proof indicating that it is always the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:01:52.860",
"Id": "433188",
"Score": "0",
"body": "@PeterCordes: `sorted(numbers, key= lambda i:itertools.cycle(str(i)), reverse=True)` would work if `cycle`s were comparable. They could be compared like lists, with some logic in order to avoid infinite loops."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:38:20.907",
"Id": "223442",
"ParentId": "223399",
"Score": "3"
}
},
{
"body": "<p>EDIT: After talking to Baldrickk in the comments, I've realized that my sort by key method doesn't work for this problem. For instance, the below approach would sort [50,505040] as 50504050 instead of 50505040. I'm leaving the answer up for those who are interested.</p>\n\n<hr>\n\n<p>This is my attempt at solving the problem assuming that the OP did indeed misinterpret the question and that the numbers can't be split up into digits. Going off of AlexV's answer I've come up with a simple sort by key solution (rather than sort by cmp). I would have posted this as a comment but I lack the reputation.</p>\n\n<p>The first step is to realize that since the first digit is the most significant, the second digit the second most significant and so on, we can simply do an alphabetical sort.</p>\n\n<pre><code>def maximum_number(lst):\n return int(\"\".join((str(n) for n in sorted(lst, key=str, reverse=True))))\n</code></pre>\n\n<p>So this will work for most cases.</p>\n\n<p>But as AlexV pointed out in a comment, this neglects that, for instance, 5 should be sorted ahead of 51 (since 551>515), 1 ahead of 10, etc.</p>\n\n<p>The key element to take note of here is that a number n that begins with a digit d should be sorted ahead of a number nk if k < d, but behind nk if k > d. If k = d, the order is arbitrary.\nThis can be adjusted for by appending the first digit of every number onto itself, yielding the following solution.</p>\n\n<pre><code>def sorting_key(num):\n num_str = str(num)\n return num_str + num_str[0]\n\ndef maximum_number(lst):\n return int(\"\".join((str(n) for n in sorted(lst, key=sorting_key, reverse=True))))\n</code></pre>\n\n<p>This passes all examples I've seen posted in other answers.</p>\n\n<hr>\n\n<p>Thanks to Baldrickk for pointing out that the first revision of this answer would fail at [50,501]</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:02:58.813",
"Id": "433142",
"Score": "0",
"body": "`maximum_number([50,501])`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:08:14.930",
"Id": "433143",
"Score": "1",
"body": "`2*str(num)` appears to be a better sorting key - I haven't checked to see it it is optimal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:12:22.067",
"Id": "433146",
"Score": "0",
"body": "@Baldrickk Thanks for pointing that out. You can account for that by using the first digit, rather than the last. I've edited the answer occordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:18:02.727",
"Id": "433147",
"Score": "0",
"body": "ah, so my `2*str(num)` was overzealous - of course the most significant digit is the most important, and the digits beyond(/below?) that should be covered by the original ordering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:29:26.417",
"Id": "433149",
"Score": "0",
"body": "@Baldrickk Actually, after thinking about it some more, I realized that you were right, my method would dictate that [50,505] is arbitrary when it clearly isn't. But I'm afraid str(num)*2 is still not enough, because now [50,505040] is still sorted wrong. You continue this indefinitely, basically I think that sort by key just doesn't work for this problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:49:16.480",
"Id": "433152",
"Score": "0",
"body": "hmmm I think we just need to find the correct key fn. we have two competing issues - value of digits in increasing order (higher is better) and number of digits in decreasing order (less is more valuable) We just need to find a way of bringing those two together"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:06:55.307",
"Id": "433158",
"Score": "0",
"body": "@Baldrickk Multiplying the string only creates a closer approximation of a number's real value as part of the resulting number. Without a ceiling on how large the numbers can be you would have to be infinitely precise. The only way I could see this happening would be by analyzing the list beforehand to find the largest number, then based on that we could know how much precision is required and therefore how many times to multiply the string. But that would defeat the point of a simple sort by key method in the first place, wouldn't it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:11:54.743",
"Id": "433161",
"Score": "0",
"body": "What's wrong with the comparator based solution in [my answer](https://codereview.stackexchange.com/a/223402/92478)? If you really want to go for `key`, maybe check the implementation of `cmp_to_key` to see if there are possible shortcuts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:27:16.247",
"Id": "433165",
"Score": "0",
"body": "@AlexV `cmp_to_key` just creates an object whose magic methods (`__lt__`, `__gt__`, etc.) call the supplied function. As for why do it instead of using a comparator function, to quote the [Python docs on sorting](https://docs.python.org/2/howto/sorting.html#key-functions), `This technique is fast because the key function is called exactly once for each input record.` That and a user expressed interest in this method in the comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:32:47.170",
"Id": "433166",
"Score": "0",
"body": "@BobRoberts: I'm aware how `cmp_to_key` works. Me question was mainly out of curiosity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:08:06.563",
"Id": "433169",
"Score": "0",
"body": "@AlexV: Having to use `cmp_to_key` isn't very elegant. It would be interesting to know if there's a good key function. In the meantime, `sorted(numbers, key=lambda i: str(i) * 1000, reverse=True)` should work fine for *many* examples, but isn't very elegant either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:02:39.297",
"Id": "433189",
"Score": "0",
"body": "@BobRoberts: `sorted(numbers, key= lambda i:itertools.cycle(str(i)), reverse=True)` would be nice. Sadly, cycles aren't comparable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:04:36.917",
"Id": "433222",
"Score": "0",
"body": "I've come up with (what I think is) a working key. (it passes @AlexV 's asserts) It's actually in line with an earlier attempt, but with a minor tweak. We were looking at sorting with strings, but sorting with lists as a key is subtly different. `k=list(str(num))``return k + k[0:1]` re-uses the adding the first character method, but in a way that sorts correctly. (though I came to it via an alternative approach this time). I haven't been able to find a way to break it so far. Now I guess we need to profile this vs the cmp approach. to see which is superior?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:20:37.153",
"Id": "433224",
"Score": "1",
"body": "@Baldrickk That method fails on [50501,50] (5050150 instead of 5050501)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:38:40.670",
"Id": "433225",
"Score": "0",
"body": "@BobRoberts ah, damn. thanks. I'd actually tried `[50, 505, 5050]` as a test and it passed that... needed to go a bit further..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:57:10.900",
"Id": "433263",
"Score": "2",
"body": "Sigh... The whole code in Ruby would be `numbers.sort{|a,b| [b, a].join <=> [a, b].join }` because sorting by comparator hasn't been removed. Python is a great language with many good design decisions but this one doesn't feel right."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:46:04.813",
"Id": "223491",
"ParentId": "223399",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223403",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T08:22:20.477",
"Id": "223399",
"Score": "7",
"Tags": [
"python",
"algorithm",
"python-3.x",
"interview-questions"
],
"Title": "Find max number you can create from an array of numbers"
} | 223399 |
<p>I am currently developing a REST service in ASP.NET Core 2.2 that acts as a wrapper upon a REST API provided by a reporting solution.</p>
<p>The reporting systems REST API authenticates the user based on a username and a password and subsequent requests must contain both a token and the cookies received during the authentication process.</p>
<blockquote>
<p>My primary goal is optimize the traffic by caching tokens and cookies
for similar requests (that use the same reporting project which has
its own REST API instance) and reuse them until their expiration. </p>
<p>My secondary goal is to write a class that is very easy to consume by
the controller which does not have even know about authentication and
retrials.</p>
</blockquote>
<p>I am using <a href="https://marketplace.visualstudio.com/items?itemName=dmitry-pavlov.ApiClientGenerationTools" rel="nofollow noreferrer">Api Client Generation Tools</a> to automatically generate the code used for actual REST API calls (type MsiRestClient).</p>
<h3>The client service</h3>
<pre><code>public class MsiRestClientService : IMsiRestClientService
{
#region Constants
private const int TokenRefreshCoolDownPeriod = 30; // seconds
#endregion
#region Variables
private static readonly object LockSync = new object();
private static readonly SemaphoreSlim GetNewTokenSemaphore = new SemaphoreSlim(1, 1);
/// <summary>
/// stores all the tokens generated for each project source
/// </summary>
private static readonly Dictionary<string, TokenInfo> MsiProjectSourceToTokenMap = new Dictionary<string, TokenInfo>();
private static readonly Dictionary<string, DateTime> LastSuccessfulTokenFetchTimestamps = new Dictionary<string, DateTime>();
#endregion
#region Properties
// this is used to provide information about current reporting instance
private IMsiProjectSourceService MsiProjectSourceService { get; }
private ILoggingService Logger { get; }
#endregion
#region Constructor
public MsiRestClientService(ILoggingService logger, IMsiProjectSourceService msiProjectSourceService)
{
Logger = logger;
MsiProjectSourceService = msiProjectSourceService;
}
#endregion
#region Private methods
private TokenInfo GetProjectSourceTokenInfo(string projectSourceName)
{
lock (LockSync)
{
return MsiProjectSourceToTokenMap.ContainsKey(projectSourceName)
? MsiProjectSourceToTokenMap[projectSourceName]
: null;
}
}
private void SetProjectSourceTokenInfo(string projectSourceName, TokenInfo token)
{
lock (LockSync)
{
MsiProjectSourceToTokenMap[projectSourceName] = token;
}
}
private DateTime? GetLastSuccessfulTokenFetchTimestamp(string projectSourceName)
{
lock (LockSync)
{
return LastSuccessfulTokenFetchTimestamps.ContainsKey(projectSourceName)
? LastSuccessfulTokenFetchTimestamps[projectSourceName]
: (DateTime?) null;
}
}
private void SetLastSuccessfulTokenFetchTimestamp(string projectSourceName, DateTime dateTime)
{
lock (LockSync)
{
LastSuccessfulTokenFetchTimestamps[projectSourceName] = dateTime;
}
}
private (MsiRestClient, CookieContainer) GetMsiRestClientInfo(string projectSourceName, CookieContainer cookies = null)
{
// using provided cookies if any, otherwise creating new ones
CookieContainer actualCookies = cookies ?? new CookieContainer();
var msiHttpClientHandler = new HttpClientHandler { CookieContainer = actualCookies };
var msiHttpClient = new HttpClient(msiHttpClientHandler);
var msiRestClient = new MsiRestClient(msiHttpClient)
{
// this is required before the generator does not fetch the URL correctly
BaseUrl = MsiProjectSourceService.GetMsiProjectSourceRestApiUrl(projectSourceName)
};
if (string.IsNullOrWhiteSpace(msiRestClient.BaseUrl))
throw new ArgumentException($"No MSI Rest Api URL found for project source {projectSourceName}");
return (msiRestClient, actualCookies);
}
private async Task<bool> RefreshToken(string projectSourceName)
{
// do not refresh if the token if it has just been successfully been refreshed recently
// this is done to avoid mass-refresh when multiple clients want to use the service to query MSI
var credentials = MsiProjectSourceService.GetMsiProjectSourceCredentials(projectSourceName);
if (credentials == null)
{
Logger.LogError($"Failed to get credentials for project source {projectSourceName}");
return false;
}
await GetNewTokenSemaphore.WaitAsync();
try
{
DateTime lastSuccessfulTokenFetchTimestamp =
GetLastSuccessfulTokenFetchTimestamp(projectSourceName) ?? new DateTime(2000, 1, 1);
int interval = (int) (DateTime.Now - lastSuccessfulTokenFetchTimestamp).TotalSeconds;
if (interval < TokenRefreshCoolDownPeriod)
return true;
var (msiRestClient, cookies) = GetMsiRestClientInfo(projectSourceName);
var authData = new AuthRequest
{
Username = credentials.Username,
Password = credentials.Password
};
try
{
await msiRestClient.PostLoginAsync(authData);
}
//TODO: replace with ApiException when NullReferenceException is solved
catch (Exception exc)
{
Console.WriteLine("Failed to authenticate for MSI project source: " + exc);
throw;
}
TokenInfo ti = new TokenInfo {Token = msiRestClient.Token, Cookies = cookies};
SetProjectSourceTokenInfo(projectSourceName, ti);
SetLastSuccessfulTokenFetchTimestamp(projectSourceName, DateTime.Now);
return true;
}
finally
{
GetNewTokenSemaphore.Release();
}
}
// checks if token information is available and reauthenticates if needed. Also, allows to forcefully reauthenticate (e.g. caller knows about a failure)
private async Task<TokenInfo> EnsureTokenInfo(string projectSourceName, bool force)
{
var tokenInfo = GetProjectSourceTokenInfo(projectSourceName);
if (force || tokenInfo == null)
{
await RefreshToken(projectSourceName);
tokenInfo = GetProjectSourceTokenInfo(projectSourceName);
}
if (tokenInfo == null)
{
throw new ApplicationException(
$"Failed to get cached info for project source {projectSourceName}. Should not happen since token info was just refreshed");
}
return tokenInfo;
}
private string HandleRestApiCallException(Exception e, int trial)
{
string errorMessage = $"Unexpected exception during Rest Api Call {trial}";
if (e is ApiException apiExc)
{
return $"ExecuteWithTokenRefresh failed #{trial}: Response = {apiExc.Response}, Code = {apiExc.StatusCode}";
}
if (e is ArgumentNullException)
{
errorMessage = $"ExecuteWithTokenRefresh failed #{trial}: {e.Message}";
Logger.LogInfo(errorMessage);
return errorMessage;
}
if (e is NullReferenceException)
{
errorMessage = "Null reference exception received while executing ExecuteWithTokenRefresh - did you fix ApiException code?";
Logger.LogError(errorMessage);
return errorMessage;
}
return errorMessage;
}
private async Task<ValidationResult<TRes>> ExecuteWithTokenRefresh<TRes>(string projectSourceName,
Func<MsiRestClient, string, Task<TRes>> requestFunc)
{
var tokenInfo = await EnsureTokenInfo(projectSourceName, false);
// creating a REST client based on data got from authentication (including cookies)
var (msiRestClient, _) = GetMsiRestClientInfo(projectSourceName, tokenInfo.Cookies);
try
{
var result = await requestFunc(msiRestClient, tokenInfo.Token);
// no exception means that it successfully completed
return new ValidationResult<TRes> {Payload = result};
}
catch (Exception e)
{
HandleRestApiCallException(e, 1);
}
// error is most probably caused by an authentication / transient REST service -> retrying
tokenInfo = await EnsureTokenInfo(projectSourceName, true);
var (msiRestClientBis, _) = GetMsiRestClientInfo(projectSourceName, tokenInfo.Cookies);
string errorMessage;
try
{
var result = await requestFunc(msiRestClientBis, tokenInfo.Token);
// no exception means that it successfully completed
return new ValidationResult<TRes> { Payload = result };
}
catch (Exception e)
{
errorMessage = HandleRestApiCallException(e, 2);
}
return new ValidationResult<TRes>
{
IsError = true,
Message = errorMessage
};
}
#endregion
#region Public methods
public async Task<TokenInfo> GetTokenInfo(string projectSourceName)
{
bool refreshResult = await RefreshToken(projectSourceName);
if (!refreshResult)
return null;
return GetProjectSourceTokenInfo(projectSourceName);
}
// all actual calls that do not deal with authentication or retrial simply use ExecuteWithTokenRefresh to wrap the actual call
public async Task<ValidationResult<SessionInfo>> GetCurrentUserSessionInfo(string projectSourceName)
{
return await ExecuteWithTokenRefresh(projectSourceName,
async (msiRestClient, token) => await msiRestClient.SessionSessionIdUserInfoGetAsync(token));
}
#endregion
}
</code></pre>
<h3>Usage</h3>
<pre><code>[HttpGet("[action]")]
public async Task<ActionResult<ValidationResult<SessionInfo>>> GetCurrentUserSessionInfo(string localName = null)
{
Logger.LogInfo("Test/GetCurrentUserSessionInfo called");
var result = await MsiRestClientService.GetCurrentUserSessionInfo(localName);
return new ActionResult<ValidationResult<SessionInfo>>(result);
}
</code></pre>
<p>Am I on the right track?</p>
| [] | [
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>Don't use regions to group members by type. This is redundant grouping. (<a href=\"https://softwareengineering.stackexchange.com/questions/53086/are-regions-an-antipattern-or-code-smell\">Regions pattern or anti-pattern?</a>)</li>\n<li>Use proper naming conventions and casing of variables. <code>LockSync</code> is generally called <code>syncRoot</code>. <code>GetNewTokenSemaphore</code> indicates a method name, rename it to <code>newTokenMutex</code>. It's a mutex because you use the semaphore as a mutex.</li>\n<li>Prefer <code>TryGetValue</code> over the two-phase <code>ContainsKey</code> + <code>Indexer</code> lookup on a <code>Dictionary</code>. Refactor <code>GetProjectSourceTokenInfo</code> and <code>GetLastSuccessfulTokenFetchTimestamp</code> to use this method instead.</li>\n<li><code>GetMsiRestClientInfo</code> is a factory method, so rename it to <code>CreateMsiRestClientInfo</code>.</li>\n<li><code>GetMsiRestClientInfo</code> creates instances of <code>HttpClient</code>. This class uses a socket connection and is <code>IDisposable</code> to manage its connection with it. But you never dispose instances of this class. Also, creating instances all the time might lead to an influx in socket connections. (<a href=\"https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/\" rel=\"nofollow noreferrer\">HttpClient Considerations</a>) I suggest to also provide a cache of instances, given the cookies and a dispose strategy.</li>\n<li><code>RefreshToken</code> mixes sandbox (<code>return false</code>) with error-prone (<code>throw</code>) statements. There is no clear specification what this method should return when. It seems a mess.</li>\n<li>Using <code>DateTime.Now</code> to validate cache expiration is bad practice. Prefer a strategy that does not rely on your system's local time. An option is to consider <code>StopWatch</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T06:15:46.557",
"Id": "224529",
"ParentId": "223401",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224529",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:02:37.590",
"Id": "223401",
"Score": "1",
"Tags": [
"c#",
"asynchronous",
"rest",
"asp.net-core",
"asp.net-core-webapi"
],
"Title": "Optimizing calls for reauthentication by caching tokens and cookies"
} | 223401 |
<p>I was toying with a way force fixed timestep loop iterations in C and came up with a fairly simple timer struct (quite different from <a href="https://codereview.stackexchange.com/questions/215537/pausable-timer-implementation-for-sdl-in-c">Pausable Timer Implementation for SDL in C</a> and decided to put it out for review. The timerstruct itself is:</p>
<pre><code>typedef struct ktimer_t {
struct timespec next; /* timespec for next iteration */
double tstep; /* seconds per time-step */
void (*keep) (struct ktimer_t *); /* keep time function */
void (*reset) (struct ktimer_t *, double); /* reset tstep & next */
} ktimer_t;
</code></pre>
<p>Where the <code>keep</code> (keep_time) function grabs the current time with calculates <code>clock_gettime()</code> and then computes the difference between the next timestep (held in <code>.next</code>) and then calls <code>nanosleep()</code> to sleep for that period of time.</p>
<p>The timer is initialized with the number of seconds (or fractions of a second) in for each timestep, assigns the member function addresses for <code>keep</code> and <code>reset</code>, stores the current time and adds the timestep to that for use computing the difference when <code>keep</code> is called. The <code>reset</code> function simply allows reset of the time to current and resetting the timestep to a different value allowing for timer reuse. The init and member functions are:</p>
<pre><code>/** takes pointer to ktimer_t contianing next timestep, subtracts
* current time from next and nanosleeps for the difference
* updating k->next to contain the next timestep.
*/
void ktimer_keep (ktimer_t *k)
{
struct timespec req = { .tv_sec = 0 }, rem = { .tv_sec = 0 };
clock_gettime (CLOCK_REALTIME, &rem); /* get current time */
req = tsdiff (&k->next, &rem); /* time to next timestep */
/* validate non-negative time difference */
if ((double)req.tv_sec < 0 || (double)req.tv_nsec < 0) {
fputs ("error: next timestep is in the past.\n", stderr);
return; /* or exit(EXIT_FAILURE) as desired */
}
else
nanosleep (&req, &rem); /* sleep until requested time */
set_nextstep (k); /* update timespec to next */
}
/** resets ktimer_t current time and initializes
* .next for the next timestep.
*/
void ktimer_reset (ktimer_t *k, double tstep)
{
clock_gettime (CLOCK_REALTIME, &k->next); /* get current time */
k->tstep = tstep; /* set timestep */
set_nextstep (k); /* update timespec to next */
}
/** declares and initializes a ktimer_t struct.
* setting .tstep timestep to tstep, assigns the
* addresses of member functions, and updates .next
* to current time + k->tstep with set_nextstep().
*/
ktimer_t ktimer_init (double tstep)
{
ktimer_t k = { .tstep = tstep,
.keep = ktimer_keep,
.reset = ktimer_reset };
clock_gettime (CLOCK_REALTIME, &k.next); /* get current time */
set_nextstep (&k); /* update timespec to next */
return k;
}
</code></pre>
<p>The two other helper functions are <code>set_nextstep()</code> and <code>tsdiff()</code>. <code>set_nextstep</code> just adds another timestep to the <code>.next</code> timespec keeping a fixed interval (aside from any negligible rounding error from the <code>double</code> addition). The <code>tsdiff</code> function computes the sleep time required to keep the iterations on a fixed time, e.g.</p>
<pre><code>/** simple helper to update timespec to next timestep
* (repetitive code)
*/
static void set_nextstep (ktimer_t *k)
{
if (k->tstep >= 1.0) /* validate if adding whole or fractional secs */
k->next.tv_sec += k->tstep; /* add number of seconds to next */
else /* or nanoseconds */
k->next.tv_nsec += k->tstep * 1e9;
}
/** tsdiff returnds a struct timespec with difference between tend/tbeg.
* tend must hold a timespec later in time than tbeg.
*/
struct timespec tsdiff (struct timespec *tend, struct timespec *tbeg)
{
struct timespec diff = { .tv_sec = 0 }; /* timespec to hold difference */
double sec = tend->tv_sec + 1e-9 * tend->tv_nsec - /* diff in seconds */
(tbeg->tv_sec + 1e-9 * tbeg->tv_nsec);
diff.tv_sec = (unsigned long)sec; /* set diff seconds */
diff.tv_nsec = (sec - (unsigned long)sec) * 1e9; /* set nanoseconds */
return diff; /* return timespec holding difference */
}
</code></pre>
<p>For use, a timer struct is either declared and initialized (or <code>.reset</code>) immediately before entering the loop to be timed, and then the <code>.keep</code> time function is called at the end of the loop invoking <code>nanosleep</code> for the difference between the time it took to process all commands within the loop and the <code>.next</code> timespec time. Example:</p>
<pre><code> ktimer_t k = ktimer_init (step); /* declare/initialize timer */
for (double i = 0; i < SECS; i += step) { /* loop seconds by timestep */
printf ("%5.2f\n", i); /* some long calculation here */
k.keep(&k); /* nanosleep time to next timestep */
}
</code></pre>
<p>My question here is two-fold (1) is this a reasonable factorization of the timekeeping having the struct store the <code>.next</code> timespec and then adding a fixed timestep each iteration, or (2) would what I called "negligible rounding error" from <code>double</code> addition the timestep each time be worse than keeping the <em>begin</em> time in the struct and passing <code>iteration * timestep</code> as the time since the beginning of the loop? (it seems like a wash, but I welcome your thoughts).</p>
<p>An additional question I have, is there any problem passing the pointer to struct itself as a parameter to the member function -- that then updates the member values of the struct itself? I can't find any part of the standard that says that's wrong, and for practical purposes the member functions are just functions, so if they happen to take a pointer to the struct as a parameter and update part of the struct, it doesn't really matter where the called function address comes from... (am I missing anything there?)</p>
<p>Here is a short example that exercises each part of the timer scheme:</p>
<pre><code>#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
/* define SECS and TSTEP in compile string as desired with -D */
#ifndef SECS
#define SECS 10 /* number of realtime seconds to run */
#endif
#ifndef TSTEP
#define TSTEP 0.5 /* handles either whole or fractional timesteps */
#endif
typedef struct ktimer_t {
struct timespec next; /* timespec for next iteration */
double tstep; /* seconds per time-step */
void (*keep) (struct ktimer_t *); /* keep time function */
void (*reset) (struct ktimer_t *, double); /* reset tstep & next */
} ktimer_t;
/** simple helper to update timespec to next timestep
* (repetitive code)
*/
static void set_nextstep (ktimer_t *k)
{
if (k->tstep >= 1.0) /* validate if adding whole or fractional secs */
k->next.tv_sec += k->tstep; /* add number of seconds to next */
else /* or nanoseconds */
k->next.tv_nsec += k->tstep * 1e9;
}
/** tsdiff returnds a struct timespec with difference between tend/tbeg.
* tend must hold a timespec later in time than tbeg.
*/
struct timespec tsdiff (struct timespec *tend, struct timespec *tbeg)
{
struct timespec diff = { .tv_sec = 0 }; /* timespec to hold difference */
double sec = tend->tv_sec + 1e-9 * tend->tv_nsec - /* diff in seconds */
(tbeg->tv_sec + 1e-9 * tbeg->tv_nsec);
diff.tv_sec = (unsigned long)sec; /* set diff seconds */
diff.tv_nsec = (sec - (unsigned long)sec) * 1e9; /* set nanoseconds */
return diff; /* return timespec holding difference */
}
/** takes pointer to ktimer_t contianing next timestep, subtracts
* current time from next and nanosleeps for the difference
* updating k->next to contain the next timestep.
*/
void ktimer_keep (ktimer_t *k)
{
struct timespec req = { .tv_sec = 0 }, rem = { .tv_sec = 0 };
clock_gettime (CLOCK_REALTIME, &rem); /* get current time */
req = tsdiff (&k->next, &rem); /* time to next timestep */
/* validate non-negative time difference */
if ((double)req.tv_sec < 0 || (double)req.tv_nsec < 0) {
fputs ("error: next timestep is in the past.\n", stderr);
return; /* or exit(EXIT_FAILURE) as desired */
}
else
nanosleep (&req, &rem); /* sleep until requested time */
set_nextstep (k); /* update timespec to next */
}
/** resets ktimer_t current time and initializes
* .next for the next timestep.
*/
void ktimer_reset (ktimer_t *k, double tstep)
{
clock_gettime (CLOCK_REALTIME, &k->next); /* get current time */
k->tstep = tstep; /* set timestep */
set_nextstep (k); /* update timespec to next */
}
/** declares and initializes a ktimer_t struct.
* setting .tstep timestep to tstep, assigns the
* addresses of member functions, and updates .next
* to current time + k->tstep with set_nextstep().
*/
ktimer_t ktimer_init (double tstep)
{
ktimer_t k = { .tstep = tstep,
.keep = ktimer_keep,
.reset = ktimer_reset };
clock_gettime (CLOCK_REALTIME, &k.next); /* get current time */
set_nextstep (&k); /* update timespec to next */
return k;
}
int main (void) {
double step = TSTEP;
ktimer_t k = ktimer_init (step); /* declare/initialize timer */
for (double i = 0; i < SECS; i += step) { /* loop seconds by timestep */
printf ("%5.2f\n", i); /* some long calculation here */
k.keep(&k); /* nanosleep time to next timestep */
}
putchar ('\n');
step /= 2.;
k.reset (&k, step); /* reset timer & tstep, repeat */
for (double i = 0; i < SECS; i += step) {
printf ("%5.2f\n", i);
k.keep(&k);
}
}
</code></pre>
<p>For the purposes of this example, I'm not overly concerned with whether <code>CLOCK_REALTIME</code> or <code>CLOCK_MONOTONIC_RAW</code>, etc.. would be best, though <code>CLOCK_MONOTONIC_RAW</code> would be the better choice. For the example and whether this was sane, the potential for discontinuous jumps in system time were not factors. I'm more concerned about whether this is a reasonable approach and if I'm missing anything obvious in the way I'm passing a pointer to the struct itself to a member function within the struct.</p>
<p>note: Windows <code>QueryPerformanceCounter()</code> should be able to provide similar functionality on that OS in the absence of <code>clock_gettime()</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:50:49.603",
"Id": "433181",
"Score": "0",
"body": "Forgot to `return 0;`? Also, it's not important, but the style is a bit inconsistent in `main`: the style of the function braces is different. I guess you just forgot the new line too :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:53:35.197",
"Id": "433184",
"Score": "0",
"body": "Yes, C99+ provides a default `return 0;` when omitted, compiling with `std=c11` it is covered, but you are correct, for completeness the `return 0;` is worth the extra line of code."
}
] | [
{
"body": "<p><strong>- error handling</strong></p>\n\n<pre><code>int nanosleep(const struct timespec *req, struct timespec *rem);\nint clock_gettime(clockid_t clk_id, struct timespec *tp);\n</code></pre>\n\n<p>Return an error code. You may want to react to it or not, but probably you should let the user know, so I would change these:</p>\n\n<pre><code>int ktimer_keep(ktimer_t *k);\nint ktimer_reset(ktimer_t *k, double tstep);\nint ktimer_init(ktimer_t *k, double tstep)\n</code></pre>\n\n<p>You also may (or may not) want to force the user to read the error code (GCC extension):</p>\n\n<pre><code>int ktimer_keep(ktimer_t *k) __attribute__((warn_unused_result));\n</code></pre>\n\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes\" rel=\"nofollow noreferrer\">Documentation here</a>.</p>\n\n<hr>\n\n<p><strong>- types</strong></p>\n\n<p><code>struct timespec::tv_sec</code> is of type <code>time_t</code>, not <code>unsigned long</code></p>\n\n<p><code>struct timespec::tv_nsec</code> is of type <code>long</code>, not <code>unsigned long</code></p>\n\n<p><a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html\" rel=\"nofollow noreferrer\"></a></p>\n\n<hr>\n\n<p><strong>- precision</strong></p>\n\n<p><code>double</code> is typically 64 bits (it can't represent all 64-bit integers), <code>long</code> is also typically 64 bits, but <code>long double</code> is typically larger than 64 bits (it's implementation defined, but it's more or less stable) and usually can represent all 64-bit integers, so maybe it would be a better type.</p>\n\n<p>Remember to use the correct constants if you do change to this type: <code>1e-9L</code> I think it is.</p>\n\n<hr>\n\n<p><strong>- Unnecessary else</strong> (From Linux <a href=\"https://github.com/torvalds/linux/blob/master/scripts/checkpatch.pl\" rel=\"nofollow noreferrer\">checkpatch.pl</a>)</p>\n\n<p>\"<code>else</code> is not generally useful after a break or return.\"</p>\n\n<p>I add to that sentence a <code>continue</code>, <code>goto</code> or <code>exit()</code>.</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (err)\n return;\nelse\n printf(\"Hello world!\\n\");\n</code></pre>\n\n<p>is equivalent to this, which is easier to read:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (err)\n return;\nprintf(\"Hello world!\\n\");\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT:</strong> continue revision</p>\n\n<hr>\n\n<p>In your case, I would use <code>goto</code> to move all the error handling to the end of the function, and let the error-free path clear (this is opinion based; feel free to disagree):</p>\n\n<pre><code>int ktimer_keep(ktimer_t *k)\n{\n struct timespec req = { .tv_sec = 0 };\n struct timespec rem = { .tv_sec = 0 };\n\n if (clock_gettime(CLOCK_REALTIME, &rem))\n goto err_lib;\n req = tsdiff (&k->next, &rem);\n\n if (req.tv_sec < 0 || req.tv_nsec < 0)\n goto err_past;\n if (nanosleep(&req, &rem))\n goto err_lib;\n\n set_nextstep(k);\n return 0;\nerr_past:\n fputs(\"error: next timestep is in the past.\\n\", stderr);\n return -1;\nerr_lib:\n perror(\"Write something meaningful here\");\n // Maybe some more cleanup here\n return errno;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>- casts (unneeded?)</strong></p>\n\n<pre><code>if ((double)req.tv_sec < 0 || (double)req.tv_nsec < 0)\n</code></pre>\n\n<p>I don't see why you would need to cast that</p>\n\n<hr>\n\n<p><strong>- Warn user if misusing the function</strong></p>\n\n<p>Given that you are using GCC, you can ensure that the user doesn't shoot himself in the foot passing a <code>NULL</code> pointer to your functions. You can do that with</p>\n\n<pre><code>int ktimer_keep (ktimer_t *k) __attribute__((nonnull(1)));\n</code></pre>\n\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes\" rel=\"nofollow noreferrer\">Documentation here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:18:52.097",
"Id": "433171",
"Score": "1",
"body": "All good points. With `int ktimer_init (ktimer_t *k, double tstep);` since the intent was to declare and initialize in a single call, we could allocate for `ktimer_t` in `init()` which would allow using an opaque pointer for the implementation when broken into a separate headers & source. Good catch on the unneeded `else` which was just a leftover from an earlier factoring of the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:46:55.687",
"Id": "433178",
"Score": "0",
"body": "@DavidC.Rankin You could add an answer with that"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:13:30.490",
"Id": "223499",
"ParentId": "223405",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T09:28:41.287",
"Id": "223405",
"Score": "5",
"Tags": [
"c",
"timer"
],
"Title": "timer struct for fixed timestep iterations in C (gcc)"
} | 223405 |
<p>I'm new in JavaScript, so I was looking for some reviews and advice for better code quality.</p>
<pre><code>import Todo from './Todo.js';
export default class Repository {
constructor(todos = []) {
this.todos = todos;
this.storage = localStorage;
}
addTodo(todo, save=true) {
this.todos = [...this.todos.filter(item => item.uuid !== todo.uuid), todo];
if (save) {
this.saveTodos();
}
}
removeTodo(todo) {
this.todos = [...this.todos.filter(item => item.uuid !== todo.uuid)];
this.saveTodos();
}
saveTodos() {
this.storage.setItem('todos', JSON.stringify(this.todos));
}
loadTodos() {
const storageTodos = JSON.parse(this.storage.getItem('todos'));
if (storageTodos !== null) {
storageTodos.map(todo => this.addTodo(Object.assign(new Todo(), todo)), false);
}
return this.todos;
}
}
</code></pre>
<p><a href="https://github.com/adbo/todo_list" rel="nofollow noreferrer">https://github.com/adbo/todo_list</a></p>
| [] | [
{
"body": "<h2>General points</h2>\n\n<ul>\n<li>There is no need to add <code>localStorage</code> to the <code>Repository</code> object as it is part of the global this.</li>\n<li>You can access localStorage values directly by the key name <sup><strong>[.1]</strong></sup>. Eg setting <code>localStorage.myData = \"Hi World\"</code>, getting <code>const message = localStorage.myData</code>, to check if it exists <code>localStorage.myData !== undefined</code>, to empty a value <code>localStorage.myData = undefined</code>, and to delete <code>delete localStorage.myData</code></li>\n<li>LocalStorage should not be trusted. Calling <code>JSON.parse</code> on data from local storage should always be wrapped in a try catch in case the data has been modified by a 3rd party.</li>\n<li>Using <code>filter</code> to remove items from an array is not as efficient as locating the item's index and splicing it. Even better would be to store the todo array as a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> indexed by <code>uuid</code> see second example.</li>\n<li>You have some poor naming due to the repeated prefixing of todo to all the functions. I can imagine that the Repository is called <code>todoList</code> and thus is would be <code>todoList.addTodo</code> <code>todoList.removeTodo</code> and so on. Would be far more readable if you drop the todo . Eg <code>todoList.add</code>, <code>todoList.remove</code>, ...</li>\n<li>You are repeating code. Both <code>add</code> and <code>remove</code> functions filter (remove) a todo. I would be better for <code>add</code> to call <code>remove</code></li>\n</ul>\n\n<h2>Good OO design</h2>\n\n<p>Javascripts class syntax is something you should avoid as it forces you to create objects with poor encapsulation (if you don't use the \"abomination\" that is <code>#</code> private prefix) Javascript has several very robust object patterns that provide air tight encapsulation and should be used if you wish to follow good OO design.</p>\n\n<p>The examples shows and immediately invoked function (IIF) pattern that defines the Object <code>Repository</code> as a function returning an ad hock <code>Object</code> that encapsulates via closure.</p>\n\n<p>The <code>todos</code> array (or map) is isolated and not directly accessible. It uses a getter to return the array of todos as a shallow copy</p>\n\n<h2>Examples</h2>\n\n<p>Both examples use IIF pattern to encapsulate the object created from the named <code>Repository</code></p>\n\n<p>Note that it has slightly different behavior than your object.</p>\n\n<p>You can instantiate the object with or without the <code>new</code> token. Eg <code>todos = Repository()</code> or <code>todos = new Repository()</code> </p>\n\n<p>The first example store data in an array that it keeps private, copied on creation and copied when accessed via the getter <code>todos</code>.</p>\n\n<h3>IFF ad hock</h3>\n\n<pre><code>export default Repository = (() => {\n const save = (todos) => localStorage.todos = JSON.stringify(todos);\n const load = () => {\n try { return localStorage.todos ? JSON.parse(localStorage.todos) : [] }\n catch(e) { return [] }\n }\n return function(todos = []) {\n todos = [...todos]; \n return Object.freeze({\n get todos() { return [...todos] },\n remove(todo, saveChanges = true) {\n const idx = todos.findIndex(item => item.uuid !== todo.uuid); \n idx > -1 && todos.splice(idx, 1); \n saveChanges && save(todos); \n }, \n add(todo, saveChanges = true) {\n this.remove(todo, false);\n todos.push(toDo);\n saveChanges && save(todos);\n },\n save() { save(todos) },\n load() {\n load().forEach(todo => this.add(Object.assign(new Todo(), todo), false));\n return this.todos;\n }\n });\n }\n})();\n</code></pre>\n\n<h3>IFF with Map</h3>\n\n<p>This example uses a map to improve the efficiency of removing items and reduces the source size. It behaves identically to the first example.</p>\n\n<p>Also as using <code>this</code> does present a security concern (even in modules) thus example references self via the named constant <code>API</code></p>\n\n<pre><code>export default Repository = (() => {\n const save = (todos) => localStorage.todos = JSON.stringify(todos);\n const load = () => {\n try { return localStorage.todos ? JSON.parse(localStorage.todos) : [] }\n catch(e) { return [] }\n }\n return function(todosInit = []) {\n const API = Object.freeze({\n get todos() { return [...todos.values()] },\n remove(todo, saveChanges = true) {\n todos.delete(todo.uuid);\n saveChanges && API.save(); \n }, \n add(todo, saveChanges = true) {\n API.remove(todo, false);\n todos.set(todo.uuid, todo);\n saveChanges && API.save();\n },\n save() { save(API.todos) },\n load() {\n load().forEach(todo => API.add(Object.assign(new Todo(), todo), false));\n return API.todos;\n }\n });\n return API;\n }\n})();\n</code></pre>\n\n<h2>Notes</h2>\n\n<p><sup><strong>[.1]</strong> Note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Basic_concepts\" rel=\"nofollow noreferrer\">MDN localStorage</a> page cites <a href=\"https://2ality.com/2012/01/objects-as-maps.html\" rel=\"nofollow noreferrer\">\"The pitfalls of using objects as maps\"</a> as reason not to use direct key access. Why only warn on localStorage why not have the same warning on every Object? Get with it MDN!!</sup></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:26:48.160",
"Id": "223419",
"ParentId": "223407",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:30:32.470",
"Id": "223407",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"repository"
],
"Title": "Simple todo list VanillaJS - repository pattern"
} | 223407 |
<p>I have this code for a post request, when the user wants to change his password. Because of all the cases and the following page renders the code came out really ugly. Is there a better way to structure this? (It works fine and does what I want.)</p>
<pre><code>// Check if old password is correct
SQL.getUserFromDB(request.session.username).then(function (results) {
// Hash and compare with stored hash
bcrypt.compare(request.body.oldPw, results[0].password, function (error, result) {
// Log possible error
if (error) console.log(error);
if (result === true) {
// Check if new passwords are both the same
if (request.body.newPw === request.body.newPw2) {
// Call mysql function
SQL.changeUserPassword(request.session.username, request.body.newPw).then(function () {
response.render('pages/changePassword', {
user: request.session.username,
text: 'Passwort erfolgreich geändert.'
});
}).catch(function (error) {
console.log(error);
if (error == 'pw') {
response.render('pages/changePassword', {
user: request.session.username,
text: 'Neues Passwort zu unsicher.'
});
} else {
// Render error page
response.render('pages/changePassword', {
user: request.session.username,
text: 'Fehler beim Ändern des Passworts.'
});
}
});
} else {
// Render error page
response.render('pages/changePassword', {
user: request.session.username,
text: 'Neue Passwörter stimmen nicht überein!'
});
}
} else {
// Render error page
response.render('pages/changePassword', {
user: request.session.username,
text: 'Altes Passwort stimmt nicht überein!'
});
}
});
// Catch sql errorsFehler beim Ändern des Passworts
}).catch(function (error) {
if (error) console.log(error);
response.render('pages/errors/loginFailed');
});
</code></pre>
<p>I tried just setting the text in the different cases and rendering one page with the text at the bottom, this didn't work however.</p>
| [] | [
{
"body": "<p>What you first need to do is convert all non-promise/callback-based operations into promises, or wrap them in one. This way, you can write seamless promise-based code. For instance, convert <code>bcrypt.compare()</code> into:</p>\n\n<pre><code>const bcryptCompare = (pw1, pw2) => {\n return new Promise((resolve, reject) => {\n bcrypt.compare(pw1, pw2, (error, result) => {\n if(error) reject(error)\n else resolve(result)\n })\n })\n}\n</code></pre>\n\n<p>There are libraries that do this for you, and newer versions of libraries usually support promise-based versions of their APIs. But if you ever need to craft this yourself, this is how it's generally done.</p>\n\n<p>Next, I would separate express from this logic. This way, you're not constrained with Express. Instead of accessing <code>request</code>, pass only the needed information to your function. Instead of immediately sending a response, consider throwing error objects instead. This way, you can defer your response logic to your routing logic.</p>\n\n<p>Next, you could turn to <code>async</code>/<code>await</code> for cleaner code. It's just syntax sugar on top of Promises, allowing asynchronous code to look synchronous.</p>\n\n<pre><code>// Custom error class to house additional info. Also used for determining the\n// correct response later.\nclass PasswordMismatch extends Error {\n constructor(message, user){\n this.message = 'Neue Passwörter stimmen nicht überein!'\n this.user = user\n }\n}\n\nclass UserDoesNotExist extends Error {...}\nclass PasswordIncorrect extends Error {...}\n\n// More custom error classes here\n\n// Our logic, which knows nothing about express and only requires a few\n// pieces of information for our operation.\nconst changePassword = async (username, oldPw, newPw, newPw2) => {\n\n // Throwing an error inside an async function rejects the promise it returns\n if (newPw !== newPw2) {\n throw new PasswordMismatch('Neue Passwörter stimmen nicht überein!', user)\n }\n\n const results = await SQL.getUserFromDB(username)\n\n if (!results) {\n throw new UserDoesNotExist('...', user)\n }\n\n const result = bcryptCompare(oldPw, results[0].password)\n\n if(result !== true) {\n throw new PasswordIncorrect('...', user)\n }\n\n try {\n SQL.changeUserPassword(username, newPw)\n } catch(e) {\n throw new PasswordChangeFailed('...', user)\n }\n}\n\n// In your express router\napp.post('route', async (request, response) => {\n // Gather the necessary data from the request\n const username = request.session.username\n const oldPw = request.body.oldPw\n const newPw = request.body.newPw\n const newPw2 = request.body.newPw2\n\n try {\n await changePassword(username, oldPw, newPw, newPw2)\n\n // If the operation didn't throw, then we're good. Happy path.\n response.render('pages/changePassword', {\n user: username,\n text: 'Passwort erfolgreich geändert.'\n });\n } catch (e) {\n // If any of the operations failed, then we determine the right response\n\n // In this case, we used a custom error. We can get the data from it.\n // You can have more of these for the other custom classes.\n if(error instanceof PasswordConfirmError){\n response.render('pages/changePassword', {\n user: error.user,\n text: error.message\n });\n\n } else {\n // Generic 500 error, if all else fails.\n }\n }\n})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:55:55.570",
"Id": "432969",
"Score": "0",
"body": "Thanks for the in-depth answer. That looks way nicer than what i hacked together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:00:26.097",
"Id": "432971",
"Score": "0",
"body": "Would you normally seperate the logic in different files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:51:37.167",
"Id": "432979",
"Score": "1",
"body": "@user3742929 Depends on your case. Small script, you don't worry about it. But when the code grows, separate them. Also, one thing to consider is that `changePassword` in my example could be used regardless of the presence of express."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:45:18.383",
"Id": "223413",
"ParentId": "223409",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:50:03.687",
"Id": "223409",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"authentication",
"express.js"
],
"Title": "Better code for error handling in NodeJs and Express"
} | 223409 |
<p>Because <a href="https://codereview.stackexchange.com/questions/223375/recursive-conversion-from-expandoobject-to-dictionarystring-object">my original question</a> was lacking many details, I have been advised to ask a new question.<br />
I will repeat the important parts of the original question and add examples etc to hopefully make it clear.</p>
<p>For <a href="https://github.com/Joelius300/ChartJSBlazor" rel="nofollow noreferrer">my blazor library</a> which is a modification of <a href="https://github.com/mariusmuntean/ChartJs.Blazor" rel="nofollow noreferrer">this awesome library</a> I have to convert an <code>ExpandoObject</code> into a <code>Dictionary<string, object></code> since <code>ExpandoObject</code>s aren't serialized properly in the newest preview versions of dotnet-core. See <a href="https://stackoverflow.com/questions/56693103/invoke-javascript-method-from-c-sharp-with-dynamic-parameter">my question related to this</a> for more details.</p>
<p>For this new question I have already improved my code with recommendations from <a href="https://codereview.stackexchange.com/a/223380/203991">this</a> and <a href="https://codereview.stackexchange.com/a/223379/203991">this</a> answer on my previous question.</p>
<p>This is my current (and hopefully already better) approach. I have added summaries to more clearly show my intent but I'm sure these could be improved as well since I'm not very good at documenting my code.<br />
Also worth mentioning if it's not clear, these changes did not affect the program and everything still works.</p>
<pre><code>/// <summary>
/// This method is specifically used to convert an <see cref="ExpandoObject"/> with a Tree structure to a <see cref="Dictionary{string, object}"/>.
/// </summary>
/// <param name="expando">The <see cref="ExpandoObject"/> to convert</param>
/// <returns>The fully converted <see cref="ExpandoObject"/></returns>
private static Dictionary<string, object> ConvertExpandoObjectToDictionary(ExpandoObject expando) => RecursivelyConvertIDictToDict(expando);
/// <summary>
/// This method takes an <see cref="IDictionary{string, object}"/> and recursively converts it to a <see cref="Dictionary{string, object}"/>.
/// The idea is that every <see cref="IDictionary{string, object}"/> in the tree will be of type <see cref="Dictionary{string, object}"/> instead of some other implementation like <see cref="ExpandoObject"/>.
/// </summary>
/// <param name="value">The <see cref="IDictionary{string, object}"/> to convert</param>
/// <returns>The fully converted <see cref="Dictionary{string, object}"/></returns>
private static Dictionary<string, object> RecursivelyConvertIDictToDict(IDictionary<string, object> value) =>
value.ToDictionary(
keySelector => keySelector.Key,
elementSelector =>
{
// if it's another IDict just go through it recursively
if (elementSelector.Value is IDictionary<string, object> dict)
{
return RecursivelyConvertIDictToDict(dict);
}
// if it's an IEnumerable check each element
if (elementSelector.Value is IEnumerable<object> list)
{
// go through all objects in the list
// if the object is an IDict -> convert it
// if not keep it as is
return list
.Select(o => o is IDictionary<string, object>
? RecursivelyConvertIDictToDict((IDictionary<string, object>)o)
: o
);
}
// neither an IDict nor an IEnumerable -> it's fine to just return the value it has
return elementSelector.Value;
}
);
</code></pre>
<p>Something I didn't mention in detail is why I need this conversion in the first place. This is also the reason <a href="https://codereview.stackexchange.com/a/223393/203991">this answer</a> probably wont help :/</p>
<p>I'll explain it with a simplified example:</p>
<pre><code>public void Demo()
{
SomeConfig config = new SomeConfig
{
Options = new SomeOptions // it can contain complex types
{
SomeInt = 2, // it can contain primative types
SomeString = null,
Axes = new List<Axis> // it can contain complex lists
{
new Axis(),
new Axis
{
SomeString = "axisString"
}
}
},
Data = new SomeData
{
Data = new List<int> { 1, 2, 3, 4, 5 }, // it can contain primative lists
SomeString = "asdf",
SomeStringEnum = MyStringEnum.Test // it can contain objects with custom parsing (for JSON.NET, not the parsing that's done when invoking the JS sadly
}
};
// now there are three options for invoking the javascript (I invoke it using IJSRuntime.InvokeAsync)
// this does not work because there are still nulls and the StringEnum will be parsed as an object instead of string (
// json.net parses it correctly because of the custom converter but .net does not as it just sees an object)
InvokeJavascript(config);
// the nulls are gone and the StringEnum is parsed correctly but
// this does not work because .Net (NOT JSON.NET) has to convert the parameter to json which is not possible if the object is an ExpandoObject
InvokeJavascript(StripNulls(config));
// this does work because .Net can serialize a Dictionary but not an ExpandoObject.
// the nulls are still gone and the StringEnum is parsed correctly
InvokeJavascript(ConvertExpandoObjectToDictionary(StripNulls(config)));
}
/// <summary>
/// Returns an object that is equivalent to the given parameter but without any null members.
/// <para>This method is necessary because of the custom parsing for string enums and because for server-side blazor projects,
/// the interop doesn't work if there are null values (no idea why, this really should be fixed sometime in the future)</para>
/// </summary>
private static ExpandoObject StripNulls(SomeConfig chartConfig)
{
// Serializing with the custom serializer settings remove null members
// this cleanChartConfigStr doesn't contain a single null value and also the StringEnums are parsed as strings instead of objects because I use JSON.NET here
string cleanChartConfigStr = JsonConvert.SerializeObject(chartConfig, JsonSerializerSettings);
// Get back an ExpandoObject with the clean config - having an ExpandoObject allows us to add/replace members regardless of type
// which is necessary for preserving the DotNetObjectRefs (see below). Also if it were to be parsed back to the original Type (SomeConfig)
// the null values would return (and the string enums would throw errors since I've only implemented writing json but that could be fixed)
dynamic clearConfigExpando = JsonConvert.DeserializeObject<ExpandoObject>(cleanChartConfigStr, new ExpandoObjectConverter());
/*
* There are DotNetObjectRefs in the config which are manually being restored here and assigned to the right property in the dynamic config
*/
return clearConfigExpando;
}
// serializer settings for json.net to ignore all the null values and use the CamelCaseNamingStrategy
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy(true, false)
}
};
</code></pre>
<p>I can show you the difference when looking at the json that get produced when invoking the javascript with different objects:</p>
<p><strong>Directly invoking the javascript with the <code>SomeConfig</code> instance from the demo results in this json code being used in the javascript:</strong></p>
<pre><code>{
"options": {
"someInt": 2,
"someString": null,
"axes": [
{
"someString": null
},
{
"someString": "axisString"
}
]
},
"data": {
"data": [
1,
2,
3,
4,
5
],
"someString": "asdf",
"someStringEnum": {}
}
}
</code></pre>
<p><strong>First parsing it with custom parsing (using JSON.NET), then reading it back as <code>ExpandoObject</code> (using JSON.NET) and converting that to a <code>Dictionary<string, object></code> results in the following json being used:</strong></p>
<pre><code>{
"options": {
"someInt": 2,
"axes": [
{},
{
"someString": "axisString"
}
]
},
"data": {
"data": [
1,
2,
3,
4,
5
],
"someString": "asdf",
"someStringEnum": "someTestThing"
}
}
</code></pre>
<p>Note that both of these json string were not produced by json.net but by .net itself when invoking the javascript using <code>IJSRuntime.InvokeAsync</code>.</p>
<p>The json of the second option is in this example exactly the same as the intermediate json <code>cleanChartConfigStr</code> in the <code>StripNulls</code> method. This <code>cleanChartConfigStr</code> does not contain the functions and <code>DotNetObjectRefs</code> which are added to the <code>ExpandoObject</code> later on in the <code>StripNulls</code> method. When using <code>JSON.stringify</code> to print the json-string of that <code>ExpandoObject</code> (that's the json-string I showed you), you won't see those functions/<code>DotNetObjectRefs</code> either but this time because <code>JSON.stringify</code> doesn't print them, not because there are non-existent.<br />
I mention this because otherwise you might think that the <code>cleanChartConfigStr</code> as json-object would be equal to the json-object produced by the <code>ExpandoObject</code> which is not true (because of those functions and <code>DotNetObjectRefs</code>).</p>
<p>I feel like this part was confusing, I hope you understand what's going on.</p>
<p>Here are the remaining classes needed for the code to make sense:<br />
Because you will need the jsRuntime and the blazor project blabla to compile, I have created <a href="https://github.com/Joelius300/ChartJSBlazor/tree/DemoCodeReview" rel="nofollow noreferrer">a small demo-branch</a> on my github. It's ugly code and no, this will not be used anymore it's just so you can try it yourself if you want. The 3 json-strings (the two I showed + the intermediate one) are printed to the console (cmd, not browser) when you access the homepage or one of the chart-pages. Keep in mind that you'll need the newest version of .net core 3 (preview6) installed to run it. I think VS 19 preview is also required.</p>
<pre><code>class SomeConfig
{
public SomeOptions Options { get; set; }
public SomeData Data { get; set; }
}
class SomeOptions
{
public int SomeInt { get; set; }
public string SomeString { get; set; }
public List<Axis> Axes { get; set; }
}
class SomeData
{
public List<int> Data { get; set; }
public string SomeString { get; set; }
public MyStringEnum SomeStringEnum { get; set; }
}
class Axis
{
public string SomeString { get; set; }
}
[JsonConverter(typeof(JsonStringEnumConverter))]
class MyStringEnum
{
public static MyStringEnum Test => new MyStringEnum("someTestThing");
private readonly string _value;
private MyStringEnum(string stringRep) => _value = stringRep;
public override string ToString() => _value;
}
class JsonStringEnumConverter : JsonConverter<MyStringEnum>
{
public sealed override bool CanRead => false;
public sealed override bool CanWrite => true;
public sealed override MyStringEnum ReadJson(JsonReader reader, Type objectType, MyStringEnum existingValue, bool hasExistingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Don't use me to read JSON");
}
public override void WriteJson(JsonWriter writer, MyStringEnum value, JsonSerializer serializer)
{
// ToString was overwritten by StringEnum -> safe to just print the string representation
writer.WriteValue(value.ToString());
}
}
</code></pre>
<p>Now, I have put a lot of time and effort in this question and I hope now there's enough detail. As already mentioned, the real code (not this small demo example) is available on <a href="https://github.com/Joelius300/ChartJSBlazor" rel="nofollow noreferrer">github</a>. The most important file for this question would be <a href="https://github.com/Joelius300/ChartJSBlazor/blob/master/ChartJs.Blazor/ChartJS/ChartJsInterop.cs" rel="nofollow noreferrer">ChartJsInterop.cs</a>.</p>
<p>Once again I'm mostly interested in the recursive solution to convert those <code>ExpandoObject</code>s. However I'm happy for any critisism so please also mention every small thing that bugs you :)</p>
<p><strong>EDIT:</strong></p>
<p>After a discussion with @t3chb0t I feel like I have to mention this:<br />
The whole exchange is in the comments.</p>
<blockquote>
<p>I'm not at all saying that using this ExpandoObject is good. It feels like a hack because it is one. However I've not found a way to remove it as I have no idea how you would do the custom serialization for .NET (instead of JSON.NET) and also how you would remove the null values. If you have an idea for that which doesn't use ExpandoObject I'd love to hear it. The ExpandoObject does not at all interfere with the typesafety and is 100% only used for the serialization (particularly the removing of the null values and adapting the custom enum values). It's never exposed publicly in any way.</p>
</blockquote>
<p>If you have an idea to get rid of the <code>ExpandoObject</code> feel free to tell me but don't just call me out for using <code>ExpandoObject</code> without understanding the situation.<br />
It is used as little as possible and only has to do with some serialization behind the scenes, the developer who uses the library will never have anything to do with an <code>ExpandoObject</code> and even if you'd develop code for this library the chance is extremely small that you would need to do something with <code>ExpandoObject</code>. It does not hurt the typesafety of the config because that's a typesafe class and has nothing to do with <code>ExpandoObject</code> until the serialization.</p>
<p>I hope you understand. If you don't, let me know what you don't understand and look at the repository. There are parts from our exchange which point out some important files:</p>
<blockquote>
<p><a href="https://github.com/Joelius300/ChartJSBlazor/blob/master/WebCore/Pages/FetchDataLinear.razor" rel="nofollow noreferrer">Here</a>'s <em>one of</em> the usecases (hint there's absolutely no <code>ExpandoObject</code> and it's entirely typesafe <em>to use</em>). <a href="https://github.com/Joelius300/ChartJSBlazor/blob/master/ChartJs.Blazor/ChartJS/LineChart/LineChartConfig.cs" rel="nofollow noreferrer">Here</a>'s the Config that is being used, once again not a single <code>ExpandoObject</code> down the tree.</p>
<p><a href="https://github.com/Joelius300/ChartJSBlazor/blob/master/ChartJs.Blazor/ChartJS/ChartJsInterop.cs" rel="nofollow noreferrer">Here</a> is the first and only use of <code>ExpandoObject</code>. This link is also in the question.</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:58:08.097",
"Id": "432954",
"Score": "2",
"body": "Now I like the question ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:30:40.030",
"Id": "433095",
"Score": "0",
"body": "I withdraw my last words. Now that I carefully read every word I have to say it's still impossible to review the deserialization part because your `SomeConfig` model is hypothetical and we can only guess how it really looks like. I won't review it because you _explain it with a simplified example_ so this is my simplified answer ;-] Posting the real model would make this question much more useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:04:12.600",
"Id": "433106",
"Score": "0",
"body": "The real model is huge with many abstractions. There's a `BaseConfig<TData, TOptions> where TData : BaseData where TOptions : BaseOptions` and the same for options and data with base classes and generics etc. I can put that into the question if that's needed but it's going to be a lot and also you can find that on my Github if you want to look at it. Should I really put that in the question (as soon as I have time so not right now)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:12:53.017",
"Id": "433108",
"Score": "0",
"body": "It depends on how useful feedback you want to get. Simplfied code results in simplified answers and consequently less helpful. I find you should post the real config. (take your time)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:15:55.480",
"Id": "433110",
"Score": "0",
"body": "Is this _\"the real model is huge with many abstractions\"_ the reason why you have decided to use `ExpandoObject` because it was too difficult to deserialize all these abstractions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T07:21:09.530",
"Id": "433122",
"Score": "0",
"body": "@t3chb0t no not at all. As mentioned in the question, I only need the ExpandoObject because I need to restore some DotNetRefs from the orignal config after removing all the null properties. I have to remove the null properties because of a issue with the js interop. Also there are string and object enums which need to be serialized correctly and I cannot specify serializer options for the serializer that is used when invoking javascript with InvokeAsync. I think I've described that in the question. You should also read the method summary of StripNulls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:53:07.630",
"Id": "433183",
"Score": "0",
"body": "@t3chb0t by the way I have explicitly mentioned that I'm mostly interested in my recursive function. If I were to add all the classes that are needed for a single Config (in my example the LineConfig) I would have to add around 500 lines of code with over 20 classes. Almost 100% of these classes just contain properties and are meant as a model to provide a type safe way to configure the chart which is normally done in plain json (thats why this library exists in the first place). I even included the string enum in the question which should be the only special thing about the serialization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:59:07.073",
"Id": "433186",
"Score": "0",
"body": ".. apart from the `NullValueHandling = NullValueHandling.Ignore` when serializing the config. You also mention \"the deserialization part\". There is only one deserialization, from the (customly) serialized json to the `ExpandoObject`. As already mentioned this is to remove all the null properties. I then need to restore the `DotNetRef`s but that is just a side effect of simply deserializing the json instead of directly passing the config - it's not important for any of the things I'm asking about. Is my question not clear enough and if so what should I add/change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:05:22.030",
"Id": "433191",
"Score": "0",
"body": "You're saying that _these classes just contain properties and are meant as a model to provide a type safe way to configure the chart_ and yet you use a type-ignorant `ExpandoObject` and then manully _hack_ the values into their target types. One day you will come here with the words: _Guys, you were right, this was completely wrong!_ ok, I won't bother with that anymore; you don't have to add anything else; I'm good... next question please ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:11:34.910",
"Id": "433192",
"Score": "0",
"body": "You have obviously not understood why I _have_ to use `ExpandoObject`. If you really think everything I do is this bad, please go ahead and check out the repository. [Here](https://github.com/Joelius300/ChartJSBlazor/blob/master/WebCore/Pages/FetchDataLinear.razor)'s the usecase (hint there's absolutely no `ExpandoObject` and it's entirely typesafe). [Here](https://github.com/Joelius300/ChartJSBlazor/blob/master/ChartJs.Blazor/ChartJS/LineChart/LineChartConfig.cs)'s the Config that is being used, once again not a single `ExpandoObject` down the tree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:15:14.820",
"Id": "433195",
"Score": "0",
"body": "@t3chb0t And [here](https://github.com/Joelius300/ChartJSBlazor/blob/master/ChartJs.Blazor/ChartJS/ChartJsInterop.cs) is the first and only use of `ExpandoObject`. This link is also in the question. I do not understand why you are acting this (imo) rude when I try to help you understand my question. I have put a lot of work into this question and linked my repos multiple time so people could check it out if they needed the actual use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:15:25.930",
"Id": "433196",
"Score": "0",
"body": "@t3chb0t Please see for yourself and understand the use of `ExpandoObject` in my code. Then you can give constructive critisism (which is btw not what you've been giving). Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:23:42.660",
"Id": "433199",
"Score": "0",
"body": "I'm not at all saying that using this `ExpandoObject` is good. It feels like a hack because it is one. However I've not found a way to remove it as I have no idea how you would do the custom serialization for .NET (instead of JSON.NET) and also how you would remove the null values. If you have an idea for that which doesn't use `ExpandoObject` I'd love to hear it. The `ExpandoObject` does not at all interfere with the typesafety and is 100% only used for the serialization (particularly the removing of the null values and adapting the custom enum values). It's never exposed publicly in any way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:34:37.747",
"Id": "433204",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95714/discussion-between-t3chb0t-and-joelius)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T17:28:21.533",
"Id": "433403",
"Score": "0",
"body": "I am thinking that perhaps a custom _DynamicObject_, rather than _ExpandoObject_ might be able to simplify things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T21:00:19.070",
"Id": "436242",
"Score": "1",
"body": "I see from the chat above that you were able to solve this, and were intending to self-answer: would you still be looking to do that? I'd be interested to see what you came up with in the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T21:14:42.777",
"Id": "436248",
"Score": "0",
"body": "@VisualMelon I was only able to make out a solution in theory. With preview6 there were some breaking changes. It's really complicated and there are so many links to multiple blogs, announcements and issues. It's really interesting though and I would advise you to look at the [issue dedicated for this](https://github.com/Joelius300/ChartJSBlazor/issues/2) where you can find a lot of information and follow ups. I will also update that issue once I have a solution and post that Here. Currently I don't feel comfortable answering the question myself yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T12:39:36.370",
"Id": "437790",
"Score": "0",
"body": "Doesn't JSON.NET have an option to strip null values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T12:44:38.247",
"Id": "437791",
"Score": "1",
"body": "@dfhwze Yes it does. So does `JsonSerializer` which is used by `IJSRuntime`. However `IJSRuntime` doesn't support using your own options so there is no way of telling `IJSRuntime` that it should discard null values. If you want to be up-to-date with this issue please look at the issue (and other issues of my repos) I've linked in the comment above. I will come back to this question and answer it myself as soon as I have a the final solution."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "19",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T11:50:49.083",
"Id": "223410",
"Score": "6",
"Tags": [
"c#",
"recursion",
"json",
"hash-map"
],
"Title": "Recursive conversion from ExpandoObject to Dictionary<string, object> #2"
} | 223410 |
<p>This is a follow up question on <strong><a href="https://codereview.stackexchange.com/questions/223322/simple-oop-currency-converter">this post</a></strong></p>
<p>This is what I changed on my previous code:</p>
<ol>
<li><p>I use <code>Exchanger</code> and <code>PairCurrency</code> class instead of <code>Bank</code></p>
</li>
<li><p>I renamed <code>addRate</code> and <code>addCommission</code> to <code>setRate</code> and <code>setCommission</code> respectively</p>
</li>
<li><p><code>Exchanger</code> object contains multiple <code>PairCurrency</code> objects which can be added to <code>Exchanger</code> by <code>addPairCurrency()</code> method.</p>
</li>
</ol>
<p>This is my code and tests:</p>
<pre><code>import pytest
class DuplicatePairError(Exception):
pass
class Exchanger:
def __init__(self):
self.pair_currencies = []
self.commission = 0.015
def addPairCurrency(self, pair_object):
if pair_object in self.pair_currencies:
raise DuplicatePairError('Cannot add duplicate pair of currency')
self.pair_currencies.append(pair_object)
@property
def last_pair(self):
return self.pair_currencies[-1]
def getRate(self, pair):
for pair_obj in self.pair_currencies:
if pair_obj.name == pair:
return pair_obj.rate
def convert(self, src_dest, amount):
return amount / self.getRate(src_dest) * (1-self.commission)
def editRate(self,new_object):
for pair_obj in self.pair_currencies:
if pair_obj.name == new_object.name:
pair_obj.rate = new_object.rate
class PairCurrency:
def __init__(self, name):
self.name = name
def setRate(self, rate):
self.rate = rate
def editRate(self, new_rate):
self.rate = new_rate
def __eq__(self, object):
return self.name == object
def test_canInitializePair_CurrenciesListInExhangeClass():
exchanger = Exchanger()
assert exchanger.pair_currencies == []
def test_canSetRateinPairCurrencyClass():
USD_GBP = PairCurrency('USDGBP')
USD_GBP.setRate(2)
assert USD_GBP.name == 'USDGBP'
assert USD_GBP.rate == 2
def test_canSetCommisionInExchanger():
exchanger = Exchanger()
assert exchanger.commission == 0.015
@pytest.fixture()
def USD_GBP():
USD_GBP = PairCurrency('USDGBP')
USD_GBP.setRate(2)
return USD_GBP
@pytest.fixture()
def GBP_USD():
GBP_USD = PairCurrency('GBPUSD')
GBP_USD.setRate(0.5)
return GBP_USD
@pytest.fixture()
def exchanger(USD_GBP,GBP_USD):
exchanger = Exchanger()
exchanger.addPairCurrency(USD_GBP)
exchanger.addPairCurrency(GBP_USD)
return exchanger
def test_canAddPairCurrencyinExchangerClass(exchanger, USD_GBP, GBP_USD):
assert USD_GBP == exchanger.pair_currencies[-2]
assert GBP_USD == exchanger.last_pair
def test_cannotAddDuplicatePair(exchanger, USD_GBP):
USD_GBP2 = PairCurrency('USDGBP')
USD_GBP2.setRate(5)
exchanger = Exchanger()
exchanger.addPairCurrency(USD_GBP)
with pytest.raises(DuplicatePairError) as excinfo:
exchanger.addPairCurrency(USD_GBP2)
assert str(excinfo.value) == 'Cannot add duplicate pair of currency'
def test_canEditRateInPairCurrencyClass(USD_GBP):
USD_GBP.editRate(3)
assert USD_GBP.rate == 3
USD_GBP.editRate(4)
assert USD_GBP.rate == 4
def test_canEditRateinExhangerClass(exchanger):
USD_GBP = PairCurrency('USDGBP')
USD_GBP.setRate(5)
exchanger.editRate(USD_GBP)
assert exchanger.getRate('USDGBP') == 5
def test_canConvertInExchangerClass(exchanger, USD_GBP, GBP_USD):
assert exchanger.convert(src_dest = 'USDGBP', amount = 100) == 49.25
assert exchanger.convert(src_dest='GBPUSD', amount=100) == 197
</code></pre>
<p>I have few questions:</p>
<ol>
<li><p>How good is my OOP design?</p>
</li>
<li><p>Is my test list fine?</p>
</li>
<li><p>Should I remove <code>editRate()</code> in <code>PairCurrency</code> and just keep <code>editRate()</code> in <code>Exchanger</code>?</p>
</li>
<li><p>Do my classes violate the <strong>SOLID Principle</strong> ?</p>
</li>
<li><p>What I have to fix to improve my code and OOP design ?</p>
</li>
</ol>
| [] | [
{
"body": "<h2>Set?</h2>\n\n<p>You have logic preventing duplicate currency pairs. The easier (and more performant) thing to do is to simply represent <code>pair_currencies</code> as a set instead of a list. When you add, it will automatically discard duplicates.</p>\n\n<h2>snake_case</h2>\n\n<p>The standard is to name methods like your <code>last_pair</code> - i.e., <code>get_rate</code>.</p>\n\n<h2>Lookups</h2>\n\n<p>You have a loop in <code>getRate</code> and <code>editRate</code> to try and find the correct currency. Instead, you should be using a dictionary, which does not require a loop.</p>\n\n<h2>Remove duplicate methods</h2>\n\n<p><code>editRate</code> and <code>setRate</code> do the exact same thing, so delete the former.</p>\n\n<h2>Equality test is wrong</h2>\n\n<p>Your <code>__eq__</code> method should be comparing to an object instance, not a string. As such, you should be comparing <code>self.name</code> with <code>object.name</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:07:14.200",
"Id": "223422",
"ParentId": "223411",
"Score": "3"
}
},
{
"body": "<p>First of all I would suggest you changing <code>PairCurrency</code> constructor from</p>\n\n<pre><code>class PairCurrency:\n def __init__(self, name):\n self.name = name\n</code></pre>\n\n<p>to</p>\n\n<pre><code>class PairCurrency:\n def __init__(self, name, ratio):\n self.name = name\n self.ratio\n</code></pre>\n\n<p>There is literally no reason to make it different. This is not a functional class but rather DataStructure.</p>\n\n<p>It's also much easier to create instances with</p>\n\n<pre><code>us = PairCurrency('US', 3)\n</code></pre>\n\n<p>than</p>\n\n<pre><code>us = PairCurrency('US')\nus.setRate(3)\n</code></pre>\n\n<p>As stated above, <code>__eq__</code> method is wrong. It should be:</p>\n\n<pre><code>def __eq__(self, other):\n return self.name == other.name and self.rate == other.rate\n</code></pre>\n\n<p>Also there is no need to create your own structures like that.</p>\n\n<p>Your <code>PairCurrency</code> class isn't better than just a simple python tuple.</p>\n\n<pre><code>PairCurrency('US', 3) == PairCurrency('US', 3) => true\n('US', 3) == ('US', 3) => true\n</code></pre>\n\n<p>The only reason you would want to do that is to increase verbosity, but this can be achieved by using builtin <code>namedtuples</code>.</p>\n\n<pre><code>from collections import namedtuple\n\nPairCurrency = namedtuple('PairCurrency', 'name rate')\nus = PairCurrency('US', 3)\nprint(us) \n=> PairCurrency(name='US', rate=3)\n</code></pre>\n\n<p>Sets would work the same with <code>tuples</code>, <code>namedtuples</code> and your custom <code>PairCurrency</code> with custom <code>__eq__</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:56:33.880",
"Id": "223458",
"ParentId": "223411",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223422",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:17:39.083",
"Id": "223411",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"design-patterns",
"unit-testing",
"unit-conversion"
],
"Title": "Simple OOP currency converter - follow-up"
} | 223411 |
<p>Im curious how to improve this code. I don't like creating objects of four different types of reporters, because this could provide some problems with testing. How about the rest of this code, for example the if-statement below?</p>
<p>EDIT: This is a fragment of application to measure loading time of our website and few other competitors. If our site is slower than one of competitors application should send email, if our site is two times slower then application should send message via sms. </p>
<pre><code>"""Module containing classes for comparing objects"""
import senders
import reporters
class Comparator:
"""Class for comparing objects"""
def compare(self, compared, competitors):
reporter = reporters.Reporter()
rules = ComparatorExtensions(compared, competitors, reporter)
send_with_email = senders.SendWithEmail()
send_with_sms = senders.SendWithSms()
save_to_file = senders.SendToFile()
show_on_console = senders.ShowOnConsole()
if rules.rule_valid_compared():
if rules.rule_compared_smaller():
send_with_email.send(reporter.format_report())
if rules.rule_compared_two_times_smaller():
send_with_sms.send(reporter.format_report())
report = reporter.format_report()
save_to_file.send(report)
show_on_console.send(report)
class ComparatorExtensions:
"""Class for extensions for comparator class"""
def __init__(self, compared, competitors, reporter):
self.compared = compared
self.competitors = (item for item in competitors if self.valid_item(item))
self._reporter = reporter
def valid_item(self, item):
result = 'loading_time' in item
if not result:
self._reporter.report_invalid(item)
return result
def rule_compared_smaller(self):
result = False
for item in self.competitors:
self._reporter.report_loading_time(item)
if item.get('loading_time') < self.compared.get('loading_time'):
self._reporter.report_smaller(self.compared, item)
result = True
return result
def rule_compared_two_times_smaller(self):
result = False
for item in self.competitors:
if (item.get('loading_time') * 2) <= self.compared.get('loading_time'):
self._reporter.report_smaller_two_times(self.compared, item)
result = True
return result
def rule_valid_compared(self):
rule_valid = self.valid_item(self.compared)
if rule_valid:
self._reporter.report_loading_time(self.compared)
return rule_valid
</code></pre>
<p>Full repository: <a href="https://github.com/adbo/benchmark" rel="nofollow noreferrer">https://github.com/adbo/benchmark</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:36:37.907",
"Id": "432967",
"Score": "1",
"body": "Welcome to Code Review! Can you provide example usage or a description of what it's supposed to do? You've included your repository, but questions are supposed to be as stand-alone as possible. Besides, the current README doesn't explain much either. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:06:55.817",
"Id": "432973",
"Score": "1",
"body": "This is a fragment of application to measure loading time of our website and few other competitors. If our site is slower than one of competitors application should send email, if our site is two times slower then application should send message via sms."
}
] | [
{
"body": "<p>According to pep8 imports should be ordered alphabetically so</p>\n\n<pre><code>import reporters\nimport senders\n</code></pre>\n\n<p>Your classes from the <code>senders</code> module don't take instantiation parameters and just have one method used so these could probably just be functions.</p>\n\n<pre><code>from senders import send_email, send_sms, save_file, show_console\n</code></pre>\n\n<p>Similarily <code>Comparator</code> only contains a single method and no state so it too should be a function</p>\n\n<pre><code>def compare(compared, competitors):\n ...\n</code></pre>\n\n<p><code>valid_item</code> and <code>rule_valid_compared</code> seem to have their responsibilities a bit mixed, I would change this to.</p>\n\n<pre><code>def is_item_valid(self, item):\n return 'loading_time' in item\n\ndef report_valid_item(self, item):\n is_valid = self.is_item_valid(item):\n if is_valid:\n self._reporter.report_loading_time(item)\n else:\n self._reporter.report_invalid(item)\n return is_valid\n</code></pre>\n\n<p>You can also reduce a lot of duplication between the two actual comparison methods by parametrize it, also as each item has already been <em>validated</em> you can replace the <code>get</code> with key lookup. </p>\n\n<pre><code>def compare_is_smaller(self, n=1, report_func=lambda a: None):\n for item in self.competitors:\n if (item['loading_time'] * n) < self.compared['loading_time']:\n report_func(self.compared, item)\n result = True\n return result\n\ndef compare_smaller(self):\n return self.compare_is_smaller(report_func=self._reporter.report_smaller)\n\ndef compare_twice_as_small(self):\n return self.compare_is_smaller(report_func=self._reporter.report_twice_as_small)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T16:03:59.127",
"Id": "223428",
"ParentId": "223412",
"Score": "1"
}
},
{
"body": "<h2>Use functions whenever possible</h2>\n\n<p>I think there are too many classes and you should consider using functions instead: it is easier to test (unit testing).</p>\n\n<h2>Use a logger</h2>\n\n<p>First thing: the code below make me think that you should use a logger instead of reinventing the wheel:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>report = reporter.format_report()\nsave_to_file.send(report)\nshow_on_console.send(report)\n</code></pre>\n\n<p>Here is how you can define a root logger which can log in the console as well as in a file:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import logging\n\n\ndef setup_logger(log_dir, log_file_name):\n # root logger\n logger = logging.getLogger()\n\n formatter = logging.Formatter(\n \"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s\")\n\n file_hdlr = logging.FileHandler(\n \"{0}/{1}\".format(log_dir, log_file_name))\n file_hdlr.setFormatter(formatter)\n logger.addHandler(file_hdlr)\n\n console_hdlr = logging.StreamHandler()\n console_hdlr.setFormatter(formatter)\n logger.addHandler(console_hdlr)\n\n logger.setLevel(logging.DEBUG)\n</code></pre>\n\n<p>This <code>setup_logger</code> function should be called at program startup, in your <code>main</code>, for instance:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n setup_logger(\"my/work/dir\", \"my_app.log\")\n</code></pre>\n\n<p>You can use this logger anywhere: in each Python module, you can define a global variable named <code>LOG</code>, and use it like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>LOG = logging.getLogger(__name__)\n\n\ndef my_function():\n LOG.info(\"log message\")\n</code></pre>\n\n<p>See the <a href=\"https://docs.python.org/3/howto/logging.html\" rel=\"nofollow noreferrer\">How To documentation</a></p>\n\n<h2>wrong usage of generator</h2>\n\n<p>In your, <em>competitors</em> is a generator, not a tuple. After having iterate a generator the first time, then the generator is exhausted. It means that the second loop will end immediately.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.competitors = (item for item in competitors if self.valid_item(item))\n</code></pre>\n\n<p>The call to <code>rule_compared_smaller</code> will iterate the <em>competitors</em>, then the call to <code>rule_compared_two_times_smaller</code> will do nothing because the <em>competitors</em> is exhausted.</p>\n\n<p>You need to create a list:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.competitors = [item for item in competitors if self.valid_item(item)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:31:24.910",
"Id": "223453",
"ParentId": "223412",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:20:33.980",
"Id": "223412",
"Score": "1",
"Tags": [
"python"
],
"Title": "Class for comparing objects in Python"
} | 223412 |
<p>The full project is <a href="https://github.com/cbryant02/ghost2" rel="nofollow noreferrer">up on GitHub</a>. The codebase is super small as it stands.</p>
<p>I'm brand new to reactive programming and Spring, and would mostly like insight on those two things. Asynchronous programming is also one of my weak points, because I'm really used to synchronous program structure - hence the need for help with reactive programming.</p>
<p>Here's a few snippets to start off with, for my specific concerns:</p>
<pre><code>@Repository
public interface GuildMetaRepository extends CrudRepository<GuildMeta, Long> {
...
@Override
@Cacheable(value = "guilds", key = "#p0")
Optional<GuildMeta> findById(Long id);
...
@Override
@CacheEvict(value = "guilds", key = "#p0.id")
void delete(GuildMeta guild);
}
</code></pre>
<p>Spring caching for Repository implementations confuses me a little - is this working as I expect? Should I be using <code>@CachePut</code> in place of <code>@Cacheable</code>?</p>
<pre><code>class CommandRegistry {
...
CommandRegistry() throws ReflectiveOperationException {
...
/* not shown: find all Command implementations with Reflections */
...
// Construct an instance of each module
for (Class<? extends Command> module : modules) {
instantiated.add(module.newInstance());
}
}
...
}
</code></pre>
<p>You might need the full context of the <code>command</code> package for this one. Basically, <code>Command</code> is the abstract class that all my command modules extend from, and it has an instance variable for the command name that subclasses call <code>super(name, ...)</code> to identify themselves with. Since it's an instance variable, though, I need to keep an instance of each module available in a <code>List<Command></code> to check against command names in chat.</p>
<p>That probably didn't make it much clearer, but I did my best. Like I said, there's more context to be had here. The general design pattern I have here is sub-par in my opinion, and I don't really have any ideas on how to fix it. There have definitely been some improvements over the first iteration, though; that was far messier.</p>
<p>I'd love to get some feedback here, whether it's on the snippets or on other code in the project - if you see a problem, hit me with it. Pull requests are always wide open as well if you feel like contributing. Thanks!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T12:58:52.677",
"Id": "223414",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"database",
"spring",
"reactive-programming"
],
"Title": "Lightweight, modular Discord bot - tips and feedback on the code?"
} | 223414 |
<p>I have created a large VBA program to automate creation of a data table that is needed to run slicers in an Excel file.<br>
While the loop works well in creating what I need, the main loop take an hour to create the list of company names that I need. I was wondering if there is a way to improve the time it takes for the loop to complete.<br>
I have 191 rows that need to be copied and then pasted 68 times each into the new sheet. I have tried a few different approaches to improve the time and have only reduced the time required to about 50 minutes. Any help would be much appreciated. I know that using select is horrible for time efficiency but all the other options I have tried have not worked well.</p>
<pre><code>Application.ScreenUpdating = False
Dim rng As Range, cell As Range
For Each cell In rng
Sheets("Input Data").Select
cell.Select
cell.Copy
Sheets("TrialSheet").Select
For i = 1 To 68
LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & LastRow).Select
ActiveSheet.Paste
Next i
Sheets("Input Data").Select
Next cell
Application.ScreenUpdating = True
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:21:13.613",
"Id": "432988",
"Score": "0",
"body": "Is the posted code working as you intend? Your description states that you have \"191 rows that need to be copied\", but your code is only copying a single cell. And your `rng` variable is never set to any range on a worksheet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:43:44.173",
"Id": "433000",
"Score": "0",
"body": "it is working fine yes. This is a small portion of a larger VBA code block. This one loop is what is causing me time issues. I set the range earlier in the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:54:25.410",
"Id": "433012",
"Score": "0",
"body": "In order to get a complete review of your code, it's best to [read this guide](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions) on how to get the best value out of Code Review. Ideally and in most cases, we're expecting to be able to copy/paste your code into our own spreadsheet, fake some data, and run it. Your example doesn't give us enough context for a complete review. If you don't wish to post a more complete example for a full review, you may get the help from the [Stack Overflow](https://stackoverflow.com/) site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:30:50.880",
"Id": "433024",
"Score": "0",
"body": "okay, I will head over there then. Thanks."
}
] | [
{
"body": "<p>Since no information was available about the size of source range being copied</p>\n<p>Following grey area in the question is assumed as follows</p>\n<ol>\n<li><p>Since 191 Rows X 68 copy X 3 columns take around 10 minutes only (with you code), the range is about 191 Rows X 15 Columns in size</p>\n</li>\n<li><p>since it has been claimed that code is working Correctly. The Cells of the range (irrespective of their row or column positions) is being copied in column A only (below one another). Though it contradicts the statement "automate creation of a data table"</p>\n</li>\n<li><p>Since the cells of the ranges are being copied and pasted. In test case only formulas are copied.</p>\n<p>So the code below will just replicate what your code is doing with some increased efficiency. As I personally don't prefer to keep calculations, event processing and screen updating off (in normal cases) i haven't added that standard lines. However you may use these standard techniques, depending on the working file condition. Make necessary changes regarding Range etc</p>\n</li>\n</ol>\n<p>Code takes only 2-3 seconds to complete with 191 Rows X 15 columns X 68 copies:</p>\n<pre><code>Sub test()\nDim SrcWs As Worksheet, DstWs As Worksheet, SrcArr As Variant\nDim Rng As Range, cell As Range, DstArr() As Variant\nDim X As Long, Y As Long, Z As Long, i As Long, LastRow As Long\nDim Chunk60K As Long\nDim tm As Double\ntm = Timer\nSet SrcWs = ThisWorkbook.Sheets("Input Data")\nSet DstWs = ThisWorkbook.Sheets("TrialSheet")\n\nSet Rng = SrcWs.Range("A1:O191")\nSrcArr = Rng.Formula\n \nLastRow = DstWs.Cells(Rows.Count, "A").End(xlUp).Row + 1\nChunk60K = 0\nZ = 1\n For X = 1 To UBound(SrcArr, 1)\n For Y = 1 To UBound(SrcArr, 2)\n For i = 1 To 68\n ReDim Preserve DstArr(1 To Z)\n DstArr(Z) = SrcArr(X, Y)\n \n If Z = 60000 Then ' To Overcome 65K limit of Application.Transpose\n DstWs.Range("A" & Chunk60K * 60000 + LastRow).Resize(UBound(DstArr, 1), 1).Formula = Application.Transpose(DstArr)\n Chunk60K = Chunk60K + 1\n Z = 1\n ReDim DstArr(1 To 1)\n Debug.Print "Chunk: " & Chunk60K & " Seconds Taken: " & Timer - tm\n Else\n Z = Z + 1\n End If\n \n Next i\n Next Y\n Next X\n\nIf Z > 1 Then DstWs.Range("A" & Chunk60K * 60000 + LastRow).Resize(UBound(DstArr, 1), 1).Formula = Application.Transpose(DstArr)\n\nDebug.Print "Seconds Taken: " & Timer - tm\nEnd Sub\n</code></pre>\n<p>Edit: <strong>With full credit to @TinMan's brilliant suggestion</strong> in his comment, the code has been modified (efficiency improved around 65%). The inherent deficiency in the above code is use of <code>ReDim Preserve</code> within the loop has been removed. This enabled use of 2D array and eliminates necessity of transposing the array. <strong>Again with many thanks to TinMan and acknowledging full credit to TinMan</strong>, The final simplified code as follows.</p>\n<pre><code>Sub test()\nDim SrcWs As Worksheet, DstWs As Worksheet, SrcArr As Variant\nDim Rng As Range, cell As Range, DstArr() As Variant\nDim X As Long, Y As Long, Z As Long, i As Long, Lastrow As Long\nDim Repeat As Long\nDim tm As Double\ntm = Timer\nSet SrcWs = ThisWorkbook.Sheets("Input Data")\nSet DstWs = ThisWorkbook.Sheets("TrialSheet")\nSet Rng = SrcWs.Range("A1:O191")\nSrcArr = Rng.Formula\nRepeat = 68\nReDim DstArr(1 To (Repeat * Rng.Count), 1 To 1)\nLastrow = DstWs.Cells(Rows.Count, "A").End(xlUp).Row + 1\nZ = 1\n \n For X = 1 To UBound(SrcArr, 1)\n For Y = 1 To UBound(SrcArr, 2)\n For i = 1 To Repeat\n DstArr(Z, 1) = SrcArr(X, Y)\n Z = Z + 1\n Next i\n Next Y\n Next X\n\nDstWs.Range("A" & Lastrow).Resize(UBound(DstArr, 1), 1).Formula = DstArr\nDebug.Print "Seconds Taken: " & Timer - tm\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:25:24.797",
"Id": "433163",
"Score": "0",
"body": "You did a good job of recreating the output using arrays. But your code could be simplified. Since each value in Rng is being repeated 68 times, we can determine that 68 * Rng.Count is the optimal size of DstArr (e.g.`ReDim DstArr(1 To (68 * Rng.Count), 1 To 1)` ). Making these changes improved the performance by %68.5 in my test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T00:42:32.903",
"Id": "433304",
"Score": "0",
"body": "@TinMan thanks again for your brilliant Idea. Post edited with your suggestion. In realty the full credit is yours only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T14:51:01.763",
"Id": "433493",
"Score": "0",
"body": "You did the hard work I simply tweaked it. I couple little details: `Repeat` should be a constant value. `Z = 1` can be removed by incremenling `Z` before the `DstArr(Z, 1) = SrcArr(X, Y)`. Nice work."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T00:59:51.417",
"Id": "223464",
"ParentId": "223416",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:10:03.297",
"Id": "223416",
"Score": "2",
"Tags": [
"performance",
"vba"
],
"Title": "Loop to copy values from one sheet and paste the values 68 times in another, time efficiency"
} | 223416 |
<p>I've decided to reproduce the JQuery selector - specifically for finding elements by <em>class name, ID, and tag</em></p>
<p>So for example the tests could be written like</p>
<pre><code>$('.box') === domSelector('.box') // Class
$('#box') === domSelector('#box') // ID
$('input') === domSelector('input') // Tag
</code></pre>
<p>Here is my approach to the problem. It works good, and I'd like to hear the ideas to simplify it or improve it in any way.</p>
<pre><code>var domSelector = function(selectors) {
if (selectors.startsWith('.')) {
return Array.from(document.getElementsByClassName(selectors.substring(1)));
}
else if (selectors.startsWith('#')) {
return [document.getElementById(selectors.substring(1))];
}
else if (!/^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g.test(selectors)) {
throw Error('Invalid Selector');
}
else {
return Array.from(document.getElementsByTagName(selectors));
}
};
</code></pre>
<ol>
<li>1st If - Check if passed value is class. (if it starts with a <strong>dot</strong>, it is a class) </li>
<li>2nd If - Check if a passed value is an ID (if it starts with <strong>#</strong>, it is an ID)</li>
<li>3rd If - Now since I already checked for both characters <strong>#</strong> and <strong>dot</strong> , I check if passed value starts with special character (Remember that it cannot start with <strong>dot</strong> or <strong>#</strong> as I already did that check). If it starts with a special character - I throw an exception that identifier is not in a valid format</li>
<li>4th If - The only left option is that element is tag. No further check needs to be done as if selector doesn't match any tags it will return an empty array.</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:37:04.207",
"Id": "432977",
"Score": "1",
"body": "Welcome to Code Review! I added [tag:reinventing-the-wheel] since you specifically mention JQuery's implementation of this. Feel free to remove it again if you disagree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:16:45.113",
"Id": "433007",
"Score": "0",
"body": "Are you aware of [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:12:05.273",
"Id": "433145",
"Score": "0",
"body": "@RoToRa Yes I am, how ever it doesn't return what I need. It would just make me write more code. The best example is when using the querySelectorAll to find elements with a matching id. If there are two elements with the same id (which shouldn't happen, but can) - querySelectorAll will return both of them while jQuerys $('#byId') returns only one just like getElementById."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:07:27.403",
"Id": "433159",
"Score": "0",
"body": "@Dino How is getting only one of two elements with the same ID a good thing? How do you know that you are getting the \"right one\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:31:13.237",
"Id": "433202",
"Score": "0",
"body": "@RoToRa Element IDs should be unique within the entire document, it's not a valid HTML if you have same ID in multiple elements. That's why you expect to get only one element when getting it by ID. And if you use querySelectorAll you have to add an extra step to return only one element - because of course elements with the same ID's might occur by fault"
}
] | [
{
"body": "<h2>Duplicated Ids!!! </h2>\n\n<p>I notice in the comments there is mention of more than 1 element with the same <code>Id</code> <strike>and that <code>getElementById</code> will only return one element, which is correct for the majority of browsers depending on the version</strike>. </p>\n\n<p><strike>Even if <code>getElementById</code> acted the same across browsers</strike> As a developer intentionally using duplicated <code>Id</code> is <strong>VERY BAD!</strong> as it will force the browser into <a href=\"https://en.wikipedia.org/wiki/Quirks_mode\" rel=\"nofollow noreferrer\">Quirks Mode</a> \n effecting performance, layout and can effect how search engine bots crawl your site. </p>\n\n<p>Though Google does say...</p>\n\n<blockquote>\n <p><em>“Although we do recommend using valid HTML, it’s not likely to be a factor in how Google crawls and indexes your site.”</em></p>\n</blockquote>\n\n<p>... from SEJ <a href=\"https://www.searchenginejournal.com/google-valid-html/258881/\" rel=\"nofollow noreferrer\">6 Reasons Why Google Says Valid HTML Matters</a> that links to <a href=\"https://support.google.com/webmasters/answer/100782\" rel=\"nofollow noreferrer\">Google Browser Compatibility</a> support page</p>\n\n<p>This is not a guarantee and not something you should trust your sites SEO on.</p>\n\n<p>The simple and safe rule is. <strong>NEVER duplicate Id's!!!</strong></p>\n\n<h2>Your code</h2>\n\n<p>Ignoring the above and looking at your code without regard to the DOM and that <code>getElementById</code> can return an array you can improve the code (readability and maintainability <sup><strong>[1.]</strong></sup>) as follows</p>\n\n<pre><code>function queryDOM(selector) {\n const VALIDATOR = /[a-z0-9!@#$%^&*)(+=._-]/i, NS = \"http://www.w3.org/1999/xhtml\";\n const type = selector[0], query = selector.slice(1);\n if (type === \".\") { return [...document.getElementsByClassName(query)] }\n if (type === \"#\") { return [document.getElementById(query)] }\n if (! VALIDATOR.test(selector)) { throw new RangeError('Invalid Selector') }\n return [...document.getElementsByTagNameNS(NS, selector)];\n}\n</code></pre>\n\n<p>or for the code newbies that need the spacing</p>\n\n<pre><code>function queryDOM(selector) {\n const VALIDATOR = /[a-z0-9!@#$%^&*)(+=._-]/i;\n const NS = \"http://www.w3.org/1999/xhtml\";\n const type = selector[0];\n const query = selector.slice(1);\n\n if (type === \".\") { \n return [...document.getElementsByClassName(query)];\n }\n\n if (type === \"#\") { \n return [document.getElementById(query)]; \n }\n\n if (! VALIDATOR.test(selector)) { \n throw new RangeError(\"Invalid Selector\"); \n }\n\n return [...document.getElementsByTagNameNS(NS, selector)];\n}\n</code></pre>\n\n<h3>Reasoning</h3>\n\n<ul>\n<li>As a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function\" rel=\"nofollow noreferrer\">function declaration</a> rather than a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function\" rel=\"nofollow noreferrer\">function expression</a> so that the function is accessible at any time after parsing.</li>\n<li>Extract the first character and remaining query in one spot to avoid logic/code duplication.</li>\n<li>Remove the redundant <code>else</code> and supporting code to reduce noise.</li>\n<li>Use ES6+ spread operator <code>...</code> (AKA <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a>) to create arrays from iteratable objects.</li>\n<li>Use the simpler bracket access for single character in string rather than the more verbose <code>String.startsWith</code> which is meant for sub strings longer than one character.</li>\n<li>Use <code>String.slice</code> rather than <code>String.substring</code></li>\n<li>Renamed function to hold to camel-case convention of upperCase acronyms and rearranging to stop clash with JS convention of PascalCase only functions used with the new token (Note your function will work as new DOMSelector())</li>\n<li>Renamed argument to not imply its an array (plurals only for arrays or array like objects) </li>\n<li>Throw a range error more suited to the error type (Really should not be throwing for this type of issue)</li>\n<li>Remove the global flag from the <code>RegExp</code></li>\n<li>Removed redundant <code>^</code>, <code>$</code>, <code>+</code> and back slashes inside the <code>[]</code> from <code>RegExp</code></li>\n<li>Added case insensitive flag to <code>RegExp</code></li>\n<li><p>Declared <code>RegExp</code> as a constant to take out of the statement to make it more readable.</p></li>\n<li><p>As you include capitals in the validation of the selector I assume you are unaware that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName\" rel=\"nofollow noreferrer\"><code>getElementsByTagName</code></a> first converts the query string to lowercase. Thus I changed the function to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagNameNS\" rel=\"nofollow noreferrer\"><code>getElementsByTagNameNS</code></a> </p>\n\n<p>The <code>getElementsByTagNameNS</code> which namespace (NS) to use is not known from your code and thus the example assumes \"<a href=\"http://www.w3.org/1999/xhtml\" rel=\"nofollow noreferrer\">http://www.w3.org/1999/xhtml</a>\". Warning quirks mode will effect the namespace.</p></li>\n</ul>\n\n<h3>Additionally</h3>\n\n<p>The function has a failure if the selector argument is not a string. As the function does throw I assume you <strong>only</strong> use it inside a <code>try catch</code> block and you handle the error when it occurs.</p>\n\n<h2>Why the complications!</h2>\n\n<p>As your code relies on some assumptions that are flawed and do not compile with valid HTML I can not approve the above as worthy of anything but as an example of what not to do.</p>\n\n<p>The code should use <code>querySelectorAll</code> and covert its iteratable return to an array. I would also drop the <code>\"DOM\"</code> in the name (what else could you be querying?) and include a node to focus the query.</p>\n\n<p>Also removing the validation as query string can be used to search attributes that may conflict with the validation.</p>\n\n<pre><code>function query(str, node = document) { return [...node.querySelectorAll(str)] }\n</code></pre>\n\n<p>Or if you control code placement and use the <code>\"use strict\"</code> directive you can use an arrow function expression to assign a named constant to prevent accidental overwriting of the function.</p>\n\n<pre><code>\"use strict\"; // << Must be at top of code.\nconst query = (str, node = document) => [...node.querySelectorAll(str)];\n</code></pre>\n\n<p>This is not at all replacement of jQuery</p>\n\n<h2>BTW</h2>\n\n<p>A reminder. <strong>NEVER duplicate Id's!!!</strong> </p>\n\n<p>See I added 3 exclamation points and made it bold to indicate how important this warning is.</p>\n\n<hr>\n\n<h2>Notes</h2>\n\n<p><sup><strong>[1.]</strong></sup> Readability and maintainability are highly subjective quantities and as such reflex my view only. I have 40Years of experience (35 as a professional) if that counts for anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T17:20:43.263",
"Id": "433240",
"Score": "0",
"body": "Thanks for your descriptive post! I agree with some of the things, how ever with some I do not. If you take a look at the JQuery's [#ID Selector API](https://api.jquery.com/id-selector/) you will see it's using the `getElementById`, and states that it will return **zero or one DOM element**. And as far as I know `querySelectorAll` is static, which means if I dynamically add some elements after the page loads - it wouldn't return those newly added elements while on the other hand `getElementsByTagName` would."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:42:19.013",
"Id": "433261",
"Score": "0",
"body": "@Dino By dynamically i presume you mean add HTML (markup) to the page (also very bad). If you add content via the DOM interface `querySelectorAll` will return a list of all matching elements including new one. Yes my bad I was thinking of direct referencing rather than `getElementById` (if referencing by id in JS browsers return an array in quirks mode)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T16:35:18.630",
"Id": "223518",
"ParentId": "223417",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:16:37.017",
"Id": "223417",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"reinventing-the-wheel",
"dom"
],
"Title": "JQuery Selector in Vanilla JS"
} | 223417 |
<p>I have a function I have written in VB for use in SSRS 2012. It takes an integer and converts it to full text duration - for example 900 becomes "15 minutes", 9000 becomes "2 hours 30 minutes", and 7201 is "2 hours 1 second".</p>
<p>The code works, and is:</p>
<pre><code>Public Function SecondsFullText(ByVal TotalSeconds As Integer) As String
Dim hours As Integer = new Integer()
Dim minutes As Integer = new Integer()
Dim seconds As Integer = new Integer()
Dim hourString as String = ""
Dim minuteString as String = ""
Dim secondString as String = ""
hours = floor(TotalSeconds / 3600)
minutes = floor((TotalSeconds mod 3600) / 60)
seconds = (TotalSeconds mod 3600) mod 60
If hours = 1 Then
hourString = Cstr(hours) & " hour"
Else If hours > 1 Then
hourString = Cstr(hours) & " hours"
End If
If minutes = 1 Then
minuteString = Cstr(minutes) & " minute"
Else If minutes > 1 Then
minuteString = Cstr(minutes) & " minutes"
End If
If seconds = 1 Then
secondString = Cstr(seconds) & " second"
Else If seconds > 1 Then
secondString = Cstr(seconds) & " seconds"
End If
If hours > 0 and (minutes > 0 or seconds > 0) Then
hourString = hourString & " "
End If
If minutes > 0 and seconds > 0 Then
minuteString = minuteString & " "
End If
return hourString & minuteString & secondString
End Function
</code></pre>
<p>My question is: how do I make this better? It seems very clunky, with too many IFs to handle the different possibilities for single/plural, spaces, etc. I feel that this can be better, but I'm not sure how.</p>
<p>This is called in Report Builder 3.0 / SSRS 2012 with this expression: <code>=Code.SecondsFullText(Parameters!Integer.Value)</code></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:17:14.080",
"Id": "432985",
"Score": "0",
"body": "It would be easier to provide a review and answer if the function that called this or displayed the resulting string was included as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:38:37.343",
"Id": "432995",
"Score": "0",
"body": "@pacmaninbw Noted, and updated. There's no real function that calls it as it's for use in a report in SSRS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:10:29.493",
"Id": "433066",
"Score": "0",
"body": "I did this as a one-liner in groovy for fun--converted milliseconds to something like 1d2h3m10s. I don't think I have the one-liner any more but I converted it into 4 significantly more readable lines you're welcome to if you want them :) (Now it's part of Java so I don't really need it any more, you can have it)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:02:26.630",
"Id": "433068",
"Score": "2",
"body": "Code aside, \"an integer\" has no units and cannot be converted to a string representation of time with additionally specifying units. So you don't just have an integer; you have *an integer number of seconds*. You need to be more careful about this in your documentation and communication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:36:16.240",
"Id": "433098",
"Score": "0",
"body": "@jpmc26 That's an interesting concept to consider. In this scenario, this is a value from a SQL query which is essentially \"time allowed in seconds\". I could have done this in SQL, but wanted to A) see if I could do it report side and B) learn different ways of looking at it. It's certainly helped my coding knowledge and the way I look at code - especially the breakdown provided by RickDavin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:42:50.753",
"Id": "433116",
"Score": "0",
"body": "In case there was any confusion, there's a fairly major typo in my comment. It should have said \"*without* additionally specifying units.\""
}
] | [
{
"body": "<p>You should look into the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=netframework-4.6.1\" rel=\"noreferrer\"><code>TimeSpan</code></a> struct, which provides a nice method <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan.fromseconds?view=netframework-4.6.1\" rel=\"noreferrer\"><code>TimeSpan.FromSeconds()</code></a>.</p>\n\n<p>Having filled a <code>TimeSpan</code> struct by e.g calling the <code>FromSeconds()</code> method, you can just access its properties <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan.seconds?view=netframework-4.6.1\" rel=\"noreferrer\"><code>Seconds</code></a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan.minutes?view=netframework-4.6.1\" rel=\"noreferrer\"><code>Minutes</code></a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timespan.hours?view=netframework-4.6.1\" rel=\"noreferrer\"><code>Hours</code></a>.</p>\n\n<p>Instead of concating strings like you do, you should consider to use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netframework-4.6.1\" rel=\"noreferrer\"><code>StringBuilder</code></a>. </p>\n\n<p>To get rid of the <code>If ... Else If</code> you can just use the singular and only if the value is greater than 1 you add a <code>s</code> to the string/StringBuilder. </p>\n\n<p>Based on the <a href=\"https://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"noreferrer\">.NET Naming Guidelines</a> method parameters should be named using <code>camelCase</code> casing hence <code>TotalSeconds</code> should be <code>totalSeconds</code></p>\n\n<p>Implementing the mentioned points will look like so </p>\n\n<pre><code>Public Function SecondsFullText(ByVal totalSeconds As Double) As String\n\n Dim timeSpan As TimeSpan = TimeSpan.FromSeconds(totalSeconds)\n Dim stringBuilder As StringBuilder = New StringBuilder()\n\n Dim hours As Integer = timeSpan.Hours\n Dim minutes As Integer = timeSpan.Minutes\n Dim seconds As Integer = timeSpan.Seconds\n\n stringBuilder.Append(ToText(hours, \"hour\"))\n If hours > 0 AndAlso (minutes > 0 OrElse seconds > 0) Then\n stringBuilder.Append(\" \")\n End If\n stringBuilder.Append(ToText(minutes, \"minute\"))\n If minutes > 0 AndAlso seconds > 0 Then\n stringBuilder.Append(\" \")\n End If\n stringBuilder.Append(ToText(seconds, \"second\"))\n Return stringBuilder.ToString()\n\nEnd Function\n\nPrivate Function ToText(value As Integer, singularName As String) As String\n\n If value = 0 Then Return String.Empty\n If value = 1 Then Return String.Format(\"{0} {1}\", value, singularName)\n Return String.Format(\"{0} {1}s\", value, singularName)\n\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:36:22.850",
"Id": "432994",
"Score": "0",
"body": "Thank you for this. Unfortunately it doesn't look as though StringBuilder is valid in the VB implementation in SSRS/Report Builder 3.0. \n\nIt returns this error: There is an error on line 46 of custom code: [BC30002] Type 'StringBuilder' is not defined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:39:25.113",
"Id": "432996",
"Score": "1",
"body": "You need to add an import to System. Text"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:17:25.420",
"Id": "433008",
"Score": "0",
"body": "How does this handle a duration greater than 24 hours?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:18:25.817",
"Id": "433009",
"Score": "1",
"body": "Then you need to query the `TotalHours` property"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:23:29.157",
"Id": "433010",
"Score": "0",
"body": "Thank you. I had to change `Dim stringBuilder As StringBuilder = New StringBuilder()` to `Dim stringBuilder As New System.Text.StringBuilder()` to make it work in SSRS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T16:10:21.673",
"Id": "433013",
"Score": "0",
"body": "@BishNaboB For hours > 24, `TimeSpan` also has a `Days` property. Note that `Hours` ranges from -23 to +23, and `Minutes` and `Seconds` both range from -59 to +59, but `Days` has no such limit, but may be negative or positive (or zero)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:12:58.517",
"Id": "451537",
"Score": "0",
"body": "Great answer, I think it would be even better if you pointed out the use of `AndAlso` and `OrElse`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:29:07.193",
"Id": "223423",
"ParentId": "223421",
"Score": "6"
}
},
{
"body": "<p>As @Hesclacher has given a fantastic answer, which is not only one that I have upvoted but I would personally mark it as the correct answer if I had the power, I am hesitant to improve upon it. But I would like to offer constructive feedback on your original code.</p>\n\n<p>I have a personal distinction between being a VB Coder and a .NET Developer. I think you can use VB.NET and be what I define to be a .NET Developer - that is you are making traditional .NET calls like any C# dev would use. I define a VB Coder has someone who still thinks and codes with VBA in mind, and such a person relies upon some of the compatibility calls, such as <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/functions/return-values-for-the-cstr-function\" rel=\"nofollow noreferrer\">CStr</a>.</p>\n\n<p>According to my own such definitions, a VB Coder would use <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/functions/return-values-for-the-cstr-function\" rel=\"nofollow noreferrer\">CStr</a> whereas a .NET Developer would use String.Format (as did Heschalcher) or better yet, <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/interpolated-strings\" rel=\"nofollow noreferrer\">Interpolated Strings</a>.</p>\n\n<p><strong>VB Coder</strong>:</p>\n\n<pre><code>hourString = Cstr(hours) & \" hours\"\n</code></pre>\n\n<p><strong>.NET Developer</strong>:</p>\n\n<pre><code>hourString = String.Format(\"{0} hours\", hours)\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>hourString = $\"{hours} hours\"\n</code></pre>\n\n<p>To calculate the number of hours, if you aren't going to use something nice like TimeSpan, I would change this line of code:</p>\n\n<pre><code>hours = floor(TotalSeconds / 3600)\n</code></pre>\n\n<p>To simply use <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/integer-division-operator\" rel=\"nofollow noreferrer\">integer division</a>:</p>\n\n<pre><code>hours = TotalSeconds \\ 3600\n</code></pre>\n\n<p>Also, VB.NET does support short-circuited conditionals (unlike VBA), so this line of code:</p>\n\n<pre><code>If hours > 0 and (minutes > 0 or seconds > 0) Then\n</code></pre>\n\n<p>could be changed to:</p>\n\n<pre><code>If hours > 0 AndAlso (minutes > 0 OrElse seconds > 0) Then\n</code></pre>\n\n<p>This example employs short-circuiting with the <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/andalso-operator\" rel=\"nofollow noreferrer\">AndAlso</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/orelse-operator\" rel=\"nofollow noreferrer\">OrElse</a> operators.</p>\n\n<p>Again, Heschachler's answer with <code>TimeSpan</code> and <code>StringBuilder</code> is spot-on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:31:35.683",
"Id": "433052",
"Score": "0",
"body": "Hi Rick. Thank you for the distinction between coder types, it's an interesting observation. I suppose the `cstr()` comes from the fact this is code added to a report in SSRS, which uses those functions. Short circuiting is something I use in SSRS, and forgot to add in to the code example. Integer division is not something I'm overly familiar with so gives me something to read up on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:21:20.717",
"Id": "223435",
"ParentId": "223421",
"Score": "3"
}
},
{
"body": "<p>Building on @RickDavin.</p>\n\n<p>VB.Net also has a robust <code>If()</code> function that shortcuts the checks (unlike VBA's <code>IIf()</code> function)</p>\n\n<pre><code>If hours = 1 Then\n hourString = Cstr(hours) & \" hour\"\nElse If hours > 1 Then\n hourString = Cstr(hours) & \" hours\"\nEnd If\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>hourstring = If(hours = 1, \"hour\", \"hours\")\n</code></pre>\n\n<p>@Heslacher's function can then be:</p>\n\n<pre><code>Private Function ToText(value As Integer, singularName As String) As String\n Return If(value = 0, String.Empty, String.Format(\"{0} {1}{2}\", value, singularName, If(value=1,\"\",\"s\")))\nEnd Function\n</code></pre>\n\n<p>Note, I am still in the VB coder camp, and my kludge to the string builder format above is based some limited practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:40:35.780",
"Id": "223455",
"ParentId": "223421",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223423",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T13:42:36.667",
"Id": "223421",
"Score": "7",
"Tags": [
"datetime",
"formatting",
"vb.net"
],
"Title": "Convert integer to full text string duration"
} | 223421 |
<p>I have this procedure which is used for bulk upload data from a temporary table (<code>temp_rules_master</code>) into two other related tables.</p>
<p>It has 5 million records. The actual 5 million records to temp table upload take less than 10 mins using this query:</p>
<pre><code>LOAD DATA LOCAL INFILE 'my_data.txt'
INTO TABLE temp_rules_master
COLUMNS TERMINATED BY '|'
LINES TERMINATED BY '\n' IGNORE 1 LINES
</code></pre>
<p>But later the following procs takes around 10 hrs for running through all those 5 million records and do the processing.</p>
<p><strong>Code Logic:</strong></p>
<ul>
<li>It iterates the master records one by one (5+ million)</li>
<li>And insert into 2 related tables <code>compatibility_error</code> (<code>ce</code>) and <code>compatibility_rule</code> (<code>cr</code>)</li>
<li>it does the below validations during the process</li>
<li>It checks if already a record exists in <code>ce</code> for the groupname. If exists, use that record id (<code>@ERROR_ID</code>) in the <code>cr</code> table. If it does not exist, creates a new <code>ce</code> record and use that id (<code>@ERROR_ID</code>) in the <code>cr</code> table.</li>
<li>Then checks if a record exists in the starting _material table for the starting_material_code. If exists use that <code>starting_material_id</code> (<code>@SM_ID</code>) in the <code>cr</code> table else set <code>@SM_ID=null</code> for it.</li>
<li>Generates a <code>uuid</code> (<code>@CODE</code>) for every <code>cr</code> record.</li>
<li>Insert a new <code>cr</code> record with the above-found values <code>@CODE</code>, <code>@ERROR_ID</code>, <code>@SM_ID</code></li>
<li>Continues the iteration for all 5+ million records</li>
</ul>
<p>Is there any way to improve the speed?</p>
<h2>Stored Procedure:</h2>
<pre><code>DELIMITER <span class="math-container">$$
DROP PROCEDURE IF EXISTS load_rules$$</span>
CREATE PROCEDURE load_rules()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE groupname,starting_material_code,lower_limit,higher_limit,description,severity,active,create_date,created_by VARCHAR(255);
DECLARE cur CURSOR FOR SELECT r.groupname,r.starting_material_code,r.lower_limit,r.higher_limit,r.description,r.severity,r.active,r.create_date,r.created_by from temp_rules_master r;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN cur;
read_loop: LOOP
FETCH cur INTO groupname,starting_material_code,lower_limit,higher_limit,description,severity,active,create_date,created_by;
IF finished = 1 THEN
LEAVE read_loop;
END IF;
/* Checks if an error already exists for the groupname */
IF (SELECT ce.id FROM compatibility_error ce WHERE ce.code=groupname) THEN
/* if exists use the existing error */
BEGIN
SELECT ce.id INTO @ERROR_ID FROM compatibility_error ce WHERE ce.code=groupname;
END;
ELSE
/* If no error exists for the groupname create a new error record */
BEGIN
insert into compatibility_error(active,create_date,created_by,modified_by,modified_date,code,description,severity)
values(true,create_date,0,0,NOW(),groupname,description,severity);
SET @ERROR_ID=LAST_INSERT_ID();
END;
END IF;
/* Checks if starting material exists */
IF (select id from starting_material sm where sm.code=starting_material_code) THEN
BEGIN
select id INTO @SM_ID from starting_material sm where sm.code=starting_material_code;
END;
ELSE
BEGIN
SET @SM_ID = null;
END;
END IF;
/* Insert rule */
select UPPER(md5(UUID())) INTO @CODE;
insert into compatibility_rule(active,create_date,created_by,modified_by,modified_date,code,description,groupname,higher_limit,lower_limit,compatibility_error_id,starting_material_id)
values(true,create_date,0,0,NOW(),@CODE,description,groupname,higher_limit,lower_limit,@ERROR_ID,@SM_ID);
END LOOP read_loop;
CLOSE cur;
select 'done...';
End$$
DELIMITER ;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:02:39.710",
"Id": "433005",
"Score": "0",
"body": "Can you be more specific about the purpose of the code? \"Processing\" could mean almost anything..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:49:18.810",
"Id": "433100",
"Score": "0",
"body": "@TobySpeight thanks I have updated now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T05:53:21.593",
"Id": "435498",
"Score": "0",
"body": "In general, try avoiding cursors when you can. Since you need to insert into multiple tables, this can be tricky. A possible solution is to use a view which internally inserts into multiple tables. Check some of the interesting answers here: https://www.sqlservercentral.com/forums/topic/insert-into-multiple-tables-at-once"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:01:59.503",
"Id": "435844",
"Score": "0",
"body": "Thx I was able to fix this by SET autocommit=0; before fetching the cursor and again reset to 1 after completing the loop. It gave a drastic improvement"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T14:34:15.293",
"Id": "223424",
"Score": "1",
"Tags": [
"performance",
"sql",
"mysql",
"stored-procedure"
],
"Title": "Stored procs fine tuning for processing bulk data - 5 million records"
} | 223424 |
<p>I wanted to use Redux to manage the state of my KendoUI components such as the grid. The online examples from Telerik do not seem to contain clear information on how to do this, so, I started to create a solution of my own. Whilst all my code works with no errors, I'd still like it to be sanity checked by people with more experience in React and Redux as I'm relatively new.</p>
<p><strong>Setup</strong></p>
<ul>
<li>ASP.NET Core 2.2</li>
<li>React with Redux</li>
<li>Thunk Middleware</li>
<li>MaterialUI</li>
<li>Kendo React</li>
</ul>
<p><strong>Process</strong></p>
<ul>
<li>Grid component is loaded</li>
<li>Props referenced from <code>componentDidMount</code> for dispatch</li>
<li>Dispatch made in <code>mapDispatchToProps</code> to fetch data</li>
<li>Grid is populated by returned data in payload.</li>
</ul>
<p><strong>src/components/vessels/VesselsContainer.js</strong></p>
<pre><code>import React from 'react';
import { connect } from 'react-redux';
import { Grid, GridColumn as Column, GridToolbar } from '@progress/kendo-react-grid';
import { fetchVessels } from '../../store/actions/vesselGridActions';
import AddIcon from '@material-ui/icons/Add';
import Fab from '@material-ui/core/Fab';
class VesselsContainer extends React.Component {
componentDidMount() {
this.props.getstuff();
}
render() {
//handle errors and loading state
if (this.props.error) {
return <div>Error! {this.props.error.message}</div>;
}
if (this.props.loading) {
return <div>Loading...</div>;
}
return (
<div>
<Grid data={this.props.vesselGridData} sortlable pageable pageSize={10}>
<Column field="VesselName" title="Name" />
<Column field="IMO" title="IMO" />
<Column field="CreatedDate" title="Created" />
</Grid>
</div>
);
}
}
const mapStateToProps = state => ({
vesselGridData: state.fetchVessels.vesselGridData,
loading: state.fetchVessels.loading,
error: state.fetchVessels.error
})
const mapDispatchToProps = (dispatch) => {
return {
getstuff: () => dispatch(fetchVessels())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(VesselsContainer);
</code></pre>
<p><strong>src/store/actions/vesselGridActions.js</strong></p>
<pre><code>import { toDataSourceRequestString, translateDataSourceResultGroups } from '@progress/kendo-data-query';
export const FETCH_VESSELS_BEGIN = 'FETCH_VESSEL_BEGIN';
export const FETCH_VESSELS_SUCCESS = 'FETCH_VESSEL_SUCCESS';
export const FETCH_VESSELS_FAILURE = 'FETCH_VESSEL_FAILURE';
//Seem to be required by Kendo
const dataState = {
skip: 0,
take: 20
}
export const actionCreators = {
fetchVesselsBegin: () => ({
type: FETCH_VESSELS_BEGIN
}),
fetchVesselsSuccess: (vessels) => ({
type: FETCH_VESSELS_SUCCESS,
payload: { vessels }
}),
fetchVesselsFailure: (error) => ({
type: FETCH_VESSELS_FAILURE,
payload: { error }
})
};
export function fetchVessels() {
const queryStr = `${toDataSourceRequestString(dataState)}`;
const hasGroups = dataState.group && dataState.group.length;
const base_url = 'api/Vessel/GetVessels';
const init = { method: 'GET', accept: 'application/json', headers: {} };
return dispatch => {
dispatch(actionCreators.fetchVesselsBegin);
return fetch(`${base_url}?${queryStr}`, init)
.then(handleErrors)
.then(response => response.json())
.then(({ Data }) => {
const gridResult = ({
result: hasGroups ? translateDataSourceResultGroups(Data) : Data,
dataState
});
dispatch(actionCreators.fetchVesselsSuccess(gridResult));
})
.catch(error => dispatch(actionCreators.fetchVesselsFailure(error)));
};
}
// Handle HTTP errors since fetch won't.
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
</code></pre>
<p><strong>src/store/reducers/vesselGridReducer.js</strong></p>
<pre><code>import { FETCH_VESSELS_BEGIN, FETCH_VESSELS_SUCCESS, FETCH_VESSELS_FAILURE } from '../actions/vesselGridActions';
const initialState = {
vesselGridData: [],
loading: false,
error: null
};
export const reducer = (state, action) => {
state = state || initialState;
switch (action.type) {
case FETCH_VESSELS_BEGIN:
return {
...state,
loading: true,
error: null
};
case FETCH_VESSELS_SUCCESS:
return {
...state,
loading: false,
vesselGridData: action.payload.vessels.result
};
case FETCH_VESSELS_FAILURE:
return {
...state,
loading: false,
error: action.payload.error,
vesselGridData: []
};
default:
return state;
}
}
</code></pre>
<p><strong>src/store/configureStore.js</strong> </p>
<pre><code>import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import * as VesselGrid from './reducers/vesselGridReducer';
export default function configureStore(history, initialState) {
const reducers = {
fetchVessels: VesselGrid.reducer
};
const middleware = [
thunk,
routerMiddleware(history)
];
// In development, use the browser's Redux dev tools extension if installed
const enhancers = [];
const isDevelopment = process.env.NODE_ENV === 'development';
if (isDevelopment && typeof window !== 'undefined' && window.devToolsExtension) {
enhancers.push(window.devToolsExtension());
}
const rootReducer = combineReducers({
...reducers,
routing: routerReducer
});
return createStore(
rootReducer,
initialState,
compose(applyMiddleware(...middleware), ...enhancers)
);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:06:54.737",
"Id": "223425",
"Score": "1",
"Tags": [
"react.js",
"jsx",
"redux"
],
"Title": "Allows the use of Redux to manage the state of a grid with the Kendo React Library"
} | 223425 |
<p>I made a script for a project I'm working on to create a tree object from a filesystem directory, without any working tree operations (can be run in a bare repository). The tree can be inserted into (a) commit(s) by using an index filter that invokes <code>git read-tree --prefix=</...></code>.</p>
<pre><code>#!/bin/bash
# createSubtreeRec <path>
# Creates a subtree with all the contents of path
# does not need to be in a work tree.
# Tree and related objects are added to the repository (unreachable)
# recursive.
# Prints the line that should be used to include the built tree in a parent
# in the form used by git mktree on stdout. This might be a blob or tree.
# <mode> <type> <hash> <name>
# ^space ^space ^tab
function createSubtreeRec () {
local path="$1"
local hash=""
local type=""
local mode=""
local treeData=""
#echo "" >&2
if [ -d "$path" ]; then
for fullpath in $path/*; do
# edited from my original post to simplify the code
treeData="$(printf '%s\n%s' "$treeData" "$(createSubtreeRec "$fullpath")")"
done
# ignore empty dirs
if [ "$treeData" ]; then
# remove leading \n
treeData="${treeData:1}"
#echo "$treeData" >&2
hash="$(echo "$treeData" | git mktree)"
printf '040000 tree %s\t%s' $hash "$(basename "$path")"
fi
elif [ -f "$path" ]; then
hash=$(git hash-object "$path" -w)
type=blob
mode=100644
if [ -x "$path" ]; then
mode=100755
fi
printf '%s blob %s\t%s' $mode $hash "$(basename "$path")"
fi
#echo "" >&2
}
# createSubtree <workdir> <path>
# Creates a subtree starting in <workdir> with the names in <path> as recursive trees,
# Use to get a tree that does not contain <workdir> but contains all of <path>
# and all contents beneath it.
# Prints the top tree's hash on standard output.
function createSubtree () {
local workdir="$1"
local path="$2"
# Get tree from
if [ "$path" != "" ]; then
local entry=$(createSubtreeRec "$workdir/$path")
else
local entry=$(createSubtreeRec "$workdir")
fi
if [ "$entry" ]; then
while [ "$path" ] && [ "$path" != "." ] ; do
local hash=$(echo "$entry" | git mktree)
path="$(dirname "$path")"
local entry="$(printf '%s %s %s\t%s' '040000' tree $hash $(basename "$path"))"
done
printf '%s\n' $hash
fi
}
</code></pre>
<p><code>createSubtreeRec</code> outputs the full tree data line because it can sometimes output blobs.</p>
<p>This code is a significant part of my runtime, so any performance improving observations would be appreciated.</p>
<p>Part of me just wants this available online as it would have helped me out, and I can't find any git builtin commands for this.</p>
| [] | [
{
"body": "<h1>Consider portable shell</h1>\n<p>Do we really need Bash for this? If we can manage without <code>local</code> variables and string indexing, then we could use a leaner, more portable shell instead. Certainly, there's no benefit using the non-standard <code>function</code> keyword - just omit it.</p>\n<p>We probably do want <code>local</code> in the recursive function, but it's good to be clear that we've made the choice for a good reason.</p>\n<h1>Add some error checking options</h1>\n<pre><code>set -eu -o pipefail\n</code></pre>\n<h1>Use more quoting</h1>\n<p>We don't want <code>$path</code> or <code>$fullpath</code> to be split:</p>\n<pre><code> for fullpath in "$path"/*; do\n f=$(basename "$fullpath")\n</code></pre>\n<p>There's some more needed later:</p>\n<pre><code> treeData=$(printf '%s\\n%s %s %s\\t%s' "$treeData" $mode $type $hash "$f")\n elif [ -d "$path/$f" ]; then\n # recurse\n treeData=$(printf '%s\\n%s' "$treeData" "$(createSubtreeRec "$fullpath")")\n</code></pre>\n<p>Shellcheck can't know that <code>$hash</code> will always be a single token, so it recommends more quoting than is actually necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:26:01.133",
"Id": "433020",
"Score": "0",
"body": "Are local variables slower? This is part of a significantly larger script that uses variables like `hash` and `path` in calling functions of this code, so I thought it'd be better to make everything local."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:28:56.210",
"Id": "433021",
"Score": "0",
"body": "I wouldn't expect a speed difference, it's just less portable. In this case, avoiding them would likely make the code much more complex, so I'd leave them be. I didn't realise you wanted a performance review - I've now added a tag for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T17:02:23.757",
"Id": "223434",
"ParentId": "223426",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>This code is a significant part of my runtime, so any performance improving observations would be appreciated.</p>\n</blockquote>\n\n<p>I'm not sure the following will bring significant improvements, but if you want to squeeze out every bit of performance, I have a few ideas.</p>\n\n<h3>(optimizing for perf) Replace <code>printf</code> with interpolated strings</h3>\n\n<p>The main reasons to use <code>printf</code>:</p>\n\n<ul>\n<li>Print text within trailing newline (better than non-portable <code>echo -n ...</code>)</li>\n<li>Use advanced formatting features as in the C-function with similar name</li>\n</ul>\n\n<p>In many places in the code these features are not needed, either because the strings don't use special formatting features, or because the strings are only used in <code>$(...)</code> context, where the trailing newlines will be stripped anyway.\nSo I suggest to replace these:</p>\n\n<blockquote>\n<pre><code>treeData=\"$(printf '%s\\n%s' \"$treeData\" \"$(createSubtreeRec \"$fullpath\")\")\"\n...\nprintf '040000 tree %s\\t%s' $hash \"$(basename \"$path\")\"\n...\nprintf '%s blob %s\\t%s' $mode $hash \"$(basename \"$path\")\"\n...\nlocal entry=\"$(printf '%s %s %s\\t%s' '040000' tree $hash $(basename \"$path\"))\"\n</code></pre>\n</blockquote>\n\n<p>With:</p>\n\n<pre><code>treeData=$treeData$'\\n'$(createSubtreeRec \"$fullpath\")\n...\necho \"040000 tree $hash\"$'\\t'\"$(basename \"$path\")\"\n...\necho \"$mode blob $hash\"$'\\t'\"$(basename \"$path\")\"\n...\nlocal entry=\"040000 tree $hash\"$'\\t'$(basename \"$path\")\n</code></pre>\n\n<p>You <em>could</em> embed tab characters in a string, it would make those lines easier to read:</p>\n\n<pre><code>echo \"040000 tree $hash $(basename \"$path\")\"\n# ^\n# tab\n</code></pre>\n\n<p>But I recommend to use <code>$'\\t'</code> as above, because I don't like invisible characters :-)</p>\n\n<h3>(optimizing for perf) Replace <code>basename \"...\"</code> with substitution</h3>\n\n<p>Instead of <code>basename \"$path\"</code>, you could write <code>${path##*/}</code>.\nThis might be a bit faster because substitution is native Bash, while <code>basename</code> is a program, with the overhead of executing another process.\nAnd I think the result should be equivalent, because the path separator <code>/</code> is not allowed in file and directory names.</p>\n\n<p>It may be tempting to replace <code>dirname \"$path\"</code> with <code>${path%/*}</code>. That requires a bit more careful thought, because the return value won't always be the same.</p>\n\n<h3>Use here-strings</h3>\n\n<p>Instead of <code>echo ... | cmd</code>, use <code>cmd <<< \"...\"</code>.</p>\n\n<h3>(optimizing for perf) Rearrange operations to avoid redundant conditions</h3>\n\n<p>Consider this piece of code from your post, with minor optimizations to remove some noise:</p>\n\n<blockquote>\n<pre><code>if [ \"$path\" ]; then\n entry=$(createSubtreeRec \"$workdir/$path\")\nelse\n entry=$(createSubtreeRec \"$workdir\")\nfi\n\nif [ \"$entry\" ]; then\n while [ \"$path\" ] && [ \"$path\" != \".\" ] ; do\n hash=$(git mktree <<< \"$entry\")\n path=$(dirname \"$path\")\n entry=\"040000 tree $hash\"$'\\t'\"${path##*/}\"\n done\n echo \"$hash\"\nfi\n</code></pre>\n</blockquote>\n\n<p>Can you spot some odd execution paths?</p>\n\n<ul>\n<li><code>$path</code> is either empty to begin with, or it will never be empty</li>\n<li>In the last iteration of the <code>while</code> loop, <code>entry</code> is computed and it will not be used</li>\n<li>If <code>$path</code> is <code>.</code> to begin with, then <code>createSubtreeRec \"$workdir/.\"</code> will get executed, and I doubt that's what you want.</li>\n</ul>\n\n<p>To eliminate some redundant paths, sometimes it helps to first <em>increase</em> the redundancy. This is logically equivalent to the above code:</p>\n\n<pre><code>if [ \"$path\" ]; then\n entry=$(createSubtreeRec \"$workdir/$path\")\n if [ \"$entry\" ]; then\n while [ \"$path\" ] && [ \"$path\" != \".\" ] ; do\n hash=$(git mktree <<< \"$entry\")\n path=$(dirname \"$path\")\n entry=\"040000 tree $hash\"$'\\t'\"${path##*/}\"\n done\n echo \"$hash\"\n fi\nelse\n entry=$(createSubtreeRec \"$workdir\")\n if [ \"$entry\" ]; then\n while [ \"$path\" ] && [ \"$path\" != \".\" ] ; do\n hash=$(git mktree <<< \"$entry\")\n path=$(dirname \"$path\")\n entry=\"040000 tree $hash\"$'\\t'\"${path##*/}\"\n done\n echo \"$hash\"\n fi\nfi\n</code></pre>\n\n<p>Now let's try to simplify it. In the <code>else</code> branch we know that <code>$path</code> is empty, and it cannot possibly change, so we can drop the <code>while</code> loop:</p>\n\n<pre><code>else\n entry=$(createSubtreeRec \"$workdir\")\n if [ \"$entry\" ]; then\n echo \"$hash\"\n fi\nfi\n</code></pre>\n\n<p>And since <code>$hash</code> is only ever set in the <code>while</code> loop we dropped, we can drop that too:</p>\n\n<pre><code>else\n entry=$(createSubtreeRec \"$workdir\")\n if [ \"$entry\" ]; then\n echo\n fi\nfi\n</code></pre>\n\n<p>At this point I wonder if you really wanted to print a blank line in this case, or if it's a bug. (I let you decide!)</p>\n\n<p>Back to the <code>if</code> branch, we have this code now:</p>\n\n<pre><code> entry=$(createSubtreeRec \"$workdir/$path\")\n if [ \"$entry\" ]; then\n while [ \"$path\" ] && [ \"$path\" != \".\" ] ; do\n hash=$(git mktree <<< \"$entry\")\n path=$(dirname \"$path\")\n entry=\"040000 tree $hash\"$'\\t'\"${path##*/}\"\n done\n echo \"$hash\"\n fi\n</code></pre>\n\n<p>Since at this point <code>$path</code> is not empty and will never be, we can simplify the <code>while</code> statement, eliminating one unnecessary evaluation per iteration:</p>\n\n<pre><code> while [ \"$path\" != \".\" ] ; do\n</code></pre>\n\n<p>This is still not ideal, since this condition will always be true for the first time, and the last computation of <code>entry</code> will not be used. We can rearrange the loop to improve on both of these points:</p>\n\n<pre><code> while true; do\n hash=$(git mktree <<< \"$entry\")\n path=$(dirname \"$path\")\n [ \"$path\" != \".\" ] || break\n entry=\"040000 tree $hash\"$'\\t'\"${path##*/}\"\n done\n echo \"$hash\"\n</code></pre>\n\n<p>I doubt any of this would have a measurable performance difference except in extremely deep paths, I thought it was an interesting exercise to share.</p>\n\n<h3>Missed one important double-quoting</h3>\n\n<p>There is one spot that missed an important double-quoting:</p>\n\n<blockquote>\n<pre><code>local entry=\"$(printf '%s %s %s\\t%s' '040000' tree $hash $(basename \"$path\"))\"\n</code></pre>\n</blockquote>\n\n<p>If the basename of <code>$path</code> contains spaces, then the result of <code>$(basename \"$path\")</code> will be subject to word-splitting. Correctly quoted, the above line would be:</p>\n\n<pre><code>local entry=$(printf '%s %s %s\\t%s' '040000' tree \"$hash\" \"$(basename \"$path\")\")\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li><p>It's true that in this example <em>we know</em> that <code>$hash</code> is safe even without double-quoting. You never know how the script might evolve, and somebody might assign something unsafe to this variable. Also, when <em>you</em> assign something to a variable, you don't want to verify if all uses of the variable are safe enough. If you develop the habit to always double-quote variables used in command arguments, you can rest assured that your code is safe.</p></li>\n<li><p>I dropped the double-quotes around the right-hand side of the assignment, because it's already safe like that. If the value contained literal spaces, that would have to be quoted though. If you feel safer to always write <code>v=\"...\"</code>, that's fine.</p></li>\n</ul>\n\n<h3>No need for input validation?</h3>\n\n<p>From the posted code it's not clear if <code>createSubtree</code> is guaranteed to get safe input. It seems to me that <code>path</code> is expected to be valid relative path from <code>worktree</code>, but I don't see how that is actually enforced.\nYou might want to add some sanity checks and fail fast (and with a big bang) when receiving something unexpected.</p>\n\n<h3>Minor things</h3>\n\n<p>I'm not a fan of assigning a default value and overwriting it like this:</p>\n\n<blockquote>\n<pre><code>mode=100644\nif [ -x \"$path\" ]; then\n mode=100755\nfi\n</code></pre>\n</blockquote>\n\n<p>I would rather spell out an <code>else</code>.</p>\n\n<hr>\n\n<p>Instead of duplicating the pattern <code>%(mode) %(type) %(hash)\\t%(name)</code> in multiple places, it might be a good idea to create a helper function for it.</p>\n\n<hr>\n\n<p>The <code>type</code> variable is assigned once and never used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T16:00:20.820",
"Id": "225470",
"ParentId": "223426",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:48:30.340",
"Id": "223426",
"Score": "3",
"Tags": [
"performance",
"bash",
"git"
],
"Title": "git Create Tree from Arbitrary Directory (works in bare repository)"
} | 223426 |
<p>I started working on a notification system that is pluggable into any project. I have not made any "plugin" type javascript libraries, usually just functions very specific to the project at hand. That said I wanted to reach out for pointers to avoid conflicts in both javascript (and css). I'm aware specificity is key in most places, common namespaces likely should be avoided (I have yet to apply more specific classing), but any insight beyond that is greatly appreciated.</p>
<p>I only just started, so in the early stages at this point, figured I'd get insight early before going down the rabbit hole too far. Lots of "To Do's" remain.</p>
<p>Early mock/demo of project in snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/** TODO:
* add close on backdrop click
* add automatic close function to hide after a designated timeframe; if specified.
* add controller/id to pair toggles with dialog (data-controls/id pair)
* add localStorage for repeat visitors.
* improve animations
* Dock Only: add minify option, minify into small icon
* Dock & popup Only: stack notifiers if more than 1 dock/popup
*/
// convert string into fragment
String.prototype.toFragment = function() {
return document.createRange().createContextualFragment(this);
};
// convert html collection into an array
HTMLCollection.prototype.toArray = function() {
return toArray(this);
};
// convert html collection into an array
NodeList.prototype.toArray = function() {
return toArray(this);
};
// matches polyfill
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
// closest polyfill
if (!Element.prototype.closest) {
Element.prototype.closest = function(s) {
var el = this;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}
// convert array-like objects into a true array
function toArray(arrayLikeObject) {
return !Array.from ? [].slice.call(arrayLikeObject) : Array.from(arrayLikeObject);
}
// remove focus from dialogs
function deselectAllDialogs() {
return document.querySelectorAll('.dialog').toArray().forEach(removeSelected);
}
// set aria-selected to false
function removeSelected(node) {
return node.setAttribute("aria-selected", false);
}
// set aria-selected to true on target
function selectTarget(event) {
return event.target.setAttribute("aria-selected", true);
}
// set aria-selected to false on parent element of target
function removeDialogSelection(event) {
return removeSelected(event.target.closest('.dialog'));
}
// add boolean hidden attribute to parent element node
function hideTargetParent(event) {
var overlay = document.querySelector('.dialog-backdrop');
if (overlay !== null) overlay.setAttribute("hidden", "");
return event.target.closest('.dialog').setAttribute("hidden", "");
}
// dialog constructor
function Dialog(params) {
var empty = _dialog.fallbacks.blank;
// setup params/attributes & fallbacks
this.title = params.title;
this.action = params.action;
this.message = params.message || _dialog.fallbacks.warning;
this.html = params.html || empty;
this.type = params.type || empty;
this.method = params.method || empty;
this.state = params.state ? " hidden" : empty;
var overlay = "";
if (this.method.trim() === "popup" && document.querySelector('.dialog-backdrop') === null) {
overlay = '<div class="dialog-backdrop" />';
}
// create html strings of dialog using only items available
var nodes = {};
nodes.start = '<div class="dialog' + this.type + this.method + '" tabindex="0"' + this.state + '><div class="inner">';
nodes.title = this.title !== void 0 ? '<strong class="title">' + this.title + '</strong>' : empty;
nodes.message = "<p>" + this.message + "</p>";
nodes.html = this.html;
nodes.action = this.action !== void 0 ? '<div class="ui">' + this.action + '</div>' : empty;
nodes.end = "</div></div>" + overlay;
// add to callable property
this.toString = Object.keys(nodes).map(function(node) {
return nodes[node]
}).join("");
// create to appendable fragment
this.toHTML = this.toString.toFragment();
}
Dialog.prototype.setup = function() {
// get fragment contents
var dialog = this.toHTML.firstChild;
// create button string
var closeString = '<button class="close" title="Close' + this.type + ' dialog.">&times;</button>';
// make focusable
dialog.setAttribute("tabindex", 0);
// insert close button
dialog.insertBefore(closeString.toFragment(), dialog.firstChild);
// add events
dialog.addEventListener('click', deselectAllDialogs, false);
dialog.addEventListener("focusin", selectTarget, false);
// add defocus/hidden on tab out/button close
var focusable = dialog.querySelectorAll('button, input, a, [tabindex="0"], textarea');
var lastFocusableItem = focusable.toArray().slice(-1)[0];
closeDialog(dialog.querySelector(".close"), lastFocusableItem);
}
function closeDialog(closeButton, lastFocusableItem) {
closeButton.addEventListener("click", hideTargetParent, false);
lastFocusableItem.addEventListener("focusout", removeDialogSelection, false);
}
console.clear();
var _dialog = {
type: {
inform: " information",
warning: " warning",
error: " error",
success: " success"
},
method: {
inline: " inline",
popup: " popup",
dock: " dock"
},
state: {
hidden: true
},
fallbacks: {
warning: "Intended message could not found; Contact an administrator.",
blank: ""
}
}
var InfoExample = new Dialog({
title: "Information Example",
message: "An “Information Dialog” message displays information to your user for a variety of reasons.",
action: "<button>More Details</button>",
type: _dialog.type.inform,
method: _dialog.method.inline,
state: !_dialog.state.hidden
});
InfoExample.setup();
document.body.appendChild(InfoExample.toHTML);
var WarningExample = new Dialog({
title: "Warning Example",
message: "A “Warning Dialog” message displays concerns to your users who are in need of such a notice.",
type: _dialog.type.warning,
method: _dialog.method.dock,
state: !_dialog.state.hidden
});
WarningExample.setup();
setTimeout(function() {
return document.body.appendChild(WarningExample.toHTML);
}, 2000);
var ErrorExample = new Dialog({
title: "Error Example",
message: "An “Error Dialog” message displays issues either unfixable or in need of user interaction in order to correct the concern.",
html: "<ul><li>additional html mark-up</li><li>is appendable</li><li>via the html property</li></ul>",
action: "<button>Reload?</button>",
type: _dialog.type.error,
method: _dialog.method.inline,
state: !_dialog.state.hidden
});
ErrorExample.setup();
document.body.appendChild(ErrorExample.toHTML);
var SuccessExample = new Dialog({
title: "Success Example",
message: "A “Success Dialog” message displays some success to the users so they are aware their interaction succeeded.",
type: _dialog.type.success,
method: _dialog.method.popup,
state: !_dialog.state.hidden
});
SuccessExample.setup();
document.getElementById('toggle').addEventListener('click', function() {
return document.body.appendChild(SuccessExample.toHTML);
}, false);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
font: normal 100%/1.75 sans-serif;
}
body {
font-size: 90%;
}
.dialog {
padding: 1rem 2rem;
border: 1px solid transparent;
width: 100%;
border-radius: 2px;
box-sizing: border-box;
overflow: hidden;
text-shadow: 0 0 1rem #fff;
min-height: 125px;
background-repeat: no-repeat;
color: hsla(0, 0%, 0%, 0.75);
}
.dialog-backdrop {
position: fixed;
background-color: hsla(0, 100%, 100%, .9);
z-index:98;
width: 100%;
height: 100%;
left:0;
top:0;
}
.dialog.inline {
display: table;
position: relative;
margin-bottom: 1rem;
box-shadow: inset 0 0 0 100vh hsla(0, 0%, 100%, .75);
}
.dialog.dock,
.dialog.popup {
display: table;
position: fixed;
box-shadow:
inset 0 0 0 100vh hsla(0, 0%, 100%, .75),
0 15px 15px -15px hsla(0, 0%, 0%, .5);
}
.dialog.dock {
bottom:1rem;
right: 1rem;
max-width: 320px;
width: 90%;
z-index:999;
}
.dialog.popup {
left: 50%;
top:50%;
transform: translate3d(-50%, -50%, 0);
max-width: 600px;
width: 90%;
z-index: 99;
}
.dialog .inner {
display: table-cell;
vertical-align: middle;
height: 100%;
}
@media (min-width:0) and (max-width:600px) {
.dialog .ui {
text-align: right;
}
}
.dialog button:not(.close) {
border-radius: 0.125rem;
padding: 0.5rem 0.666rem;
font-weight: 500;
opacity: 0.85;
background-color: transparent;
color: #fff;
transition: all 0.1s;
}
.dialog button:not(.close):focus,
.dialog button:not(.close):hover {
transform: scale(1.025);
outline: 0;
opacity: 1;
cursor: pointer;
box-shadow: 0 6px 6px -6px hsla(0, 0%, 0%, 0.5);
}
.dialog button:not(.close):active {
box-shadow: none;
border-style: solid;
transform: scale(1);
}
.dialog ul,
.dialog ol,
.dialog dl,
.dialog p {
margin-top: 0;
}
.dialog .title {
display: block;
opacity: 0.666;
}
.dialog *:last-child {
margin-bottom: 0;
}
.dialog .close {
opacity: 0;
border: 1px solid transparent;
background-color: transparent;
position: absolute;
right: 0.25rem;
top: 0.333rem;
border-radius: 2px;
font-size: 125%;
line-height: 1;
transform: scale(0.001);
transition: all 0.2s;
}
.dialog:hover .close,
.dialog[aria-selected="true"] .close {
opacity: 1;
transform: scale(1);
transition: all 0.2s;
}
.dialog .close:hover {
cursor: pointer;
transition: all 0.075s;
background-color: hsla(0, 0%, 0%, 0.05);
}
.dialog:focus,
.dialog .close:focus,
.dialog .close:active {
outline: none;
}
.dialog.information .title,
.dialog.information .close {
color: #3498db;
}
.dialog.error .title,
.dialog.error .close {
color: #e74c3c;
}
.dialog.success .title,
.dialog.success .close {
color: #27ae60;
}
.dialog.warning .title,
.dialog.warning .close {
color: #f39c12;
}
.dialog.information button:not(.close) {
background-color: #3498db;
}
.dialog.error button:not(.close) {
background-color: #e74c3c;
}
.dialog.success button:not(.close) {
background-color: #27ae60;
}
.dialog.warning button:not(.close) {
background-color: #f39c12;
}
.dialog.information,
.dialog.information button:not(.close),
.dialog.information .close:focus {
border-color: #3498db;
}
.dialog.error,
.dialog.error button:not(.close),
.dialog.error .close:focus {
border-color: #e74c3c;
}
.dialog.success,
.dialog.success button:not(.close),
.dialog.success .close:focus {
border-color: #27ae60;
}
.dialog.warning,
.dialog.warning button:not(.close),
.dialog.warning .close:focus {
border-color: #f39c12;
}
.dialog[aria-selected="true"] {
outline-offset: 2px;
}
.dialog.information[aria-selected="true"] {
outline: 1px dotted #3498db;
}
.dialog.error[aria-selected="true"] {
outline: 1px dotted #e74c3c;
}
.dialog.success[aria-selected="true"] {
outline: 1px dotted #27ae60;
}
.dialog.warning[aria-selected="true"] {
outline: 1px dotted #f39c12;
}
.dialog.warning {
background-image: /*url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><path fill="hsl(37, 90%, 51%)" transform="rotate(-24 189.3957061767577,212.6444854736327)" opacity="0.25" d="m157.686503,13.297016c17.52217,-28.348917 45.973192,-28.281451 63.453674,0l217.201324,351.405852c23.392095,37.845479 6.352658,68.525489 -38.036599,68.525489l-421.783126,0c-44.399125,0 -61.504216,-30.557766 -38.036599,-68.525489l217.201324,-351.405852l0,0zm31.734289,117.845789c-11.122387,0 -20.139037,9.123588 -20.139037,20.079224l0,120.953847c0,11.089359 8.939114,20.079224 20.139037,20.079224c11.122589,0 20.139037,-9.123789 20.139037,-20.079224l0,-120.953847c0,-11.089561 -8.938913,-20.079224 -20.139037,-20.079224l0,0zm0,241.668442c11.122589,0 20.139037,-9.01665 20.139037,-20.139037c0,-11.122589 -9.016448,-20.139037 -20.139037,-20.139037c-11.122387,0 -20.139037,9.016448 -20.139037,20.139037c0,11.122387 9.01665,20.139037 20.139037,20.139037l0,0z"/></svg>'),*/
linear-gradient(45deg, #fff 0%, hsla(37, 90%, 51%, .25) 100%);
}
.dialog.information {
background-image: /*url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><path fill="hsl(204, 70%, 53%)" transform="rotate(-45 256.01535034179676,255.98666381835938)" opacity="0.25" d="m480.014141,252.986668c-1.7,-123.7 -103.3,-222.6 -227,-221s-222.6,103.3 -221,227c1.7,123.7 103.3,222.6 227,221c123.7,-1.7 222.7,-103.3 221,-227zm-224,-141.1c17.7,0 32,14.3 32,32s-14.3,32 -32,32c-17.7,0 -32,-14.3 -32,-32s14.3,-32 32,-32zm44,283.1l-88,0l0,-11l22,0l0,-160l-22,0l0,-12l66,0l0,172l22,0l0,11z" /></svg>'),*/
linear-gradient(45deg, #fff 0%, hsla(204, 70%, 53%, .25) 100%);
}
.dialog.error {
background-image: /* url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><circle fill="hsl(6, 78%, 57%)" opacity="0.25" r="253.44" cy="256" cx="256"/><path fill="hsl(255, 0%, 100%)" d="m350.019,144.066l17.521,17.522c6.047,6.047 6.047,15.852 0,21.9l-183.933,183.931c-6.047,6.048 -15.852,6.047 -21.9,0l-17.521,-17.522c-6.047,-6.047 -6.047,-15.852 0,-21.9l183.932,-183.933c6.048,-6.046 15.853,-6.046 21.901,0.002z"/><path fill="hsl(255, 100%, 100%)" d="m367.54,349.899l-17.522,17.522c-6.047,6.047 -15.852,6.047 -21.9,0l-183.932,-183.933c-6.047,-6.047 -6.047,-15.852 0,-21.9l17.522,-17.522c6.047,-6.047 15.852,-6.047 21.9,0l183.932,183.933c6.048,6.048 6.048,15.853 0,21.9z"/></svg>'),*/
linear-gradient(45deg, #fff 0%, hsla(6, 78%, 57%, .25) 100%);
}
.dialog.success {
background-image: /* url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><path opacity="0.25" fill="hsl(145, 63%, 42%)" id="svg_2" d="m255.999998,7.084824c-137.5017,0 -248.915175,111.413475 -248.915175,248.915175s111.413475,248.915175 248.915175,248.915175c137.5017,0 248.915175,-111.413475 248.915175,-248.915175s-111.413475,-248.915175 -248.915175,-248.915175zm-38.414313,337.112522c-2.872098,2.872098 -6.940904,5.265513 -10.531027,5.265513s-7.658928,-2.513086 -10.650697,-5.385184l- 67.015624,-67.015624l21.301395,-21.301395l56.484597,56.484597l149.349105,-150.426142l20.942382,21.660407l-159.880131,160.717827z"/></svg>'),*/
linear-gradient(45deg, #fff 0%, hsla(145, 63%, 42%, .25) 100%);
}
[hidden] {
display: none !important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="toggle" style="margin-bottom:1rem;">
Toggle Success Modal
</button></code></pre>
</div>
</div>
</p>
<p><strong>Sidenote</strong><br>Would a custom event method be a source of concern for matching random selectors? e.g. the following code block:</p>
<pre><code>function emitEvent(args, fn) {
var parent = args.parent === void 0 ? window : args.parent;
parent.addEventListener(args.type, function (event) {
if (!event.target.matches(args.selector)) return;
return fn(event);
}, false );
}
emitEvent({type: "click", selector: ".someClass"}, callback);
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:33:15.080",
"Id": "223436",
"Score": "1",
"Tags": [
"javascript",
"event-handling",
"dom",
"callback"
],
"Title": "Creating a reusable plugin (Dialog/Notifier as example)"
} | 223436 |
<p>I'm rather new to programming. So far I've only done some small coding tasks once every now and then, and this the first "bigger" project for me. I love the idea of object-oriented programming and I've heard a lot of good things about Python and Pygame, so I decided to give it a shot and get coding.</p>
<p>The result is a house full of <code>Cats</code> and <code>Mice</code> (who share the parent class <code>Animal</code>). They move around randomly, stay in the enclosed area, and of course the <code>Mice</code> are afraid of <code>Cats</code> and flee in a panic if they get too close.</p>
<p>I tried my best to come up with a sensible class structure and to produce straightforward, easy-to read code with clear and concise comments.</p>
<p>I'm interested in every type of suggestions and tips, from a complete restructuring of the program to simple variable names and missing spaces. In case anyone wants the standalone *.exe, it can be downloaded <a href="https://drive.google.com/file/d/1LsiMv7vdNhfKgXOofpugH2T50g2nRDjg/view?usp=sharing" rel="nofollow noreferrer">here</a>. Thanks for your time!</p>
<pre><code># The program simulates cats and mice moving inside an enclosed area called "house"
# Animals make turns at random intervals when they randomly choose a new direction and speed.
# When the have reached the selected direction and speed, they move straight ahead with constant speed
# until the next turn happens.
# When animals leave the boundary defined by the buffer zone, their next turn directs them back
# to the center of the house.
# Cats move around randomly but still respect the buffer zone.
# Mice also respect the buffer zone, but additionally flee from cats once they get too close
# The behaviour of cats and mice can be influenced through a variety of parameters to create a nice and realistic feel.
# <editor-fold desc="Preamble">
import pygame # for awesomeness
import random # for random numbers
import math # for mathematical stuff
# import subprocess # for creating the *.exe from command line
# House parameters
FRAME_RATE = 30
HOUSE_NAME = "House of Cat and Mouse™"
HOUSE_SIZE_HORIZONTAL = 800
HOUSE_SIZE_VERTICAL = 800
HOUSE_SIZE_BUFFER = 100
HOUSE_COLOR_FLOOR = (255, 215, 150) # Light Brown [RGB]
HOUSE_COLOR_BORDER = (255, 140, 0) # Orange [RGB]
HOUSE_LINE_WIDTH_BORDER = 5
MICE_NUMBER = 100
CATS_NUMBER = 2
# Mouse behavior
MOUSE_BEHAVIOR = dict(
SPEED_MIN=0,
SPEED_MAX=70,
SPEED_CHANGE_MIN=0,
SPEED_CHANGE_MAX=40,
ACCELERATION_MIN=10,
ACCELERATION_MAX=100,
TURN_ANGLE_MIN=0.1 * math.pi,
TURN_ANGLE_MAX=0.8 * math.pi,
TURN_SPEED_MIN=1 * math.pi,
TURN_SPEED_MAX=3 * math.pi,
TURN_TIME_MIN=0.3,
TURN_TIME_MAX=0.6,
TURN_ANGLE_TOLERANCE_BUFFER=0.2 * math.pi,
COLOR=(108, 110, 107), # The Official Mouse Grey
RADIUS=10 # Mice are slim
)
MOUSE_TURN_ANGLE_TOLERANCE_CAT = 0.1 * math.pi
MOUSE_DISTANCE_PANIC = 150
MOUSE_SPEED_PANIC = 200
MOUSE_TURN_SPEED_PANIC = 5 * math.pi
MOUSE_TURN_TIME_PANIC = 0.3
# Cat behavior
CAT_BEHAVIOR = dict(
SPEED_MIN=30,
SPEED_MAX=60,
SPEED_CHANGE_MIN=0,
SPEED_CHANGE_MAX=20,
ACCELERATION_MIN=10,
ACCELERATION_MAX=20,
TURN_ANGLE_MIN=0 * math.pi,
TURN_ANGLE_MAX=0.3 * math.pi,
TURN_SPEED_MIN=0.5 * math.pi,
TURN_SPEED_MAX=1 * math.pi,
TURN_TIME_MIN=0.5,
TURN_TIME_MAX=1,
TURN_ANGLE_TOLERANCE_BUFFER=0.25 * math.pi,
COLOR=(0, 0, 0), # The Blackest Black
RADIUS=20 # Cats are fat
)
# </editor-fold>
# Top class, contains the animals and directs the flow of the program
class House:
# Animals stored as class variables to give cat and mouse instances access to them
# Needed to let the mice check if cats are near
mice = None # Object to store all the mice
cats = None # Object to store all the cats
def __init__(self):
self.frame_rate = FRAME_RATE # Maximum frame rate (can be lower) [1/s]
self.name = HOUSE_NAME # Name of the house, shown on the window bar [string]
self.size_horizontal = HOUSE_SIZE_HORIZONTAL # Width of the house [px]
self.size_vertical = HOUSE_SIZE_VERTICAL # Height of the house [px]
self.size_buffer = HOUSE_SIZE_BUFFER # Width of buffer at house edges that makes animals turn back [px]
self.color_floor = HOUSE_COLOR_FLOOR # Color of the background [RGB]
self.color_border = HOUSE_COLOR_BORDER # Color of the border [RGB]
self.line_width_border = HOUSE_LINE_WIDTH_BORDER # Line width of the border to the buffer zone [px]
self.mice_number = MICE_NUMBER # Number of mice in the house [-]
self.cats_number = CATS_NUMBER # Number of cats in the house [-]
House.mice = [] # Object to store all the mice
House.cats = [] # Object to store all the cats
self.program_window = pygame.display.set_mode((self.size_horizontal, self.size_vertical)) # Create window
pygame.display.set_caption(self.name) # Set name of window
self.clock = pygame.time.Clock() # Set game clock (takes care of frame rate)
self.create_mice() # Create all the mice
self.create_cats() # Create all the cats
# Create self.mice_number mice in the house
def create_mice(self):
for i in range(self.mice_number):
House.mice.append(Mouse())
# Create self.cats_number cats in the house
def create_cats(self): # Create self.cats_number cats in the house
for i in range(self.cats_number):
House.cats.append(Cat())
# Updates movement of all animals in the house
def update_animal_movement(self):
for i in House.mice:
i.update_position() # Update coordinates (happens every frame)
if i.frame_number_current >= i.frame_number_end_of_turn: # Do turn when the current turn_time is reached
i.do_turn()
for i in House.cats:
i.update_position() # Update coordinates (happens every frame)
if i.frame_number_current >= i.frame_number_end_of_turn: # Do turn when the current turn_time is reached
i.do_turn()
self.clock.tick(FRAME_RATE) # Wait till next frame
# Draws the house and all the animals contained
def draw(self):
self.program_window.fill(self.color_floor) # Fill window with floor color (covers previous frame)
pygame.draw.rect(self.program_window, self.color_border, # Draw border to buffer zone
(self.size_buffer, self.size_buffer, self.size_horizontal - 2 * self.size_buffer,
self.size_vertical - 2 * self.size_buffer), self.line_width_border)
for i in House.mice: # Draw all the mice
i.draw()
for i in House.cats: # Draw all the cats
i.draw()
pygame.display.flip() # Update whole window area
# Parent class of cats and mice, defines most of their general behaviour
class Animal:
def __init__(self, animal_behaviour):
self.speed_min = animal_behaviour["SPEED_MIN"] # Minimum move speed of the animal [px/s]
self.speed_max = animal_behaviour["SPEED_MAX"] # Maximum move speed of the animal [px/s]
# Minimum change of speed from the start to the end of a turn [px/s]
self.speed_change_min = animal_behaviour["SPEED_CHANGE_MIN"]
# Maximum change of speed from the start to the end of a turn [px/s]
self.speed_change_max = animal_behaviour["SPEED_CHANGE_MAX"]
# Minimum acceleration when changing speed [px/s^2]
self.acceleration_min = animal_behaviour["ACCELERATION_MIN"]
# Maximum acceleration when changing speed [px/s^2]
self.acceleration_max = animal_behaviour["ACCELERATION_MAX"]
self.turn_angle_min = animal_behaviour["TURN_ANGLE_MIN"] # Minimum change of direction when turning [rad]
self.turn_angle_max = animal_behaviour["TURN_ANGLE_MAX"] # Maximum change of direction when turning [rad]
self.turn_speed_min = animal_behaviour["TURN_SPEED_MIN"] # Minimum angular velocity of direction change [rad/s]
self.turn_speed_max = animal_behaviour["TURN_SPEED_MAX"] # Maximum angular velocity of direction change [rad/s]
self.turn_time_min = animal_behaviour["TURN_TIME_MIN"] # Minimum time to next turn of the animal [s]
self.turn_time_max = animal_behaviour["TURN_TIME_MAX"] # Maximum time to next turn of the animal [s]
# Acceptable direction difference to the center of the window when returning from the buffer zone [rad]
self.turn_angle_tolerance_buffer = animal_behaviour["TURN_ANGLE_TOLERANCE_BUFFER"]
self.color = animal_behaviour["COLOR"] # Color of the animal [RGB]
self.radius = animal_behaviour["RADIUS"] # Radius of the circle that represents the animal [px]
self.speed_current = None # Current speed of the animal [px/s]
self.speed_end_of_turn = None # Target speed at the end of the current turn [px/s]
self.acceleration = None # Acceleration while changing speed for the current turn [px/s^2]
# Speed change per frame while changing speed, equals self.acceleration / FRAME_RATE [px/s]
self.speed_change_per_frame = None
self.direction_current = None # Current movement direction of the animal (0 means left, pi/2 means down) [rad]
# Target movement direction at the end of the current turn (0 means left, pi/2 means down) [px/s]
self.direction_end_of_turn = None
self.turn_speed = None # Angular velocity while changing direction for the current turn [rad/s]
self.turn_time = None # Duration of the current turn [s]
# Direction change per frame while changing direction, equals self.turn_speed / FRAME_RATE [rad]
self.direction_change_per_frame = None
# Current horizontal coordinate of animal (distance from left edge of the window) [px]
self.position_horizontal = None
# Current vertical coordinate of animal (distance from top edge of the window) [px]
self.position_vertical = None
self.frame_number_current = None # Number of frames since the start of the current turn [-]
self.frame_number_end_of_turn = None # Number of frames when the current turn will end [-]
self.is_accelerating = None # Check if animal is increasing speed in the current turn [bool]
self.is_turning_clockwise = None # Check if animal is turning clockwise in the current turn [bool]
self.set_initial_state() # Set start conditions (speed, direction) of the animal
self.do_turn() # Defines first turn of the animal
# Set start conditions (speed, direction) of the animal
def set_initial_state(self):
self.speed_current = random.uniform(self.speed_min, self.speed_max)
self.direction_current = random.uniform(-math.pi, math.pi)
self.position_horizontal = random.uniform(HOUSE_SIZE_BUFFER, HOUSE_SIZE_HORIZONTAL - HOUSE_SIZE_BUFFER)
self.position_vertical = random.uniform(HOUSE_SIZE_BUFFER, HOUSE_SIZE_VERTICAL - HOUSE_SIZE_BUFFER)
# Placeholder for the execution of a turn (cats and mice move differently)
def do_turn(self):
pass
# Executes a turn when the animal is relaxed (not in buffer, not near cat for mice only)
def do_turn_relaxed(self):
# Randomly increase/decrease speed
self.speed_end_of_turn = self.speed_current + random.choice([1, -1]) * random.uniform(self.speed_change_min,
self.speed_change_max)
if self.speed_end_of_turn > self.speed_max: # Set speed to maximum if value turned out bigger
self.speed_end_of_turn = self.speed_max
if self.speed_end_of_turn < self.speed_min: # Set speed to minimum if value turned out smaller
self.speed_end_of_turn = self.speed_min
# Randomly change direction
self.direction_end_of_turn = self.direction_current + random.choice([1, -1]) * random.uniform(
self.turn_angle_min, self.turn_angle_max)
self.acceleration = random.uniform(self.acceleration_min, self.acceleration_max) # Select random acceleration
self.turn_speed = random.uniform(self.turn_speed_min, self.turn_speed_max) # Select random turn speed
self.turn_time = random.uniform(self.turn_time_min, self.turn_time_max) # Select random turn time
# Executes a turn when the animal is in the buffer zone (close to the edges)
def do_turn_in_buffer(self):
self.speed_end_of_turn = self.speed_max # Move with maximum speed to get back inside quickly
# Move approximately towards the center of the house
self.direction_end_of_turn = self.direction_to_point(HOUSE_SIZE_HORIZONTAL / 2,
HOUSE_SIZE_VERTICAL / 2) + random.uniform(
-self.turn_angle_tolerance_buffer, self.turn_angle_tolerance_buffer)
self.acceleration = self.acceleration_max # Accelerate as quick as possible
self.turn_speed = self.turn_speed_max # Turn as quick as possible
self.turn_time = self.turn_time_max # Go towards center for the longest time possible (to gain some separation)
# Determines whether the animal is in the buffer zone (true if close to the edges) [bool]
def in_buffer(self):
if (self.position_horizontal < HOUSE_SIZE_BUFFER or
self.position_horizontal > HOUSE_SIZE_HORIZONTAL - HOUSE_SIZE_BUFFER or
self.position_vertical < HOUSE_SIZE_BUFFER or
self.position_vertical > HOUSE_SIZE_VERTICAL - HOUSE_SIZE_BUFFER):
return True
else:
return False
# Determines angular direction from animal to the given point [rad]
def direction_to_point(self, x, y):
return math.atan2(-self.position_vertical + y, -self.position_horizontal + x)
# Contains the operations ALL ANIMALS need after executing a turn (setting variables etc)
def edit_parameters_after_doing_turn(self):
# Keeps the direction value between -pi and pi
self.direction_current = math.remainder(self.direction_current, 2 * math.pi)
self.direction_end_of_turn = math.remainder(self.direction_end_of_turn, 2 * math.pi)
# Checks if animal is accelerating (increasing speed) in current turn
if self.speed_current < self.speed_end_of_turn:
self.is_accelerating = True
else:
self.is_accelerating = False
# Checks if clockwise or counterclockwise rotation is quicker (true if clockwise is quicker)
if math.remainder(self.direction_current - self.direction_end_of_turn, 2 * math.pi) < 0:
self.is_turning_clockwise = True
else:
self.is_turning_clockwise = False
self.speed_change_per_frame = self.acceleration / FRAME_RATE
self.direction_change_per_frame = self.turn_speed / FRAME_RATE
self.frame_number_end_of_turn = self.turn_time * FRAME_RATE
self.frame_number_current = 0 # Resets frame counter (determines end of turn)
# Updates the movement and coordinates of the animal based on target values for current turn (happens every frame)
def update_position(self):
# If accelerating, increase speed until target speed reached
if self.is_accelerating and self.speed_current < self.speed_end_of_turn:
self.speed_current += self.speed_change_per_frame
# If slowing down, decrease speed until target speed reached
elif not self.is_accelerating and self.speed_current > self.speed_end_of_turn:
self.speed_current -= self.speed_change_per_frame
# If turning clockwise, turn until target direction is reached
# (complicated because direction values can switch from positive to negative)
if self.is_turning_clockwise:
if self.direction_end_of_turn > 0 and self.direction_current < self.direction_end_of_turn:
self.direction_current += self.direction_change_per_frame
elif self.direction_end_of_turn < 0 and self.direction_current < self.direction_end_of_turn + math.pi * (
abs(self.direction_current) + self.direction_current) / abs(self.direction_current):
self.direction_current += self.direction_change_per_frame
# If turning counterclockwise, turn until target direction is reached
# (complicated because direction values can switch from negative to positive)
else:
if self.direction_end_of_turn < 0 and self.direction_current > self.direction_end_of_turn:
self.direction_current -= self.direction_change_per_frame
elif self.direction_end_of_turn > 0 and self.direction_current > self.direction_end_of_turn - math.pi * (
abs(self.direction_current) - self.direction_current) / abs(self.direction_current):
self.direction_current -= self.direction_change_per_frame
# Update horizontal position
self.position_horizontal += math.cos(self.direction_current) * self.speed_current / FRAME_RATE
# Update horizontal position
self.position_vertical += math.sin(self.direction_current) * self.speed_current / FRAME_RATE
self.frame_number_current += 1 # Increase frame counter (determines end of turn)
# Draws the animal
def draw(self):
pygame.draw.circle(house.program_window, self.color, (round(self.position_horizontal),
round(self.position_vertical)), self.radius, 0)
# The Cat class is almost identical to the parent class Animal
# Cats, just like raptors, don't know fear so they don't need any special behavior
class Cat(Animal):
def __init__(self):
Animal.__init__(self, CAT_BEHAVIOR) # Cat-specific movement
# Executes cat turn
def do_turn(self):
if self.in_buffer(): # Move towards center when in buffer zone (close to edges)
self.do_turn_in_buffer()
else: # Else stay relaxed and move random
self.do_turn_relaxed()
self.edit_parameters_after_doing_turn() # General stuff after turn of all Animals
# Mouses are cowards and run away from cats, so they need more special features
class Mouse(Animal):
def __init__(self):
Animal.__init__(self, MOUSE_BEHAVIOR) # Mouse-specific movement (quicker than cats)
# Angle tolerance when mouse flees from cat [rad]
self.turn_angle_tolerance_cat = MOUSE_TURN_ANGLE_TOLERANCE_CAT
self.distance_panic = MOUSE_DISTANCE_PANIC # Distance to a cat that makes mice panic and flee [px]
self.speed_panic = MOUSE_SPEED_PANIC # Mice run extra fast when they panic [px/s]
self.turn_speed_panic = MOUSE_TURN_SPEED_PANIC # Mice turn extra fast when they panic [rad/s]
# Mice panic for short durations at a time, which sometimes makes them run zig-zag (looks nice) [s]
self.turn_time_panic = MOUSE_TURN_TIME_PANIC
self.is_near_cat = None # Is me near cat? (true if cat near) [bool]
# Checks if cat is near. Returns ID of cat if cat is near, otherwise returns false [ID or bool]
def near_cat(self):
for i in House.cats:
if math.sqrt((self.position_horizontal - i.position_horizontal) ** 2 +
(self.position_vertical - i.position_vertical) ** 2) < self.distance_panic:
return i
return False
# Executes mouse turn
def do_turn(self):
self.is_near_cat = self.near_cat()
if self.is_near_cat is not False: # Fleeing from cats is first priority
self.do_turn_near_cat()
elif self.in_buffer(): # Only think about buffer zone when far away from cats
self.do_turn_in_buffer()
else:
self.do_turn_relaxed() # Else, stay relaxed and move slowly and randomly
self.edit_parameters_after_doing_turn() # General stuff after turn of all Animals
# Executes a turn when the mouse is near a cat
def do_turn_near_cat(self):
self.speed_end_of_turn = self.speed_panic # Set speed to panic mode
# Set direction away from cat (with some tolerance)
self.direction_end_of_turn = math.remainder(self.direction_to_point(self.is_near_cat.position_horizontal,
self.is_near_cat.position_vertical) + math.pi, 2 * math.pi) + random.uniform(
-self.turn_angle_tolerance_cat, self.turn_angle_tolerance_cat)
self.acceleration = self.acceleration_max # Set acceleration to maximum
self.turn_speed = self.turn_speed_panic # Set turn speed to panic mode
# Set turn time to panic mode (shorter, makes for nice zig-zag runs sometimes)
self.turn_time = self.turn_time_panic
# Main loop, where it all comes together
if __name__ == "__main__":
# Creates standalone executable
# subprocess.call(
# 'pyinstaller HouseOfCatAndMouse.py --onefile --name HouseOfCatAndMouse --log-level ERROR -w', shell=True)
pygame.init() # Initialize pygame (whatever this does)
house = House() # Build a house and fill it with animals
running = True
while running:
for event in pygame.event.get(): # Check if user terminates program (needed to prevent crash every time)
if event.type == pygame.QUIT:
running = False
house.update_animal_movement() # Update animal movement in the house
house.draw() # Draw house and content
</code></pre>
| [] | [
{
"body": "<p>So many good things, so many weird things.</p>\n\n<p>First of all, I love your comments. They made this review very easy.</p>\n\n<p>With that said, I have a couple major complaints:</p>\n\n<p><code>dict</code> is not very type-safe; it requires you to access common properties by strings. I highly suggest storing those in a class instead, maybe something like AnimalProperties? That would be the smallest step from where you're at now.</p>\n\n<p>My suggestion would be to either take full advantage of named parameters (shoutout to <code>**kwargs</code>), or configure the <code>Cat</code> and <code>Mouse</code> properties externally. Having them in the same script as a dict doesn't really sit too well with me.</p>\n\n<p>And I'd say take a look at whether all of your boolean fields are necessary. For example, in <code>Mouse</code>, <code>self.is_near_cat</code> is only used to hold the result from <code>self.near_cat()</code>, which either seems to either return <code>False</code> (should be <code>None</code>) if not near a <code>Cat</code> or a <code>Cat</code> if it's near one. You can pass that cat value to <code>self.do_turn_near_cat</code> as <code>self.do_turn_near_cat(self, cat)</code>, because that method should require a <code>Cat</code> to begin with, and thus remove the need for that boolean field in <code>Mouse</code>.</p>\n\n<p>Also, avoid writing confusing things like <code>if self.is_near_cat is not False</code>, because I immediately thought \"sooo, if it's <code>True</code>?\" I said to use <code>None</code> above because <code>None</code> is <a href=\"https://docs.python.org/2.4/lib/truth.html\" rel=\"nofollow noreferrer\">falsy</a>.</p>\n\n<p>To drive that particular example home:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> # Checks if cat is near. Returns ID of cat if cat is near, otherwise returns false [ID or bool]\n def near_cat(self):\n for i in House.cats:\n if math.sqrt((self.position_horizontal - i.position_horizontal) ** 2 +\n (self.position_vertical - i.position_vertical) ** 2) < self.distance_panic:\n return i\n return None\n\n # Executes mouse turn\n def do_turn(self):\n near_cat = self.near_cat()\n if near_cat: # Fleeing from cats is first priority\n self.do_turn_near_cat(near_cat)\n elif self.in_buffer(): # Only think about buffer zone when far away from cats\n self.do_turn_in_buffer()\n else:\n self.do_turn_relaxed() # Else, stay relaxed and move slowly and randomly\n self.edit_parameters_after_doing_turn() # General stuff after turn of all Animals\n\n # Executes a turn when the mouse is near a cat\n def do_turn_near_cat(self, cat):\n self.speed_end_of_turn = self.speed_panic # Set speed to panic mode\n # Set direction away from cat (with some tolerance)\n self.direction_end_of_turn = math.remainder(self.direction_to_point(cat.position_horizontal,\n cat.position_vertical) + math.pi, 2 * math.pi) + random.uniform(\n -self.turn_angle_tolerance_cat, self.turn_angle_tolerance_cat)\n self.acceleration = self.acceleration_max # Set acceleration to maximum\n self.turn_speed = self.turn_speed_panic # Set turn speed to panic mode\n # Set turn time to panic mode (shorter, makes for nice zig-zag runs sometimes)\n self.turn_time = self.turn_time_panic\n</code></pre>\n\n<p>There are many details like this, so try to look at all your functions, what they require, and model those appropriately, and take a closer look at the necessity of all your class fields.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:29:14.727",
"Id": "433257",
"Score": "0",
"body": "Thanks! About the dict-part, would it make sense to store the values inside an own class from the OOP-point-of-view? (It's not like they are a seperate \"physical entity\" from the actual animal). Also, as you mention the **kwargs, would it be better practice to use **kwargs or a class here?\nAlso thanks for the near_cat example, would've never thought of doing it like this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:46:03.427",
"Id": "433262",
"Score": "1",
"body": "I agree with @AleksandrH. The repetition of those named values indicates that they are better served as properties of the `Animal` class. `**kwargs` is mostly just to add extra named properties, but since the extra named properties for `Mouse` seem mandatory, I would advise not using it here. Instead, I would suggest accepting them in the init method as named parameters with your configured values as defaults."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:54:02.880",
"Id": "223447",
"ParentId": "223437",
"Score": "3"
}
},
{
"body": "<p>I'll comment on two specific things I noticed while briefly reviewing (I hope I don't come across as harsh where I'm just stating observations):</p>\n\n<ul>\n<li><p><strong>OOP</strong>: One thing that stood out to me immediately is the dictionaries. The beauty of OOP is that it allows object hierarchies, and for those objects to inherit properties from their base class. A good rule of thumb: If you ever find yourself copy-pasting code, you're doing something wrong. Both <code>CAT_BEHAVIOR</code> and <code>MOUSE_BEHAVIOR</code> have the same entries in the dictionary with just different value assignments—why not make those keys properties of the <code>Animal</code> base class?</p></li>\n<li><p><strong>Comments and functions</strong>: For the math calculations, your comments were helpful (even though I still didn't understand the math; I didn't have time to carefully review it, unfortunately). That said, there are a lot of \"useless\" comments, or ones that don't belong in good code. These are \"what\" comments that basically restate what the code is doing instead of providing insight. For example, <code>mice = None # Object to store all the mice</code>, <code>House.mice = [] # Object to store all the mice</code>, and <code>self.create_mice() # Create all the mice</code>. And of course their cat variants. As well as these two: <code># Create self.mice_number mice in the house</code> and <code># Draw all the mice</code>. There are also comments on things that are in fact unclear because of poor naming (either on your part or pygame's). For example: <code>pygame.display.flip() # Update whole window area</code>. I would wrap this in a function named exactly that: <code>update_window_area(self)</code>. But this by far is the worst offender, in my opinion: <code>edit_parameters_after_doing_turn() # General stuff after turn of all Animals</code>. Not only is the function itself quite long and doing multiple complex computations, but the name itself is also not too informative (and the comment doesn't help!). Consider giving each animal an <code>Update</code> method—<code>Update</code> is pretty idiomatic in game dev as a loop that should run on each frame update/tick. Within <code>Update</code>, use multiple low-level methods that do one thing each.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:12:34.633",
"Id": "433251",
"Score": "0",
"body": "Thanks! About the first part, how could I make the values part of the animal-class if they are different for cat and mice? Would I just set them to \"None\" in the animal-class and define them in the cat/mouse-class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:22:03.373",
"Id": "433254",
"Score": "1",
"body": "You'd define properties using `self.propertyName = value` and then set the values within the concrete derived classes. Search \"python inheritance\" online for some examples if you're curious :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:25:19.630",
"Id": "433255",
"Score": "0",
"body": "So I would give every animal some \"base stats\" that are later overridden in the child classes, is this correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T00:41:05.537",
"Id": "433303",
"Score": "1",
"body": "@MaxD If by base stats you mean properties that belong to all `Animal`s (all instances of the `Animal` class), then yep. All derived classes (classes that extend `Animal`) will inherit those properties. Meaning in the mouse class, you could do `self.nameOfPropertInBaseClass` to set the value. Of course, the derived classes need not only rely on their base class properties; they can also define some of their own."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:33:50.840",
"Id": "223462",
"ParentId": "223437",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:40:25.667",
"Id": "223437",
"Score": "3",
"Tags": [
"python",
"beginner",
"object-oriented",
"pygame"
],
"Title": "Object-oriented cat-and-mouse in Pygame"
} | 223437 |
<p>I don't find this algorithm in Go language here, so I just want to check that it is really most efficient algorithm in Go:</p>
<pre><code>func checkUnique(s *string) bool {
var a [256]bool
for _, ascii := range *s {
if a[ascii] {
return false
}
a[ascii] = true
}
return true
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T11:48:04.867",
"Id": "433625",
"Score": "0",
"body": "There is no reason what-so-ever to use a `*string` argument here instead of a simple `string`. Although Go is pass-by-value the value of a Go `string` is effectively two int-sized values (an integer string length and a pointer to the start of the string) so passing a string of any size by value is efficient."
}
] | [
{
"body": "<p>This is about the most efficient strategy you can get when it comes to uniqueness checking on a string, as far as I know. It can get pretty crazy with memory inefficiency with bigger data types, but it's still O(N) time.</p>\n\n<p>But unless you are specifically dealing with ASCII-only strings, be careful with hardcoding the size of your filter array. Go will try to parse the string into single Unicode code points, also called <a href=\"https://golang.org/ref/spec#Rune_literals\" rel=\"nofollow noreferrer\">runes</a>. You can find an example of that <a href=\"https://golang.org/doc/effective_go.html#for\" rel=\"nofollow noreferrer\">here</a>, which explicitly shows how characters can span multiple bytes.</p>\n\n<p>Based on the answer to <a href=\"https://stackoverflow.com/questions/10229156/how-many-characters-can-utf-8-encode/10229225\">this SO question</a>, UTF-8 encoding can be anywhere from 1-4 bytes. Using the same strategy, a bool array that handles all 4 possible bytes would be of size <pre>2<sup>32</sup> = 4,294,967,296</pre></p>\n\n<p>Yikes, over 4GB of almost entirely unused memory. The most memory-efficient way I can think of approaching that would be a 256-way tree, where you track each byte encountered by creating nodes for each byte in the rune, and check for the rune by checking for existence of each node in order.</p>\n\n<p>Is it still linear time? Well, existence is easy because the depth of the 256-way tree is <em>at most</em> 4, given the maximum number of bytes in a UTF-8 character, so we check for at most 4 things, which is constant. Same kind of logic applies to setting node values when we encounter unique runes. Since these are done per rune, it's still O(N), more memory efficient, and handles all UTF-8 characters.</p>\n\n<p>I've actually never worked with Go before, thanks for inspiring me to research a bit :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T05:07:10.677",
"Id": "433316",
"Score": "1",
"body": "You don't need an array of length \\$2^{32}\\$, it's enough to have 0x110000 since the maximum Unicode code point is U+10FFFF, which is a little over one million, not 4 billion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T17:00:58.750",
"Id": "433399",
"Score": "2",
"body": "Another alternative to using an array would be to use a `map[rune]bool`. So as you go along insert runes into the map, then check if a value is in the map: `_, ok := m[curr]`, etc. While it may not be [guaranteed](https://stackoverflow.com/a/29690063/6789498) \\$O(1)\\$ insert, I assume the Go runtime has heavily optimized maps."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:10:36.670",
"Id": "223444",
"ParentId": "223438",
"Score": "4"
}
},
{
"body": "<p>In Go, string character values are Unicode characters encoded in UTF-8. UTF-8 is a variable-length encoding which uses one to four bytes per character.</p>\n\n<p>Rewriting your ASCII code for Unicode,</p>\n\n<p><code>unique.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"unicode/utf8\"\n)\n\nfunc ascii(s string) (int, bool) {\n if len(s) > utf8.RuneSelf {\n return 0, false\n }\n\n var ascii [utf8.RuneSelf]bool\n for i := 0; i < len(s); i++ {\n b := int(s[i])\n if b >= utf8.RuneSelf {\n return 0, false\n }\n if ascii[b] {\n return len(s), false\n }\n ascii[b] = true\n }\n return len(s), true\n}\n\nfunc hashmap(s string) bool {\n var chars = make(map[rune]struct{}, len(s)/(utf8.UTFMax-1))\n for _, r := range s {\n if _, ok := chars[r]; ok {\n if r != utf8.RuneError {\n return false\n }\n }\n chars[r] = struct{}{}\n }\n return true\n}\n\nfunc unique(s string) bool {\n if i, u := ascii(s); i >= len(s) {\n return u\n }\n\n var chars []uint8\n for _, r := range s {\n if int(r) >= 8*len(chars) {\n var t []uint8\n if r >= rune(1<<16) {\n if len(s) <= 1000 {\n return hashmap(s)\n }\n t = make([]uint8, (utf8.MaxRune+1+7)/8)\n } else if r >= rune(1<<8) {\n t = make([]uint8, (1<<16)/8)\n } else {\n t = make([]uint8, (1<<8)/8)\n }\n copy(t, chars)\n chars = t\n }\n char := chars[r/8]\n if char&(1<<uint(r%8)) != 0 {\n if r != utf8.RuneError {\n return false\n }\n }\n char |= (1 << uint(r%8))\n chars[r/8] = char\n }\n return true\n}\n\nfunc main() {\n var r [utf8.MaxRune + 1]rune\n for i := range r {\n r[i] = rune(i)\n }\n s := string(r[:])\n fmt.Println(unique(s))\n r[0] = r[len(r)-1]\n s = string(r[:])\n fmt.Println(unique(s))\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/31i7YLzJDhM\" rel=\"nofollow noreferrer\">https://play.golang.org/p/31i7YLzJDhM</a></p>\n\n<p>Output:</p>\n\n<pre><code>true\nfalse\n</code></pre>\n\n<hr>\n\n<p>A benchmark using the 95 printable ASCII characters.</p>\n\n<pre><code>$ go test unique.go ascii_test.go -bench=. -benchmem\nasciiChar: n 95; min U+0020; max U+007E\nBenchmarkASCII-8 18052088 66.0 ns/op 0 B/op 0 allocs/op\n$\n</code></pre>\n\n<p><code>ascii_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"testing\"\n \"unicode\"\n)\n\n// ASCII printable characters\n// asciiChar: n 95; min U+0020; max U+007E\nvar asciiChar = func() []rune {\n var ascii []rune\n for r := rune(0); r <= unicode.MaxASCII; r++ {\n if unicode.IsPrint(r) {\n ascii = append(ascii, r)\n }\n }\n fmt.Printf(\"asciiChar: n %d; min %U; max %U\\n\", len(ascii), ascii[0], ascii[len(ascii)-1])\n return ascii\n}()\n\nvar u bool\n\nfunc BenchmarkASCII(b *testing.B) {\n s := string(asciiChar)\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n u = unique(s)\n if !u {\n b.Fatal(u)\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>A benchmark (stress test) using the 89,233 Unicode Han script characters. For Version 12.0 of the Unicode Standard (2019) there are a total of 137,929 characters.</p>\n\n<pre><code>$ go test unique.go han_test.go -bench=. -benchmem\nhanChar: n 89233; min U+2E80; max U+2FA1D\nBenchmarkHan-8 1602 740748 ns/op 147456 B/op 2 allocs/op\n$\n</code></pre>\n\n<p><code>han_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"testing\"\n \"unicode\"\n)\n\n// Unicode Han script\n// hanChar: n 89233; min U+2E80; max U+2FA1D\nvar hanChar = func() []rune {\n var han []rune\n for r := rune(0); r <= unicode.MaxRune; r++ {\n if unicode.In(r, unicode.Han) {\n han = append(han, r)\n }\n }\n fmt.Printf(\"hanChar: n %d; min %U; max %U\\n\", len(han), han[0], han[len(han)-1])\n return han\n}()\n\nvar u bool\n\nfunc BenchmarkHan(b *testing.B) {\n s := string(hanChar)\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n u = unique(s)\n if !u {\n b.Fatal(u)\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T05:10:42.157",
"Id": "433317",
"Score": "0",
"body": "You didn't review the code but presented an alternative solution, without even explaining anything. That's against the spirit of this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T05:26:14.067",
"Id": "433318",
"Score": "1",
"body": "@RolandIllig: I did review the code. The code is for extended ASCII,. In Go, it should be for Unicode."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:25:16.150",
"Id": "223487",
"ParentId": "223438",
"Score": "0"
}
},
{
"body": "<p>Why not use a golang map as mentioned in one of the comments above?</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func unique(arr string) bool {\n m := make(map[rune]bool)\n for _, i := range arr {\n _, ok := m[i]\n if ok {\n return false\n }\n\n m[i] = true\n }\n\n return true\n}\n</code></pre>\n<p>Time complexity would be O(1) for insertion most of the time and in O(N) it would be done.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T14:37:08.413",
"Id": "251210",
"ParentId": "223438",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223444",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T18:40:54.423",
"Id": "223438",
"Score": "4",
"Tags": [
"performance",
"strings",
"go"
],
"Title": "Check whether a string has all unique characters (time efficiency)"
} | 223438 |
<p>An update to this post can be found <a href="https://codereview.stackexchange.com/questions/223587/finding-paths-between-triangles-efficiently-in-3d-geometry-updated">here</a></p>
<p>I've been writing some functions used to find paths between two types of triangles - alphas and betas. Alphas are triangles that have been in a zone we consider important, have an "interesting" value above a given threshold, and are "active". Betas are essentially anything that isn't an Alpha. </p>
<p>The position of the zone and the geometry of the model can change between invocations.</p>
<p>This is written in C++03, compiled into a MEX file (.mexw64) to be executed by MATLAB R2016B on a Linux machine. Those are all hard limits.</p>
<p>This code uses a good deal of functions and data from an external libraries and objects. However, most of the methods used are very simple array lookups, nothing performance-hindering. </p>
<p>Everything works correctly so far in testing, but performance has become a significant problem.</p>
<p><strong>The code:</strong></p>
<pre><code>// Doxygen block exists here
// Various includes go here
// Only needed because ultimately MATLAB needs an error code, not a C++
// exception
#define SUCCESS 0
#define DYN_ALLOC_ERR 1
#define PTHREAD_ERR 2
/*
* Design notes: I considered having a modified version of the geometry checking
* section that just pushed _new_ alphas onto the global vector of alphas
* and set a flag to cull old ones, but that actually seemed significantly less
* efficient than just making a new one each time since all the same checks need
* to be made regardless however, if validAlphas gets very large, this could
* be highly inefficient due to push_back, so the idea of pushing on
* just new ones and culling may actually be the best solution.
*
* Also: Could maintain a sum of validAlphas and use that to re-size it upon
* re-creation to save some overhead from resizing, maybe?
*/
// The indices of two triangles who have a valid alpha and a beta that can
// be seen from it. 120k paths * 8 bytes per pair = ~1GB on the heap.
// No, ushort won't be enough here.
struct ABPair
{
unsigned int alphaTriIndex;
unsigned int betaTriIndex;
};
// Useful for multithreading, stolen and modified from craytracer.h
struct ThreadData
{
CRayTracer* rt;
pthread_t threadId; // ID returned by pthread_create
unsigned uThreadID; // Index
std::vector<ABPair*> validPathsThread; // valid pairs that this thread
// found
unsigned int numTris; // Input argument, the number of
// triangles in the mesh
double distThreshold; // Input argument, the maximum
// distance between triangles
};
// Exceptions for experimentation
class PThreadException: public std::exception
{
virtual const char* what() const throw()
{
return "Exception occured in a pthread_attr_init or pthread_create\n";
}
};
class DynAllocationException: public std::exception
{
virtual const char* what() const throw()
{
return "Exception occured when attempting to malloc or calloc\n";
}
};
// Note: Globals must exist here so that when the MEX file exits and goes
// Back to MATLAB, this information is maintained.
// (AFAIK, mexMakeMemoryPersistant() wouldn't make sense here. I can link
// to discussions on that topic)
// An indicator for every tri to tell if it has been removed (neccesary for
// maintaining previous state to check if we need to call findPaths())
static bool* triActive = NULL;
// A map from a given face to the element it resides in
static unsigned int* faceToElementMap = NULL;
// All valid paths. Must be maintained, because we don't know if
// findPaths() will be called. It may not be if geometry hasnt changed.
static std::vector<ABPair*> validPaths;
// The previous state of what alphas were considered valid. Neccesary to see
// if a change has occured that isn't geometry-based.
static unsigned int* validAlphaIndex;
// Not neccesary as a global if it's just getting re-generated each time.
// However, if we do decide to append and cull instead of regenerating, this
// needs to stay.
static std::vector<unsigned int> validAlphas;
// Needed so we can accurately determine alphas.
// I removed this in the past, thinking it wasn't needed. As it turns out,
// it's absolutely needed and very helpful.
static bool* hasBeenInZone;
// Useful everywhere
CRayTracerClass* rayTracer = NULL;
NanoRTWrapperClass nanoRTWrapper = NULL;
// Function declarations
// Not required, but prevents warnings depending on how functions are ordered
// and call each other
// (Including the mexFunction here would be redundant, as it exists in mex.h)
void exitFcn();
bool isTriInZoneRadius(const unsigned int itri);
bool checkForModelChanges(const unsigned int numTris,
const float* iValues,
const double iThreshold
);
void initialize(const float* elemFace,
const unsigned int numElems,
const unsigned int facePerElMax,
unsigned int* numTri,
unsigned int* numFace
);
void* findPathsThread(void *data);
void findPathsThreadSpooler(const unsigned int numTris,
const double distThreshold
);
void mapFacesToElements(const float* elemFace,
const unsigned int numElems,
const unsigned int facePerElMax
);
bool checkPairValid(const unsigned int i,
const unsigned int j,
const double distThreshold
);
bool isTriAlpha(const unsigned int itri,
const float* iValues,
const double iThreshold
);
void findPaths(const unsigned int numTris,
const double distThreshold
);
//mainfunc declaration goes here
/**
* @brief exitFcn - Cleans up malloc'd or calloc'd memory if someone in the
* MATLAB script calls "clear mexfilename" or "clear all".
*/
void exitFcn()
{
//mexPrintf("exitFcn() called\n");
if(triActive)
{
free(triActive);
}
if(faceToElementMap)
{
free(faceToElementMap);
}
if(validAlphaIndex)
{
free(validAlphaIndex);
}
if(hasBeenInZone)
{
free(hasBeenInZone);
}
for(unsigned int i = 0; i < validPaths.size(); i++)
{
free(validPaths[i]);
}
}
/**
* @brief Checks if a given tri is currently in the zone's external radius.
* Implementation stolen from CRayTracerClass::trace_inverseray_tri
* Not sure if we need to raytrace, so I omitted it
* @param itri - The index of the triangle to check
* @return True if in the radius, false if not
*/
bool isTriInZoneRadius(const unsigned int itri)
{
//Omitted
}
/**
* @brief Checks if the model has changed (either in terms of alphas or
* geometry) and re-generates the vector of alphas
* @param numTris - The number of triangles in the finite mesh
* @param iValues - The ivalue at each node
* @param iThreshold - The interesting value threshold beyond which an alpha
* is interesting enough to be valid
* @return True if the list of alphas or the geometry has changed, false if
* neither have
*/
bool checkForModelChanges(const unsigned int numTris,
const float* iValues,
const double iThreshold
)
{
bool modelChanged = false;
bool isAlpha;
bool currentlyActive;
// Two checks need to happen - geometry changes and for the list of valid
// alphas to change
// Also regenerates the vector of valid alphas from scratch as it goes
for(unsigned int i = 0; i < numTris; i++)
{
// Active means it has 1 exposed face, not 2 (internal) or 0 (gone)
currentlyActive = nanoRTWrapper->getTriActive(i);
// Has the geometry changed?
if(currentlyActive != triActive[i])
{
modelChanged = true;
triActive[i] = currentlyActive;
}
// Get whether this triangle is an alpha:
isAlpha = isTriAlpha(i, iValues, iThreshold);
// Triangle is a valid alpha now, but wasn't before
if((isAlpha == true) && (validAlphaIndex[i] == false))
{
validAlphaIndex[i] = true;
modelChanged = true;
}
// Was valid before, is no longer valid now
else if((isAlpha == false) && (validAlphaIndex[i] == true))
{
validAlphaIndex[i] = false;
modelChanged = true;
//cullalphasFlag = true;
}
// Generating the set of all valid alphas
if(isAlpha)
{
validAlphas.push_back(i);
}
}
return modelChanged;
}
/**
* @brief Initializes this MEX file for its first run
* @param rt - A pointer to the raytracer object
* @param numTris - The total number of triangles in the finite mesh
* @param numFaces - The total number of faces in the finite mesh
* @param elemFace - The map of elements to the faces that they have
* @param numElems - The number of elements in the finite mesh
* @param facePerElMax - The maximum number of faces per element
*/
void initialize(const float* elemFace,
const unsigned int numElems,
const unsigned int facePerElMax,
unsigned int* numTri,
unsigned int* numFace
)
{
DynAllocationException e;
// Fetch number of tris and faces
// Must be done every time, since we're storing locally and not globally
// However:
// They're never modified
// They never change between calls from the MATLAB script
// They're used frequently in many functions
// I think that's a strong candidate for being a global
unsigned int numTris = nanoRTWrapper->getTriCount();
*numTri = numTris;
unsigned int numFaces = nanoRTWrapper->getFaceCount();
*numFace = numFaces;
/*
* Allocate some space for things we need to be persistent between runs of
* this MEX file. And check that the allocation succeeded, of course.
*/
if(triActive == NULL)
{
if(NULL ==
(triActive =
static_cast<bool*>(calloc(numTris, sizeof(bool))))
)
{
throw e;
}
}
if(hasBeenInZone == NULL)
{
if(NULL ==
(hasBeenInZone =
static_cast<bool*>(calloc(numTris, sizeof(bool))))
)
{
throw e;
}
}
if(validAlphaIndex == NULL)
{
if(NULL ==
(validAlphaIndex =
static_cast<unsigned int*>(calloc(numTris, sizeof(unsigned int))))
)
{
throw e;
}
}
if(faceToElementMap == NULL)
{
if(NULL ==
(faceToElementMap =
static_cast<unsigned int*>(calloc(numFaces, sizeof(unsigned int))))
)
{
throw e;
}
mapFacesToElements(elemFace, numElems, facePerElMax);
}
return;
}
/**
* @brief Is something that can be used by pthread_create(). Threads will skip
* over some of the work, and do isValidPair on others. Thus...multithreading.
* @param data - The data structure that will hold the results and arguments
*/
void* findPathsThread(void *data)
{
struct ThreadData* thisThreadsData = static_cast<struct ThreadData*>(data);
const unsigned uThreadID = thisThreadsData->uThreadID;
const unsigned uNumThreads = rayTracer->m_uNumThreads;
const double distThreshold = thisThreadsData->distThreshold;
const unsigned int numTris = thisThreadsData->numTris;
std::vector<ABPair*>& validPathsThread = thisThreadsData->validPathsThread;
// Loop over all valid alphas
for(unsigned int i = 0; i < validAlphas.size(); i++)
{
if ((i % uNumThreads) == uThreadID)
{
// Loop over all triangles (potential betas)
for(unsigned int j = 0; j < numTris; j++)
{
if(checkPairValid(i, j, distThreshold))
{
ABPair* temp =
static_cast<ABPair*>(malloc(sizeof(ABPair)));
temp->alphaTriIndex = validAlphas[i];
temp->betaTriIndex = j;
validPathsThread.push_back(temp);
}
}
}
}
return NULL;
}
/**
* @brief Creates as many threads as the system has available, and then uses
* pthread_create() to dish out the work of findPaths()
* @param numTris - The number of triangles in the finite mesh
* @param distThreshold - The maximum distance an alpha and beta can be
* apart
*/
void findPathsThreadSpooler(const unsigned int numTris,
const double distThreshold
)
{
std::vector<ThreadData> threadData(rayTracer->m_nProc);
pthread_attr_t attr;
int rc;
PThreadException e;
// I think this is checking to make sure something doesn't already exist,
// not sure what though
if((rc = pthread_attr_init(&attr)))
{
throw e;
}
// We know how many threads the system supports
// So all this does is walk through an array of them and start them up
for(unsigned uThread = 0; uThread < rayTracer->m_uNumThreads; uThread++)
{
ThreadData& data = threadData[uThread];
data.rt = rayTracer;
data.uThreadID = uThread;
data.numTris = numTris;
data.distThreshold = distThreshold;
if(rayTracer->m_uNumThreads > 1)
{
if((rc = pthread_create(&data.threadId, &attr, &findPathsThread, &data)))
{
throw e;
}
}
else
{
findPathsThread(&data);
}
}
// Join all threads
for(unsigned uThread = 0; uThread < rayTracer->m_uNumThreads; uThread++)
{
std::vector<ABPair*>& validPathsThread =
threadData[uThread].validPathsThread;
if(rayTracer->m_uNumThreads > 1)
{
void* res;
if((rc = pthread_join(threadData[uThread].threadId, &res)))
{
throw e;
}
}
// validPathsThread is the set of ABPairs that this thread found
// while validPaths is the globally maintained set of valid paths
// Take each thread's results and merge it into the overall results
validPaths.insert(validPaths.end(),
validPathsThread.begin(),
validPathsThread.end());
}
return;
}
/*
void cullAlphas()
{
for(unsigned int i = 0; i < validAlphas.size(); i++)
{
if(!isValidAlpha(validAlphas[i]))
{
validAlphas.erase(i);
}
}
}
*/
/**
* @brief Determines the elements that each face belongs to
* @details the MATLAB script maintains a map of all faces per element.
* This is the opposite of what we want. Accessing it linearly
* walks by column, not by row. Also, MATLAB stores everything 1-indexed.
* Finally, the MATLAB script left them stored as the default, which are singles.
* @param elemFace - A MATLAB facePerElMax by numElems array, storing which
* faces belong to each element (elements being the row number)
* @param numElems - The total number of elements (rows) in the array
* @param facePerElMax - The max number of faces per element (the number of
* columns)
*/
void mapFacesToElements(const float* elemFace,
const unsigned int numElems,
const unsigned int facePerElMax
)
{
unsigned int i;
// elemFace[0] = 1. We don't know how elemFace will be structured precisely,
// so we need to keep going until we find a face in it that equals our number
// of faces, since it's 1-indexed.
for(i = 0; i < (numElems * facePerElMax); i++)
{
faceToElementMap[static_cast<unsigned int>(elemFace[i]) - 1] =
(i % numElems);
// Is the next face for that element a NaN? If so, we can skip it. Keep
// skipping until the next element WON'T be NaN.
// Don't cast here, as NaN only exists for floating point numbers,
// not integers.
while(isnan(elemFace[i + 1]) && ((i + 1) < (numElems * facePerElMax)))
{
i++;
}
}
}
/**
* @brief checkPairValid - Checks if a pair of an alpha index (of validAlphas),
* beta index form a valid path
* @param i - Index into validAlphas
* @param j - Index into all tris (potential beta)
* @param distThreshold - The max distance the tri's centers can be apart
* @return Whether the pair forms a valid path
*/
bool checkPairValid(const unsigned int i,
const unsigned int j,
const double distThreshold
)
{
double path_dist_sqrd;
double path_dist;
double alphaCoords[3];
double betaCoords[3];
nanort::Ray<double> ray;
// If they're not an alpha currently, they must be a potential beta,
// must also be alive
if(!validAlphaIndex[j] && triActive[j])
{
alphaCoords[0] =
rayTracer->m_vecTriFixedInfo[validAlphas[i]].center.x();
alphaCoords[1] =
rayTracer->m_vecTriFixedInfo[validAlphas[i]].center.y();
alphaCoords[2] =
rayTracer->m_vecTriFixedInfo[validAlphas[i]].center.z();
betaCoords[0] = rayTracer->m_vecTriFixedInfo[j].center.x();
betaCoords[1] = rayTracer->m_vecTriFixedInfo[j].center.y();
betaCoords[2] = rayTracer->m_vecTriFixedInfo[j].center.z();
// Determine distance squared between alpha and beta
// (x2-x1)^2 + (y2-y1)^2 +(z2-z1)^2
path_dist_sqrd = pow((betaCoords[0] - alphaCoords[0]), 2)
+ pow((betaCoords[1] - alphaCoords[1]), 2)
+ pow((betaCoords[2] - alphaCoords[2]), 2);
// Doing this instead of doing the sqrt to save doing the sqrt when not
// needed for performance
if(path_dist_sqrd <= pow(distThreshold, 2))
{
path_dist = sqrt(path_dist_sqrd);
// Set up a nanort::Ray's origin, direction, and max distance
ray.org[0] = alphaCoords[0]; // x
ray.org[1] = alphaCoords[1]; // y
ray.org[2] = alphaCoords[2]; // z
ray.dir[0] = (betaCoords[0] - alphaCoords[0]) / path_dist;
ray.dir[1] = (betaCoords[1] - alphaCoords[1]) / path_dist;
ray.dir[2] = (betaCoords[2] - alphaCoords[2]) / path_dist;
// TODO: Subtract some EPSILON here so it doesn't report a hit because it
// hit the beta itself (assuming that's how it works)
ray.max_t = path_dist;
// Call ShootRay() to check if there is a path (calls nanoRT)
if(!(nanoRTWrapper->shootRay(ray)))
{
return true;
}
else
{
// There's no path
return false;
}
}
else
{
// The distance is too far between alpha and beta
return false;
}
}
else
{
// The beta is either dead or currently an alpha
return false;
}
}
/**
* @brief Determines if a given triangle is a valid alpha.
* @param itri - The triangle index to check
* @return True if it is an alpha, false if it is not
*/
bool isTriAlpha(const unsigned int itri,
const float* iValues,
const double iThreshold
)
{
double tri_avg_interesting;
const unsigned int* tri_nodes;
// Do the simple checks first, as it's more performant to do so
// alternate consideration (acccuracy, wouldn't affect performance)
//if(triActive[itri] && (hasBeenAlpha[itri] || isTriInZoneRadius(itri)))
if(triActive[itri] && (hasBeenInZone[itri] || isTriInZoneRadius(itri)))
{
// Retrieve the average iValue of this triangle
tri_nodes = nanoRTWrapper->getTriNodes(itri);
tri_avg_interesting = (iValues[tri_nodes[0]]
+ iValues[tri_nodes[1]]
+ iValues[tri_nodes[2]]) / 3;
if(tri_avg_interesting > iThreshold)
{
return true;
}
}
return false;
}
/**
* @brief Uses the raytracer object's current state as well as arguments to
* generate pairs of unobstructed paths between alphas and betas.
* @param numTris - The number of triangles in the finite element mesh
* @param distThreshold - The max distance an alpha and beta pair can be
* apart before not being considered in calculations
*/
void findPaths(const unsigned int numTris,
const double distThreshold
)
{
// This function once held more importance, but yes, it could be omitted
// at this point.
// Spool up some threads to take care of the work
try
{
findPathsThreadSpooler(numTris, distThreshold);
}
catch(DynAllocationException& e)
{
throw e;
}
return;
}
// Doxygen header (omitted)
int mainFunc(args)
{
// Initialize the program if we're on a first run
try
{
initialize(elemFace, numElems, facePerElMax, &numTris, &numFaces);
}
catch(DynAllocationException& e)
{
return DYN_ALLOC_ERR;
}
// Need to see if we need to call findPaths
if(checkForModelChanges(numTris, iValues, iThreshold))
{
// Remove old list of valid paths
for(unsigned int i = 0; i < validPaths.size(); i++)
{
free(validPaths[i]);
}
validPaths.clear();
try
{
findPaths(numTris,
distThreshold);
}
catch(PThreadException& e)
{
return PTHREAD_ERR;
}
}
//mexPrintf("Number of valid paths: %d\n", validPaths.size());
/*
* Walk over all paths and do some calculations
*/
return SUCCESS;
}
// Doxygen block goes here, omitted
void mexFunction(int nlhs,
mxArray *plhs[],
int nrhs,
const mxArray *prhs[]
)
{
// Register exit function
mexAtExit(exitFcn);
// Prep for writing out results
// Checking to make sure # of arguments was right from MATLAB
// Input argument handling to convert from mxArrays to double*, float*, etc
//*errcode = mainFunc(some args)
// retrieve execution time in clock cycles, convert to seconds, print
// Put the outputs in plhs
}
</code></pre>
<p><strong>Callgraph(?):</strong></p>
<p>This isn't exactly a callgraph, but it might be useful to get an idea of the flow of the program.</p>
<p><a href="https://i.stack.imgur.com/gODi8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gODi8.png" alt="enter image description here"></a></p>
<p><strong>The Problem: Performance</strong></p>
<p>For medium-size models (104k tris, 204k faces, 51k elems) it can take up to a couple seconds for this to complete, even though the worst of it is multi-threaded on a powerful 4C/8T machine. (roughly 100*104k size loop)</p>
<p>For any models where the number of alphas is very large (50K) it can take up to <em>three minutes</em> for a single execution to complete because of how large that double-nested for loop must become. (50k^2 size loop)</p>
<p><strong>Possible optimizations:</strong></p>
<p>An optimization that may be worth considering is creating a sphere around all alphas, and use its center and radius to cull the remaining triangles down to a smaller size based on the threshold distance. However, the benefit of this is extremely variable and may actually be zero for smaller meshes. And to create the sphere, we need to find the two triangle centers that are the furthest apart, an O(alphas^2) operation...very slow if there are many. And there's no easy way to tell in advance if using this technique would be beneficial for the given state of the mesh, so it's not easy to toggle on and off as needed.</p>
<p>As well, it's possible something can be done with nanoRT's BVHs, but I'm not very familiar with BVH's or what they'd let me do in this</p>
<p><strong>Note: How it's being used:</strong></p>
<p>The MATLAB script will likely call this many times. In small models, it may finish its own loop within tenths of a second and then call ours again. In larger ones, there may be half a second between calls. In total, this may be called hundreds of times.</p>
<p><strong>Note: How it's being built:</strong></p>
<p>This isn't built using the <code>MEX</code> command in MATLAB, nor by using Visual Studio. Instead, g++ is used to create an object file (.o) and then g++ is used again to create the .mexw64 file in a method I'm not entirely familiar with. (This is also a hard limit I cannot touch)</p>
<p>I occasionally compiled with very aggressive warnings enabled to catch things like sign conversion, promotions, bad casts, etc.</p>
<p><strong>Profiling:</strong></p>
<p>I would love to be able to profile this code. However, it seems impossible. MEX files built using <code>MEX</code> command in MATLAB can be done. MEX files compiled in Visual Studio can be profiled. But we're not doing either of those, and so when I try to profile with either MATLAB or Visual Studio, it just doesn't work.</p>
<p>Even if I could, I don't think it would reveal anything surprising. The numbers we're working with are large, so the double-nested loop at the core of it grows very large.</p>
<p>If need be, I could stick a ton of clock() calls around the start/end of every method to get some more info, though that's not precise. (Line-by-line)</p>
<p><strong>Final Notes:</strong></p>
<p>I'm fresh out of college and this is my first real production code. I'm more familiar with C than C++, so I'm sure that bled into the code. Suggestions for style are always welcome, though performance is the most major concern here.</p>
<p><strong>Update:</strong></p>
<p>Thanks to all for the help. I wish I could mark all 3 answers as solutions, as each were helpful. In total, it's managed to shave 8.2% off of the total runtime. And it's just generally less C-like and more C++ like. I may post an updated question now that this has been taken care of. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:35:29.817",
"Id": "433043",
"Score": "0",
"body": "Is C++11 not usable for you for some reason?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:37:25.817",
"Id": "433044",
"Score": "0",
"body": "@Edward Yes, due the environment this will ultimately be run on C++11 is impossible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:09:07.500",
"Id": "433082",
"Score": "0",
"body": "Why is `mexFunction` mostly empty? It seems your MEX-file doesn’t do anything at all except register the at-exit function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:14:21.227",
"Id": "433083",
"Score": "0",
"body": "@CrisLuengo I omitted that code, as it wasn't relevant to the performance problem and would've just cluttered the post. I just wanted to show that it existed and what it generally did with the comments."
}
] | [
{
"body": "<h2>Efficiency</h2>\n\n<p>Things that jump out.</p>\n\n<pre><code>std::vector<ABPair*> validPathsThread;\n</code></pre>\n\n<p>An array of pointer looks odd. Especially since ABPair is simply a pair of integers. I notice in the code you are using <code>malloc()</code> to allocate them which itself is a very expensive operation.</p>\n\n<p>I would just remove the pointer here:</p>\n\n<p>Then this code:</p>\n\n<pre><code> ABPair* temp =\n static_cast<ABPair*>(malloc(sizeof(ABPair)));\n\n temp->alphaTriIndex = validAlphas[i];\n temp->betaTriIndex = j;\n\n validPathsThread.push_back(temp);\n</code></pre>\n\n<p>simplifies to:</p>\n\n<pre><code> validPathsThread.emplace_back(validAlphas[i], j);\n</code></pre>\n\n<h2>Simplify Types</h2>\n\n<p>You don't need to define your own <code>what()</code> on exceptions.</p>\n\n<pre><code>class PThreadException: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Exception occured in a pthread_attr_init or pthread_create\\n\";\n }\n};\n\nclass DynAllocationException: public std::exception\n{\n virtual const char* what() const throw()\n {\n return \"Exception occured when attempting to malloc or calloc\\n\";\n }\n};\n</code></pre>\n\n<p>Simplify to:</p>\n\n<pre><code>// Exceptions for experimentation\nstruct PThreadException: public std::runtime_exception\n{\n PThreadException(): std::exception(\"Exception occured in a pthread_attr_init or pthread_create\\n\") {}\n};\n\nstruct DynAllocationException: public std::runtime_exception\n{\n DynAllocationException(): std::exception(\"Exception occured when attempting to malloc or calloc\\n\") {}\n};\n</code></pre>\n\n<p>Simple bag types like this:</p>\n\n<pre><code>struct ABPair\n{\n unsigned int alphaTriIndex;\n unsigned int betaTriIndex;\n};\n</code></pre>\n\n<p>Can be simpler defined using standard types.</p>\n\n<pre><code>using ABPair = std::pair<unsigned int, unsigned int>;\n</code></pre>\n\n<h2>Memory Management</h2>\n\n<p>There is a lot of memory management code that looks like C. You should remove all calls to malloc/calloc/free and replace with new/delete then you should remove all references to new/delete with containers (using reserve() or resize() to make sure you have pre-allocated enough space).</p>\n\n<h2>Throwing Exceptions</h2>\n\n<p>Don't do this:</p>\n\n<pre><code> DynAllocationException e;\n ...\n throw e;\n</code></pre>\n\n<p>Just do this:</p>\n\n<pre><code> throw DynAllocationException();\n</code></pre>\n\n<h2>Uneeded Loop</h2>\n\n<pre><code> // Loop over all valid alphas\n for(unsigned int i = 0; i < validAlphas.size(); i++)\n {\n if ((i % uNumThreads) == uThreadID)\n {\n // Do Work\n }\n }\n</code></pre>\n\n<p>This is the same as writing:</p>\n\n<pre><code> for(unsigned int i = uThreadID; i < validAlphas.size(); i += uNumThreads) {\n // Do Work\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:22:25.740",
"Id": "433061",
"Score": "0",
"body": "Are you sure on those exceptions? They're not the same, and both fail for me. The pthread one fails with ```no matching function for call to 'std::exception::exception(const char [60])``` and the DynAllocationException fails with ```error: expected unqualified-id before string constant```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:26:42.957",
"Id": "433062",
"Score": "0",
"body": "I did originally have them as a pair, but converted to a struct before we realized storing some extra information about the paths would be too costly in memory. I do have one question though, could I just revise to validPaths.push_back(std::make_pair(validAlphas[i], j))? Or is there a reason to not go that route?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:06:52.633",
"Id": "433064",
"Score": "0",
"body": "Fixed the exceptions. Yes you can do: `validPaths.push_back(std::make_pair(validAlphas[i], j))` But using `validPaths.emplace_back(validAlphas[i], j)` would be even better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:44:53.107",
"Id": "433067",
"Score": "0",
"body": "Those exceptions still don't seem to work: ```error: expected class-name before '{' token``` right after the inheritance. Also, emplace_back doesn't work either on a vector of pairs,I get ```'class std::vector<std::pair<unsigned int, unsigned int> >' has no member named 'emplace_back'; did you mean 'push_back'?```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:53:46.880",
"Id": "433101",
"Score": "0",
"body": "`std::runtime_exception` is defined in `<stdexcept>`. The method `emplace_back()` comes in `C++11`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:53:36.097",
"Id": "433119",
"Score": "0",
"body": "@MartinYork The answer is great as one expects from you, However, I would to mention the inherent cost of std::pair vs an aggregate, in that the former is more convenient but less expressive. You have to remember what is first and what is second. It comes with all the bells and whistles, but this is a significant cost that should be mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T14:39:00.503",
"Id": "433381",
"Score": "0",
"body": "@MartinYork It looks like it still doesn't work even with stdexcept included. ```error: type 'std::exception' is not a direct base of 'PThreadException'``` and the same for the other one."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:00:53.967",
"Id": "223448",
"ParentId": "223439",
"Score": "5"
}
},
{
"body": "<p>Your double for-loop:</p>\n\n<pre><code> const double distThreshold = thisThreadsData->distThreshold;\n\n for(unsigned int i = 0; i < validAlphas.size(); i++)\n {\n // Loop over all triangles (potential betas)\n for(unsigned int j = 0; j < numTris; j++)\n {\n if(checkPairValid(i, j, distThreshold))\n</code></pre>\n\n<p>calls <code>checkPairValid()</code>:</p>\n\n<pre><code>bool checkPairValid(const unsigned int i,\n const unsigned int j,\n const double distThreshold\n )\n{\n double path_dist_sqrd;\n\n if(!validAlphaIndex[j] && triActive[j])\n {\n alphaCoords[0] = rayTracer->m_vecTriFixedInfo[validAlphas[i]].center.x();\n //...\n\n // Determine distance squared between alpha and beta\n // (x2-x1)^2 + (y2-y1)^2 +(z2-z1)^2\n path_dist_sqrd = pow((betaCoords[0] - alphaCoords[0]), 2)\n + pow((betaCoords[1] - alphaCoords[1]), 2)\n + pow((betaCoords[2] - alphaCoords[2]), 2);\n\n // Doing this instead of doing the sqrt to save doing the sqrt when not\n // needed for performance\n if(path_dist_sqrd <= pow(distThreshold, 2))\n {\n</code></pre>\n\n<p>If you moved the <code>!validAlphaIndex[j] && triActive[j]</code> check out of <code>checkPairValid()</code>, to the caller (the double loop), you could avoid the overhead of the function call when those indices are not valid. Alternately, generate a list of the <code>j</code> indices once, and just loop over the valid indices, replacing <span class=\"math-container\">\\$O(n^2)\\$</span> validity/active checks with a <span class=\"math-container\">\\$O(n)\\$</span> validity/active check.</p>\n\n<p>Also, you are doing calculations on <code>path_dist_sqrd</code> to avoid the square-root. Yet, you are still calling <code>pow(distThreshold, 2)</code> on the order of <span class=\"math-container\">\\$50,000^2\\$</span> times, when that value is constant. <code>pow()</code> is not a fast function, or <code>sqrt(x)</code> would simply be defined as <code>pow(x, 0.5)</code>.</p>\n\n<p>Additionally, each call of <code>checkPairValid()</code> has to look up <code>validAlphas[i]</code>, to get the correct index into <code>rayTracer->m_vecTriFixedInfo[__]</code>. This value is needed three times, and the compiler will likely cache the value. But it will not be cached across the 50,000 calls of the inner loop, where <code>i</code> remains constant. Instead of passing in an index to an index, look up <code>validAlpha[i]</code> in the outer loop, and pass that triangle index to <code>checkPairValid()</code>. Or lookup and cache <code>rayTracer->m_vecTriFixedInfo[validAlphas[i]].center</code> in the outer loop, and pass a reference to that coordinate to <code>checkPairValid()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:44:35.413",
"Id": "433063",
"Score": "0",
"body": "Thanks for the tip on pow(), that makes good sense. I think I was mixing up the speed of doubling (equivalent to a shift) with that pow(x, 2). I've also moved the checks out of checkPairValid to avoid the function call overhead, that's a good catch. The validAlpha[i] as well was a great point, and I've fixed that now. (By the way, what's the practice on this site? Do I update my post with my fixes as I make them?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:08:46.457",
"Id": "433065",
"Score": "1",
"body": "No, don't update your post. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:04:19.140",
"Id": "223449",
"ParentId": "223439",
"Score": "2"
}
},
{
"body": "<p>Just one quick comment to add to the previous answers. You have static variables like this:</p>\n\n<pre><code>static bool* triActive = NULL;\n</code></pre>\n\n<p>These are assigned the pointer to a memory block, and you need an at-exit function to free these memory blocks. In C++ it is considered good practice to avoid “naked pointers” like these. If you follow that advice, you won’t need the at-exit function any more.</p>\n\n<p>For example, you could instead do:</p>\n\n<pre><code>std::vector<bool> triActive;\n</code></pre>\n\n<p>Your <code>initialize</code> function then just needs to resize the array to the appropriate size:</p>\n\n<pre><code>if(triActive.empty())\n triActive.resize(numTris, false);\n</code></pre>\n\n<p>Note that you also don’t need the <code>static</code> keyword here. In file scope, all variables are global, and will live for the duration of the program (since this is a DLL/SO, for the duration of it being loaded in memory). <code>static</code> here means to not make it visible outside the file.</p>\n\n<p>Inside a function, the <code>static</code> keyword means to keep the variable alive in between function calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:17:28.387",
"Id": "433084",
"Score": "0",
"body": "I suppose it's not obvious, but that's a C-style way of showing an array. So faceToElementMap, validAlphaIndex, hasBeenInZone, etc, are all arrays, which get malloc'd for many, many values. (hundreds of thousands depending on the size of the mesh)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:30:07.660",
"Id": "433085",
"Score": "0",
"body": "@Tyler: You’re right, sorry, I didn’t read the code carefully enough. I’ve changed the answer to suggest something different with these static variables."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:14:35.303",
"Id": "223468",
"ParentId": "223439",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223449",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T19:19:00.323",
"Id": "223439",
"Score": "3",
"Tags": [
"c++",
"performance",
"matlab",
"c++03"
],
"Title": "Finding paths between triangles efficiently in 3D geometry"
} | 223439 |
<p>This is my attempt on the Python 3 Sal's Shipping challenge on Codecademy (<a href="https://www.codecademy.com/courses/learn-python-3/projects/sals-shipping?action=resume_content_item" rel="nofollow noreferrer">Challenge Link</a> (instructions in the link)).</p>
<p>I'd really appreciate anyone to take the time to review my code. I'm a very new to programming and I really wanna improve my coding, so all feedback is apreciated.</p>
<pre><code>def groundCost(weight):
if weight > 10:
cost = weight * 4.75
elif weight > 6:
cost = weight * 4
elif weight > 2:
cost = weight * 3
else:
cost = weight * 1.5
cost += 20
return cost
def droneCost(weight):
if weight > 10:
cost = weight * 14.25
elif weight > 6:
cost = weight * 12
elif weight > 2:
cost = weight * 9
else:
cost = weight * 4.5
return cost
def costCalc(weight):
g = groundCost(weight)
p = 125
d = droneCost(weight)
gS = "Ground Shipping"
pS = "Premium Ground Shipping"
dS = "Drone Shipping"
if d == g or d == p or g == p:
if d == g and d == p:
print("All shipping methods cost $125 according to your items weight")
return
if d == g:
same1 = dS
same2 = gS
cost = d
if d == p:
same1 = dS
same2 = pS
cost = d
if g == p:
same1 = gS
same2 = pS
cost = g
print("Youre cheapest shipping method is "+same1+" and "+same2+" as they both cost $"+str(cost))
return
elif (g < d) and g < p:
cheapMeth = gS
cost = g
elif (p < d) and p < g:
cheapMeth = pS
cost = p
elif (d < g) and d < p:
cheapMeth = dS
cost = d
print("Youre cheapest shipping method is "+cheapMeth+" costing $"+str(cost))
return
weight = int(input())
costCalc(weight)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:00:19.190",
"Id": "433060",
"Score": "1",
"body": "The challenge you link to is in their Pro program, so not everyone can see it. This and the fact that you should *always provide at least the essential parts of the challenge description* means that you have work to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:05:15.077",
"Id": "433081",
"Score": "1",
"body": "Please can you include the core of the challenge description. I'm a bit confused that you output \"All shipping methods cost $125 according to your items weight\" but I can't find any value where this can be true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:55:15.207",
"Id": "433120",
"Score": "0",
"body": "I thought that there was a possibility of that being true so i just added that part just in case, but turns out that it wasn't possible according to you hehe."
}
] | [
{
"body": "<p>Ok, first of all you should've take care of variable names. Naming them like <code>p</code>, <code>g</code>, <code>e</code>, etc is really a bad habbit. </p>\n\n<p>Once you change them, it's much easier to read.</p>\n\n<pre><code>def cost_calc(weight):\n ground_cost = calculate_ground_cost(weight)\n drone_cost = calculate_drone_cost(weight)\n premium_cost = 125\n ground_shipping_name = \"Ground Shipping\"\n premium_shipping_name = \"Premium Ground Shipping\"\n drone_shipping_name = \"Drone Shipping\"\n</code></pre>\n\n<p>Second python naming convention tells you to use underscores while naming variables or functions.</p>\n\n<p>Third, your functionc that calculates costs can be minimized in many ways, when one of them is:</p>\n\n<pre><code>import bisect \n\ndef calculate_ground_cost(weight):\n limits = [2, 6, 10]\n multipliers = [1.5, 3, 4, 4.75]\n idx = bisect.bisect_left(limits, weight)\n return (weight * multipliers[idx]) + 20\n\ndef calculate_drone_cost(weight):\n limits = [2, 6, 10]\n multipliers = [4.5, 9, 12, 14.25]\n idx = bisect.bisect_left(limits, weight)\n return (weight * multipliers[idx])\n</code></pre>\n\n<p>Then you should take care of IFs statements that are really messy.</p>\n\n<pre><code>if drone_cost == ground_cost or drone_cost == premium_cost or ground_cost == premium_cost:\n</code></pre>\n\n<p>Is equvalent to</p>\n\n<pre><code>if drone_cost == ground_cost == premium_cost:\n</code></pre>\n\n<p>And the next rule good to follow is <strong>always</strong> return ASAP.</p>\n\n<pre><code>if drone_cost == ground_cost == premium_cost:\n return \"All shipping method cost %s according to your items weight\" % premium_cost\n</code></pre>\n\n<p>Then all of this mess:</p>\n\n<pre><code>if d == g and d == p:\n print(\"All shipping methods cost $125 according to your items weight\")\n return \n if d == g:\n same1 = dS\n same2 = gS\n cost = d\n if d == p:\n same1 = dS\n same2 = pS\n cost = d\n if g == p:\n same1 = gS\n same2 = pS\n cost = g\n print(\"Youre cheapest shipping method is \"+same1+\" and \"+same2+\" as they both cost $\"+str(cost))\n return\n</code></pre>\n\n<p>Can be changed to</p>\n\n<pre><code>if ground_cost == drone_cost:\n return \"Youre cheapest shipping method is %s and %s as they both cost$%s\" %(ground_shipping_name, premium_shipping_name, ground_cost)\n</code></pre>\n\n<p>Because this is the last \"IF\" that is matching the statement.</p>\n\n<p>And at the end, where u try to determine what is the lowest cost:</p>\n\n<pre><code> elif (g < d) and g < p:\n cheapMeth = gS\n cost = g\n elif (p < d) and p < g:\n cheapMeth = pS\n cost = p\n elif (d < g) and d < p:\n cheapMeth = dS\n cost = d\n print(\"Youre cheapest shipping method is \"+cheapMeth+\" costing $\"+str(cost))\n return\n</code></pre>\n\n<p>You can change it to </p>\n\n<pre><code>costs = sorted([\n (ground_cost, ground_shipping_name), \n (drone_cost, drone_shipping_name), \n (premium_cost, premium_shipping_name)])\n\nmin_cost, method = costs[0]\nreturn \"Your cheapest shipping method is %s costing $%s\" % (method, min_cost)\n</code></pre>\n\n<p>So at the end, your code look like:</p>\n\n<pre><code>import bisect \n\ndef calculate_ground_cost(weight):\n limits = [2, 6, 10]\n multipliers = [1.5, 3, 4, 4.75]\n idx = bisect.bisect_left(limits, weight)\n return (weight * multipliers[idx]) + 20\n\ndef calculate_drone_cost(weight):\n limits = [2, 6, 10]\n multipliers = [4.5, 9, 12, 14.25]\n idx = bisect.bisect_left(limits, weight)\n return (weight * multipliers[idx])\n\ndef cost_calc(weight):\n ground_cost = calculate_ground_cost(weight)\n drone_cost = calculate_drone_cost(weight)\n premium_cost = 125\n ground_shipping_name = \"Ground Shipping\"\n premium_shipping_name = \"Premium Ground Shipping\"\n drone_shipping_name = \"Drone Shipping\"\n if drone_cost == ground_cost == premium_cost:\n return \"All shipping methodrone_shipping_name cost $125 according to your items weight\"\n\n if ground_cost == drone_cost:\n return \"Youre cheapest shipping method is %s and %s as they both cost$%s\" %(ground_shipping_name, premium_shipping_name, ground_cost)\n\n costs = sorted([\n (ground_cost, ground_shipping_name), \n (drone_cost, drone_shipping_name), \n (premium_cost, premium_shipping_name)])\n\n min_cost, method = costs[0]\n\n return \"Your cheapest shipping method is %s costing $%s\" % (method, min_cost)\n\n\nweight = int(input(\"Enter weight: \"))\nprint(cost_calc(weight))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:52:45.067",
"Id": "433118",
"Score": "0",
"body": "ooh thanks, i really need to study this bisect class"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:39:17.347",
"Id": "223454",
"ParentId": "223445",
"Score": "2"
}
},
{
"body": "<p>Idiomatic changes & small changes:</p>\n\n<ol>\n<li>Indent with 4 spaces, not 2.</li>\n<li>Variable and function names should be in <code>lower_snake_case</code>.</li>\n<li>Unneeded parentheses is unidiomatic.</li>\n<li>Use spaces around concatenation, so <code>\"+abc</code> becomes <code>\" + abc</code>.</li>\n<li>Use a <code>if __name__ == '__main__':</code> guard to prevent your code from running when it’s not the initialised file.</li>\n<li>Have two spaces around top level function definitions.</li>\n<li>“You’re” has an apostrophe in it, but you should be using “your” instead. Because you aren’t a cheapest shipping method.</li>\n</ol>\n\n<p>Further changes:</p>\n\n<ol>\n<li>Use <code>if</code>, <code>elif</code> and <code>else</code> rather than just <code>if</code>.</li>\n<li><p>You can make your code dry by merging <code>ground_cost</code> and <code>drone_cost</code> together.</p></li>\n<li><p>You can simplify your code by using <code>sorted</code>.</p>\n\n<p>You sort <code>g</code>, <code>d</code> and <code>p</code>. From this you can then iterate through the list and see how many are the same.</p>\n\n<p>This makes <code>cost_calc</code> contain only three simple <code>if</code> statements.</p>\n\n<p>You would have to add something like a <a href=\"https://docs.python.org/3/library/enum.html#enum.Enum\" rel=\"nofollow noreferrer\"><code>enum.Enum</code></a> to know what type each value is, when sorting.</p></li>\n</ol>\n\n<pre><code>import enum\n\n\ndef size_cost(value, sizes):\n for size, cost in sizes[:-1]:\n if value > size:\n return cost\n return sizes[-1][1]\n\n\nground_costs = [\n (10, 4.75),\n (6, 4),\n (2, 3),\n (None, 1.5),\n]\ndrone_cost = [\n (10, 14.25),\n (6, 12),\n (2, 9),\n (None, 4.5),\n]\n\n\nclass Shipping(enum.Enum):\n GROUND = 'Ground'\n PREMIUM = 'Premium Ground'\n DRONE = 'Drone'\n\n\ndef cost_calc(weight):\n costs = [\n (Shipping.GROUND, size_cost(weight, ground_costs) * weight + 20),\n (Shipping.PREMIUM, 125),\n (Shipping.DRONE, size_cost(weight, drone_cost) * weight)\n ]\n costs.sort(key=lambda i: i[1])\n price = costs[0][1]\n costs = [s for s, p in costs if p == price]\n if len(costs) == 3:\n print(\"All shipping methods cost $125 according to your items weight\")\n elif len(costs) == 2:\n print(\n \"Your cheapest shipping method is \"\n + costs[0].value\n + \" shipping and \"\n + costs[1].value\n + \" shipping as they both cost $\"\n + str(price)\n )\n else:\n print(\n \"Your cheapest shipping method is \"\n + costs[0].value\n + \" shipping costing $\"\n + str(price)\n )\n\n\nif __name__ == '__main__':\n cost_calc(int(input()))\n</code></pre>\n\n<p>Output is also what you’d expect:</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> cost_calc(1)\nYour cheapest shipping method is Drone shipping costing $4.5\n>>> cost_calc(5)\nYour cheapest shipping method is Ground shipping costing $35\n>>> cost_calc(1000)\nYour cheapest shipping method is Premium Ground shipping costing $125\n>>> cost_calc(10 / 3)\nYour cheapest shipping method is Ground shipping and Drone shipping as they both cost $30.0\n>>> cost_calc(105 / 4.75)\nYour cheapest shipping method is Ground shipping and Premium Ground shipping as they both cost $125.0\n</code></pre>\n\n<p><strong>NOTE</strong>: <a href=\"https://github.com/Peilonrayz/Stack-Exchange-contributions/tree/master/code-review/223445\" rel=\"nofollow noreferrer\">Complete changes</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:50:54.630",
"Id": "433117",
"Score": "0",
"body": "thanksss a bunch, lots of new things im learning from this post."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T01:56:34.967",
"Id": "223467",
"ParentId": "223445",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223467",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T20:25:30.120",
"Id": "223445",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"console"
],
"Title": "My Sal's Shipping challenge on Codecademy"
} | 223445 |
<p>This is the original question:
<a href="https://www.geeksforgeeks.org/run-length-encoding/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/run-length-encoding/</a></p>
<blockquote>
<p>Given an input string, write a function that returns the Run Length
Encoded string for the input string.<br> For example, if the input string
is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6”.</p>
</blockquote>
<p>the only change I did is that if the character appears once there is no need to print 1 after the letter.</p>
<p>Please review for perfomance</p>
<pre><code>using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
/// <summary>
/// https://www.geeksforgeeks.org/run-length-encoding/
/// </summary>
[TestClass]
public class RunLengthEncoding
{
[TestMethod]
public void RunLengthEncodingTest()
{
string str = "wwwwaaadexxxxxxywww";
string expected = "w4a3dex6yw3";
Assert.AreEqual(expected, RLE.Encode(str));
}
}
public class RLE
{
public static string Encode(string str)
{
str = str.ToLower();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
int counter = 1;
if (!char.IsLetter(str[i]))
{
throw new ArgumentException("string should contains only letters");
}
while (i < str.Length - 1 && str[i] == str[i + 1])
{
counter++;
i++;
}
if (counter == 1)
{
stringBuilder.Append(str[i]);
}
else
{
stringBuilder.Append(str[i]);
stringBuilder.Append(counter);
}
}
return stringBuilder.ToString();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:55:56.747",
"Id": "433230",
"Score": "0",
"body": "What is Test class and Test Method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T21:55:33.057",
"Id": "433285",
"Score": "0",
"body": "@Shad this is ms test attribute for unit testing. Read about those if you do not know what they are"
}
] | [
{
"body": "<p>One thing I noticed. You're modifying the loop counter inside the loop to run another loop. This is one way in a large project to create unseen bugs. By keeping track of the previous character it is fairly easy to code this with only one loop.</p>\n\n<p>Your trapping strings that have other characters besides letters, but you're neglecting empty strings and null.</p>\n\n<p>Here's one way the revised code can look:</p>\n\n<pre><code>static string Encode(string input)\n{\n if (input == null || input.Length == 0)\n {\n ArgErrHandler(\"String must have at least one letter.\");\n }\n if (input.Any(x => !char.IsLetter(x)))\n {\n ArgErrHandler(\"String must have only letters.\");\n }\n if (input.Length == 2 || input.Length == 1)\n {\n return (input.Length == 1 || input[0] != input[1]) ? input : $\"{input[0]}{2}\";\n }\n int limit = input.Length - 1;\n int counter = 1;\n StringBuilder sb = new StringBuilder();\n int i = 1;\n char prev = '\\0';\n do\n {\n\n prev = input[i - 1];\n if (input[i] == prev)\n {\n ++counter;\n }\n else\n {\n if (counter > 1)\n {\n sb.Append($\"{prev}{counter}\");\n }\n else\n {\n sb.Append(prev);\n }\n prev = input[i];\n counter = 1;\n }\n } while (++i < limit);\n if (input[i] == prev)\n {\n ++counter;\n sb.Append($\"{prev}{counter}\");\n }\n else\n {\n if (counter > 1)\n {\n sb.Append($\"{prev}{counter}{input[i]}\");\n }\n else\n {\n sb.Append($\"{prev}{input[i]}\");\n }\n }\n return $\"{sb}\";\n}\nprivate static void ArgErrHandler(string message)\n{\n throw new ArgumentException(message);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:12:23.863",
"Id": "433138",
"Score": "1",
"body": "It looks like this fails if there is a single character input - the do loop is always executed and input[1] gives an out of range exception - and for a two character input the post loop check looks for input[2] which gives an out of range exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:44:25.247",
"Id": "433292",
"Score": "0",
"body": "@AlanT - It's fixed"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T02:40:00.667",
"Id": "223469",
"ParentId": "223450",
"Score": "3"
}
},
{
"body": "<p>Looking at the original question is seems that the input is constrained to be lower case letters. If this is so, then the <code>str.Lower()</code> is unneeded. Even if we decide that we do want to covert to lower, doing it upfront for the whole string means an extra traversal; it can be done as we process.</p>\n\n<p>It is possible to do this in a single loop without the inner while and its checks if we append a sentinel onto the end of the input. I don't know that it saves much on performance but it does cut out a few checks</p>\n\n<pre><code>public string Encode(string input)\n{\n if (input == null || input.Length == 0)\n {\n throw new ArgumentException(\"String must have at least one letter.\");\n }\n\n int counter = 0;\n StringBuilder sb = new StringBuilder();\n char prev = char.ToLower(input[0]);\n\n foreach(var rawChar in input.Append('\\0').Skip(1))\n {\n var ch = char.ToLower(rawChar);\n counter++;\n if (ch == prev) continue;\n\n if(!char.IsLetter(prev))\n { \n throw new ArgumentException(\"string should contains only letters\");\n }\n sb.Append($\"{prev}{(counter > 1 ? counter.ToString() : \"\")}\");\n counter = 0;\n prev = ch;\n }\n return sb.ToString();\n}\n</code></pre>\n\n<p><strong>Note:</strong> <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append?view=netframework-4.7.1\" rel=\"nofollow noreferrer\">Enumerable.Append()</a> is 4.7.1 and above. </p>\n\n<p><strong>EDIT</strong> <br/>\nRevised linq-less version. Sill uses the sentinel but 'injects' it when we get to the end of the loop</p>\n\n<pre><code>public string Encode(string input)\n{\n if (input == null || input.Length == 0)\n {\n throw new ArgumentException(\"String must have at least one letter.\");\n }\n\n int counter = 0;\n StringBuilder sb = new StringBuilder();\n char prev = char.ToLower(input[0]);\n\n for(var index = 1; index <=input.Length; index++)\n {\n var ch = index == input.Length\n ? '\\0'\n : char.ToLower(input[index]);\n counter++;\n if (ch == prev) continue;\n\n if (!char.IsLetter(prev))\n {\n throw new ArgumentException(\"string should contains only letters\");\n }\n if (counter == 1)\n {\n sb.Append(prev);\n }\n else\n {\n sb.Append(prev);\n sb.Append(counter);\n }\n counter = 0;\n prev = ch;\n }\n\n return sb.ToString();\n\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>So I ran some numbers on this</p>\n\n<p>The options were</p>\n\n<p><OL>\n<LI>Sentinel or not</LI>\n<li>Linq or not</li>\n<li>Append count separately or use string interpolation</li>\n<li>convert to lower up front or per character</li>\n</ol></p>\n\n<p>I tried 3 different inputs</p>\n\n<ul>\n<li>1000 copies of the sample string (wwwwaaadexxxxxx)</li>\n<li>1000 copies of the sample string x 4 (wwwwaaadexxxxxxwwwwaaadexxxxxxwwwwaaadexxxxxxwwwwaaadexxxxxx)</li>\n<li>1000 random strings or lengths between 10 and 250</li>\n</ul>\n\n<p>I ran each dataset 10 times and averaged the results (discarding the first each time as it was generally an outlier - startup costs?)</p>\n\n<p><strong>Results</strong></p>\n\n<p><em>1000 Copies of wwwwaaadexxxxxx</em></p>\n\n<p>Original => 10,239 ticks <br/>\nOriginal PerChar Lower => 20,725 ticks <br/>\nOriginal String Interpolation => 22,309 ticks <br/></p>\n\n<p>Sentinel Linq PerChar Lower Interpolation => 19,409 ticks <br/>\nSentinel Linq PerChar Lower Append => 12,350 ticks <br/>\nSentinel Linq str Lower Append => 8,860 ticks <br/></p>\n\n<p>Sentinel NoLinq PerChar Lower Interpolation => 20,284 ticks <br/>\nSentinel NoLinq PerChar Lower Append => 8,702 ticks <br/>\nSentinel NoLinq Str Lower Append => 5,786 ticks <br/></p>\n\n<p><em>1000 Copies of wwwwaaadexxxxxxwwwwaaadexxxxxxwwwwaaadexxxxxxwwwwaaadexxxxxx</em></p>\n\n<p>Original => 28,064 ticks <br/>\nOriginal PerChar Lower => 53,718 ticks <br/>\nOriginal String Interpolation => 44,618 ticks <br/></p>\n\n<p>Sentinel Linq PerChar Lower Interpolation => 80,699 ticks <br/>\nSentinel Linq PerChar Lower Append => 41,440 ticks <br/>\nSentinel Linq str Lower Append => 35,716 ticks <br/></p>\n\n<p>Sentinel NoLinq PerChar Lower Interpolation => 59,850 ticks <br/>\nSentinel NoLinq PerChar Lower Append => 35,956 ticks <br/>\nSentinel NoLinq Str Lower Append => 20,038 ticks <br/></p>\n\n<p><em>1000 random strings or lengths between 10 and 250</em></p>\n\n<p>Original => 60,350 ticks <br/>\nOriginal PerChar Lower => 146,490 ticks <br/>\nOriginal String Interpolation => 170,631 ticks <br/></p>\n\n<p>Sentinel Linq PerChar Lower Interpolation => 221,283 ticks <br/>\nSentinel Linq PerChar Lower Append => 79,732 ticks <br/>\nSentinel Linq str Lower Append => 42,773 ticks <br/></p>\n\n<p>Sentinel NoLinq PerChar Lower Interpolation => 197,249 ticks <br/>\nSentinel NoLinq PerChar Lower Append => 64,996 ticks <br/>\nSentinel NoLinq Str Lower Append => 30,775 ticks <br/></p>\n\n<p><strong>Interpretation</strong></p>\n\n<p>Firstly, string interpolation bad, it looks cute (a Matter of Personal Preference MOPP(tm)) but is not performant.</p>\n\n<p>Secondly, and surprisingly to me, upfront conversion of the whole string ToLower() is better than character by character. For the original code this is not a surprise as there are a lot of repeated conversions needed but even in the Sentinel version where we only convert each character once, it is better to convert the string upfront and then process it.</p>\n\n<p>Thirdly, linq performance varied. The sentinel version using linq was never better than the no linq version but sometimes it was better than the original code, sometimes it wasn't (this was not data related as I repeated the same dataset multiple times and sometimes it was faster, sometimes slower)</p>\n\n<p><strong>Bottomline</strong></p>\n\n<p>Pretty much everything in my original answer was wrong (well, except for the concept of the sentinel) <br/>\nWhen answering performance questions it is important to run the numbers :) <br/></p>\n\n<pre><code>public string Sentinel_NoLinqStrLowerAppend(string input)\n{\n if (input == null || input.Length == 0)\n {\n throw new ArgumentException(\"String must have at least one letter.\");\n }\n\n input = input.ToLower();\n\n int counter = 0;\n StringBuilder sb = new StringBuilder();\n char prev = input[0];\n\n for (var index = 1; index <= input.Length; index++)\n {\n var ch = index == input.Length\n ? '\\0'\n : input[index];\n counter++;\n if (ch == prev) continue;\n\n if (!char.IsLetter(prev))\n {\n throw new ArgumentException(\"string should contains only letters\");\n }\n if (counter == 1)\n {\n sb.Append(prev);\n }\n else\n {\n sb.Append(prev);\n sb.Append(counter);\n }\n counter = 0;\n prev = ch;\n }\n\n return sb.ToString();\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:55:59.863",
"Id": "433185",
"Score": "0",
"body": "Actually, `Append`, `char.ToLower` and `$\"{prev}{...}\"` each add some overhead, making this roughly 2-3 times slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:15:07.913",
"Id": "433194",
"Score": "0",
"body": "@Pieter Witvoet char.ToLower() per character is slower than str.ToLower() and then processing? Not disagreeing, I haven't run any performance tests, but just curious as to why. Is it cheaper to create a new lower case version of the string than to lowercase the characters individually?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T21:01:29.047",
"Id": "433281",
"Score": "0",
"body": "I don't know, but I guess it's the additional checks that `char.ToLower` does, together with the repeated call overhead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:03:07.020",
"Id": "223494",
"ParentId": "223450",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223469",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:29:32.903",
"Id": "223450",
"Score": "2",
"Tags": [
"c#",
"performance",
"programming-challenge",
"compression"
],
"Title": "Run length encoding in C#"
} | 223450 |
<p>This is the original question
<a href="https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/</a></p>
<blockquote>
<p>Given two sorted arrays, find their union and intersection.</p>
<pre><code>Example:
Input : arr1[] = {1, 3, 4, 5, 7}
arr2[] = {2, 3, 5, 6}
Output : Union : {1, 2, 3, 4, 5, 6, 7}
Intersection : {3, 5}
Input : arr1[] = {2, 5, 6}
arr2[] = {4, 6, 8, 10}
Output : Union : {2, 4, 5, 6, 8, 10}
Intersection : {6}
</code></pre>
</blockquote>
<p>I also added one more case of finding items which are only in one of the two arrays and called it <em>Diff</em>.</p>
<p>Please review for performance. <br>
<strong>Please do not comment</strong> about code in the same class as the test and the functions not being static. It is just faster for me like this to get to the point of the exercise.</p>
<pre><code>using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
/// </summary>
[TestClass]
public class UnionAndIntersectionOfTwoSortedArrays2
{
[TestMethod]
public void UnionTest()
{
int[] arr1 = { 1, 3, 4, 5, 7 };
int[] arr2 = { 2, 3, 5, 6 };
int[] union = { 1, 2, 3, 4, 5, 6, 7 };
CollectionAssert.AreEqual(union, Union(arr1, arr2));
}
[TestMethod]
public void IntersectionTest()
{
int[] arr1 = { 1, 3, 4, 5, 7 };
int[] arr2 = { 2, 3, 5, 6 };
int[] intersection = { 3, 5 };
CollectionAssert.AreEqual(intersection, Intersection(arr1, arr2));
}
[TestMethod]
public void DiffTest()
{
int[] arr1 = { 1, 3, 4, 5, 7 };
int[] arr2 = { 2, 3, 5, 6 };
int[] diff = { 1, 2, 4, 6, 7 };
CollectionAssert.AreEqual(diff, Diff(arr1, arr2));
}
private int[] Diff(int[] arr1, int[] arr2)
{
int i = 0;
int j = 0;
int n = arr1.Length;
int m = arr2.Length;
List<int> list = new List<int>();
while (i < n && j < m)
{
if (arr1[i] == arr2[j])
{
i++;
j++;
}
else if (arr1[i] < arr2[j])
{
list.Add(arr1[i]);
i++;
}
else
{
list.Add(arr2[j]);
j++;
}
}
while (i < n)
{
list.Add(arr1[i]);
i++;
}
while (j < m)
{
list.Add(arr2[j]);
j++;
}
return list.ToArray();
}
private int[] Intersection(int[] arr1, int[] arr2)
{
int i = 0;
int j = 0;
int n = arr1.Length;
int m = arr2.Length;
List<int> list = new List<int>();
while (i < n && j < m)
{
if (arr1[i] == arr2[j])
{
list.Add(arr1[i]);
i++;
j++;
}
else if (arr1[i] < arr2[j])
{
i++;
}
else
{
j++;
}
}
return list.ToArray();
}
public int[] Union(int[] arr1, int[] arr2)
{
int i = 0;
int j = 0;
int n = arr1.Length;
int m = arr2.Length;
List<int> list = new List<int>();
while (i < n && j < m)
{
if (arr1[i] < arr2[j])
{
list.Add(arr1[i]);
i++;
}
else if (arr2[j] < arr1[i])
{
list.Add(arr2[j]);
j++;
}
else // equals
{
list.Add(arr1[i]);
i++;
j++;
}
}
//handle the rest
for (; i < n; i++)
{
list.Add(arr1[i]);
}
for (; j < m; j++)
{
list.Add(arr2[j]);
}
return list.ToArray();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T04:33:56.393",
"Id": "433086",
"Score": "0",
"body": "_It is just faster for me like this to get to the point of the exercise._ If you code really fast, would you also expect a fast review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:26:37.403",
"Id": "433112",
"Score": "0",
"body": "@dfhwze I mean to say that please disregard why it is not separate class for test and for the rest of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:34:08.173",
"Id": "433113",
"Score": "0",
"body": "I get what you mean, but still it would be a very small effort to extract the algorithm to a separate class and call that class in the unit tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:36:19.197",
"Id": "433114",
"Score": "0",
"body": "@dfhwze I started doing it. because for some reason you find it very annoying.. and I appreciate the code reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:44:55.807",
"Id": "433135",
"Score": "1",
"body": "It looks like both `Union()` and `Intersection()` are the basic implementation of the algorithms which do not handle duplicates (`Union` of { 1, 2, 2, 2, 3 } and { 2, 3, 4, 5 }) gives {1, 2, 2, 2, 3, 4, 5} not {1, 2, 3, 4, 5} and `Intersection` of { 2,5,5,6,6} and {4,6,6,8,10} gives {6,6} not {6}) is this intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:50:16.670",
"Id": "433180",
"Score": "0",
"body": "@AlanT, I am not sure, but I will do one with duplicates, thanks for noticing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:11:55.103",
"Id": "433266",
"Score": "2",
"body": "I see you are practicing various algorithms but writing working code is a _no-brainer_. Doing it in a way that can be maintained, tested and easily understood, with intuitive API is much much harder and on higher levels this is what counts most. Currently you just write _something_ to solve the task avoiding to implement additional types to encapsulate the logic in proper modules. If you want to improve your skills you should try to write more professional code with proper types, names etc. I would still classify this code as _beginner_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:00:17.843",
"Id": "433286",
"Score": "0",
"body": "@t3chbot thanks for the comment. I have been working for Intel for more than 7 years as a software developer. What you say is absolutely correct. But that has almost no meaning in jobs interviews. So I practice both. At Intel of course my peer code review and design review everything with me. Stuff like S. O. L. I. D principles and design patterns and maintable well written code is a must."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:00:57.780",
"Id": "433287",
"Score": "0",
"body": "Now forget everything and take 3 questions put a clock to 45 minutes and solve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:04:18.437",
"Id": "433288",
"Score": "0",
"body": "I have noticed that Google, Amazon, Microsoft, Facebook and Apple and many other companies have very high demands on job interviews. I am trying to get to that level of solving and written good code for those interviews. I already got job offers from some of them and failed some of them. So I keep practicing. I think we do not use stuff like max heap and Trie trees on our day to day job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:15:46.147",
"Id": "433289",
"Score": "0",
"body": "@t3chb0t I also try to tackle more complex interview questions like so https://codereview.stackexchange.com/questions/223218/boggle-using-trie-and-dfs/223249#223249"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T10:16:06.337",
"Id": "433349",
"Score": "0",
"body": "If one of your primary goals is to write working code within 45 minutes without paying attention to any coventions or clean-code _rules_, or in other words simply quick-n-dirty, then IMO you only have one question: _Can this code be improved in terms of language features?_ or _Can this code be technically done better?_ - anything else would go beyond what you are trying to achieve here. I think this is your only question in this _series_, am I right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T11:18:48.547",
"Id": "433360",
"Score": "0",
"body": "@t3chbot I am not sure there is right or wrong here. Some of the code reviews gave me wonderful insights of things I was not even aware of. Some technical and some sruff like you are looking at the problem from a wrong point of view. I think it is very hard to pin point what can be done in 45 minutes. All the reviews you and many others give me definitely raise the bar. Remember the goal for me is to get better in any type of coding. So please continue to review I learn from each review."
}
] | [
{
"body": "<ul>\n<li>You can optimize all 3 methods if you initialize <code>list</code>'s capacity to the longest of the two arrays. Resizing a list involves allocating a new internal array and copying old items into the new array, which is something to keep in mind if you care about performance.</li>\n<li>Your tests often contain small pieces of manually crafted data. That's not a very scalable approach. It's easy to generate large amounts of test data with a bit of Linq: <code>Enumerable.Range(0, 1000).Select(i => random.Next(0, 1000)).OrderBy(n => n).ToArray()</code> gives you an input array. Verification can be done with a few loops (is every number in <code>arr1</code> and <code>arr2</code> present in <code>union</code>, and is every number in <code>union</code> present in either <code>arr1</code> or <code>arr2</code>?). For the duplicate-handling implementation verification is even easier with a combination of Linq's <code>Union</code>, <code>Intersect</code> and <code>OrderBy</code> methods.</li>\n<li>Names like <code>i</code>, <code>j</code>, <code>n</code> and <code>m</code> are not very descriptive - specifically which array they're associated with is not clear from their names. Changing them to something like <code>index1</code>, <code>index2</code>, <code>length1</code> and <code>length2</code> will make that relationship clear.</li>\n<li>If you're storing array lengths in local variables, then why not also store the results of <code>arr1[i]</code> and <code>arr2[j]</code> in local variables before comparing them? Both of these are micro-optimizations that affect the readability of the code, so I would only do this for performance-sensitive code, and only when profiling shows that it's actually an improvement.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T19:26:25.623",
"Id": "433414",
"Score": "1",
"body": "Regarding the first and last points, the attempts at optimising could well go wrong if it messes with the CLR. It used to be the case, for example, and cycling forward through an array was faster than backward because the optimiser would remove redundant bound checks: any additional indirection (e.g. stuffing lengths in variables) might break this. As you say: only do it if you know it is a problem and it shows an improvement upon (realistic) measurement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T19:59:39.400",
"Id": "433419",
"Score": "0",
"body": "Would you allow names as i1, i2, n1, n2 or prefer the longer names as mentioned in your answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T20:25:54.867",
"Id": "433422",
"Score": "1",
"body": "@dfhwze: personally I find the longer variant a bit easier to read so that's how I would write it, but in both cases the relationship with `arr1` is clear, so I'd be fine with either."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T19:15:33.327",
"Id": "223583",
"ParentId": "223451",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "223583",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T21:35:20.237",
"Id": "223451",
"Score": "2",
"Tags": [
"c#",
"programming-challenge",
"array"
],
"Title": "Union, Intersection and Diff of two sorted arrays in C#"
} | 223451 |
<p><strong>Coding challenge:</strong></p>
<blockquote>
<p>Convert a given long URL into a Tiny URL. The length of this Tiny URL
should be fixed and the same for all URLs. You should return the full
URL if given a shortened URL.</p>
</blockquote>
<p>I am aware this code is technically flawed as there will be clashes owing to the limitations of the <code>hash</code> function in Python. </p>
<p>Therefore I am not specifically looking for coding suggestions on this specific library. Instead what I am curious to know is if this can be improved to use an even shorter URL extension (e.g: 6 characters) that is unique. </p>
<p>I considered using a different hashing function from the <code>import hashing</code> library but the output of these are usually 32-64 characters long and therefore certainly not a "Tiny" URL.</p>
<pre><code>class TinyURL:
def __init__(self):
self.storedURLS = {}
def encode(self, long):
tiny = hex(hash(long))
self.storedURLS[tiny] = long
return tiny
def decode(self, tiny):
if tiny in self.storedURLS:
return self.storedURLS[tiny]
else:
return "Tiny URL is not in the database"
t = TinyURL()
encoded = t.encode("google.com")
print(encoded)
decoded = t.decode(encoded)
print(decoded)
</code></pre>
| [] | [
{
"body": "<p>I know this isn't really what you're asking for, but I have a couple suggestions about how the code is setup and written.</p>\n\n<p>Coming from languages that use <code>long</code> as a type, a line like:</p>\n\n<pre><code>self.storedURLS[tiny] = long\n</code></pre>\n\n<p>Is a little jarring initially. No, <code>long</code> is not a type or builtin in Python, but I think it would be neater if a more descriptive name was used, and one that doesn't clash with other languages. I'd probably write it closer to</p>\n\n<pre><code>class TinyURL:\n def __init__(self):\n self.storedURLS = {}\n\n def encode(self, full_address):\n minified_address = hex(hash(full_address))\n self.storedURLS[minified_address] = full_address\n\n return minified_address\n\n def decode(self, minified_address):\n if minified_address in self.storedURLS:\n return self.storedURLS[minified_address]\n else:\n return \"Tiny URL is not in the database\"\n</code></pre>\n\n<hr>\n\n<p>I also disagree with a String message being returned in the result of a lookup failure in <code>decode</code>. What if the caller wants to check for failure? They'd have to check the return against a known error message, which is clunky.</p>\n\n<p>I'd return <code>None</code> in the event of failure, then document that fact.</p>\n\n<pre><code>def decode(self, minified_address):\n \"\"\"Returns the full address associated with the given minified address,\n or None in the event of an invalid minified_address.\n \"\"\"\n return self.storedURLS.get(minified_address, None) # None is the default\n</code></pre>\n\n<p>That way, you can easily handle a failed lookup:</p>\n\n<pre><code>t = TinyURL()\n\nfull_address = t.decode(\"bad address\")\n\nif full_address:\n print(\"valid\")\n\nelse:\n print(\"invalid\")\n</code></pre>\n\n<p>And I <em>think</em> with the new assignment expression, you'll be able to write that even more succinctly:</p>\n\n<pre><code>if full_address := t.decode(\"bad address\"):\n print(\"valid\", full_address)\n\nelse:\n print(\"invalid\")\n</code></pre>\n\n<p>Although apparently 3.8 isn't released yet? I think the above should work, although I don't think I can test it quite yet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:32:13.777",
"Id": "433071",
"Score": "0",
"body": "Thanks. I remember ```long``` being a builtin method in Visual Basic 6 (years and years ago!). I take your point though. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:34:15.133",
"Id": "433072",
"Score": "2",
"body": "@EML Really, it's not a big deal, I just personally don't like the look of it. I switch back and forth between languages a fair amount, and that line gave me a short \"they're assigning a type?\" moment. I wouldn't be surprised if other Java/C++ writers feel similarly (although I'm curious if that's the case)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T23:29:47.540",
"Id": "223461",
"ParentId": "223456",
"Score": "6"
}
},
{
"body": "<p>While I agree with <a href=\"https://codereview.stackexchange.com/a/223461/98493\">the other answer</a> that you should not return a special string denoting failure, in Python you should refrain from returning <em>any</em> special return value (though if you do, <code>None</code> is an OK choice).</p>\n\n<p>Instead you usually want to raise an informative exception, which can then be handled by the caller. Here the code already raises a <code>KeyError</code>, which you could keep, or you could add a custom exception.</p>\n\n<pre><code>def decode(self, tiny_url):\n \"\"\"Returns the full address associated with the given tiny url.\n Raises a `KeyError` in the event of an invalid `tiny_url`. \"\"\"\n return self.urls[tiny_url]\n\n...\n\ntry:\n decoded = t.decode(encoded)\nexcept KeyError:\n print(\"Invalid\")\nprint(decoded)\n</code></pre>\n\n<p>Note that I also changed the name of <code>TinyURL.storedURLS</code> in order to conform to Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> as variable and function names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:54:28.113",
"Id": "223482",
"ParentId": "223456",
"Score": "5"
}
},
{
"body": "<p>If you really want to cut down on the number of characters that you need to guarantee a certain amount of robustness, it would be wise to pick a greater pool of characters to choose from. At the moment you are basically left with 16 valid values (0, 1, ..., 9, A, ..., F). Case does not count here since <code>0xA</code> is equal to <code>0xa</code>. For 6 characters that leaves you with <span class=\"math-container\">\\$16^6=2^{24}\\$</span> possible short-urls.</p>\n\n<p>If you were to encode them using the <a href=\"https://docs.python.org/3/library/base64.html\" rel=\"nofollow noreferrer\">base64</a> alphabet, you would have 64 characters to choose from, which grants you <span class=\"math-container\">\\$64^6=2^{36}\\$</span> possible short-urls. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import base64\n\ndesired_length = 6\nencoded_hash = base64.urlsafe_b64encode(\n str(hash(\"www.google.com\")).encode(\"ascii\")\n)\nminified_address = encoded_hash[:desired_length]\n</code></pre>\n\n<p>A character of a base64 string will represent 6bit instead of 4bit as a hex value does. As a consequence you would need to pick a length that is a multiple of two if you ever wanted to revert the encoded bytes, but that should not be necessary in your case. Take note that I opted for the url-safe version of the base64 alphabet which replaces <code>/</code> by <code>_</code> and <code>+</code> by <code>-</code>.</p>\n\n<hr>\n\n<p>It might also be worth to think about using a \"stable\" hash function, e.g. from <a href=\"https://docs.python.org/3/library/hashlib.html\" rel=\"nofollow noreferrer\"><code>hashlib</code></a> or one of the general purpose hash functions presented <a href=\"http://www.partow.net/programming/hashfunctions/\" rel=\"nofollow noreferrer\">here on this site</a>, instead of the built-in <code>hash(...)</code> which uses a random seed to <a href=\"https://stackoverflow.com/a/27522708\">mitigate certain attacks</a> (also <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__hash__\" rel=\"nofollow noreferrer\">here</a> in the documentation of <code>object.__hash__</code>). But that depends on whether you want to map <code>www.google.com</code> to the same short-url every time your program is queried or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:10:37.317",
"Id": "433144",
"Score": "0",
"body": "Is there not a risk that ```encoded_hash[:desired_length]``` would cause a clash as the first 6 characters may be the same but the last characters may be different?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:19:28.760",
"Id": "433148",
"Score": "2",
"body": "Of course there is a risk. But the risk is also present if you just use a shorter hash. A hash of a given bit-length \\$n\\$ can only represent \\$2^n\\$ values without collision. If you were to encode them in hex and pick 6 characters you end up with \\$n=24\\$ (\\$n=36\\$ for base64)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:08:21.363",
"Id": "223495",
"ParentId": "223456",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "223495",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T22:51:38.310",
"Id": "223456",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"url",
"hashcode"
],
"Title": "Tiny URL creator"
} | 223456 |
<p>I was asked this question in an interview:</p>
<blockquote>
<p>Given a string <code>s</code> consisting of <code>0</code>, <code>1</code> and <code>?</code>. The question mark can
be either <code>0</code> or <code>1</code>. Find all possible combinations for the string.</p>
</blockquote>
<p>I came up with below code but I wanted to know whether it is the best way to solve the problem?</p>
<pre><code> public static void main(String[] args) {
List<String> output = new ArrayList<>();
addCombinations("0?1?", 0, output);
System.out.println(output);
}
private static void addCombinations(String input, int index, List<String> output) {
for (int i = index; i < input.length(); ++i) {
if (input.charAt(i) == '?') {
addCombinations(input.substring(0, i) + "0" + input.substring(i + 1), i + 1, output);
addCombinations(input.substring(0, i) + "1" + input.substring(i + 1), i + 1, output);
return;
}
}
output.add(input);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T13:36:46.300",
"Id": "433376",
"Score": "0",
"body": "Could you maybe add an example of the expected output? I'm pretty sure I understand it but I think it wouldn't hurt your post."
}
] | [
{
"body": "<p>For an interview setting, I think the code presented to be a very decent initial solution but for the lack of comments:<br>\nit is easy to read (and consequently should be easy to maintain). </p>\n\n<p>It invites a question if there is any (semi-obvious) way to reduce machine resources used.</p>\n\n<p>(<em><a href=\"https://codereview.stackexchange.com/a/223523/93149\">AJNeufeld</a> is entirely right about <code>StringBuilder</code> vs <code>StringBuffer</code> - leaving it as is as a reminder not to present code in an answer without consulting an IDE.</em>)<br>\nOnly then I'd be inclined to suggest passing a <code>StringBuffer</code> as Java does almost all <code>String</code> manipulation using one using <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html#setCharAt(int,char)\" rel=\"nofollow noreferrer\"><code>setCharAt(int, char)</code></a> - this also removes most of the <em>code replication</em> (expression, really) I'd pick as a nit.</p>\n\n<pre><code> if (pattern.charAt(i) == '?') {\n // collect solutions for same problem with one '?' less\n StringBuffer atEntry = new StringBuffer(pattern);\n pattern.setCharAt(i, '0');\n addCombinations(pattern, i + 1, output);\n atEntry.setCharAt(i, '1');\n addCombinations(atEntry, i + 1, output);\n return;\n }\n}\noutput.add(pattern.toString());\n</code></pre>\n\n<p>But this not only calls <code>addCombinations()</code> for strings without wild cards, it instantiates as many <code>StringBuffer</code>s needlessly as there are combinations. With a slightly modified interface:</p>\n\n<pre><code> addCombinations(pattern, pattern.indexOf('?'), output);\n…\n/** Appends to <code>output</code> all combinations replacing the\n * character at <code>wildAt</code> and every <code>'?'</code>\n * to the end of <code>pattern</code> with <code>'0'</code> and\n * <code>'1'</code>. */\nprivate static void\naddCombinations(String pattern, int wildAt, List<String> output) {\n int next = pattern.indexOf('?', wildAt);\n StringBuffer modifyable = new StringBuffer(pattern);\n for (char digit = '0' ; digit <= '1' ; digit++) {\n modifyable.setCharAt(wildAt, digit);\n String modified = modifyable.toString();\n if (next < 0)\n output.add(modified);\n else\n addCombinations(modified, next, output);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T07:13:01.747",
"Id": "433121",
"Score": "0",
"body": "(As a further \"improvement\", one could try and identify *runs* of `?` and replace them by zero-padded binary representations of a counter value from an appropriate range.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:06:26.333",
"Id": "433137",
"Score": "0",
"body": "(I knew there was something odd not cloning `pattern`. It has been plain wrong.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:49:24.083",
"Id": "223481",
"ParentId": "223463",
"Score": "2"
}
},
{
"body": "<p>Such a problem is also looking whether the interviewed has a nice logic filtering, simplifying things.</p>\n\n<p>Now the problem actually only varies for the question marks. So:</p>\n\n<pre><code>void allCombinations(String pattern) {\n if (!pattern.matches(\"[01\\\\?]+\") {\n throw new IllegalArgumentException(\"Invalid pattern: \" + pattern);\n }\n int questionMarks = pattern.replaceAll(\"[^\\\\?]\", \"\").length();\n if (questionMarks == 0) {\n System.out.println(pattern);\n return;\n }\n if (questionMarks > 63) {\n throw new IllegalArgumentException(\"Limited to 63 question marks: 2^63 combinations.\");\n }\n long n = 1L << questionMarks; // Number of combinations.\n ...\n for (long i = 0; i < n; ++i) {\n // The bits of i[0 .. questionMarks-1] should fill in the pattern's qm's.\n ...\n }\n}\n</code></pre>\n\n<p>The real work, its optimal programming I leave to your creativity.</p>\n\n<p>The important thing is not to overcomplicate the combinating algorithm, a counter upto <code>2^questionMarks</code> (java: <code>1 << questionMarks</code>) suffices here.</p>\n\n<p>Your solution loop + recursion is not that adequate, and seeing that this problem delivers <strong>O(2<sup>n</sup>)</strong> I would not be entirely satisfied.</p>\n\n<p>Also one should consider how to deliver the result: a <code>List<String></code> is immensive. An iterator like function would be better. Explained.</p>\n\n<hr>\n\n<p><strong><em>One implementation</em></strong></p>\n\n<p>As the work to do was still not entirely trivial:</p>\n\n<pre><code> long n = 1L << questionMarks; // Number of combinations.\n ...\n char[] chars = pattern.toCharArray();\n int[] qmIndices = new int[questionMarks];\n int qmII = 0;\n for (int j = 0; qmII < questionMarks && j < chars.length; ++i) {\n if (chars[j] == '?') {\n qmIndices[qmII++] = j;\n }\n }\n for (long i = 0; i < n; ++i) {\n // The bits of i[0 .. questionMarks-1] should fill in the pattern's qm's.\n int bits = i;\n for (int j = 0; j < questionMarks; ++j) {\n chars[qmIndices[j]] = (char)('0' + (bits & 1));\n bits >>= 1;\n }\n System.out.println(new String(chars));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T04:58:20.333",
"Id": "433314",
"Score": "0",
"body": "Thanks for your suggestion. So basically we are getting total number of combinations we need to make and then in the for loop we need to execute it. I am now confuse how should I write things in the for loop so that we can get all the combinations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T09:34:54.533",
"Id": "433341",
"Score": "0",
"body": "I'll write some simple (=not optimal) code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T11:06:17.093",
"Id": "433355",
"Score": "0",
"body": "There is no requirement that limits the number of questionmarks, so why whould you build/implement this? Neither is this needed. You can either recursivly or dynamically fill all questionsmarks, without needing to limit input size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T12:03:07.443",
"Id": "433363",
"Score": "0",
"body": "@RobAu With N = number of question marks, you get 2^N combinations. Using a long for 63/64 bits seems sufficient (2^63 results), but one could do more bits. However the application would run _very long_, and one could no longer keep the data in memory: array lengths and List sizes are just ints. **Just in this case** an input validation would prevent probably unwanted/undeliverable behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T12:05:07.970",
"Id": "433364",
"Score": "0",
"body": "There is also no requirement to keep it all in memory. Nor are there runtime-limitations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T12:09:50.400",
"Id": "433365",
"Score": "0",
"body": "@RobAu okay, but the original question kept a result. I proposed not to do that. And I could have given an unlimited result (if so desired kept in a database), but it seems overkill. For a job interview question rather questionable. _It is a rather stupid problem, what do you think?_ (I won't make a BitSet i.o. long implementation.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T12:18:07.417",
"Id": "433367",
"Score": "0",
"body": "`BitSet` and output to Iterator/Stream implementation would be my preference :). Just start at 0. Have it the number of questionmarks wide. Each iteration add 1 to the bitset (need to implement this yourself, as BitSet doens't have a `next()` method). Fill the questionmarks with the 1 and 0 from the bitset. Iterate. Until all the bits are 1, then you are done. This has minimal memory footprint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T12:26:43.873",
"Id": "433369",
"Score": "0",
"body": "@RobAu I like BitSet also very much; it has so many goodies. Bye."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:54:17.250",
"Id": "223504",
"ParentId": "223463",
"Score": "1"
}
},
{
"body": "<h2>Usability</h2>\n\n<p>Your <code>addCombinations(String input, int index, List<String> output)</code> is harder to use than necessary. The user must:</p>\n\n<ul>\n<li>create the storage for the result</li>\n<li>pass in a mysterious <code>0</code> value</li>\n</ul>\n\n<p>It would be better to add a \"helper\" function, to do these tasks for the user:</p>\n\n<pre><code> public static void main(String[] args) {\n List<String> output = combinations(\"0?1?\");\n System.out.println(output);\n }\n\n public static List<String> combinations(String input) {\n List<String> output = new ArrayList<>();\n addCombinations(input, 0, output);\n return output;\n }\n</code></pre>\n\n<h2>Flexibility</h2>\n\n<p>Will <code>'?'</code> always be the replacement target? Will the replacements only be the characters <code>'0'</code> and <code>'1'</code>? It wasn't asked by the interviewer, but you could make the function more flexible. Or at least mention the possibility to the interviewer.</p>\n\n<h2>Code Style</h2>\n\n<p>This screams \"hacky\":</p>\n\n<pre><code> for (int i = index; i < input.length(); ++i) {\n if (input.charAt(i) == '?') {\n // Do work\n return;\n }\n }\n output.add(input);\n</code></pre>\n\n<p>You are looping ... but only execute the \"real\" body of the loop exactly once -- and <code>return</code> if you do -- and if you get to the end without doing work, you do some different work. As an interviewer, unless you've impressed me elsewhere, I'd be moving on to the next candidate.</p>\n\n<p>What you are doing - what you intend to do - is find the first <code>'?'</code>, replace that with <code>'0'</code> and <code>'1'</code>, and recursing to find other occurrences for replacement. Make that clearer.</p>\n\n<pre><code> int position = input.indexOf('?', index);\n if (position >= 0) {\n addCombinations( ... );\n addCombinations( ... );\n } else {\n output.add(input);\n }\n</code></pre>\n\n<p>You've got two cases: found and not found. Recursive and leaf. No embedded <code>return</code>. Pretty clear.</p>\n\n<h2>Premature Optimization?</h2>\n\n<p>You've got an optimization which may be unnecessary. You pass in <code>index</code> to indicate where to start searching for the next <code>'?'</code>. But you've replaced the <code>'?'</code>, so if you omitted this, and simply started searching from the start of the string, it would still work. Yes, you will be doing some unnecessary searching of the beginning of the string over and over again, but you've also removed passing the extra argument on the stack, which complicates the <code>addCombinations(...)</code> call.</p>\n\n<p>To be fair, I've used <code>String.indexOf()</code> to do the searching, which is very fast, where as your code did the search itself, with a loop, a <code>String.charAt()</code> and a comparison, which would be significantly slower, so the optimization definitely makes sense in the original code.</p>\n\n<h2>The Better Way</h2>\n\n<p>As metioned by @greybeard, <code>StringBuffer.setCharAt()</code> would be much simpler to the string manipulation currently being done. <em>But it is still the wrong choice</em>. <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html#setCharAt(int,char)\" rel=\"nofollow noreferrer\"><code>StringBuilder.setCharAt()</code></a> is what you want. (<code>StringBuilder</code> is <code>StringBuffer</code>, but without the synchronization overhead).</p>\n\n<p>Instead of creating and throwing away multiple <code>StringBuilder</code> objects, it would be possible to reuse one <code>StringBuilder</code> object for all recursive calls. Create the <code>StringBuilder</code> in the helper method I introduced, and pass it (instead of <code>input</code>) into the <code>addCombinations()</code> method. When a <code>?</code> is found, replace it with a <code>0</code> and recurse, then a <code>1</code> and recurse, <em>and then change it back to a <code>?</code></em> before returning to ensure subsequent processing still works.</p>\n\n<pre><code>public static List<String> combinations(String input) {\n StringBuilder workspace = new StringBuilder(input);\n List<String> output = new ArrayList<>();\n addCombinations(workspace, output);\n return output;\n}\n\nprivate static void addCombination(StringBuilder workspace, List<String> output) {\n int position = workspace.indexOf('?');\n if (position >= 0) {\n workspace.setCharAt(position, '0');\n addCombination(workspace, output);\n workspace.setCharAt(position, '1');\n addCombination(workspace, output);\n workspace.setCharAt(position, '?');\n } else {\n output.add(workspace.toString());\n }\n}\n</code></pre>\n\n<p>There is still a lot of repeated work going on. With 4 question marks, the first question mark is found once, the second is found twice, the third is found 4 times, and the fourth is found 8 times. You could count the number of question marks, create an <code>int positions[]</code> array, and locate all the question marks only once. You could also create an <code>int state[]</code> array, and use that to turn the recursion into a loop. Finally, once each execution of the loop generates one new combination, you could extract the body of the loop into its own <code>Supplier<String></code>, and use <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/stream/Stream.html#generate(java.util.function.Supplier)\" rel=\"nofollow noreferrer\"><code>Stream::generate(Supplier<? extends T>)</code></a> to create a stream of combinations on demand, instead of filling in a list, but we've ran way beyond reasonable expectations for an interview question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:23:27.223",
"Id": "223523",
"ParentId": "223463",
"Score": "4"
}
},
{
"body": "<h2>Managing memory requirements</h2>\n\n<p>Did you get the method signature from the interviewer? If not, it could use some improvement. Consider Joop Eggen's answer and the worst case scenario, where there are 2^63 different combinations. While his approach is likely the most efficient computationally, the method signature limits the operation to calculating everything before the results can be examined. It requires storage of 5.81e+20 characters in memory (what's that... 581 exabytes?)</p>\n\n<p>Instead of passing a collection to which the results are collected, pass a consumer so that the caller has a control over how the results are stored and processed. Taking AJNeufeld's solution, as it has already a bit improved method signatures:</p>\n\n<pre><code>public static void combinations(String input, Consumer<String> consumer) {\n StringBuilder workspace = new StringBuilder(input);\n addCombinations(workspace, consumer);\n}\n\nprivate static void addCombination(StringBuilder workspace,\n Consumer<String> consumer) {\n\n ...\n } else {\n consumer.accept(workspace.toString());\n }\n}\n</code></pre>\n\n<p>This way, if the caller is only intersted in one specific result, it can, for example, throw an unchecked exception from the consumer as soon as the correct one has been found to make the algorithm stop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T11:49:12.477",
"Id": "433362",
"Score": "1",
"body": "This! **Always** check the requirements with the interviewer. What does 'Find all' mean? Print? A total list? Iterator? etc. Are the memory / cpu / execution contraints? etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T08:51:15.450",
"Id": "223551",
"ParentId": "223463",
"Score": "2"
}
},
{
"body": "<h2>Requirements</h2>\n\n<p>It all depends on what you think is 'best'. The code that can be implemented in as little time as possible? The most efficient code? In terms of memory? CPU?</p>\n\n<p>The solution below doesn't do any input checking, but instead is an approach that would be rather fast and very memory efficient</p>\n\n<h2>Return type</h2>\n\n<p>I prefer a solution that has an <code>Iterator</code> or <code>Stream</code> and uses as less memory as needed.</p>\n\n<h2>State</h2>\n\n<p>The problem is that you have to keep state of all the <code>?</code> you replace. This screams for a <code>BitSet</code>.</p>\n\n<p>Basically, the solution keeps replacing all the <code>?</code> with bits in the current <code>BitSet</code>. For each iteration, determine the next <code>BitSet</code> and create a new String with the 0 and 1 in the correct places.</p>\n\n<p>Lets see:</p>\n\n<pre><code>input n'th iteration bitset output\n---------------------------------------\n01?0? 0 00 01000\n01?0? 1 01 01001\n01?0? 2 10 01100\n01?0? 3 11 01101\n</code></pre>\n\n<p>This is very memory efficient, as you only need 2 bits of state. Also efficient in terms of operations, as you build a <code>String</code> on the go, and never use slow <code>String</code> manipulation.</p>\n\n<h2>Reuse</h2>\n\n<p>Unfortunately, Java does not offer a <code>FixedBitSet</code> or a <code>next()</code> method on <code>BitSet</code>, so you'd have to implement it yourself</p>\n\n<h2>Solution</h2>\n\n<pre><code>package org.robau;\n\nimport java.util.BitSet;\nimport java.util.Iterator;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\nimport java.util.stream.StreamSupport;\n\npublic class Strings {\n\n public static void main(String[] args) {\n\n Iterable<String> iterable = () -> getAllCominations(\"0??0?1\");\n Stream<String> s = StreamSupport.stream(iterable.spliterator(), false);\n s.forEach(System.out::println);\n }\n\n // Given a string s consisting of 0, 1 and ?. The question mark can be either 0\n // or 1. Find all possible combinations for the string.\n static Iterator<String> getAllCominations(String s) {\n\n // Create a bitset the size of \"the number of '?' in S\" + 1 for \n int nbits = (int) s.chars().filter(ch -> ch == '?').count() + 1; \n\n FixedBitSet sbs = new FixedBitSet(nbits);\n char[] input = s.toCharArray();\n\n return new Iterator<String>() {\n\n @Override\n public boolean hasNext() {\n\n boolean isDone = sbs.get(sbs.getSize()-1); \n //We don't have a next() if we have the overflowbit set\n return !isDone;\n }\n\n @Override\n public String next() {\n\n String s = mergeWithInput(sbs);\n sbs.next();\n return s;\n }\n\n private String mergeWithInput(FixedBitSet sbs) {\n int bitSetIndex =0;\n StringBuilder sb = new StringBuilder(input.length);\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == '?') {\n sb.append(sbs.get(bitSetIndex)? '1': '0');\n bitSetIndex++;\n }\n else\n {\n sb.append(s.charAt(i));\n }\n }\n return sb.toString();\n }\n\n };\n }\n\n static class FixedBitSet extends BitSet {\n private int size;\n\n public FixedBitSet(int nbits) {\n super(nbits);\n this.size = nbits;\n }\n\n public int getSize() {\n return size;\n }\n\n public void next() {\n\n boolean carry = true;\n for (int i = 0; i < size; i++) {\n\n if (carry && !get(i)) {\n flip(i);\n return;\n } else if (carry && get(i)) {\n flip(i); // keep carrying\n } else if (!carry && !get(i)) {\n //done\n return;\n } else {\n //keep carry, take to next bit\n }\n }\n }\n\n @Override\n public String toString() {\n final StringBuilder buffer = new StringBuilder(size);\n IntStream.range(0, size).mapToObj(i -> get(i) ? '1' : '0').forEach(buffer::append);\n return buffer.toString();\n }\n\n }\n\n\n\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T13:02:09.437",
"Id": "223566",
"ParentId": "223463",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T00:03:30.027",
"Id": "223463",
"Score": "7",
"Tags": [
"java",
"algorithm",
"interview-questions",
"combinatorics"
],
"Title": "String combinations of 0 and 1"
} | 223463 |
<p>New to programming with the goal being to create my own roguelike. I am mostly interested right now in creating my item generation system. I want the code to create a random item that can then be used, stored in an inventory etc. Want to know if the below is a smart way to begin with. Any suggestions to make the below better would be much appreciated.</p>
<p>The item description within function is just there as placeholder so I can see if the code was working. Will this object be permanent ? IE everytime I call create_item it will create a permanent object - Sorry for terminology and if incorrect legit second week of playing with Python :)</p>
<pre><code>import random
i_quality = ["Good", "Bad"]
i_quality = random.choice(i_quality)
i_base = ["Sword", "Gun"]
i_base = random.choice(i_base)
i_element = ["Fire", "Water"]
i_element = random.choice(i_element)
class Item(object):
def __init__ (self, quality, base, element):
self.quality = quality
self.base = base
self.element = element
def create_Item():
new_item = Item(i_quality, i_base, i_element)
i_description = (new_item.quality + " " + new_item.base + " of " + new_item.element)
print (i_description)
create_Item()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T01:22:27.687",
"Id": "433078",
"Score": "0",
"body": "Just note, the last bit that you added isn't relevant for a Code Review (yes, these sites are very strict on what's on topic). The answer though is no: A new `new_item` will be created when the function enters, and destroyed (some time after) the function exits. You need to return it or store it somewhere if you want to use it."
}
] | [
{
"body": "<p>This isn't bad code for someone learning the language, but there are a few things I'd change:</p>\n\n<p>At the top you have:</p>\n\n<pre><code>i_quality = [\"Good\", \"Bad\"]\ni_quality = random.choice(i_quality)\n</code></pre>\n\n<p>And other such lines. The main problem here is you're overwriting <code>i_quality</code>. What if you wanted to generate a second quality later? You overwrote your master list of qualities. Have them as separate variables:</p>\n\n<pre><code>all_qualities = [\"Good\", \"Bad\"]\nall_bases = [\"Sword\", \"Gun\"]\nall_elements = [\"Fire\", \"Water\"]\n\ni_quality = random.choice(all_qualities)\ni_base = random.choice(all_bases)\ni_element = random.choice(all_elements)\n</code></pre>\n\n<hr>\n\n<p>Be careful how you name things and what the responsibilities of functions are. <code>create_Item</code> does create an <code>Item</code>, but it also prints it out then discards it. Such a function isn't very useful. The caller could have just called the <code>Item</code> constructor themselves and then printed the object if they wanted to. Your function does some formatting, but that would be better off in the <code>__str__</code> method of <code>Item</code>.</p>\n\n<p>What would make for a useful factory function though would be a <code>create_random_item</code> function that returns a random <code>Item</code>. Taking all that together, I'd change this code to something closer to:</p>\n\n<pre><code>import random\n\nall_qualities = [\"Good\", \"Bad\"]\nall_bases = [\"Sword\", \"Gun\"]\nall_elements = [\"Fire\", \"Water\"]\n\nclass Item(object):\n def __init__ (self, quality, base, element):\n self.quality = quality\n self.base = base\n self.element = element\n\n # What Python will call when you ask it to\n # display an Item using str\n def __str__(self):\n return self.quality + \" \" + self.base + \" of \" + self.element\n\ndef create_random_item():\n quality = random.choice(all_qualities)\n base = random.choice(all_bases)\n element = random.choice(all_elements)\n\n return Item(quality, base, element)\n\nfor _ in range(10): # We'll create 10 random weapons and print them out\n item = create_random_item()\n print(str(item)) # str calls item's __str__\n\nGood Gun of Fire\nGood Sword of Fire\nBad Sword of Water\nGood Sword of Fire\nGood Sword of Water\nGood Sword of Fire\nBad Gun of Water\nBad Sword of Water\nBad Gun of Water\nBad Sword of Water\n</code></pre>\n\n<hr>\n\n<ul>\n<li><p>This could be further improved though. Any time you have a closed set of members of a set (like how \"fire\" and \"water\" are members of the \"elements\" set), you should likely being using an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Enum</a>. They help avoid errors in many cases, and allow IDEs to assist you in auto-completing names.</p></li>\n<li><p>In <code>__str__</code>, you could also make use of <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">f-strings</a> to avoid needing to manually concat using <code>+</code>. It would be neater to write:</p>\n\n<pre><code>def __str__(self):\n return f\"{self.quality} {self.base} of {self.element}\"\n</code></pre>\n\n<p>That allows for much less noise and allows you to focus more on what you what printed, and less on dealing with opening and closing quotes and <code>+</code>s.</p></li>\n<li><p>For the sake of context, <code>create_random_item</code> may make more sense as a <a href=\"https://stackoverflow.com/questions/735975/static-methods-in-python\">static method</a>. It makes it clearer what class it's associated with, since then you'd call the method as:</p>\n\n<pre><code>Item.create_random_item()\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T01:55:12.763",
"Id": "433080",
"Score": "0",
"body": "My friend most helpful thank you - I love how everything seems to be a giant logic puzzle :) I really appreciate the pointers back to work. I had no idea __str__(self) allows you to return a string! amazing"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T01:16:02.820",
"Id": "223466",
"ParentId": "223465",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223466",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T01:04:34.507",
"Id": "223465",
"Score": "3",
"Tags": [
"python",
"beginner",
"random"
],
"Title": "Random item generation system to be used in a roguelike"
} | 223465 |
<p>I just write a simple method which returns a string based on the number in accepts as a parameter. I used <code>if/elif/esle</code> here but I think for this simple scenario I wrote long code. I want to know is it possible to shorten this code in any way except using a lambda method. Also, I'm interested to know about the performance of <code>if/elif/else</code>. Is there any other solution which can make faster this method?</p>
<pre><code>def oneTwoMany(n):
if n == 1:
return 'one'
elif n == 2:
return 'two'
else:
return 'many'
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T08:19:57.863",
"Id": "435425",
"Score": "0",
"body": "This has received close-votes because it lacks context. You could improve it by adding more information: where will this method be used? How is the output used? Is it likely to change in the future? Are there many of these methods, all slightly different, which you need to maintain? What range of values should it accept? (e.g. zero)"
}
] | [
{
"body": "<p>You can instead use a dictionary to define your <code>n</code> values:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>nums = {1: 'one', 2: 'two'}\n</code></pre>\n\n<p>Then, when you want to use this, you can use <code>.get()</code>. <code>.get()</code> has a default argument which is returned when a dict doesn't have a key you've requested; here we use <code>'many'</code> to be returned.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def oneTwoMany(n):\n nums = {1: 'one', 2: 'two'}\n return nums.get(n, 'many')\n</code></pre>\n\n<p>If you really want to be concise you can stop defining <code>nums</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def oneTwoMany(n):\n return {1: 'one', 2: 'two'}.get(n, 'many')\n</code></pre>\n\n<p><em>As an aside to the downvoters of the question; it may be a simple question but I don't see how it breaks any rules.</em></p>\n\n<p>EDIT: incorporating some other answers which (quite rightly) suggest catching certain invalid inputs.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def oneTwoMany(n):\n if type(n) is not int:\n raise TypeError('Invalid input, value must be integer')\n elif n < 1:\n raise ValueError('Invalid input, value is below 1')\n else:\n return {1: 'one', 2: 'two'}.get(n, 'many')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T18:11:09.953",
"Id": "433250",
"Score": "0",
"body": "@Thank you dear for your nice solution and support. As you mentioned, this seems a simple question but in my opinion, can help me a lot and my others to think different and learn new flexible and file solutions. You're code and solution is really nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T09:30:20.517",
"Id": "433339",
"Score": "0",
"body": "This solution, just like the original, breaks on corner cases. Try `oneTwoMany(0)` and `oneTwoMany(-1)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T09:43:16.117",
"Id": "433344",
"Score": "0",
"body": "@Richard Neumann, What do you suggest in that case? Should we extend the if/elif/ clauses? I should mention that this solution in my scenario which is a simple task is enough but as you mentioned in real and more complex cases it causes the program to break. What we can to do to improve it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T09:59:51.103",
"Id": "433345",
"Score": "0",
"body": "Maybe say `'none'` on `0` and raise a `ValueError` on negative numbers."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T14:17:49.910",
"Id": "223509",
"ParentId": "223471",
"Score": "4"
}
},
{
"body": "<p>I'd question your objectives here. Yes, it's admirable to keep code concise, but we should also strive to make it <strong>robust</strong>. As it currently stands, we will return <code>'many'</code> for any of these inputs:</p>\n\n<ul>\n<li><code>0</code></li>\n<li><code>-5</code></li>\n<li><code>0.1</code></li>\n<li><code>True</code></li>\n<li><code>None</code></li>\n<li><code>\"foobar\"</code></li>\n<li><code>[]</code></li>\n</ul>\n\n<p>Consider throwing an exception if the input is not a positive integer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T07:37:46.830",
"Id": "223719",
"ParentId": "223471",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223509",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:01:55.863",
"Id": "223471",
"Score": "0",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Descriptive quantity (one, two, many) from number"
} | 223471 |
<p>This is based upon an exercise in chapter 5 of <em>Automate the Boring Stuff with Python</em>.</p>
<p>This code contains functions <code>addToInventory</code> which modifies a given inventory of items to add new items as well as update existing items and <code>displayInventory</code> which displays the items and their values. The main operation is adding the contents of a list <code>dragonloot</code> to inventory <code>inv</code>. </p>
<p>I have tried to do this in two ways, one by calling <code>addToInventory</code> and after that calling <code>displayInventory</code>. This method leads to errors. Another way I tried was by printing the new inventory values within <code>addtoInventory</code>. This works fine. Why doesn't the first method work? I have put both the methods as comments within my code, indicated by <code>""" """</code>. </p>
<p>I know C++ pretty well, but I'm new to Python. Expected result:
Inventory:
gold coin: 45 rope:1 dagger:1 ruby:1 Total number of items is 48</p>
<pre><code>def addToInventory(inventory, addedItems):
draft = {}
for i in addedItems:
if (i not in draft):
draft[i]=1
else:
draft [i]= draft [i] + 1
for i in draft:
if i not in inventory:
inventory[i]=draft[i]
else:
inventory[i] = inventory[i]+draft[i]
"""for i in inventory:
print(str(inventory[i]) + " " + str(i))"""
def displayInventory(inventory):
print ("Inventory: ")
total=0
for i in inventory.items():
total+=1
print (str(inventory[i])+" "+str(i))
print("Total number of items is"+str(total))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
"""displayInventory(inv) when I use this line in place of above comment I get errors"""
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:18:46.690",
"Id": "433091",
"Score": "1",
"body": "please add the expected result to your code. What will inventory be after you performed your function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:25:30.257",
"Id": "433133",
"Score": "2",
"body": "Please note that explaining your own code to you is usually considered [off-topic](/help/dont-ask) here on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T08:11:06.083",
"Id": "433333",
"Score": "0",
"body": "Thanks for letting me know, in case I have doubts in my code is there any chat or somewhere where I could ask?"
}
] | [
{
"body": "<p>You overwrite inv with the return value of addToInventory</p>\n\n<pre><code>inv = addToInventory(inv, dragonLoot)\n</code></pre>\n\n<p>Yet add to inventory does not return anything. \nIn order to first get your code to work, just return the inventory:</p>\n\n<pre><code>def addToInventory(inventory, addedItems):\n draft = {}\n for i in addedItems:\n if (i not in draft):\n draft[i]=1\n else:\n draft [i]= draft [i] + 1\n for i in draft:\n if i not in inventory:\n inventory[i]=draft[i]\n else:\n inventory[i] = inventory[i]+draft[i]\n return inventory\n</code></pre>\n\n<p>And then lets improve that function using the <a href=\"https://docs.python.org/2/library/collections.html\" rel=\"nofollow noreferrer\">collections</a> library such as:</p>\n\n<pre><code>from collections import Counter\n\ndef addToInventory(inv, loot):\n loot_counter = Counter(loot)\n return dict(loot_counter + Counter(inv))\n</code></pre>\n\n<p>Further, for the second displayInventory function, you iterate over dict.items(), yet you then try to use the item itself as an index. Instead iterate over dict.keys() and you will be fine: </p>\n\n<pre><code>def displayInventory(inventory):\n print (\"Inventory: \")\n total=0\n for i in inventory.keys():\n total+=1\n print (str(inventory[i])+\" \"+str(i))\n print(\"Total number of items is\"+str(total))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:31:47.733",
"Id": "223474",
"ParentId": "223472",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223474",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T05:10:22.710",
"Id": "223472",
"Score": "0",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Using another function on modified dictionary"
} | 223472 |
<p>I have a more massive sp, in which I use some temporary tables, below is a part of the sp where I am updating a field in a temporary table two times.</p>
<pre><code>Update #BalSheet
set OBCr = OBDr + isnull(trialDeb.amount,0)
from (
Select v.AccountId,
v.CompanyId,
Sum(isnull(v.Amount,0)) Amount
From #vwJournalDetails v , #TempJournalHeader h
where v.JournalCredit = 1 and // 1
h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate
group by v.CompanyId, v.AccountId
) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and
trialDeb.CompanyId = @intCompanyId and
#BalSheet.AcType ='L'
Update #BalSheet
set OBCr = OBDr - isnull(trialDeb.amount,0)
from (
Select v.AccountId,
v.CompanyId,
Sum(isnull(v.Amount,0)) Amount
From #vwJournalDetails v , #TempJournalHeader h
where v.JournalCredit = 0 and // 2
h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate
group by v.CompanyId, v.AccountId
) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and
trialDeb.CompanyId = @intCompanyId and
#BalSheet.AcType ='L'
</code></pre>
<p>As you can see, the two update query looks similar, and the only difference is in the where condition checking <code>v.JournalCredit</code> value.</p>
<p>If the <code>v.JournalCredit = 1</code> I add the amount to the current value in the table, and when the <code>v.JournalCredit = 0</code> I subtract the amount from the current value. </p>
<p>it is working correctly, but there are other update queries similar to this in the sp, So I was wondering if there is any way to mix these update query into one?</p>
| [] | [
{
"body": "<p>You can use a CASE statement in your SET to choose the operation to perform. Not only will this make maintenance easier, it will improve performance as well since you'll only be touching the target table once.</p>\n\n<pre><code>UPDATE #BalSheet\nSET OBCr = CASE\n WHEN trialDeb.JournalCredit = 1 THEN OBDr + ISNULL(trialDeb.Amount, 0)\n WHEN trialDeb.JournalCredit = 0 THEN OBDr - ISNULL(trialDeb.Amount, 0)\n END\nFROM ( SELECT v.AccountId,\n v.CompanyId,\n v.JournalCredit,\n SUM(ISNULL(v.Amount, 0)) AS Amount\n FROM #vwJournalDetails AS v,\n #TempJournalHeader AS h\n WHERE v.JournalCredit IN ( 0, 1 )\n AND h.JournalId = v.JournalId\n AND h.CompanyId = v.CompanyId\n AND h.JournalDate >= @dtPrevFinUnclosedSDate\n AND h.JournalDate <= @dtLastFinUnclosedEDate\n GROUP BY v.CompanyId,\n v.AccountId,\n v.JournalCredit) AS trialDeb\nWHERE trialDeb.Accountid = #BalSheet.AccId\n AND trialDeb.CompanyId = #BalSheet.CompanyID\n AND trialDeb.CompanyId = @intCompanyId\n AND #BalSheet.AcType = 'L' ;\n</code></pre>\n\n<p>Note that I don't know if you still need the v.JournalCredit filter so I just changed it to an IN clause to ensure only 0 & 1 were touched. If those are the only two possible values, you can remove that predicate to improve the performance as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T17:14:04.360",
"Id": "224231",
"ParentId": "223477",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T06:02:12.913",
"Id": "223477",
"Score": "1",
"Tags": [
"sql",
"sql-server"
],
"Title": "Updating field in Temporary table"
} | 223477 |
<p>I have a <code>users</code> table where some users have the same name:</p>
<pre><code>+----+------+
| id | name |
+----+------+
| 1 | Joe |
| 2 | Joey |
| 3 | Joe |
+----+------+
</code></pre>
<p>... and a <code>purchases</code> table:</p>
<pre><code>+---------+--------+
| user_id | amount |
+---------+--------+
| 1 | 400 |
| 1 | 200 |
| 2 | 700 |
| 3 | 100 |
+---------+--------+
</code></pre>
<h1>Goal</h1>
<p>I want to show <strong>for each user, their name and the sum of their purchases</strong> like this (yes there are two people named Joe, no worry):</p>
<pre><code>+------+-------+
| name | total |
+------+-------+
| Joe | 600 |
| Joey | 700 |
| Joe | 100 |
+------+-------+
</code></pre>
<h1>My code</h1>
<pre><code>SELECT name, totals.total
FROM
(
SELECT user_id, SUM(amount) total
FROM purchases
GROUP BY user_id
) AS totals
INNER JOIN users u
ON totals.user_id=u.id;
</code></pre>
<p>It works, producing the right output.</p>
<p>How can I improve this code, in particular by not using a subquery?</p>
<p>Table creation code:</p>
<pre><code>CREATE TABLE users (id INT UNIQUE NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20));
INSERT INTO users (name) VALUES ('Joe'), ('Joey'), ('Joe');
CREATE TABLE purchases (user_id INT NOT NULL, amount INT);
INSERT INTO purchases (user_id, amount) VALUES (1, 400), (1, 200), (2, 700), (3, 100);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:28:36.573",
"Id": "433134",
"Score": "1",
"body": "I appreciate you adding the DDL (create table) and data load (insert statements) in the question. This facilitates reviewing SQL alot!"
}
] | [
{
"body": "<p>If you don't want to use a subquery, you can include the second table with a <em>join</em> before the <em>group by</em>:<br>\n<a href=\"https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=9373829f66ba3958fba27549da94a2c0\" rel=\"nofollow noreferrer\">SQL Fiddle</a></p>\n\n<pre><code>SELECT max(name) name, SUM(amount) total\nFROM purchases\nINNER JOIN users on users.id = purchases.user_id\nGROUP BY user_id\nORDER BY user_id\n</code></pre>\n\n<p>yielding</p>\n\n<pre><code>name total\nJoe 600\nJoey 700\nJoe 100\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:22:55.347",
"Id": "223485",
"ParentId": "223484",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223485",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T08:13:19.517",
"Id": "223484",
"Score": "1",
"Tags": [
"sql",
"mysql",
"join"
],
"Title": "MySQL GROUP BY id, then show name"
} | 223484 |
<p>I would like to know how I might improve my code?
I just started coding and liking it a few days ago so I am quite new to this whole world...</p>
<p>The objective is to calculate the amount of water one has drunk in a day. Depending on the user's input, the app tells him or her if the amount of water drunk is great or not. </p>
<p>Now I would like know how I might improve this whole code?
And I'd be grateful for some advice (what I could improve etc)...</p>
<pre><code>package com.ahmed.everything;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class DrinkingWater {
public static void main(String [] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Amount of water your bottle can hold: ");
// entering amount of water bottle can hold
double litre = sc.nextDouble();
System.out.print("How many bottles have you drunk today? : ");
// amount of bottles for today
double bottles = sc.nextDouble();
// calculating water drunk
double total = (bottles * litre);
// result
if (bottles == 1) {
System.out.print("You've only drunk one bottle today! :(" + "\n");
}
else {
System.out.println("Today, you have drunk " + bottles + " bottles. Which equals to " + total + " liters of water.");
}
// advice
if (total < 4) {
System.out.println("You did not drink enough water, drink at least 4 liters to stay healthy!");
}
else if (total >= 4) {
System.out.println("Good job! You've drunk enough water today! :)");
}
else;
//short time span
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
TimeUnit.SECONDS.sleep(1);
System.out.println(".");
TimeUnit.SECONDS.sleep(1);
System.out.println("Did you like our little app? Please review it from 1-5. 1 being considerer as very good and 5 as very bad.");
int note = sc.nextInt();
if (note <= 4 || note >= 1) {
System.out.println("Thanks for your review.");
}else {
System.out.println("That's better, we'll do our best the next time");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:56:23.447",
"Id": "433154",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] | [
{
"body": "<p><strong>Check your if expression in review part:</strong></p>\n\n<blockquote>\n<pre><code>if (note <= 4 || note >= 1) {\n System.out.println(\"Thanks for your review.\");\n}else {\n System.out.println(\"That's better, we'll do our best the next time\");\n}\n</code></pre>\n</blockquote>\n\n<p>This will always print \"Thanks for your review\" since whatever the value of note will be always true either for <code><= 4</code> or <code>>= 1</code>.</p>\n\n<p>Using an IDE (for example IntelliJ, netbeans, eclipse) helps you mitigate this kind of problems, but it's still better to always review your code.</p>\n\n<p><a href=\"https://i.stack.imgur.com/0HXnx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0HXnx.png\" alt=\"mitigate always true in if expression\"></a></p>\n\n<hr>\n\n<p><strong>Confusing result and advise:</strong></p>\n\n<p><em>I'm not sure if the application is happy that I drank enough water or sad because I only drank 1 bottle</em>. </p>\n\n<p>As stated in your question:</p>\n\n<blockquote>\n <p>The objective is to calculate the amount of water one has drunk in a\n day. Depending on the user's input, the app tells him or her if the\n amount of water drunk is great or not.</p>\n</blockquote>\n\n<p>Then I think you don't need to tell them how many bottles they drink or at least remove the sad face to avoid confusion.</p>\n\n<p><a href=\"https://i.stack.imgur.com/bH7XZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bH7XZ.png\" alt=\"confusing result and advise\"></a></p>\n\n<hr>\n\n<p><strong>User input problems:</strong></p>\n\n<p>Case 1: What if the user input a letter instead of number? This will happen:</p>\n\n<p><a href=\"https://i.stack.imgur.com/q6bWV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q6bWV.png\" alt=\"enter image description here\"></a></p>\n\n<p>Case 2: What if the user input a negative number? Then this will happen:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xLaM9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xLaM9.png\" alt=\"enter image description here\"></a></p>\n\n<p>As you can see in case 1, this will break your program. Although in case 2 the program will not crash, I think it's impossible to drink negative amount of water.</p>\n\n<p><em>To solve this kind of issue, you can use try/catch expression</em>. Something like this:</p>\n\n<pre><code>double litre = 0;\nboolean isInvalidInput = false;\ndo {\n try {\n System.out.print(\"Amount of water your bottle can hold: \");\n // entering amount of water bottle can hold\n litre = sc.nextDouble();\n isInvalidInput = false;\n } catch (InputMismatchException e) {\n isInvalidInput = true;\n }\n sc.nextLine();\n} while(isInvalidInput || litre < 0);\n</code></pre>\n\n<p>If you use the code above, this will be the output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3g4AF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3g4AF.png\" alt=\"tryCatch\"></a></p>\n\n<p>As you can see, the program will ask the same question repeatedly until the user enters a correct input</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T10:37:55.453",
"Id": "433738",
"Score": "0",
"body": "Thank you very much for being so kind and reviewing my code. I do not know how to use try/catch expressions yet. Just put it on my to-do list. Thanks again! I'll try it out"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T04:17:41.507",
"Id": "223538",
"ParentId": "223488",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Do not forget to close the <code>scanner</code></li>\n<li>No need for obvious comments, try to comment why not what, we understand what already</li>\n<li>Why do you have the empty <code>else;</code> ?</li>\n<li>Be consistent using <code>println</code>, no need for + \"\\n\"</li>\n<li>Make use of <code>printf</code></li>\n<li>Use loops or methods instead of copy / paste</li>\n<li>Your last condition is always <code>true</code>, add tests to your apps</li>\n<li><code>if (bottles == 1)</code> but no sad face for 0 bottles? It is even worse.. </li>\n<li>Initialise / introduce variables just before you need them, not somewhere irrelevant (see how I moved <code>double total = (bottles * litre);</code>)</li>\n</ul>\n\n<p>Here is what I have after applying the changes..</p>\n\n<pre><code>import java.util.Scanner;\nimport java.util.concurrent.TimeUnit;\n\nclass DrinkingWater {\n public static void main(String[] args) throws Exception {\n try (Scanner sc = new Scanner(System.in)) {\n System.out.print(\"Amount of water your bottle can hold: \");\n double litre = sc.nextDouble();\n\n System.out.print(\"How many bottles have you drunk today? : \");\n double bottles = sc.nextDouble();\n\n if (bottles == 1) {\n System.out.println(\"You've only drunk one bottle today! :(\");\n } else {\n System.out.printf(\"Today, you have drunk %s bottles. Which equals to %s liters of water.\\n\", bottles, total);\n }\n\n double total = (bottles * litre);\n if (total < 4) {\n System.out.println(\"You did not drink enough water, drink at least 4 liters to stay healthy!\");\n } else if (total >= 4) {\n System.out.println(\"Good job! You've drunk enough water today! :)\");\n }\n\n for (int i = 0; i < 3; i++) {\n TimeUnit.SECONDS.sleep(1);\n System.out.print(\".\");\n }\n\n System.out.println(\"Did you like our little app? Please review it from 1-5. 1 being considerer as very good and 5 as very bad.\");\n int note = sc.nextInt();\n if (note <= 4 || note >= 1) {\n System.out.println(\"Thanks for your review.\");\n } else {\n System.out.println(\"That's better, we'll do our best the next time\");\n }\n }\n }\n}\n</code></pre>\n\n<p>Keep up the good work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T11:32:02.283",
"Id": "433747",
"Score": "0",
"body": "Thank you so much for your time as well. I'll try to see if I understand everything it now does and will get back to you asap :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T17:28:04.063",
"Id": "223687",
"ParentId": "223488",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:15:30.097",
"Id": "223488",
"Score": "3",
"Tags": [
"java",
"beginner"
],
"Title": "Calculate total water drunk in a day"
} | 223488 |
<p>This is a simple implementation of IO completion ports in user mode for Linux.</p>
<p>In Windows IO completion ports work like this: There is a global queue for issuing IO requests. Some worker kernel threads pop from this queue and operate on each request. There is a queue associated with each port you create. When you associate a file handle to a port and perform IO on it it is associated with the same queue. When a worker thread in the Kernel finishes your request it pushes the result into your queue. Then you pop from the port queue using <code>GetQueuedCompletionStatus</code>.</p>
<p>So to sum up: You make a request and bind your queue with it and submit it to a kernel queue and worker threads will do the IO for you then send you the result in your queue.</p>
<p>However in Linux the system doesn't have those worker threads. So to simulate IO completion ports I had to use worker threads in user mode and queues in user mode with <code>epoll</code>.</p>
<p>It is implemented like this:
There is a global thread queue that you push your requests to and workers pop from. There is also a global <code>epoll</code> file descriptor. You submit the request either using <code>epoll</code> (sockets) or directly pushing into the queue for files that don't support <code>epoll</code>. When you create a port you are actually creating a queue to pop from. When you bind a file to the port you bind it to the queue it has. When you issue read or write request you submit a request as described above. When you wait on the port handle you are popping from the queue.</p>
<p>The implementation is at a very early stage and I tested it only with files on disk.</p>
<p>I left out things like handling errors or joining the IO threads for now as I am more concerned with the design at first. Also I used a C-style approach in dealing with structures that could be avoided with C++ constructors and methods.</p>
<p>And this is my code:</p>
<pre><code>#include <queue>
#include <condition_variable>
#include <unistd.h>
#include <sys/epoll.h>
#include <thread>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
template <class T>
class SafeQueue
{
public:
SafeQueue()
{}
void Push(const T& val);
void Push(T&& val);
void Pop(T& val);
T Pop();
void Clear();
bool IsEmpty();
size_t Size();
private :
std::queue<T> q;
std::mutex mtx;
std::condition_variable cv;
};
template<class T>
inline void SafeQueue<T>::Push(const T& val)
{
std::unique_lock<std::mutex> lock(mtx);
q.emplace(val);
cv.notify_one();
}
template<class T>
inline void SafeQueue<T>::Push(T&& val)
{
std::unique_lock<std::mutex> lock(mtx);
q.emplace(std::move(val));
cv.notify_one();
}
template<class T>
inline void SafeQueue<T>::Pop(T& val)
{
std::unique_lock<std::mutex> lock(mtx);
while (q.empty())
{
cv.wait(lock);
}
val = q.front();
q.pop();
}
template <class T>
inline T SafeQueue<T>::Pop()
{
T val;
std::unique_lock<std::mutex> lock(mtx);
while (q.empty())
{
cv.wait(lock);
}
val = q.front();
q.pop();
return val;
}
template <class T>
inline void SafeQueue<T>::Clear()
{
std::unique_lock<std::mutex> lock(mtx);
while(!q.empty())
q.pop();
}
template <class T>
inline bool SafeQueue<T>::IsEmpty()
{
std::unique_lock<std::mutex> lock(mtx);
return q.empty();
}
template <class T>
inline size_t SafeQueue<T>::Size()
{
std::unique_lock<std::mutex> lock(mtx);
return q.size();
}
#define Io_Chunk_Size size_t(1024)
enum IoOpCode
{
IoWriteCode,
IoReadCode,
IoSpecialCode,
};
enum class IoStatusCode
{
IoStatusOk,
IoStatusPending,
IoStatusFailed,
};
struct IoContext
{
IoStatusCode code;
unsigned int bytes;
void *buffer;
unsigned int key;
};
struct IoOperationStruct
{
IoOperationStruct()
{}
IoOperationStruct(const epoll_event& ev);
std::shared_ptr<SafeQueue<IoContext*>> rport;
int fd;
char *buffer;
IoOpCode code;
IoContext *context;
size_t rest;
size_t offset;
};
static int io_epoll_instance;
static SafeQueue<IoOperationStruct*> io_requests;
static bool IoStopFlag;
void IoMainThread()
{
epoll_event evs[50];
while(!IoStopFlag)
{
int num = epoll_wait(io_epoll_instance, evs, 50, 10000);
if (num < 0)
return;
for (int i = 0; i < num; ++i)
{
io_requests.Push((IoOperationStruct*)evs[i].data.ptr);
}
}
}
bool AddIoToQueue(IoOperationStruct *IoStruct, bool modify = false)
{
epoll_event ev;
ev.events = EPOLLONESHOT;
switch(IoStruct->code)
{
case IoWriteCode :
ev.events |= EPOLLOUT;
break;
case IoReadCode :
ev.events |= EPOLLIN;
break;
default:
break;
}
ev.data.ptr = IoStruct;
bool res = epoll_ctl(io_epoll_instance, modify ? EPOLL_CTL_MOD : EPOLL_CTL_ADD,IoStruct->fd, &ev) != -1;
if (!res)
{
if (errno == EPERM)
{
res = true;
io_requests.Push(IoStruct);
}
}
if (!res)
cout << "failed with error : " << strerror(errno) << endl;
return res;
}
struct HANDLE
{
shared_ptr<SafeQueue<IoContext*>> q;
int fd;
unsigned int key;
};
HANDLE CreateIoCompletionPort()
{
HANDLE port;
port.q = make_shared<SafeQueue<IoContext*>>();
port.fd = 0;
return port;
}
void CloseHandle(HANDLE Handle)
{
Handle.q.reset();
if (Handle.fd)
close(Handle.fd);
Handle.fd = 0;
}
HANDLE BindToPort(HANDLE port, int fd, unsigned int key)
{
HANDLE handle;
handle.fd = fd;
handle.q = port.q;
handle.key = key;
return handle;
}
bool GetQueuedCompletionStatus(HANDLE port, unsigned int *num_of_bytes, IoContext **ctx, unsigned int *key, unsigned int wait_time)
{
port.q->Pop(*ctx);
*num_of_bytes = (*ctx)->bytes;
*key = (*ctx)->key;
if (*num_of_bytes)
(*ctx)->code = IoStatusCode::IoStatusOk;
else
(*ctx)->code = IoStatusCode::IoStatusFailed;
return true;
}
bool WriteFile(HANDLE Handle, const void *data, size_t size, IoContext * Ctx)
{
if (!data || !size || !Ctx)
return false;
IoOperationStruct *IoStruct = new IoOperationStruct();
IoStruct->fd = Handle.fd;
IoStruct->rport = Handle.q;
IoStruct->buffer = (char*)data;
IoStruct->context = Ctx;
IoStruct->offset = 0;
IoStruct->rest = size;
IoStruct->code = IoOpCode::IoWriteCode;
IoStruct->context->bytes = 0;
IoStruct->context->code = IoStatusCode::IoStatusPending;
return AddIoToQueue(IoStruct);
}
bool ReadFile(HANDLE Handle, void *data, size_t size, IoContext *Ctx)
{
if (!data || !size || !Ctx)
return false;
IoOperationStruct *IoStruct = new IoOperationStruct();
IoStruct->fd = Handle.fd;
IoStruct->rport = Handle.q;
IoStruct->buffer = (char*)data;
IoStruct->context = Ctx;
IoStruct->offset = 0;
IoStruct->rest = size;
IoStruct->code = IoOpCode::IoReadCode;
IoStruct->context->bytes = 0;
IoStruct->context->code = IoStatusCode::IoStatusPending;
return AddIoToQueue(IoStruct);
}
bool IoHandleWrite(IoOperationStruct & IoStruct)
{
if (!IoStruct.rest)
return false;
size_t to_write = std::min(IoStruct.rest, Io_Chunk_Size);
int written = write(IoStruct.fd, IoStruct.buffer + IoStruct.offset, to_write);
if (written < 0)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
return true;
return false;
}
IoStruct.offset += written;
IoStruct.rest -= written;
IoStruct.context->bytes += written;
if (!IoStruct.rest)
return false;
return true;
}
bool IoHandleRead(IoOperationStruct& IoStruct)
{
if (!IoStruct.rest)
return false;
size_t to_read = std::min(IoStruct.rest, Io_Chunk_Size);
int was_read = read(IoStruct.fd, IoStruct.buffer + IoStruct.offset, to_read);
if (was_read < 0)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
return true;
return false;
}
IoStruct.offset += was_read;
IoStruct.context->bytes += was_read;
IoStruct.rest -= was_read;
if (!IoStruct.rest)
return false;
return true;
}
void IoHandleResult(bool result, IoOperationStruct *IoStruct)
{
if (!result)
{
shared_ptr<SafeQueue<IoContext*>> rport = IoStruct->rport;
IoContext *Ctx = IoStruct->context;
delete IoStruct;
rport->Push(Ctx);
}
else
{
if (!AddIoToQueue(IoStruct, true))
return IoHandleResult(false, IoStruct);
}
}
void IoHandlerThread()
{
IoOperationStruct *IoStruct;
while(!IoStopFlag)
{
io_requests.Pop(IoStruct);
if (IoStruct->code == IoOpCode::IoWriteCode)
{
bool result = IoHandleWrite(*IoStruct);
IoHandleResult(result, IoStruct);
}
else if (IoStruct->code == IoOpCode::IoReadCode)
{
bool result = IoHandleRead(*IoStruct);
IoHandleResult(result, IoStruct);
}
else if (IoStruct->code == IoOpCode::IoSpecialCode)
{
IoHandleResult(false, IoStruct);
}
}
}
void start_io_ports()
{
io_epoll_instance = epoll_create(10);
if (io_epoll_instance < 0)
cout << "failed to open epoll with error : " << strerror(errno) << endl;
IoStopFlag = false;
std::thread(IoMainThread).detach();
for (size_t i = 0; i < std::thread::hardware_concurrency(); ++i)
{
std::thread(IoHandlerThread).detach();
}
}
HANDLE port;
std::condition_variable cv;
std::mutex mtx;
void worker_thread()
{
cout << "id : " << this_thread::get_id() << endl;
while (1)
{
unsigned int bytes;
unsigned int key;
IoContext *ctx;
GetQueuedCompletionStatus(port, &bytes, &ctx, &key, 1000);
cout << " ======== " << endl;
cout << "io was performed " << endl;
cout << "bytes transferred : " << bytes << endl;
cout << " ========= " << endl;
delete (char*)ctx->buffer;
delete ctx;
}
}
int main()
{
start_io_ports();
port = CreateIoCompletionPort();
int fd = open("/sdcard/Ayat/test.txt", O_WRONLY | O_CREAT);
if (fd < 0)
{
cout << "error : " << strerror(errno) << endl;
return 0;
}
HANDLE file = BindToPort(port, fd, 5);
std::thread(worker_thread).detach();
sleep(1);
while (1)
{
cout << "submitting a job" << endl;
char *buff = new char[10010];
IoContext *ctx = new IoContext();
ctx->buffer = buff;
size_t to_write = 0;
for (size_t i = 0; i < 10000; i += 9)
{
memcpy(buff + i, "ttttttttt", 9);
to_write += 9;
}
if(!WriteFile(file, buff,to_write, ctx))
cout << "failed !" << endl;
sleep(2);
}
CloseHandle(file);
sleep(10000000000000000);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:57:57.453",
"Id": "223492",
"Score": "1",
"Tags": [
"c++",
"asynchronous",
"linux"
],
"Title": "C++ - simulating Windows' IO completion ports in Linux"
} | 223492 |
<p>I made this easy game to improve my C++.</p>
<p>The functions like <code>NoFlicker</code> and <code>ShowCursor</code> are copied from the Internet, but I made <code>AlignString</code> by myself and I'm proud of it.</p>
<p>Function <code>changeP()</code> swaps players. Before I created this function and edited my code, I had <code>player1pick</code> and <code>player2pick</code>; now it's more clear. Function <code>Result(char p)</code> takes <code>p</code> from <code>winCheck(pChar)</code>. <code>pChar</code> is symbol of active player and <code>winCheck()</code> checks if there are 4 blocks in one of the ways and then returns <code>p</code> as result.</p>
<p>The first thing in <code>main</code> rescales console also from internet. <code>Setup()</code> sets everything up before new game. <code>Pick()</code> asks active player for column. <code>draw()</code> draws field and the tagged lines are about coloring it but it's more complicated than I thought.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <Windows.h>
#include <conio.h>
using namespace std;
bool gameOver, p1t, p2t;
char p1[25], p2[25], player[25];// , winner[25];
const unsigned short int X = 9, Y=7;
char field[7][8];//7 - lower border, 8 - 2 side borders
int temp[7] = {6,6,6,6,6,6,6};//to know on what lvl next block will be placed
int cPick, pColor;//column pick
char pChar;//player char for later change by players desire
void NoFlicker(short int x, short int y) { //No flickering fix (Internet)
COORD pos = { x, y };
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}//End of NoFlicker
void ShowCursor(bool showFlag) { //Show the cursor while drawing (Internet)
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(out, &cursorInfo);
cursorInfo.bVisible = showFlag; // set the cursor visibility
SetConsoleCursorInfo(out, &cursorInfo);
}//End of ShowCursor
void AlignString(string text, int y) { //Aligns strings to the Middle (by me)
int size;
size = 60 - (text.length() / 2);
for (int ent = 0; ent <= y; ent++) {
cout << "\n";
}
for (int gap = 0; gap < size; gap++) {
cout << " ";
}
cout << text;
}//End of AlignString
void draw() {
NoFlicker(0, 40);
cout << "\t\t\t\t\t\t\t 1234567 \n";
for (int i = 0; i < Y; i++) {
cout << "\t\t\t\t\t\t\t";
for (int j = 0; j < X; j++) {
if (i == Y-1 || j == 0 || j == X-1) {
//SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 9);
field[i][j] = 219;
//cout << field[i][j];
}else if (cPick == j) {
//SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), pColor);
field[temp[cPick - 1]][j] = pChar;
//cout << field[i][j];
} /*else {
if (field[i][j] == 1){
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14);
cout << field[i][j];
} else if(field[i][j] == 2) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 4);
cout << field[i][j];
} else {
field[i][j] = ' ';
cout << field[i][j];
}*/
cout << field[i][j];
}cout << endl;
}
/*cout << endl;
for (int i = 0; i < 7; i++) {
cout <<temp[i];
}cout << endl;*/
}
void changeP() {//changes players
if (p1t) {
pChar = 1; //current player's symbol
pColor = 14;
strcpy_s(player, p1);//googled this function
p1t = false; //player's 1 turn
p2t = true;//player's 2 turn
}
else if (p2t) {
pChar = 2;
pColor = 4;
strcpy_s(player, p2);
p1t = true;
p2t = false;
}
}
void result(char p) {
if (p == 1) {
gameOver = true;
AlignString(p1, 1);
AlignString("Won the game! It was fair match", 1);
AlignString("New game will start in less than 10 seconds!", 10);
}
else if (p == 2) {
gameOver = true;
AlignString(p2, 1);
AlignString("Won the game! It was fair match!", 1);
//strcpy_s(winner, p1);
AlignString("New game will start in less than 10 seconds!",10);
}
}
char winCheck(char p) {
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 9; j++) {
if (field[i][j] == p && field[i+1][j + 1] == p && field[i+2][j + 2] == p && field[i+3][j + 3] == p) {//Diagonal Right Down Check
return p;
}
if (field[i][j] == p && field[i][j + 1] == p && field[i][j + 2] == p && field[i][j + 3] == p) {//Horizontal Check
return p;
}
if (field[i][j] == p && field[i-1][j + 1] == p && field[i-2][j + 2] == p && field[i-3][j + 3] == p) {//Diagonal Right Up Check
return p;
}
if (field[i][j] == p && field[i - 1][j] == p && field[i - 2][j] == p && field[i - 3][j] == p) {//Vertical Check
return p;
}
}
}
}
void pick() {
AlignString(player, 1);
AlignString("you can pick your column --> ",1);
cin >> cPick;
if (cPick > 7 || cPick < 1) {
AlignString("nIllegal pick. Try again!", 1);
pick();
} else {
temp[cPick - 1] -= 1;
if (temp[cPick - 1] < 0) {
AlignString("This column is full. Try another one!",1);
pick();
}
system("cls");
}
}
void setup() {
ShowCursor(false);
gameOver = false;
p1t = true;
p2t = false;
AlignString("Player 1, write your name or how you wanna be called here --> ",5);
//cout << "\n\t\t\t\";
cin.getline(p1, 25);
AlignString("Ok now, Player 2, write your name or how you wanna be called here --> ",1);
cin.getline(p2, 25);
system("cls");
draw();
}
void main() {
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r); //stores the console's current dimensions
MoveWindow(console, r.left, r.top, 900, 900, TRUE); // 800 width, 100 height
setup();
while (!gameOver) {
changeP();
pick();
draw();
result(winCheck(pChar));
}
Sleep(10000);
main();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:36:37.263",
"Id": "433173",
"Score": "1",
"body": "I know nothing of `<Windows.h>` or `<conio.h>`, so not qualified to review this, but you probably ought to eliminate `using namespace std;` and all those globals, as well as the call of `main()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T15:49:33.940",
"Id": "433392",
"Score": "0",
"body": "I've updated my answer to cover one of your additional questions."
}
] | [
{
"body": "<p><strong>Usage of main()</strong><br />\nIn C++ <code>main()</code> should only be called by the operating system, <a href=\"https://en.cppreference.com/w/cpp/language/main_function\" rel=\"nofollow noreferrer\">never by the program itself</a>, it is the entry point into the program from the operating system. <a href=\"https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c/18721336\">The definition of <code>main()</code> is integer so that it can return the status of the program to whatever is calling it</a>.</p>\n<p>Due to the recursive nature of the use of <code>main()</code> in this program it is possible that a stack overflow will occur and that may cause security risks on the computer running this program. A stack overflow may have other undesired side affects as well.</p>\n<blockquote>\n<p><strong>EDIT</strong> As pointed out by @TobySpeight calling <code>main()</code> from inside a c++ program results in Undefined Behavior. This means that it could do almost anything and none of what would do can be expected and is probably a bad thing. For example data within the program can be corrupted. Back when I started programming it could have shut down the computer by causing a Kernel Panic.</p>\n<p>There is a perfectly good loop in <code>main()</code> for executing the game, to run another game put the game loop and the sleep statement into an outer loop.</p>\n</blockquote>\n<p>This is an example of <code>main()</code> without calling itself, it compiles, I don't know if it works:</p>\n<pre><code>int main() {\n\n HWND console = GetConsoleWindow();\n RECT r;\n GetWindowRect(console, &r); //stores the console's current dimensions\n MoveWindow(console, r.left, r.top, 900, 900, TRUE); // 800 width, 100 height\n string playAgain("no");\n\n do {\n setup();\n while (!gameOver) {\n changeP();\n pick();\n draw();\n result(winCheck(pChar));\n }\n std::cout << "Enter yes to play again";\n std::getline(std::cin, playAgain);\n } while (playAgain.compare("yes") == 0);\n\n}\n</code></pre>\n<p><strong>using namespace std</strong><br />\nThe use of this statement may cause collisions of function names and variables, it would be much better to use <code>std::cin</code>, <code>std::cout</code> and <code>std::string</code> rather than having this statement in the code. Having this statement in a header file can cause even more confusion. As you write more complex program that are object oriented you may find yourself defining <code>cin</code> and <code>cout</code> for your objects so that they can be input or output.</p>\n<p><strong>Global Variables</strong><br />\nThe use of global variables makes writing and debugging code more difficult. Global variables may be modified anywhere in the program and changes to a variable can be difficult to track down.</p>\n<p><strong>Magic Numbers</strong><br />\nNumeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, since it isn't clear what they are or mean.</p>\n<p>There are a number of numeric constants used in the code, such as 0, 1, 2, 4, 14, 40, and 219. This makes the code harder to read and understand. It isn't clear what <code>pColor = 4</code> or <code>pColor = 14</code> are doing and it really isn't clear what this statement is doing <code>field[i][j] = 219;</code></p>\n<p>You can use <code>const int PLAYER_ONE = 1;</code> or <code>const int FIELD_HEIGHT = 7; const int FIELD_WIDTH = 8;</code> to define symbolic constants rather than numbers. This will make the code easier to read, and if you need to change the size of field you only need to edit in one place rather than multiple places. It will also make easier to understand any for loops that move through the <code>field</code> matrix.</p>\n<p><strong>String Versus C Style String</strong><br />\nThe code already includes the C++ string class, it might be better if p1, p2 and player were defined as string rather C style character arrays. The built in <code>std::cin</code> and <code>std::cout</code> already know how to handle the string class.</p>\n<p><strong>Use struct or class</strong><br />\nThere could be a struct or class that represents a player. It could have the fields <code>int id;</code>, <code>string name;</code> and <code>int color;</code>. This would reduce the number of variables for each player.</p>\n<pre><code> std::cin >> p1.name;\n\n std::cin >> p2.name;\n</code></pre>\n<p>or the struct or class could contain a function that gets the user name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T16:09:57.230",
"Id": "433231",
"Score": "0",
"body": "Hi, thank you for your feedback.\n\nmain():\nwhen i shouldn't call in prograb but only OS how would I make it repeat?\n\nusing namespace std;\nwhat collisions? If I don't have two same names then they can't collide and I can't see what std has to do with it.\n\nGlobal variables:\nWhere should I put them then? When I use them in multiple functions.\n\nMagic numbers:\nI don't get it. and the 0, 1,2...are numbers from ascii except 4 and 14 they are colors and how should I do it without using them?\nwhen I tried to use string something didnt worked so I switched to char field idr what didnt work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T16:16:18.043",
"Id": "433232",
"Score": "0",
"body": "and about the structs or classes I dont know what struct is and classes I haven't learned yet. Like I know how they work, whats their syntax creating objects then but Idk how to use or when to use them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T17:37:20.860",
"Id": "433243",
"Score": "1",
"body": "Calling `main()` is Undefined Behaviour, so *anything* could happen. not limited to the normal effects of infinite recursion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T14:27:15.830",
"Id": "223511",
"ParentId": "223493",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T09:58:24.187",
"Id": "223493",
"Score": "0",
"Tags": [
"c++",
"console",
"winapi",
"connect-four"
],
"Title": "Simple \"Connect 4\" game"
} | 223493 |
<p>Based on userAccessData Object i need to filter the properties so what ever properties inside the fields are there they will be exist in the updatedValue, i am able to do it.</p>
<p>also one more thing if the ouput is an empty object then there is no need to have that object want to remove that also</p>
<p>i have tried the below code. its working but is there any better way and how should i remove the empty object</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const userAccessData = {
forms: {
student: [
{
studentDetails: ['read', 'create', 'update'],
},
],
class: [
{
classDetails: ['read', 'create', 'update'],
},
{
classSecondaryDetails: ['read', 'create', 'update'],
},
],
school: [
{
schoolContact: ['read', 'create', 'update'],
},
{
schoolAddress: ['read'],
},
{
schoolBasicDetails: ['read', 'create'],
},
{
schoolLocationDetails: ['read', 'create', 'update'],
},
],
},
fields: {
school: {
schoolAddress: [
{
isAddress: ['read', 'update'],
},
],
schoolLocationDetails: [
{
status: ['read'],
},
],
schoolContact: [
{
contactAddress: ['read'],
},
{
contactStatus: ['read', 'create'],
},
],
},
student: {
studentDetails: [
{
isAvailable: ['read'],
},
],
},
class: {
classDetails: [
{
classId: ['read', 'create', 'update'],
},
],
},
},
};
let updatedValue = {
values: {
schoolContact: {},
schoolLocationDetails: {
status: '123',
},
schoolAddress: {
isAddress: 'yes',
status: 'no'
},
}
};
const updateDetailsWithAccess = (updatedData, accessListData, selectedSection) => {
const accessForms = Object.keys(accessListData[selectedSection]);
Object.keys(updatedData.values).forEach((o) => {
if (accessForms.indexOf(o) === -1) {
delete updatedData.values[o];
}
});
Object.keys(updatedData.values).forEach((o) => {
const accessFormsForFields = accessListData[selectedSection][o].map(field => Object.keys(field)[0])
Object.keys(updatedData.values[o]).forEach((field) => {
if (accessFormsForFields.indexOf(field) === -1) {
delete updatedData.values[o][field];
}
});
});
return updatedData;
};
console.log(updateDetailsWithAccess(updatedValue, userAccessData.fields, 'school'))</code></pre>
</div>
</div>
</p>
<p><strong>expected output</strong></p>
<pre><code>{
"values": {
"schoolLocationDetails": {
"status": "123"
},
"schoolAddress": {
"isAddress": "yes"
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:39:08.910",
"Id": "433150",
"Score": "1",
"body": "I'm sorry I don't have the time to check it right now, but if I was you I would have tried using https://deepdash.io/#filterdeep. You should try to reduce as much as possible the `forEach` cycles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:41:28.837",
"Id": "433151",
"Score": "0",
"body": "but is there any need of additional package, i have tried another way but it was taking more time. this was the comparatively better one from my end. So that's why i asked for a review. It will be helpful if you have a look at the above"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:12:38.930",
"Id": "223496",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "removing the properties based on another object - better way"
} | 223496 |
<p>Here is my code, which doesn't seem to work for <strong>numbers in between -1 and 0</strong> (works perfectly fine otherwise)</p>
<p>I think the code enters an infinite loop, somehow, hence I get no result after entering the number. Please have a look and let me know what changes should be made. I am a beginner at programming and would appreciate any help!</p>
<pre><code> cube = float(input('Enter:'))
if abs(cube) > 1:
num_guesses = 0
epsilon = 0.0001
low = 0
high = cube
guess = (high + low) / 2.0
while abs(abs(guess) ** 3 - abs(cube)) >= epsilon:
if cube > 0:
if guess ** 3 < cube:
low = guess
else:
high = guess
guess = (low + high) / 2.0
num_guesses += 1
else:
if guess ** 3 > cube:
low = guess
else:
high = guess
guess = (low + high) / 2.0
num_guesses += 1
if abs(cube) < 1:
num_guesses = 0
epsilon = 0.0001
low = cube
high = 1
guess = (high + low) / 2.0
while abs(abs(guess) ** 3 - abs(cube)) >= epsilon:
if cube > 0:
if guess ** 3 < cube:
low = guess
else:
high = guess
guess = (low + high) / 2.0
num_guesses += 1
else:
low = -1
high = cube
if guess ** 3 > cube:
high = guess
else:
low = guess
guess = (low + high) / 2.0
num_guesses += 1
print(num_guesses)
print('The cube root of',cube,'is closest to',guess)
</code></pre>
<p>Thanks a lot!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T11:03:05.253",
"Id": "433156",
"Score": "1",
"body": "Welcome to Code Review! Your [code has to be working as intended](/help/on-topic) before it is ready to be reviewed. Code that is not yet working as intended is [off-topic](/help/dont-ask) here. [so] is usually a more appropriate place to ask for help on how to solve such issues. Once everything works, come back and we will be happy to provide feedback on how it can be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:10:34.767",
"Id": "433170",
"Score": "0",
"body": "@arya_stark, try to use only _one `while` loop_ ; that should actually make the entire problem simpler. In addition try to start with `high = 1 + abs(cube)` and `low = -high`. You guess is correct, and the update of `low` and `high` also seems correct."
}
] | [
{
"body": "<p>There are some problems with your code, the algorithm being (too complicated, it is also) wrong.</p>\n\n<p>In addition to that, you haven't made any <strong>functions</strong>, which you should strongly consider doing.</p>\n\n<p>The better way of writing this script is to write two (or more) functions, one function being the actual <code>cuberoot</code> function which accepts one (or two) argument, namely the number you want to find the cube root for. It should return one number, the cube root.</p>\n\n<p>Writing functionality in function, or perhaps <em>encapsulating functionality in functions</em> allows you to more easily test the function. Having all functionality in functions, also allows you to <strong>import cuberoot</strong> from a different file. This is essential when building more complex applications and libraries later.</p>\n\n<p>I have attached one example of how you can modularize your code so that it is both easy to test and easy to import, and not least of all, it's easy to read and thus understand.</p>\n\n<p>As you can see in the <code>while</code> loop, it is quite close to your example, but a bit simplified.</p>\n\n<p>I have also added an <code>assert</code> statetment in the <code>main</code> function to easily verify that the result is correct. Adding automatic tests are now quite easy as well.</p>\n\n<p>The bottommost <code>__main__</code> part is there to ensure that the <code>main</code> function is called only if we call the file as a script:</p>\n\n<pre><code>$ python cuberoot.py -0.5\n-0.7936859130859375\n</code></pre>\n\n<hr>\n\n<p>Here is the <em>refactored</em> code:</p>\n\n<pre><code>def cuberoot(cube, epsilon=0.0001):\n \"\"\"Compute cube root of n using binary search.\n\n We yield the result when |result**3-n|<epsilon.\n \"\"\"\n high = 2 + abs(cube)\n low = -high\n while True:\n guess = (low + high) / 2.0\n err = abs(cube - guess ** 3)\n if err < epsilon:\n return guess\n if guess ** 3 > cube:\n high = guess\n else:\n low = guess\n\n\ndef main():\n \"\"\"Read one number from command line and print its cube root.\"\"\"\n from sys import argv\n\n try:\n cube = float(argv[1])\n except ValueError:\n exit(\"Usage: cuberoot n [n must be a number]\")\n except IndexError:\n exit(\"Usage: cuberoot n\")\n\n cr = cuberoot(cube)\n assert abs(cr ** 3 - cube) < 0.0001 # verify the result\n print(cr)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T16:18:32.203",
"Id": "223516",
"ParentId": "223497",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223516",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T10:54:12.603",
"Id": "223497",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "Cube root in Python 3 using Bisection Search: Numbers in -1 to 0"
} | 223497 |
<p>I tried to make a function able to compute the binary sum. Binary numbers are passed as list composed of <code>1</code> and <code>0</code>, like <code>[1,1,0,1]</code>, <code>[0,0,1]</code>, etc.
It seems to work. I tried to improve the code, but I don't think this is the best way to make it work. How can I improve this?</p>
<pre><code>def check(value):
if value%2 == 0: #check if the number can be divided by 2
amount = int(value / 2) #if so, set the value to 0 and the amount as the number divided by 2
value = 0
elif value%2 != 0: #if not so, set the value to 0 and the amount as the previous even number divided by 2
amount = int((value-1)/2)
value = 1
return value, amount #returns the 2 value.
def binary_sum(*args):
"""The program compute the binary sum of 2+ binary lists, like [1,1,1,1] + [0,0,0,1]"""
i = -1 #control variable
result = [] #list that will be filled by results' binary numbers
value = 0
amount = 0 #amount carried over
binaryLength = [] #list of all args length
for x in args: binaryLength.append(len(x)) #get the length of each args elements
maxLength = max(binaryLength) #get the max length among args elements
for x in args:
if len(set(binaryLength)) != 1: #checks if all elements have the same length
delta = maxLength - len(x) - 1 #if not so, it adds as many zeros as delta value indicates
while (delta) >= 0:
x[:0] = [0]
delta -= 1
while i >= -maxLength: #starts the sum from the end.
for j in args: value += j[i] #get the sum of all the last list element( for each arg)
value += amount
value, amount = check(value) #uses binary sum properties: it returns a value between 0 and 1, and the amount, an integer
result.insert(i, value) #inserts the value at the beginning of the list
i-=1 # needed to iterate the process
value = 0 #resets the value
if amount != 0: #At the end, if there's amount it inserts it at the beginning of result list:
while amount not in [0,1]: #if is not equal to 0 or 1 converts the int amount in binary number
value = amount
value, amount = check(value)
result.insert(i, value)
i-=1
result.insert(i, amount) #if is equal to 1 inserts it at the start of the list.
return result #returns the result as list.
</code></pre>
| [] | [
{
"body": "<p>A binary sum (any sum, really) only needs four things:</p>\n\n<ul>\n<li>The left operand</li>\n<li>The right operand</li>\n<li>A variable to store the carry value (bit)</li>\n<li>A variable to store the output value</li>\n</ul>\n\n<p>You can greatly simplify this problem by moving from right to left—after all, that is how numbers are traditionally summed in any number system (decimal, octal, hex, binary, anything).</p>\n\n<p>Let's start with some of the problems in your code and then look at a better approach:</p>\n\n<h3>Variable naming</h3>\n\n<p>Some of your variable names don't make sense. For example:</p>\n\n<ul>\n<li><code>value = 0</code> (what value?)</li>\n<li><code>amount = 0 #amount carried over</code> (why not call this <code>carry</code>?)</li>\n<li><code>binaryLength = [] #list of all args length</code> (I'm still not quite sure what this means)</li>\n</ul>\n\n<p>There's also the issue of using <code>x</code> in your loops. Is it possible to understand what it represents? Sure. But you use too many <code>x</code>s, <code>i</code>s, and <code>j</code>s. It's all too much to keep track of. Consider renaming <code>x</code> to <code>arg</code>: <code>for arg in args</code>. There—it certainly reads better.</p>\n\n<h3>Functions and their length</h3>\n\n<p>Your <code>binary_sum</code> function is monstrous—it's too long and is doing lots of things at once. Years down the line, if you revisit your code, are you sure you will be able to follow what it's doing? I'm personally having trouble following along.</p>\n\n<p>So where do you start? I suggest running through all of your comments and classifying them:</p>\n\n<ul>\n<li><p>Good comments: state why you're doing something and don't explain <em>what</em> you're doing.</p></li>\n<li><p>Bad comments: the code itself is difficult to understand; the comment is there to basically tell the reader <em>what</em> you're doing.</p></li>\n</ul>\n\n<p>You have a lot of bad comments. Consider splitting <code>binary_sum</code> into different function calls, using informative names that tell the reader what those functions are doing. The outer <code>for</code> and <code>while</code> loops look like good candidates, at first glance.</p>\n\n<h3>A simpler approach</h3>\n\n<p>Let's take a step back and consider one issue at a time:</p>\n\n<ol>\n<li>We're given two input lists. Okay, but what if they're not of the same length? You seem to have already recognized this. At this point, you should consider writing a generic function that, given a list and a desired length, will pad that list with zeros at the front until the list is of the desired length (assuming the number isn't negative—does the problem state anything about this or two's complement?):</li>\n</ol>\n\n<pre><code>def padWithZeros(num, desiredLength):\n zerosNeeded = desiredLength - len(num)\n return [0] * zerosNeeded + num\n</code></pre>\n\n<p>If negative numbers do need to be accounted for, then it's just a matter of using <code>[num[0]] * bitsNeeded</code> instead of the hardcoded <code>0</code> in <code>[0] * zerosNeeded</code>.</p>\n\n<ol start=\"2\">\n<li>Okay, one problem down. Now let's get the numbers from the command line. Don't throw this into the <code>binary_sum</code> function. Instead, the <code>binary_sum</code> function should take two numbers to add. We'll pass along those numbers from <code>main</code>. Consider using the <code>sys</code> library.</li>\n</ol>\n\n<pre><code>import sys\n...\ndef main():\n num1 = sys.argv[1]\n num2 = sys.argv[2]\n print(\"{} + {} = {}\".format(num1, num2, binary_sum(num1, num2))\n</code></pre>\n\n<p><strong>Edit</strong>: Oversight on my part. This doesn't work because the <code>sys.argv</code> tokens will ignore the list elements.</p>\n\n<p>There. Short and sweet, and it's clear what we're doing. This will be the entry point for the program.</p>\n\n<ol start=\"3\">\n<li>Now let's get to the <code>binary_sum</code> method. We need to pad the shorter number:</li>\n</ol>\n\n<pre><code>def binary_sum(num1, num2):\n if len(num1) < len(num2):\n num1 = padWithZeros(num1, len(num2))\n elif len(num2) < len(num1):\n num2 = padWithZeros(num2, len(num1))\n</code></pre>\n\n<p><strong>Edit</strong>: we can make this (and <code>padWithZeros</code>) even simpler by considering just the difference <code>len(num1) - len(num2)</code>. If it's negative, then <code>num1</code> is shorter than <code>num2</code>, so pad <code>num1</code> with the negative of that difference. If it's positive, then <code>num1</code> is longer than <code>num2</code>, so pad <code>num2</code> with that difference.</p>\n\n<p>What do we do next? Now that we have two lists of equal length, we can begin traversing them using a single iterator/index. Let's express an algorithm: Moving right to left, take the digit from num1 and add it to the digit from num2, plus the carry, and then determine what the corresponding result bit should be as well as what the new carry should be. Repeat until we process the leftmost bit.</p>\n\n<p>We have these possibilities (the last bit is the carry in these computations):</p>\n\n<p>1 + 1 + 1 = 3 (011) = 1 carry 1</p>\n\n<p>1 + 1 + 0 = 2 (10) = 0 carry 1</p>\n\n<p>1 + 0 + 0 = 1 (01) = 1 carry 0</p>\n\n<p>1 + 0 + 1 = 2 (10) = 0 carry 1</p>\n\n<p>0 + 0 + 0 = 0 (00) = 0 carry 0</p>\n\n<p>0 + 0 + 1 = 1 (01) = 1 carry 0</p>\n\n<p>There are two approaches:</p>\n\n<ul>\n<li><p>Straightforward approach: Use a series of <code>if/elif</code> to evaluate the decimal results: <code>0</code>, <code>1</code>, <code>2</code>, or <code>3</code>.</p></li>\n<li><p>Math trick: the result bit is by definition always the sum modulo 2. The carry bit is always the sum divided by 2.</p></li>\n</ul>\n\n<p>Of course, you also have to decide if there's going to be any overflow/cutoff. If the carry bit at the very end is a <code>1</code>, then you should either add a <code>01</code> to the front of the result (no overflow) or simply do nothing (overflow, result is inaccurate).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T05:33:50.343",
"Id": "433319",
"Score": "0",
"body": "You missed the requirement that it must add **two or more** binary lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T11:07:32.280",
"Id": "433358",
"Score": "0",
"body": "Where was that requirement stated? I didn't notice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T13:24:38.123",
"Id": "433373",
"Score": "0",
"body": "The docstring of `binary_sum`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T14:26:14.103",
"Id": "223510",
"ParentId": "223501",
"Score": "2"
}
},
{
"body": "<p>You've got <em>way too much</em> code. You are not using the built-in tools Python provides to solve this problem, making your job much, much harder.</p>\n\n<hr>\n\n<p>In your <code>check(value)</code> function, you are checking:</p>\n\n<pre><code>if value % 2 == 0:\n # ...\nelif value % 2 != 0:\n # ...\n</code></pre>\n\n<p>If <code>value % 2 == 0</code> is <code>False</code>, then <code>value % 2 != 0</code> is guaranteed to be <code>True</code>. There is no need for the <code>elif ...:</code>; you could simply use an <code>else:</code> clause.</p>\n\n<p>In both cases, you assign <code>amount = int( ... / 2)</code>. Python has built-in integer division operator, <code>//</code>, so these statements could become simply <code>amount = ... // 2</code>. In the second case, because <code>value</code> is odd, you divide <code>value - 1</code> by two. This \"subtract 1\" is unnecessary. Using integer division (or dividing and then casting to an integer) will truncate the result to an integer.</p>\n\n<p>Afterwards, in the first case, when <code>value % 2</code> is zero, you assign <code>value = 0</code>, where as in the second case, when <code>value % 2</code> is one, you assign <code>value = 1</code>. You could simply assign <code>value = value % 2</code>.</p>\n\n<pre><code>def check(value):\n amount = value // 2\n value = value % 2\n return value, amount\n</code></pre>\n\n<p>Or slightly shorter:</p>\n\n<pre><code>def check(value):\n return value % 2, value // 2\n</code></pre>\n\n<p>Or even better, use the built-in function <a href=\"https://docs.python.org/3/library/functions.html#divmod\" rel=\"nofollow noreferrer\"><code>divmod(a,b)</code></a> which does the same thing. But you will have to swap the variables you assign to, because <code>divmod(a,b)</code> returns the result of the division first, and the modulo remainder second:</p>\n\n<pre><code>amount, value = divmod(value, 2)\n</code></pre>\n\n<hr>\n\n<p>In your <code>binary_sum(*args)</code> function, you are given a variable number of lists, and you want to take one element from each list, then take the next element from each list, and then take the next element from each list, and so on. In Python, this is the <code>zip()</code> function. (Note: \"zip\" is short for \"zipper\", not zip-compression.)</p>\n\n<pre><code>for addends in zip(*args):\n # ...\n</code></pre>\n\n<p>Except we have a wrench in the works; you want to start from the end and work towards the front. That is hard. It is easier if each list is <a href=\"https://docs.python.org/3/library/functions.html?highlight=reversed#reversed\" rel=\"nofollow noreferrer\"><code>reversed()</code></a>, so starting from the start is starting from what was the end. We can then <code>zip()</code> those <code>reversed()</code> lists together:</p>\n\n<pre><code>for addends in zip(*map(reversed, args)):\n # ...\n</code></pre>\n\n<p>Except we have another wrench in the works; the lists aren't all the same length, and <code>zip</code> stops when any of the lists runs out of items. You need to add 0's at the start, so they are the same length. Except we've reversed the lists, so we need to add 0's to the end. That's easy. We just need <a href=\"https://docs.python.org/3/library/itertools.html?highlight=zip_longest#itertools.zip_longest\" rel=\"nofollow noreferrer\"><code>itertools.zip_longest(*args, fillvalue=0)</code></a> to provide the extra 0's.</p>\n\n<pre><code>from itertools import zip_longest\n\nfor addends in zip_longest(*map(reversed, args), fillvalue=0):\n # ...\n</code></pre>\n\n<p>Now <code>addends</code> is first the 1's column digits, then the 2's column digits, then the 4's column digits, and so on. We can just sum the <code>addends</code> together, along with any carry from the previous column:</p>\n\n<pre><code>digits = []\ncarry = 0\nfor addends in zip_longest(*map(reversed, args), fillvalue=0):\n total = sum(addends) + carry\n carry, digit = divmod(total, 2)\n digits.append(digit)\n</code></pre>\n\n<p>And then, add the carry bits to end once you've run out of columns:</p>\n\n<pre><code>while carry > 0:\n carry, digit = divmod(carry, 2)\n digits.append(digit)\n</code></pre>\n\n<p>Finally, since we've generated the result in the wrong order, you'll have to reverse it again, so the most significant digit is first.</p>\n\n<pre><code>from itertools import zip_longest\n\ndef binary_sum(*args):\n digits = []\n\n carry = 0\n for addends in zip_longest(*map(reversed, args), fillvalue=0):\n total = sum(addends) + carry\n carry, digit = divmod(total, 2)\n digits.append(digit)\n\n while carry > 0:\n carry, digit = divmod(carry, 2)\n digits.append(digit)\n\n return digits[::-1]\n</code></pre>\n\n<p>A few tests:</p>\n\n<pre><code>>>> binary_sum([1,1,1,0])\n[1, 1, 1, 0]\n>>> binary_sum([1,1,1,0], [1,0])\n[1, 0, 0, 0, 0]\n>>> binary_sum([1,1,1,1], [1])\n[1, 0, 0, 0, 0]\n>>> binary_sum([1,1,1,1], [0,0,0,1])\n[1, 0, 0, 0, 0]\n>>> binary_sum([1,1,1,1], [1,0,0,0])\n[1, 0, 1, 1, 1]\n>>> binary_sum([1], [1], [1], [1], [1])\n[1, 0, 1]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T05:20:39.417",
"Id": "223540",
"ParentId": "223501",
"Score": "3"
}
},
{
"body": "<p>And here is an example of approaching it from the \"other\" side.\nAlgorithm here would be:</p>\n\n<p>Input: binary numbers: [1, 0], [1, 1, 1]</p>\n\n<p>Output: Sum of inputs as binary number: [1, 0, 1]</p>\n\n<p>Algorithm:</p>\n\n<ol>\n<li>Convert binary to base 10 digit, ex: [1, 1, 1] -> 7, [1, 0] -> 2</li>\n<li>Add them: 7 + 2 -> 9</li>\n<li>Convert to binary: [1, 0, 0, 1] </li>\n</ol>\n\n<p>Implementation:</p>\n\n<pre><code> def binary_sum(*numbers):\n stringify = lambda digits: ''.join(map(str, digits)) \n numbers = [stringify(n) for n in numbers] \n\n to_base10 = lambda digits: int(digits, 2)\n to_base2 = lambda number: [int(d) for d in bin(number)[2:]] # bin(9) -> '0b1001', thus cut first two chars\n\n base10_sum = sum([to_base10(n) for n in numbers]) # 1 + 2 step\n return to_base2(base10_sum) # 3 step\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T03:09:12.693",
"Id": "433685",
"Score": "0",
"body": "[Every answer must make at least one insightful observation about the code in the question.](https://codereview.stackexchange.com/help/how-to-answer) Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T12:53:19.947",
"Id": "223673",
"ParentId": "223501",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T12:40:30.480",
"Id": "223501",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Compute binary sum with Python 3"
} | 223501 |
<p>I am doing an image drawing and rendering library, and would like some feedback on this code, it simply draws a line in any direction.</p>
<p>The equation for that is:</p>
<p>m = (y2 - y1) / (x2 - x1)</p>
<p>b = y1 - m * x1</p>
<p>y = mx + b</p>
<p>It works but all these if statements are bothering me, and I am not sure if it's the best solution.</p>
<pre><code>proc line*(img: var Image, x1, y1, x2, y2: int) =
# Necessary pass the values to variables so we can manipulate them
var
a1 = x1
a2 = x2
b1 = y1
b2 = y2
# To draw correctly we need to iterate over the longest axis
if abs(a1 - a2) > abs(b1 - b2):
swap(a1, b1)
swap(a2, b2)
# ¹ To make sure we are iterating from the lower to the higher
if b1 > b2:
swap(a1, a2)
swap(b1, b2)
let m = (a2 - a1) / (b2 - b1)
let s = float(a1) - m * float(b1)
# ¹ Since we swiped the axis we need to swap x and y
if abs(x1 - x2) > abs(y1 - y2):
for b in b1..b2:
let a = float(b) * m + s
img.pixel(b, toInt(a), img.strokeColor)
else:
for b in b1..b2:
let a = float(b) * m + s
img.pixel(toInt(a), b, img.strokeColor)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T15:03:16.553",
"Id": "433388",
"Score": "0",
"body": "Hi, could you maybe expand a little bit more on what your code is doing? I think you're overcomplicating it with the axis swapping and all"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:29:23.107",
"Id": "223506",
"Score": "6",
"Tags": [
"image",
"graphics",
"nim"
],
"Title": "Drawing a line in any direction with pixels"
} | 223506 |
<p>If you want to use a custom deleter in <code>unique_ptr</code> you either have to pass a functor or the signature of a delete function as template argument. If you have a freestanding delete function (often from a C API) you have to pass the actual address of the function to every instance of your <code>unique_ptr</code>. To avoid that I created a little template that converts a freestanding delete function into a functor.</p>
<pre><code>template<auto* FN>
struct Deleter;
template<typename Ptr, void(*FN)(Ptr*)>
struct Deleter<FN>
{
void operator()(Ptr* ptr)
{
FN(ptr);
}
};
</code></pre>
<p>Usage:</p>
<pre><code>#include <memory>
// Delete function
void delete_float(const float* ptr)
{
delete ptr;
}
int main()
{
// How you normally specify a deleter
std::unique_ptr<float, decltype(&delete_float)> float_ptr1(new float(3.141), &delete_float);
// With the helper template
std::unique_ptr<float, Deleter<&delete_float>> float_ptr2(new float(3.141));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T17:47:10.573",
"Id": "433245",
"Score": "1",
"body": "Also it might be helpful to point out the [original problem](http://coliru.stacked-crooked.com/a/dfc666fbaea4b0f2) you want to solve with this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T07:26:06.220",
"Id": "433326",
"Score": "0",
"body": "There is no need for a new type, just use `std::integral_constant` like [here](https://stackoverflow.com/a/56411620/3204551)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:48:06.510",
"Id": "223508",
"Score": "0",
"Tags": [
"c++",
"memory-management",
"template",
"pointers",
"callback"
],
"Title": "Helper to convert arbitrary function into a custom deleter"
} | 223508 |
<p>Here is my code for the KenKen puzzle:</p>
<p><a href="https://i.stack.imgur.com/bwHCk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bwHCk.png" alt="enter image description here"></a></p>
<p>The user must fill in each embolded regions with numbers in the range <code>1-n</code> where n is the board dimensions (e.g: 4*4, n=4) such that the total of that region equals the target number in the corner using the designated symbol. </p>
<p>Each row and column MUST contain the numbers 1-4 only once. </p>
<p>So the top square must use the numbers <code>1-4</code> to create 36 using the multiplication operand (e.g: 4*3*3*1). This is valid if the two threes are placed in a diagonal relationship to each other</p>
<p>When filling in a region, the order is arbitrary. So for example if considering the bottom left corner with a target of 2 and operand of "minus" then placing 2 above 1 <strong>or</strong> 1 above 2 would not be relevant. </p>
<p>If you don't understand, <a href="https://en.wikipedia.org/wiki/KenKen" rel="nofollow noreferrer">please see here</a>.</p>
<pre><code>import operator
from itertools import product, permutations
import numpy as np
def calculate(numbers, target, op):
operator_dict = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv}
running_total = numbers[0]
for number in numbers[1:]:
running_total = operator_dict[op](running_total, number)
if running_total == target:
return True
return False
def valid_number(row, column, board, size):
valid_row = set()
for number in range(1, size + 1):
if number not in board[row]:
valid_row.add(number)
valid_column = set()
column_numbers = [int(board[i, column]) for i in range(size)]
for number in range(1, size + 1):
if number not in column_numbers:
valid_column.add(number)
valid_numbers = valid_row & valid_column
yield from valid_numbers
def is_valid_sum(board, instruction_array, number_groups):
for group in range(1, number_groups + 1):
coordinates = []
list_numbers = []
next_group = 0
for i, j in product([row for row in range(size)], [column for column in range(size)]):
if instruction_array[i][j][0] == group:
if len(instruction_array[i][j]) == 2:
next_group = 1
break
target = instruction_array[i][j][1]
op = instruction_array[i][j][2]
list_numbers.append(int(board[i, j]))
if next_group == 1:
continue
combination_numbers = permutations(list_numbers, len(list_numbers))
for combination in combination_numbers:
target_reached = calculate(combination, target, op)
if target_reached:
break
if target_reached:
continue
else:
return False
return True
def is_full(board, size):
for row in range(size):
for column in range(size):
if board[row, column] == 0:
return False
return True
def solve_board(board, instruction_array, size, number_groups):
if is_full(board, size):
if is_valid_sum(board, instruction_array, number_groups):
return True, board
return False, board
for i, j in product([row for row in range(size)],
[column for column in range(size)]): # Product is from itertools library
if board[i, j] != 0:
continue
for number in valid_number(i, j, board, size):
board[i, j] = number
is_solved, board = solve_board(board, instruction_array, size, number_groups)
if is_solved:
return True, board
board[i, j] = 0
return False, board
return False, board
def fill_obvious(board, instruction_array, size):
# Fill fixed numbers
for row in range(size):
for column in range(size):
if len(instruction_array[row][column]) == 2:
board[row, column] = instruction_array[row][column][1]
return board
if __name__ == "__main__":
# Instructions in the array are in the format groupID, target, symbol.
# The group ID is necessary for the situation where two neighbouring groups have the same target AND symbol
# Which is possibility in the game
# Squares which have a fixed number take a group number and the number as input. DO NOT place a symbol in the square
instruction_array = [[[1, 36, "*"], [1, 36, "*"], [6, 1, "-"], [6, 1, "-"]],
[[1, 36, "*"], [1, 36, "*"], [5, 12, "*"], [7, 2, "/"]],
[[2, 2, "-"], [5, 12, "*"], [5, 12, "*"], [7, 2, "/"]],
[[2, 2, "-"], [3, 3, "+"], [3, 3, "+"], [4, 3]]]
number_groups = 7
size = len(instruction_array[0])
board = np.zeros(size * size).reshape(size, size)
board = fill_obvious(board, instruction_array, size)
is_solved, solved = solve_board(board, instruction_array, size, number_groups)
if is_solved:
print(solved)
else:
print("Cannot solve")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-06T13:04:02.283",
"Id": "433485",
"Score": "0",
"body": "Sorry. Yes. I worked out a way to solve it that would be much faster. My apologies. I have reopened it"
}
] | [
{
"body": "<p>In <code>calculate</code> I see a few things:</p>\n\n<ul>\n<li><p>I'd put the translation dictionary outside of the function. I think it makes more sense as a \"global constant\" than it does as something local to that function. That also gives you a way to check for the validity of an operator string for free if you ever need that:</p>\n\n<pre><code>if some_string in operator_dict:\n</code></pre></li>\n<li><p>Your accumulation loop that splits the head off then iterates the rest could be made much neater by using a <a href=\"https://docs.python.org/2/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\">reduction</a>. If you don't supply an initial value for a reduction, it automatically uses the first element as the starting accumulator.</p></li>\n<li><p>Your <code>return</code> could be simplified down to just returning the condition. I also wouldn't put the <code>return True</code> inside the <code>if</code> body, then not put the <code>return False</code> in an <code>else</code>.</p></li>\n</ul>\n\n<p>I'd write this closer to:</p>\n\n<pre><code>from functools import reduce\n\nOPERATOR_SYM_TO_FUNC = {\"+\": operator.add,\n \"-\": operator.sub,\n \"*\": operator.mul,\n \"/\": operator.truediv}\n\ndef calculate(numbers, target, op_sym):\n op = OPERATOR_SYM_TO_FUNC[op_sym]\n\n total = reduce(op, numbers)\n\n return total == target\n</code></pre>\n\n<hr>\n\n<p>In <code>solve_board</code>, I can't offhand see why you're returning <code>board</code> in this case. If <code>board</code> were immutable, ya, that would make sense. You're directly mutating the board that's passed in though. I think it creates necessary bulk, especially in lines like:</p>\n\n<pre><code> is_solved, board = solve_board(board, instruction_array, size, number_groups)\n</code></pre>\n\n<p>The <code>board</code>s are the same, so there's not really any gain.</p>\n\n<p>With how you have it, I would just return the boolean status. It may make sense however to make a copy of the input board, then mutate and return the copy. This prevents the original board from getting mutated by accident. If you chose to do that, instead of returning a <code>True</code>/<code>False</code> to indicate success, you could return the board on a successful solve, and <code>None</code> when the board is unsolvable.</p>\n\n<p>I'll also point out that you have the lines:</p>\n\n<pre><code>for i, j in product([row for row in range(size)],\n [column for column in range(size)]): # Product is from itertools library\n</code></pre>\n\n<p>I think instead of that comment, you should just use a qualified name:</p>\n\n<pre><code>import itertools\n\nfor i, j in itertools.product([row for row in range(size)],\n [column for column in range(size)]):\n</code></pre>\n\n<p>That's a little bulky, but your list comprehensions in there are unnecessary. <code>[row for row in range(size)]</code> is basically just <code>range(size)</code>. If you really wanted it as a strict list, it would likely be neater to use <code>list(range(size))</code> instead. Strictness likely isn't beneficial here though, so I'd just use ranges:</p>\n\n<pre><code>for i, j in itertools.product(range(size), range(size)]):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:54:26.313",
"Id": "433270",
"Score": "0",
"body": "Thanks. Nice to know these shortcuts for making more succint code :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T19:46:50.067",
"Id": "223524",
"ParentId": "223513",
"Score": "7"
}
},
{
"body": "<p>In addition to the comments Carcigenicate provided, there are some places where you can improve the efficiency. For example, the following code in <code>valid_number()</code> iterates over the row <code>size</code> times to fill <code>valid_row</code>. Then the same thing is done to fill <code>valid column</code>.</p>\n\n<pre><code>valid_row = set()\nfor number in range(1, size + 1): <- this loops 'size' times\n if number not in board[row]: <- this also loops 'size' times\n valid_row.add(number)\n</code></pre>\n\n<p>This can be improved by starting with a full set and removing numbers that are already in the row or column.</p>\n\n<pre><code>def valid_number(row, column, board, size):\n\n valid_numbers = set(range(1,size+1))\n\n for number in range(1, size+1):\n valid.discard(board[row, i])\n valid.discard(board[i, column])\n\n yield from valid_numbers\n</code></pre>\n\n<p>Every time <code>is_valid_sum()</code> is called, the entire instruction array is scanned once for each group to determine which cells are in the group, and what the op is. This information doesn't change, so it would be more efficient to calculate that information up front. <code>make_group()</code> builds a dictionary mapping group numbers to the target value, operator and cells for that group. It should be created and passed as an argument to <code>solve_board()</code>.</p>\n\n<pre><code>TARGET = 0\nOP = 1\nCELLS = 2\n\ndef make_groups(instruction_array):\n groups = {}\n\n for r in range(1, size+1):\n for c in range(1, size+1):\n # this presumes all instruction have an op\n # use 'None' for pre-filled cells\n group_number,target,op = instruction_array[r][c]\n\n if op:\n\n if group_number not in groups:\n groups[group_number] = [target, op, []]\n\n groups[group_number][CELLS].append((r,c))\n\n return groups\n</code></pre>\n\n<p>Then, <code>is_valid_sum()</code> can be simplified to something like:</p>\n\n<pre><code>def is_valid_sum(board, groups):\n for target, op, cells in groups.items():\n list_numbers = [board[r,c] for r,c in cells]\n\n combination_numbers = permutations(list_numbers, len(list_numbers))\n for combination in combination_numbers:\n if calculate(combination, target, op):\n break # the beak skips over the else\n else:\n continue # this is done if the loop finishes normally\n\n return False \n return True\n</code></pre>\n\n<p>I used the <code>else</code> with the <code>for combination...</code> loop to clarify the logic. Although it might make more sense to move the permutation calculations and the loop into the calculate function. If the op is '+' or '*', the permutations are not needed. If the op is '-' or '/', the largest number should be first unless the target can be a fraction or negative.</p>\n\n<p>One last observation, <code>is_full()</code> is called by <code>solve_board()</code> to determine if the boards is filled up. <code>solve_board()</code> is a recursive function that tries to fill a cell on every recursion. Pass it a count of the number of cells that need to be filled and decrement the count with each level of recursion. When the count reaches zero the board is full. So <code>is_full()</code> is not needed. Like so, where <code>num_cells</code> is the number of cells left to fill:</p>\n\n<pre><code>def solve_board(board, instruction_array, size, groups, num_cells):\n if num_cells == 0:\n return is_valid_sum(board, instruction_array, number_groups), board\n\n for i, j in product(range(size),range(size)):\n\n ...\n is_solved, board = solve_board(board, instruction_array, size, groups, num_cells-1)\n ...\n</code></pre>\n\n<p>There are other optimizations that could be made, but that's all for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T07:27:21.790",
"Id": "223543",
"ParentId": "223513",
"Score": "2"
}
},
{
"body": "<p>You use <code>numpy</code> to represent your board but don't take advantage of some of its capabilities to simplify your code. Some loops are unnecessary as they can be performed by a numpy operation.</p>\n\n<p>You also use <code>itertools.product</code> to loop over indices where a double <code>enumerate</code> for-loop would fit better. You also use it in <code>solve_board</code> to search for the first entry which is still 0 and then stop afterwards; better use a generator of possible indexes and extract the first using <code>next</code> to make it more explicit. This will also allows you to check for completion of the board, if the generator is exhausted and raise <code>StopIteration</code>.</p>\n\n<p>Your <code>is_valid_sum</code> function would also benefit from being split in two to be able to return early instead of using all those flags.</p>\n\n<p>And a <code>solve</code> or <code>main</code> function that would perform the boilerplate that you do in your <code>if __name__ == '__main__'</code> guard would be appreciated.</p>\n\n<p>Proposed changes:</p>\n\n<pre><code>import itertools\nimport numpy as np\n\n\nOPERATORS = {\n '+': np.add,\n '-': np.subtract,\n '*': np.multiply,\n '/': np.true_divide,\n}\n\n\ndef valid_number(row, column, size):\n candidates = np.arange(1, size + 1)\n candidates = np.setdiff1d(candidates, row, assume_unique=True)\n candidates = np.setdiff1d(candidates, column, assume_unique=True)\n return candidates\n\n\ndef check_group(board, instructions, group):\n group_numbers = []\n for i, row in enumerate(instructions):\n for j, instruction in enumerate(row):\n if instruction[0] != group:\n continue\n try:\n _, target, operation = instruction\n except ValueError:\n # Case of fixed-number groups\n return board[i, j] == instruction[1]\n else:\n group_numbers.append(board[i, j])\n\n for combination in itertools.permutations(group_numbers):\n if OPERATORS[operation].reduce(combination, dtype=float) == target:\n return True\n\n return False\n\n\ndef is_valid_sum(board, instructions, groups):\n for group in groups:\n if not check_group(board, instructions, group):\n return False\n return True\n\n\ndef solve_board(board, instructions, groups):\n empty_rows, empty_cols = np.where(board == 0)\n try:\n i, j = next(zip(empty_rows, empty_cols))\n except StopIteration:\n # Board is full\n return is_valid_sum(board, instructions, groups)\n\n row = board[i]\n column = board[:, j]\n for number in valid_number(row, column, *row.shape):\n board[i, j] = number\n if solve_board(board, instructions, groups):\n return True\n board[i, j] = 0\n return False\n\n\ndef solve(instructions):\n size = len(instructions)\n board = np.zeros((size, size), dtype=int)\n\n groups = set()\n for i, row in enumerate(instructions):\n assert size == len(row)\n for j, instruction in enumerate(row):\n if len(instruction) == 2:\n board[i, j] = instruction[1]\n groups.add(instruction[0])\n\n is_solved = solve_board(board, instructions, groups)\n return board if is_solved else None\n\n\nif __name__ == \"__main__\":\n # Instructions in the array are in the format groupID, target, symbol. The\n # group ID is necessary for the situation where two neighbouring groups\n # have the same target AND symbol; which is a possibility in the game.\n\n # Squares which have a fixed number take a group number and the number as\n # input. DO NOT place a symbol in the square\n\n board = solve([\n [[1, 36, \"*\"], [1, 36, \"*\"], [6, 1, \"-\"], [6, 1, \"-\"]],\n [[1, 36, \"*\"], [1, 36, \"*\"], [5, 12, \"*\"], [7, 2, \"/\"]],\n [[2, 2, \"-\"], [5, 12, \"*\"], [5, 12, \"*\"], [7, 2, \"/\"]],\n [[2, 2, \"-\"], [3, 3, \"+\"], [3, 3, \"+\"], [4, 3]],\n ])\n\n if board is None:\n print(\"Cannot solve\")\n else:\n print(board)\n</code></pre>\n\n<p>You may also be able to simplify the <code>is_valid_sum</code> and <code>check_group</code> functions by storing more than the group numbers; <em>e.g.</em> target, op and list of indices for said group.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T08:52:38.833",
"Id": "223552",
"ParentId": "223513",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223552",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:01:05.017",
"Id": "223513",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "KenKen solver - Python"
} | 223513 |
<p>I have this <code>ProductSearchContainer.js</code> file that it's getting too long to handle and maintain.</p>
<p>What it's responsible for:</p>
<ul>
<li>Doing network requests to get a list of products</li>
<li>Filter that list with filters values it gets from URL query string and update state with the new filteredList</li>
<li>It also holds functions to simulate the length of products on each filter before you click it. For example: a color filter with <strong>Black(5)</strong> indicating that you'll get 5 products if you click on <strong>Black</strong>.</li>
<li>Along other functions</li>
</ul>
<p>The file was getting too big (600+ lines) and I decide to move some pieces of logic to other files.</p>
<p>For each filter category (brand, price, rating, etc) I have two functions:</p>
<ul>
<li>1 to apply the active filters (get a <code>list</code> and the <code>activeFilters</code> array and it returns a filtered list for those filters.</li>
<li>1 to simulate the next filter length (like I explained above on the colors example)</li>
</ul>
<p><strong>Note:</strong> You'll see below that they rely on state variable <code>activePriceFilters</code> but they don't call any React Hook in their execution.</p>
<hr>
<p><strong>OPTION #1</strong></p>
<p>My 1st thought was to turn into a custom hook. So I did. And it works (see snippet below).</p>
<pre><code>function usePriceFilter(activePriceFilters) {
function applyPriceFilter(list, activePriceFilters) {
console.log('I will get a list and return it filtered by activePriceFilters');
}
function simulateNextPriceFilter(list, someTestPriceFilter) {
console.log('I will get a list and return the length of the filtered list by price');
}
return [applyPriceFilter,simulateNextPriceFilter];
}
</code></pre>
<p>And I consume by doing: </p>
<p><code>const [applyPriceFilter,simulateNextPriceFilter] = usePriceFilter(activePriceFilters)</code></p>
<p>I mean, my custom hook is basically a higher order function but I think it still qualifies as a custom hook:</p>
<p><a href="https://reactjs.org/docs/hooks-custom.html" rel="nofollow noreferrer">From React DOCS:</a></p>
<blockquote>
<p>A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.</p>
</blockquote>
<hr>
<p><strong>OPTION #2</strong></p>
<p>But I guess I could also turn into a regular <code>.js</code> file, export both functions and just do the regular import on them. Like:</p>
<p><code>import {applyPriceFilter,simulateNextPriceFilter} from './priceFilterHelpers</code></p>
<hr>
<p><strong>QUESTION:</strong></p>
<p>Is there a difference in functionaly or performance between the 2 approaches? Should I favor 1 instead of the other?</p>
<p>I think that the custom hook's is more readable, but is there anything else I'm gaining by doing this?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function App() {
const [activePriceFilters,setActivePriceFilters] = React.useState(['10to20','50+']);
const [applyPriceFilter, simulateNextPriceFilter] = usePriceFilter(activePriceFilters);
return(
<React.Fragment>
<button onClick={applyPriceFilter}>Apply Price Filters</button>
<button onClick={simulateNextPriceFilter}>Simulate Price Filter</button>
</React.Fragment>
);
}
function usePriceFilter(activePriceFilters) {
function applyPriceFilter(list, activePriceFilters) {
console.log('I will get a list and return it filtered by activePriceFilters');
}
function simulateNextPriceFilter(list, someTestPriceFilter) {
console.log('I will get a list and return the length of the filtered list by price');
}
return [applyPriceFilter,simulateNextPriceFilter];
}
ReactDOM.render(<App/>, document.getElementById('root'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Well, in your case, your \"hook\" isn't really managing any state. I would say that you can safely hold it in a simple file and import it. But if your functions were to do something more than just logging, I would make a custom hook, since it would most likely work better with the lifecycle of components, triggering re-renders when needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:59:36.400",
"Id": "223906",
"ParentId": "223514",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223906",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:32:29.393",
"Id": "223514",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "Import function vs turning it into custom hook"
} | 223514 |
<pre><code>SELECT pl_from, NS, page_title, L_NS, L_titles, num_L, SB, IU, WP
FROM (
SELECT
pl_from,
-- pl_from_namespace does not appear to be consistently reliable;
-- it might be better to select from the page table and join the pagelinks table to it.
CASE
-- This fails on pages missing from the page table (presumably because they were deleted).
WHEN pl_from_namespace != page_namespace THEN CONCAT(pl_from_namespace, ' vs. ', page_namespace)
ELSE pl_from_namespace
END AS NS,
page_title,
pl_namespace AS L_NS,
GROUP_CONCAT(pl_title SEPARATOR ' ') AS L_titles,
COUNT(pl_title) AS num_L,
CASE
WHEN MAX(CASE WHEN pl_title LIKE '%/sandbox' THEN 1 END) = 1 THEN '(SB)'
ELSE ''
END AS SB,
CASE
WHEN EXISTS (
SELECT 1
FROM templatelinks
WHERE
tl_from = pl_from
AND tl_title = 'Under_construction'
) THEN '(C)'
ELSE ''
END AS C,
CASE
WHEN EXISTS (
SELECT 1
FROM categorylinks
WHERE
cl_from = pl_from
AND cl_to = 'Pages_using_Under_construction_with_the_placedby_parameter'
) THEN '(PB)'
ELSE ''
END AS C_PB,
CASE
WHEN EXISTS (
SELECT 1
FROM templatelinks
WHERE
tl_from = pl_from
AND (tl_title = 'In use' OR tl_title = 'GOCEinuse')
) THEN '(IU)'
ELSE ''
END AS IU,
CASE
WHEN EXISTS (
SELECT 1
FROM templatelinks
WHERE
tl_from = pl_from
AND tl_title = 'Copyvio-revdel'
) THEN '(RD1)'
ELSE ''
END AS RD1,
CASE
WHEN EXISTS (
SELECT 1
FROM templatelinks
WHERE
tl_from = pl_from
AND tl_title = 'Wikipedia_person_user_link'
) THEN '(WP)'
ELSE ''
END AS WP,
CASE
WHEN EXISTS (
SELECT 1
FROM categorylinks
WHERE
cl_from = pl_from
AND cl_to = 'Candidates_for_speedy_deletion'
) THEN '(CSD)'
ELSE ''
END AS CSD
FROM pagelinks
LEFT JOIN page ON page_id = pl_from
WHERE
pl_from_namespace = 0
AND pl_namespace = 2
-- In the future: AND pl_namespace != 0
GROUP BY pl_from
ORDER BY SB, page_title
) AS t1
WHERE
(
(C = '' AND RD1 = '' AND WP = '' AND CSD = '')
OR num_L != 1
)
AND (C_PB = '' OR num_L != 2)
</code></pre>
<p>Currently this query is run on an online database replicate of Wikipedia, so you can see <a href="https://quarry.wmflabs.org/query/37287" rel="nofollow noreferrer">this query's result</a>.</p>
<h1>What is this supposed to do? How does it work?</h1>
<p>Relevant background: MediaWiki wikis separates pages into <em>namespaces</em> that are intended to store different types of content. On Wikipedia, the article namespace (which contains all of the actual encyclopedia) is the main namespace. Namespaces are somewhat analogous to how Stack Exchange sites separate content into the main questions site and the Meta domain for internal site discussion (however, Wikipedia sorts many things into namespaces that SE sites don't).</p>
<p>This query searches for internal links from articles to the user namespace. Getting all these links is easy; the complexity arises from filtering out some of the results under specific conditions.</p>
<p>Before going further, there's one essential piece of background about the MediaWiki database schema: the columns of each table are specifically named to be distinct, so each column starts with a prefix specific to its originating table. This query uses 4 tables: <code>page</code> with prefix <code>page_</code>, <code>pagelinks</code> with prefix <code>pl_</code>, <code>templatelinks</code> with prefix <code>tl_</code>, and <code>categorylinks</code> with prefix <code>cl_</code>.</p>
<p>The basic goals of the query are as follows:</p>
<ul>
<li>Take all link on articles (i.e. <code>pagelinks</code> rows where <code>pl_from_namespace = 0</code>) that link to user namespace (i.e. where <code>pl_namespace = 2</code>) from the <code>pagelinks</code> table</li>
<li><code>GROUP BY pl_from</code> to allow counting of links per page through <code>COUNT(pl_title) AS num_L</code>, and to generally organize rows as page-specific.
<ul>
<li>This also uses the aggregate function <code>GROUP_CONCAT(pl_title SEPARATOR ' ') AS L_titles</code> to list each link in the final output output.</li>
</ul></li>
<li>Filter out page rows that:
<ul>
<li>have any of the following templates: <code>'Under_construction'</code>, <code>'Copyvio-revdel'</code>, <code>'Wikipedia_person_user_link'</code> or has the category <code>'Candidates_for_speedy_deletion'</code>
<ul>
<li>(A page "has a template" if there's a row in <code>templatelinks</code> where <code>tl_from = pl_from AND tl_title = 'Template_title'</code>. A page "has a category" if there's a row in <code>categorylinks</code> where <code>cl_from = pl_from AND cl_to = 'Category_title'</code>)</li>
</ul></li>
<li>AND have one link (<code>numL = 1</code>)</li>
</ul></li>
<li>Additionally filter out page rows that have the category <code>'Pages_using_Under_construction_with_the_placedby_parameter'</code> AND have two links (<code>numL = 2</code>)</li>
<li>Take note of rows that have a <code>page_title</code> ending with <code>/sandbox</code> or have the template <code>'In_use'</code> or <code>'GOCEinuse'</code> by using what amounts to Boolean columns.</li>
</ul>
<p>These documentation links may also be useful if one wants to understand the Mediawiki database better, but should not be required to answer the question: <a href="https://www.mediawiki.org/wiki/Manual:Database_layout" rel="nofollow noreferrer">Database layout manual</a>, <a href="https://www.mediawiki.org/wiki/Manual:Page_table" rel="nofollow noreferrer"><code>page</code> table</a>, <a href="https://www.mediawiki.org/wiki/Manual:Pagelinks_table" rel="nofollow noreferrer"><code>pagelinks</code> table</a>, <a href="https://www.mediawiki.org/wiki/Manual:Templatelinks_table" rel="nofollow noreferrer"><code>templatelinks</code> table</a>, <a href="https://www.mediawiki.org/wiki/Manual:Categorylinks_table" rel="nofollow noreferrer"><code>categorylinks</code> table</a></p>
<h1>Improvements I'm looking for</h1>
<p>My query already runs in less than a second, so I'm not too concerned about efficiency (though I welcome any suggestions).</p>
<p>What I'm mainly looking for is general SQL advice. I strongly suspect there are much much better ways to handle repeated structures like:</p>
<pre><code> CASE
WHEN EXISTS (
SELECT 1
FROM templatelinks
WHERE
tl_from = pl_from
AND tl_title = 'template_title'
) THEN '(col_name)'
ELSE ''
END AS col_name
</code></pre>
<p>If you need any clarification or have any questions, feel free to comment and I will reply.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:42:22.370",
"Id": "433226",
"Score": "0",
"body": "I'm having nightmares thinking about how to represent this in jOOQ!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:46:55.887",
"Id": "433227",
"Score": "2",
"body": "It's a pleasant change to see a [tag:sql] question with a decent problem statement, tables description and the rest. Welcome to Code Review, and please help sustain this high standard! Sorry I'm not qualified enough in SQL to review it myself..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T16:49:12.133",
"Id": "433235",
"Score": "0",
"body": "How can we test our own queries on this database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T17:06:30.250",
"Id": "433236",
"Score": "1",
"body": "@dfhwze To access Quarry, the website where I ran the query, you'll have to create an account on any Wikimedia wiki (accounts are global, so [an account on the English Wikipedia](https://en.wikipedia.org/wiki/Special:CreateAccount) works) and then connect to Quarry through OAuth (it's straightforward). Alternatively, a less convenient option is to download [a Wikipedia database dump](https://dumps.wikimedia.org/). There are other APIs to connect to Wikipedia database replicates, but I'm not familiar with them; generally, they will also require a Wikimedia wiki account."
}
] | [
{
"body": "<blockquote>\n <p>I strongly suspect there are much much better ways to handle repeated\n structures like:</p>\n</blockquote>\n\n<p>In mysql, you can use <code>ifnull</code> to shorten this:</p>\n\n<blockquote>\n<pre><code> CASE\n WHEN EXISTS (\n SELECT 1\n FROM templatelinks\n WHERE\n tl_from = pl_from\n AND tl_title = 'template_title'\n ) THEN '(col_name)'\n ELSE ''\n END AS col_name\n</code></pre>\n</blockquote>\n\n<pre><code>select (ifnull((\n select '(col_name)' \n from templatelinkswhere \n where tl_from = pl_from \n and tl_title = 'template_title')\n , '')\n) as col_name;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T17:24:23.097",
"Id": "223519",
"ParentId": "223515",
"Score": "2"
}
},
{
"body": "<p>Consider the following tips and best practices:</p>\n<ol>\n<li><p><strong>TABLE QUALIFIERS:</strong> First and foremost, always qualify all fields in all clauses (<code>SELECT</code>, <code>WHERE</code>, <code>JOIN</code>, etc.) with table names or table aliases using period denotation. Doing so facilitates readability and maintainability.</p>\n</li>\n<li><p><strong>PREFIXED FIELD NAMES:</strong> Related to above, avoid prefixing field names (<em>pl_from, tl_title, cl_to</em>). Instead, use table aliases to period qualify identifiers in query to avoid collision or confusion. Of course if this is Wikimedia's setup, there's nothing you can do.</p>\n</li>\n<li><p><strong>CASE SUBQUERIES:</strong> Avoid subqueries in <code>CASE</code> statements which requires row by row logic calculation. Instead, use multiple <code>LEFT JOIN</code> on <em>templatelinks</em> and <em>categorylinks</em> tables and then run the needed <code>CASE</code> logic where <code>NOT EXISTS</code> render as <code>NULL</code>.</p>\n</li>\n<li><p><strong>GROUP BY</strong>: Unfortunately, at a disservice to newcomers in SQL due to MySQL's <a href=\"https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_by\" rel=\"nofollow noreferrer\">ONLY FULL GROUP BY</a> mode turned off, your aggregate inner query is not ANSI compliant. Always include all non-aggregated columns in <code>GROUP BY</code> for consistent, valid results.</p>\n<p>Your query would fail in practically all other RDBMS's (Oracle, Postgres, etc.) as your <code>GROUP BY</code> query is incomplete and does not adhere to ANSI rules since <em>page_title</em>, <em>pl_namespace</em>, and now the new <code>LEFT JOIN</code> fields are not included. In SQL where at least one aggregate is used such as <code>COUNT</code>, all grouped columns must be included in <code>GROUP BY</code> clause but can be optionally omitted in <code>SELECT</code> (not other way around). NOTE: your results may change with such code refactoring. The Wikimedia interface may not allow setting/mode adjustments.</p>\n</li>\n<li><p><strong>AGGREGATION</strong>: Related to above, you may need to handle all unit level calculations including <code>CASE</code> statements in the inner query and move aggregation to top level <code>SELECT</code>. If you need to include other unit level fields in final resultset but not in aggregation, run a <code>JOIN</code> on the aggregated subquery or via a CTE.</p>\n</li>\n</ol>\n<hr />\n<p>Below is an adjustment to your SQL query with unit level calculations handled in derived table subquery and all aggregations moved to top level. Previous outer <code>WHERE</code> now becomes <code>HAVING</code> since aggregates are involved. Depending on your needs and results, additional adjustments may be needed. But again, be sure to run with complete <code>GROUP BY</code> to include all non-aggregated columns. As mentioned, you will not be warned by the Wikimedia engine.</p>\n<pre><code>SELECT sub.pl_from, \n sub.page_title, \n sub.L_NS, \n MAX(sub.NS) AS NS, \n GROUP_CONCAT(sub.pl_title SEPARATOR ' ') AS L_titles,\n COUNT(sub.pl_title) AS num_L, \n MAX(sub.SB) AS SB, \n MAX(sub.IU) AS IU, \n MAX(sub.WP) AS WP \nFROM \n (SELECT pl.pl_from,\n CASE\n WHEN pl.pl_from_namespace != p.page_namespace \n THEN CONCAT(pl.pl_from_namespace, ' vs. ', p.page_namespace)\n ELSE pl.pl_from_namespace\n END AS NS,\n p.page_title,\n pl.pl_namespace AS L_NS, \n pl.pl_title,\n CASE\n WHEN MAX(CASE WHEN pl.pl_title LIKE '%/sandbox' THEN 1 END) = 1 THEN '(SB)'\n ELSE ''\n END AS SB,\n CASE \n WHEN t.tl_title = 'Under_construction' \n THEN '(C)' \n ELSE ''\n END AS C,\n CASE \n WHEN c.cl_to = 'Pages_using_Under_construction_with_the_placedby_parameter' \n THEN '(PB)' \n ELSE '' \n END AS C_PB,\n CASE\n WHEN (t.tl_title = 'In use' OR t.tl_title = 'GOCEinuse')\n THEN '(IU)'\n ELSE ''\n END AS IU,\n CASE\n WHEN t.tl_title = 'Copyvio-revdel'\n THEN '(RD1)'\n ELSE ''\n END AS RD1,\n CASE\n WHEN t.t_title = 'Wikipedia_person_user_link'\n THEN '(WP)'\n ELSE ''\n END AS WP,\n CASE\n WHEN c.cl_to = 'Candidates_for_speedy_deletion'\n THEN '(CSD)'\n ELSE ''\n END AS CSD\n FROM pagelinks pl\n LEFT JOIN page p ON p.page_id = pl.pl_from\n LEFT JOIN templatelinks t ON t.tl_from = pl.pl_from\n LEFT JOIN categorylinks c ON c.cl_from = pl.pl_from\n\n WHERE pl.pl_from_namespace = 0\n AND pl.pl_namespace = 2\n ) AS sub\n\nGROUP BY sub.pl_from, \n sub.page_title, \n sub.L_NS \nHAVING\n (\n (MAX(sub.C) = '' AND MAX(sub.RD1) = '' AND MAX(sub.WP) = '' AND MAX(sub.CSD) = '')\n OR COUNT(sub.pl_title) != 1 \n )\n AND (MAX(sub.C_PB) = '' OR COUNT(sub.pl_title) != 2)\n \nORDER BY MAX(sub.SB), \n sub.page_title\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T21:52:49.790",
"Id": "434661",
"Score": "0",
"body": "`Always include non-aggregated columns in GROUP BY for consistent, valid results.` I'm a bit confused. Are you talking about the other aggregated columns in the `SELECT` statement? Because `pl.pl_from` isn't itself aggregated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:31:12.073",
"Id": "434667",
"Score": "0",
"body": "Any non-aggregated columns should be placed in the `GROUP BY` clause. Right now you only include *pl_from* but not *page_title*, *pl_namespace*, etc. Basically, anything that is NOT called in `COUNT`, `SUM`, `MIN`, `MAX`, `AVG`, `GROUP_CONCAT`, and other aggregates should be in `GROUP BY`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:34:58.483",
"Id": "434669",
"Score": "0",
"body": "And intuitively, the correct use of aggregate query makes sense semantically because your `count` and `group_concat` is grouped by the listed groupings. Right now, it is unclear what the `count` is since it is adjacent to non-aggregated unit level fields. Other RDBMS would raise the needed error such as SQL Server: `Column 'XXXXX' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.` Or Postgres: `ERROR: column \"XXXXC\" must appear in the GROUP BY clause or be used in an aggregate function`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:33:15.263",
"Id": "434709",
"Score": "1",
"body": "I have suggested an edit to clarify this in the answer. You are welcome to accept or reject as you see fit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T18:07:23.910",
"Id": "434754",
"Score": "0",
"body": "Currently, I like your answer the best, so I will accept it. However, I still don't fully understand the issue with `GROUP BY` and aggregate functions (I understand it in the abstract, but I haven't quite gotten an intuitive grasp of why it's necessary or how I would fix it in practice), so I would appreciate you finishing the code so there's a working example of how to apply it to this situation. That is not to say that your answer is necessarily lacking on the explanation side, and I think I will be able to understand it on my own if I spend a bit more time pondering it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T14:31:52.480",
"Id": "434878",
"Score": "0",
"body": "See updated query and explanation. Further adjustments may be needed. Query has not been tested. Once you become acclimated in SQL, the incomplete `GROUP BY` is clear as day! Sorry the MySQL mode does not throw error to help you learn. Happy coding!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:20:56.260",
"Id": "223964",
"ParentId": "223515",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223964",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T15:34:43.603",
"Id": "223515",
"Score": "4",
"Tags": [
"sql",
"mysql",
"wikipedia"
],
"Title": "Finding Wikipedia articles with specific types of user page links"
} | 223515 |
<p>I'm working on prepared statements for my website and I'm wondering if it's possible to have multiple prepared statements one after another. In this example, I have 2 select statements. I'm hoping that the question marks I have as placeholders won't be overwriting one another. After that's been answered, I was wondering if this code was still open to <em>SQL injection</em>. </p>
<pre><code>function getHomeUploads($conn) {
$userName = $_GET["user"];
$sqluserid = "SELECT * FROM users WHERE userName = ?;";
$useridstmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($useridstmt, $sqluserid)) {
echo "SQL statement failed";
}
else {
mysqli_stmt_bind_param($useridstmt, "s", $userName);
mysqli_stmt_execute($useridstmt);
$useridresult = mysqli_stmt_get_result($useridstmt);
while ($useridrow = mysqli_fetch_assoc($useridresult)) {
if($useridrow['userid'] > 0) {
$userid = $useridrow['userid'];
$sqlusercontent = "SELECT * FROM posts WHERE hostid = ? AND userid = ? AND commentid = 0;";
$stmtusercontent = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmtusercontent, $sqlusercontent)) {
echo "SQL statement failed";
}
else {
mysqli_stmt_bind_param($stmtusercontent, "ss", $userid, $userid);
mysqli_stmt_execute($stmtusercontent);
$usercontent = mysqli_stmt_get_result($stmtusercontent);
$postid = 1;
echo "<div class='homepostcontainer'>";
echo "<div class='homepostcontainerscroll'>";
while ($row = mysqli_fetch_assoc($usercontent)) {
// Text fileid
if ($row['fileid'] == 1) {
echo "<div class='postbox'>";
echo "<div class='postscroll'>";
echo $row['title']."<br>";
echo $row['date']."<br>";
echo $row['description']."<br>";
echo "</div>";
echo "<div class='InfoBar'> <a href=view.php?user=".$userName."&post=".$postid.">•••</a> </div>";
echo "</div>";
}
// Picture fileid
else if ($row['fileid'] == 2) {
$filename = "posts/".$userid."/".$postid."*";
$fileinfo = glob($filename);
$fileext = explode(".", $fileinfo[0]);
$fileactualext = $fileext[1];
echo "<div class='postbox'>";
echo "<div class='postscroll'>";
echo $row['title']."<br>";
echo $row['date']."<br>";
echo "<img src='posts/".$userid."/".$postid.".".$fileactualext."'><br>";
echo $row['description']."<br>";
echo "</div>";
echo "<div class='InfoBar'> <a href=view.php?user=".$userName."&post=".$postid.">•••</a> </div>";
echo "</div>";
}
else {
echo '';
}
$postid++;
}
echo "</div>";
echo "</div>";
}
}
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T21:15:43.737",
"Id": "433282",
"Score": "0",
"body": "You have a basic question about the correctness of your code. Such questions [have no place of Code Review](https://codereview.stackexchange.com/help/dont-ask). Just remove it from your question, after you've made sure your code is working. There's a lot to improve in your code, so Code Review would be [the right place to learn how to make your code better](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T21:36:55.403",
"Id": "433283",
"Score": "0",
"body": "Sorry for that, I should clarify that the webpage loads correctly. I just want to know if there's anything wrong with 2 prepared statements within the same function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:42:17.923",
"Id": "433290",
"Score": "0",
"body": "You can have two prepared statements, or three. No problem. Perhaps you could say something about the purpose of the function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T01:42:20.723",
"Id": "433306",
"Score": "0",
"body": "Thank you KIKO, if you answer the question ill upvote it.\nThe purpose of the function is to pull from two different tables. The first table has info i need to open the second one. So I'm pulling the userid from users table and then im using the same userid to see what kinds of posts theyve made in a posts table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T05:01:20.673",
"Id": "433315",
"Score": "0",
"body": "What is a \"home upload\", and why did you choose that name?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T08:07:20.717",
"Id": "433331",
"Score": "0",
"body": "The function used to do something else and I haven't changed it to something that makes more sense. I will do that soon!"
}
] | [
{
"body": "<ol>\n<li><p>Passing the database connection as a variable is a good technique.</p></li>\n<li><p>Validate user input as much as possible before considering executing any processes. If the input is missing or invalid, don't do anything with the submission.</p>\n\n<pre><code>if (empty($_GET[\"user\"])) { // add your validation here if possible\n echo \"Missing/Invalid data submitted\";\n // halt the script or redirect or whatever\n}\n</code></pre></li>\n<li><p>Use object-oriented mysqli syntax because it is more brief and IMO cleaner to read.</p></li>\n<li><p>Do not perform iterated queries. You can easily condense you iterated queries into one simple query using an INNER JOIN. Something like this should do (untested):</p>\n\n<pre><code>SELECT *\nFROM users u\nINNER JOIN posts p USING userid \nWHERE u.user_name = ?\n AND p.hostid = p.userid\n AND p.commentid = 0\n</code></pre>\n\n<p><code>USING</code> is a convenient shorthand keyword when the two joining columns are identical; otherwise use <code>ON</code> and declare the columns individually. <a href=\"https://stackoverflow.com/q/11366006/2943403\">MySQL ON vs USING?</a> You should also replace <code>*</code> in the SELECT clause with the exact columns you need from either table. (Never ask for more than you need.) With the above query, you will only need to bind <code>$_GET\"user\"]</code> once since there is now only one placeholder.</p></li>\n<li><p>I don't typically endorse printing from the same function that does the processing. If you are going to print nested html elements, you can improve readability by tabbing them.</p></li>\n<li><p>There is a cleaner way to extract the file extension than picking up post-explosion debris. <a href=\"https://stackoverflow.com/a/173876/2943403\">How do I get (extract) a file extension in PHP?</a></p>\n\n<pre><code>$ext = pathinfo($filename, PATHINFO_EXTENSION);\n</code></pre></li>\n<li><p>If <code>$row['fileid']</code> isn't 1 or 2, don't bother printing an empty string.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T08:05:06.587",
"Id": "433330",
"Score": "1",
"body": "Wow, thank you for all of this info. I'll be using this answer as a reference for a while!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T07:45:35.603",
"Id": "223545",
"ParentId": "223526",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223545",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T20:21:03.790",
"Id": "223526",
"Score": "3",
"Tags": [
"php",
"mysqli",
"sql-injection"
],
"Title": "Displaying a user's uploaded posts"
} | 223526 |
<p>I started to learn Python not long ago to automate certain tasks I work on. I want to optimize a script I wrote that takes a line in an Excel file and prints a pattern of text based on this line's content. Here's an example of output from my code:</p>
<pre><code>mgmt_cli add access-rule layer "network" position bottom name "thirdline" source.1 "Value1front" source.2 "Value2front" source.3 "x3front" destination "Dest1front" service "HTTP" track.type "Log" action "Accept"
</code></pre>
<p>How would you optimize this code?</p>
<p>Link to the example file (just click Valider et Télécharger le Fichier) <a href="http://dl.free.fr/hFlGmywIN" rel="nofollow noreferrer">http://dl.free.fr/hFlGmywIN</a><br>
Link to full code : <a href="https://pastebin.com/CR5SXHRQ" rel="nofollow noreferrer">https://pastebin.com/CR5SXHRQ</a></p>
<pre><code>import xlrd
import re
loc = ("Dir\StackoverflowExample.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
# Extracting number of rows
def CaseMulti(CellContent, CellName):
#takes a cell and a string as parameters, prints a pattern like Cell.X ="string", X starts with 0 and ends at the number of line in the Cell
case = str(CellContent)
x= re.split ("\s", case) #splits the cell contents in a list using regex where space is the separator for the list's elements
if name == CellContent: # deals with the cell with spaces between objects no clue how it work but it does
return "name " + '"{}"'.format(CellContent)
else:
s=0
string =""
anycells = ["any","Any", "ANY"] # tests if the soure, destination or service has any ==> returns nothing
if str(x[0]) in anycells :
return " "
else:
if len(x)==1: # case where te cell has one line (or a word with no spaces)
string= CellName + " " +'"{}"'.format(case)
else: # case where multilines/mutli spaces
while s<len (x) :
listelement = x[s]
string = string + CellName+'.'+str(s+1)+ ' ' +'"{}"'.format(listelement)
s=s+1
return string
for numberofrows in range (5):
print "Rule " + str (numberofrows)
name= sheet.cell_value(numberofrows,1)
source = sheet.cell_value(numberofrows,2)
destination = sheet.cell_value(numberofrows,3)
protocole = sheet.cell_value(numberofrows,4)
log = sheet.cell_value(numberofrows,5)
action = sheet.cell_value(numberofrows,6)
#firewall = sheet.cell_value(numberofrows,7)
try:
print ("mgmt_cli add access-rule layer \"network\" position bottom " + str(CaseMulti(name,"name")) + str(CaseMulti(source, " source")) + str(CaseMulti(destination, " destination")) + str(CaseMulti(protocole, " service")) + ' track.type "Log" ' + str(CaseMulti(action, " action")) )
except :
numberofrows +=1
</code></pre>
| [] | [
{
"body": "<p>It seems a main thing you need to learn about is <code>f-strings</code></p>\n\n<p>These are an update to the old <code>format</code> method.</p>\n\n<pre><code>print \"Rule \" + str (numberofrows)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>print(f\"Rule str(numberofrows)\")\n</code></pre>\n\n<p>and </p>\n\n<pre><code>\"name \" + '\"{}\"'.format(CellContent)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>f\"name {CellContent}\"\n</code></pre>\n\n<p><strong>NOTE</strong> Python 3 uses () for print statements</p>\n\n<p>It is also worth using a PEP8 checker (such as <code>black</code> - <code>pip install black</code>) to make your code more readable </p>\n\n<hr>\n\n<p>You could also change things like</p>\n\n<pre><code>s=s+1\n</code></pre>\n\n<p>to</p>\n\n<pre><code>s += 1\n</code></pre>\n\n<hr>\n\n<p>Rather than saying </p>\n\n<pre><code>anycells = [\"any\",\"Any\", \"ANY\"] \nif str(x[0]) in anycells\n...\n</code></pre>\n\n<p>You could say</p>\n\n<pre><code>if str(x[0]).lower() == \"any\"\n</code></pre>\n\n<hr>\n\n<p>Are you sure this is your code?\nThis looks very much like Python 2 code which hasn't been used for over 6 years. I am curious why you would write something in Python 2 still? It seems odd to learn Python 2 as a new beginner</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:50:00.333",
"Id": "433293",
"Score": "0",
"body": "thank you for your input. Yes this is my real code and it's in python 2, last time I coded was in Turbo Pascal that's why it looks very old"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:03:42.070",
"Id": "223530",
"ParentId": "223528",
"Score": "-1"
}
},
{
"body": "<p><strong>STYLING</strong></p>\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, there are a few improvements to be made to your code:</p>\n<ul>\n<li>Imports: Your imports should go in alphabetical order</li>\n<li>Variable/Function Names: You should use <code>snake_case</code> instead of <code>camelCase</code></li>\n<li>Parameter Names: This may just be how I view your code, but how your parameters are named look like your taking in objects. You should use lowercase variables for better readability.</li>\n<li>Spacing: You should use 4 spaces for each indent. For variable declaration and assignment, the <code>=</code> should be separated by a space on each side for readability, like so: <code>s=0</code> to <code>s = 0</code>.</li>\n<li>Main Guard: You should wrap any regular code in a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">if '<strong>name</strong> == '<strong>main</strong>'</a> guard, to make sure that the code is only being run when that file is the main file, and not being imported by anything.</li>\n</ul>\n<p><strong>STRING FORMATTING</strong></p>\n<p>All throughout your code, you put strings together using <code>+</code> and <code>.format</code>. Luckily there is an easier way, by putting an <code>f</code> before the string like so: <code>f"content here"</code>. This erases the need to have verbose <code>+</code> in your strings, and you no longer have to cast <code>int</code> to <code>str</code> with this method, you can just write the code in the brackets <code>{your code here}</code>.</p>\n<p>Example:</p>\n<p><code>return "name " + '"{}"'.format(cell_content)</code></p>\n<p>to</p>\n<p><code>return f"name \\"{cell_content}\\""</code></p>\n<p>Here is the updated code:</p>\n<pre><code>import re\nimport xlrd\n\nloc = ("Dir\\StackoverflowExample.xlsx")\n\nwb = xlrd.open_workbook(loc) \nsheet = wb.sheet_by_index(0) \nsheet.cell_value(0, 0) \n\n# Extracting number of rows \n\ndef case_multi(cell_content, cell_name):\n #takes a cell and a string as parameters, prints a pattern like Cell.X ="string", X starts with 0 and ends at the number of line in the Cell\n case = str(cell_content) \n x = re.split ("\\s", case) #splits the cell contents in a list using regex where space is the separator for the list's elements\n if name == cell_content: # deals with the cell with spaces between objects no clue how it work but it does\n return f"name \\"{cell_content}\\""\n else:\n s = 0\n string = "" \n if str(x[0]).lower() == "any":\n return " " \n else:\n if len(x) == 1: # case where the cell has one line (or a word with no spaces)\n string = f"{cell_name} \\"{case}\\""\n else: # case where multilines/mutli spaces\n while s < len(x):\n listelement = x[s]\n string += f"{cell_name}.{str(s + 1)} \\"{listelement}\\""\n s += 1\n\n return string\n\ndef main():\n\n for number_of_rows in range(5):\n\n print "Rule " + str(number_of_rows)\n name= sheet.cell_value(number_of_rows, 1)\n source = sheet.cell_value(number_of_rows, 2)\n destination = sheet.cell_value(number_of_rows, 3)\n protocole = sheet.cell_value(number_of_rows, 4)\n log = sheet.cell_value(number_of_rows, 5)\n action = sheet.cell_value(number_of_rows, 6)\n #firewall = sheet.cell_value(number_of_rows, 7)\n\n try:\n print ("mgmt_cli add access-rule layer \\"network\\" position bottom " + str(case_multi(name,"name")) + str(case_multi(source, " source")) + str(case_multi(destination, " destination")) + str(case_multi(protocole, " service")) + ' track.type "Log" ' + str(case_multi(action, " action")) )\n except:\n number_of_rows += 1\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T03:26:20.430",
"Id": "433307",
"Score": "0",
"body": "To be clear, PEP-8 specifies that indentation should be 4 spaces per level, not a TAB character. This is an important convention to follow, since indentation matters in Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T03:27:21.550",
"Id": "433308",
"Score": "0",
"body": "@200_success Is a tab not already 4 spaces? I already had the clarification next to it I just assumed they were the same length"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T03:31:30.417",
"Id": "433309",
"Score": "0",
"body": "I would avoid any mention of \"tab\", since that just adds a possible misinterpretation: an ASCII character 9, and configuring your text editor or terminal to use 4-character-wide tabstops."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T22:19:25.623",
"Id": "223531",
"ParentId": "223528",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T21:17:36.430",
"Id": "223528",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-2.x",
"excel",
"formatting"
],
"Title": "Print a pattern of text based on a line from an Excel file"
} | 223528 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.