text stringlengths 1 2.12k | source dict |
|---|---|
javascript, ecmascript-6, vue.js
Title: Vue and JSONPlaceholder application
Question: I have put together this small application that uses the JSONPlaceholder API and Vue.js.
The application crosses users and posts and displays the posts by user (author):
var app = new Vue({
el: "#app",
data: {
base_url: "https://jsonplaceholder.typicode.com",
uid: 1,
currentUser: null,
userData: null,
users: [],
posts: []
},
methods: {
toggleActiveUser(user) {
this.uid = user.id;
},
getUsers() {
axios
.get(`${this.base_url}/users`)
.then((response) => {
this.users = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
getCurrentUser() {
axios
.get(`${this.base_url}/users/${this.uid}`)
.then((response) => {
this.currentUser = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
getPosts() {
axios
.get(`${this.base_url}/posts?userId=${this.uid}`)
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
}
},
created() {
this.getUsers();
this.getCurrentUser();
this.getPosts();
},
watch: {
currentUser() {
this.getCurrentUser();
},
posts() {
this.getPosts();
}
},
filters: {
capitalize(value) {
return value.charAt(0).toUpperCase() + value.slice(1);
},
titlecase(value) {
return value.toLowerCase().replace(/(?:^|[\s-/])\w/g, function(match) {
return match.toUpperCase();
});
},
lowercase(value) {
return value.toLowerCase();
}
}
});
.logo {
width: 30px;
} | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
.nav-item {
width: 100%;
}
@media (min-width: 768px) {
.nav-item {
width: auto;
}
}
.post-grid {
margin-top: 1rem;
justify-content: center;
display: flex;
flex-wrap: wrap;
}
.post {
display: flex;
flex-direction: column;
margin-bottom: 30px;
}
.post-container {
flex: 1;
padding: 15px;
background: #fcfcfc;
border: 1px solid #eaeaea;
}
.post-title {
font-size: 18px !important;
}
.short-desc {
text-align: justify;
}
/* User Info */
.table.user-info {
margin-bottom: 0;
}
.table.user-info>tbody>tr:first-child>td {
border-top: none !important;
}
.table.user-info td {
padding: 6px !important;
}
.table.user-info tr td:first-child {
font-weight: 500;
width: 32% !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div id="app">
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand p-0" href="#">
<img src="https://www.pngrepo.com/png/303293/180/bootstrap-4-logo.png" alt="" class="logo">
</a>
<button class="navbar-toggler d-md-none ml-auto" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button> | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
<!-- Links -->
<div class="navbar-nav navbar-expand-md w-100">
<ul class="navbar-nav navbar-expand-md collapse navbar-collapse" id="navbarSupportedContent">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<!-- Dropdown -->
<li class="nav-item dropdown nav-item">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Authors</a>
<div class="dropdown-menu" v-if="users">
<a class="dropdown-item" href="#" v-for="user in users" :key="user.id" @click="toggleActiveUser(user)">{{user.name}}</a>
</div>
</li>
</ul>
</div>
</nav>
<div class="container">
<h1 class="h4 mt-3">Posts by {{currentUser?.name}}</h1>
<div v-if="currentUser != null">
<button type="button" class="btn btn-md btn-success" data-toggle="modal" data-target="#exampleModalCenter">
More about this author
</button>
</div>
<div class="row post-grid" v-if="posts">
<div class="col-sm-6 post" v-for="post in posts">
<div class="post-container">
<h2 class="display-4 post-title">{{post.title | titlecase}}</h2>
<div class="short-desc">
{{post.body | capitalize}}
</div>
</div>
</div>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
<div v-if="currentUser != null" class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">{{currentUser?.name}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table class="table user-info">
<tr>
<td>Lives in</td>
<td>{{currentUser?.address.city}}</td>
</tr>
<tr>
<td>Address</td>
<td>{{currentUser?.address.street}}, {{currentUser?.address.suite}}</td>
</tr>
<tr>
<td>Zipcode</td>
<td>{{currentUser?.address.zipcode}}</td>
</tr>
<tr>
<td>Email</td>
<td>
<a href="mailto:{{currentUser?.email | lowercase}}">{{currentUser?.email | lowercase}}</a>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Questions:
Is the code verbose?
Does the application leave a lot to be desired in regards to optimization? | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
Is the code verbose?
Does the application leave a lot to be desired in regards to optimization?
Answer: 1. Is the code verbose?
I would say it is a bit verbose. I first read over the methods to get data via XHR - e.g. users, posts, current user - and noted that they all have similar structure. I considered suggesting that there be one request to get all three types of data to reduce network traffic and allow simplifying the code, but I realize it is an external API being utilized, plus I noticed two of the three methods are called in watchers (see important point related to that in the next section), If that is necessary to have only certain data returned and you had control over the API endpoints then the endpoint could accept a list of data to return.
2. Does the application leave a lot to be desired in regards to optimization?
I would say yes - check this out: There is the method getCurrentUser which will set currentUser, and also there is an entry in watch for currentUser that calls this.getCurrentUser() - this typically leads to an infinite loop. The owners of the API likely would not like that! If it was my API and I was checking the logs it might look like a Denial of Service attack...
The same is true for posts. See this illustrated in the snippet below- notice the console logs that continue unceasingly (though they stop if the button labeled X Hide results is clicked).
Does the currentUser and posts change other than when the created lifecycle hook is called? | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
var app = new Vue({
el: "#app",
data: {
base_url: "https://jsonplaceholder.typicode.com",
uid: 1,
currentUser: null,
userData: null,
users: [],
posts: []
},
methods: {
toggleActiveUser(user) {
this.uid = user.id;
},
getUsers() {
axios
.get(`${this.base_url}/users`)
.then((response) => {
this.users = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
getCurrentUser() {
axios
.get(`${this.base_url}/users/${this.uid}`)
.then((response) => {
this.currentUser = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
getPosts() {
axios
.get(`${this.base_url}/posts?userId=${this.uid}`)
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
}
},
created() {
this.getUsers();
this.getCurrentUser();
this.getPosts();
},
watch: {
currentUser() {
console.log('watch current user - calling getCurrentUser()');
this.getCurrentUser();
},
posts() {
console.log('watch current posts - calling getPosts()');
this.getPosts();
}
},
filters: {
capitalize(value) {
return value.charAt(0).toUpperCase() + value.slice(1);
},
titlecase(value) {
return value.toLowerCase().replace(/(?:^|[\s-/])\w/g, function(match) {
return match.toUpperCase();
});
},
lowercase(value) {
return value.toLowerCase();
}
}
});
.logo {
width: 30px;
}
.nav-item {
width: 100%;
}
@media (min-width: 768px) {
.nav-item {
width: auto;
}
} | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
.nav-item {
width: 100%;
}
@media (min-width: 768px) {
.nav-item {
width: auto;
}
}
.post-grid {
margin-top: 1rem;
justify-content: center;
display: flex;
flex-wrap: wrap;
}
.post {
display: flex;
flex-direction: column;
margin-bottom: 30px;
}
.post-container {
flex: 1;
padding: 15px;
background: #fcfcfc;
border: 1px solid #eaeaea;
}
.post-title {
font-size: 18px !important;
}
.short-desc {
text-align: justify;
}
/* User Info */
.table.user-info {
margin-bottom: 0;
}
.table.user-info>tbody>tr:first-child>td {
border-top: none !important;
}
.table.user-info td {
padding: 6px !important;
}
.table.user-info tr td:first-child {
font-weight: 500;
width: 32% !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div id="app">
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand p-0" href="#">
<img src="https://www.pngrepo.com/png/303293/180/bootstrap-4-logo.png" alt="" class="logo">
</a>
<button class="navbar-toggler d-md-none ml-auto" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button> | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
<!-- Links -->
<div class="navbar-nav navbar-expand-md w-100">
<ul class="navbar-nav navbar-expand-md collapse navbar-collapse" id="navbarSupportedContent">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<!-- Dropdown -->
<li class="nav-item dropdown nav-item">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Authors</a>
<div class="dropdown-menu" v-if="users">
<a class="dropdown-item" href="#" v-for="user in users" :key="user.id" @click="toggleActiveUser(user)">{{user.name}}</a>
</div>
</li>
</ul>
</div>
</nav>
<div class="container">
<h1 class="h4 mt-3">Posts by {{currentUser?.name}}</h1>
<div v-if="currentUser != null">
<button type="button" class="btn btn-md btn-success" data-toggle="modal" data-target="#exampleModalCenter">
More about this author
</button>
</div>
<div class="row post-grid" v-if="posts">
<div class="col-sm-6 post" v-for="post in posts">
<div class="post-container">
<h2 class="display-4 post-title">{{post.title | titlecase}}</h2>
<div class="short-desc">
{{post.body | capitalize}}
</div>
</div>
</div>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
javascript, ecmascript-6, vue.js
<div v-if="currentUser != null" class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">{{currentUser?.name}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table class="table user-info">
<tr>
<td>Lives in</td>
<td>{{currentUser?.address.city}}</td>
</tr>
<tr>
<td>Address</td>
<td>{{currentUser?.address.street}}, {{currentUser?.address.suite}}</td>
</tr>
<tr>
<td>Zipcode</td>
<td>{{currentUser?.address.zipcode}}</td>
</tr>
<tr>
<td>Email</td>
<td>
<a href="mailto:{{currentUser?.email | lowercase}}">{{currentUser?.email | lowercase}}</a>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Other comments
Style nit-pick - filter method names
I noticed there are filters like titlecase and lowercase which deviate from the camelCase style. I would prefer those be lowerCase and titleCase but that's just my opinion and you are free to ignore it. | {
"domain": "codereview.stackexchange",
"id": 42705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, ecmascript-6, vue.js",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
Title: Advent of Code 2021 Day 4: Play Bingo against a Giant Squid
Question: [This is my first post here - though I have been lurking in the back reading, plussing, and hopefully learning for over two years]
Below is my solution for Advent of Code 2021 Day 4, where you are playing bingo against a giant squid.
You are given a set of bingo cards, and the list of numbers that will be drawn; the target for part 1 is to identify the bingo card that wins first, and for part 2, the card that wins last. For more details, check this link.
Some remarks:
this is supposed to be developed against the clock. Therefore, reusability is not a very important consideration.
error checking is not required, and not done. Bad input will blow everything apart; please ignore this.
I work in a C++20 environment (but didn't necessarily use any features of it). I marked it C++20 because if C++20 offers something I missed, I want to learn about it.
What I am looking for:
what is bad / poor / smelly?
what could be improved?
what could I do better using the C++20 feature set? I know about the capabilities, but didn't see any way to take advantage of it.
Here is the include BingoCard.h:
#pragma once
#include <array>
#include <iostream>
#include <sstream>
#include <vector>
constexpr size_t BingoCardSize = 5;
using Card = std::array<int, BingoCardSize* BingoCardSize>;
class BingoCard
{
public:
static BingoCard Create(std::istream& input); // construct by reading the numbers from input
int DrawNumbers(const std::vector<int>& n) noexcept; // draw numbers till 'bingo'
int GetRemainder() const noexcept; // get sum of numbers remaining after 'bingo'
private:
BingoCard(Card& n) noexcept : number(n) {} // constructor
bool HasBingo() const noexcept; // check for 'bingo' | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
private:
const Card number; // numbers on the bingo card
std::array<bool, BingoCardSize * BingoCardSize> hit{ false }; // flags if a number was hit
};
Here the class code in BingoCard.cpp:
#include "BingoCard.h"
BingoCard BingoCard::Create(std::istream& input)
{
Card n;
for (int i = 0; i < n.size(); ++i) input >> n[i];
return BingoCard(n);
}
bool BingoCard::HasBingo(void) const noexcept // check for 'bingo'. note: diagonals are NOT considered 'bingo'
{
for (int i = 0; i < BingoCardSize; ++i)
{
bool row{ true };
bool col{ true };
for (int j = 0; j < BingoCardSize; ++j)
{
row &= hit[BingoCardSize * i + j]; // check along row
col &= hit[i + BingoCardSize * j]; // check along column
}
if (row || col) return true;
}
return false;
}
int BingoCard::DrawNumbers(const std::vector<int>& draw) noexcept
{
for (int n = 0; n < draw.size(); ++n)
{
for (int j = 0; j < BingoCardSize * BingoCardSize; ++j)
{
if (number[j] == draw[n])
{
hit[j] = true;
if (HasBingo()) return n;
break;
}
}
}
return draw.size();
}
int BingoCard::GetRemainder(void) const noexcept
{
int sum{ 0 };
for (int i = 0; i < BingoCardSize * BingoCardSize; ++i)
{
if (!hit[i]) sum += number[i];
}
return sum;
}
and here the main program:
#include "BingoCard.h"
void AoC2021_04(std::istream& input)
{
std::string line{};
// read all numbers drawn during the game
std::vector<int> draw{};
getline(input, line);
std::istringstream str(line);
int z0{ 0 };
while (str >> z0) {
draw.emplace_back(z0);
char comma{};
str >> comma; // read the comma and ignore it
}
// read all Bingocards
std::vector<BingoCard> board{};
while (getline(input, line)) // the success of this blank line read means there is another board coming
{
board.emplace_back(BingoCard::Create(input));
} | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
// find the BingoCards with the earliest [Part 1] and latest [Part 2] 'bingo' (that is, the minimum / maximum of DrawNumbers return value)
int min{ std::numeric_limits<int>::max() };
int mini{ -1 };
int max{ 0 };
int maxi{ -1 };
for (int i = 0; i < board.size(); ++i)
{
auto n = board[i].DrawNumbers(draw);
if (n < min)
{
min = n;
mini = i;
}
if (n > max)
{
max = n;
maxi = i;
}
}
int z1 = board[mini].GetRemainder() * draw[min]; // AoC solution is min BingoCard's remainder times the winning number
std::cout << "AoC2021 Day 4 Part 1: " << z1 << '\n';
int z2 = board[maxi].GetRemainder() * draw[max]; // AoC solution is max BingoCard's remainder times the winning number
std::cout << "AoC2021 Day 4 Part 2: " << z2 << '\n';
}
int main()
{
AoC2021_04(std::cin);
}
my input data (if you go to AoC and log in, you get a different input - everyone gets a slightly different one. I am quite sure the code above works for any input):
37,60,87,13,34,72,45,49,61,27,97,88,50,30,76,40,63,9,38,67,82,6,59,90,99,54,11,66,98,23,64,14,18,4,10,89,46,32,19,5,1,53,25,96,2,12,86,58,41,68,95,8,7,3,85,70,35,55,77,44,36,51,15,52,56,57,91,16,71,92,84,17,33,29,47,75,80,39,83,74,73,65,78,69,21,42,31,93,22,62,24,48,81,0,26,43,20,28,94,79
66 78 7 45 92
39 38 62 81 77
9 73 25 97 99
87 80 19 1 71
85 35 52 26 68
47 38 84 53 16
66 3 63 92 94
71 41 59 1 87
17 67 62 73 33
69 12 26 82 55
89 94 65 57 6
27 77 60 19 83
72 58 0 29 91
33 75 50 64 87
24 88 32 93 38
35 82 7 49 43
58 8 56 54 6
74 53 98 59 84
4 40 11 67 14
89 1 44 51 45
44 51 57 75 19
33 54 24 96 1
30 0 45 47 38
58 78 17 74 14
91 60 32 67 10
72 91 61 45 49
68 67 31 69 96
92 52 9 34 36
16 77 62 55 41
42 88 53 4 15
68 98 73 81 41
36 43 87 48 95
55 62 8 12 30
23 34 59 72 85
38 7 16 13 79
66 98 23 69 89
71 84 79 14 53
10 62 60 44 28
49 43 29 45 75
72 94 5 64 3
27 99 41 10 91
2 94 16 85 75
25 95 15 34 36
90 72 76 20 29
55 18 93 53 69 | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
27 99 41 10 91
2 94 16 85 75
25 95 15 34 36
90 72 76 20 29
55 18 93 53 69
84 87 16 80 64
48 45 63 53 25
10 44 65 58 59
94 31 41 35 89
42 29 71 69 61
63 44 74 33 3
65 47 90 52 38
9 13 91 4 45
26 39 94 68 93
56 31 41 59 32
17 6 85 74 19
58 93 9 92 31
90 69 2 87 11
67 94 53 66 30
15 41 59 51 45
7 59 76 14 15
51 3 88 17 2
42 39 98 84 65
54 48 9 56 74
68 5 1 24 13
55 34 94 50 28
8 14 93 64 52
92 62 9 51 38
31 74 73 24 59
33 65 7 75 32
30 93 48 17 33
67 7 5 0 69
54 76 52 1 87
99 73 50 25 16
13 20 41 77 62
54 0 33 23 75
50 4 29 18 94
14 8 38 48 53
84 13 12 91 83
69 78 55 47 26
30 65 70 51 1
22 53 86 46 89
99 79 20 24 64
18 92 82 0 68
57 33 61 12 83
22 47 21 38 57
41 63 61 95 79
7 52 87 71 14
40 45 92 73 48
42 0 26 94 5
90 98 47 85 52
19 44 48 59 88
93 81 7 16 63
1 45 84 11 24
78 27 62 77 37
34 2 6 3 56
48 47 12 58 76
89 78 30 75 20
91 39 97 69 28
96 64 32 61 67
62 25 53 56 97
42 34 24 64 95
17 35 7 79 68
30 74 54 78 3
88 66 18 38 90
63 45 80 89 76
39 57 71 25 79
6 3 28 94 34
82 18 95 42 33
96 36 27 83 66
20 87 59 86 21
14 61 7 23 56
5 33 91 0 1
97 65 82 95 72
18 26 35 47 69
86 65 41 97 40
2 73 68 34 3
88 71 79 70 95
48 62 1 50 77
13 67 20 15 55
98 16 93 30 24
39 11 56 13 3
14 83 76 58 60
73 81 63 88 92
74 96 51 43 77
4 12 43 46 53
34 37 50 60 56
96 98 10 65 38
40 24 80 77 73
23 67 84 64 13
5 19 85 1 58
41 15 44 57 22
2 66 80 94 71
40 55 89 79 0
56 81 23 30 24
0 29 94 4 68
81 2 20 95 43
49 40 37 30 96
19 23 42 26 85
61 17 12 72 88
64 26 61 32 68
80 24 31 67 49
72 15 88 98 50
73 55 86 38 10
87 34 52 29 63
76 61 36 54 10
63 56 75 67 29
11 9 41 4 43
83 88 45 93 74
72 70 94 60 98
44 99 39 5 23
53 69 68 60 83
81 72 1 97 20
43 96 91 11 32
51 7 8 86 25
62 36 39 20 5
52 59 6 74 95
2 83 44 43 66
96 55 79 42 37
34 32 19 0 90
84 8 65 35 78
57 83 4 82 36
3 29 74 60 90
86 47 53 26 10
52 51 40 32 6
69 32 77 72 44
34 54 82 94 23
1 60 2 11 36
17 52 0 73 31
5 90 24 21 53 | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
69 32 77 72 44
34 54 82 94 23
1 60 2 11 36
17 52 0 73 31
5 90 24 21 53
42 24 18 44 5
74 19 76 62 34
61 66 4 77 47
92 94 78 39 97
25 91 11 22 23
11 87 83 93 8
7 73 85 84 3
65 16 71 12 44
88 61 54 19 97
72 57 80 59 45
30 55 1 62 39
31 45 34 6 43
68 93 38 57 60
70 32 5 95 92
35 83 66 36 91
76 89 54 36 21
99 28 62 78 73
17 72 96 13 91
79 65 37 81 14
33 86 31 11 25
3 93 37 88 47
4 6 19 87 30
76 22 33 69 64
36 52 60 82 53
39 5 61 67 90
28 6 59 61 75
40 4 65 43 93
41 32 60 89 18
22 11 12 9 0
26 15 78 90 30
8 87 74 70 76
45 43 63 84 25
18 68 92 4 31
66 22 29 71 91
15 50 64 52 1
3 93 25 71 43
45 48 52 4 94
36 34 47 74 97
12 27 64 14 80
41 17 21 32 88
76 62 68 24 0
97 43 37 3 79
65 25 52 28 20
29 18 90 89 48
35 66 19 53 82
57 98 86 69 24
55 74 49 12 35
68 50 70 38 75
82 56 73 5 89
90 10 15 14 95
98 86 47 87 81
62 51 3 79 10
60 39 61 9 77
36 50 89 49 88
63 95 1 15 69
72 71 51 33 23
12 35 97 34 99
4 32 36 88 80
5 17 3 56 1
44 19 47 98 26
55 56 75 5 74
4 86 60 67 68
21 45 40 17 2
43 39 20 88 33
24 70 58 13 98
34 28 86 65 80
82 23 98 91 0
61 62 43 51 49
39 10 58 1 11
8 83 17 97 31
7 96 2 18 26
15 86 34 76 61
75 93 68 3 83
63 37 85 8 74
11 51 32 14 23
25 33 24 86 75
63 73 97 37 47
76 72 34 81 27
93 91 70 20 98
11 94 64 28 6
70 86 59 78 95
47 18 64 40 68
49 55 20 12 53
60 76 35 83 50
32 73 91 46 28
31 21 92 97 89
14 82 51 1 62
43 58 90 18 24
56 79 54 35 48
29 39 45 86 66
62 74 81 27 23
28 92 66 86 29
98 95 14 35 11
13 69 70 64 79
51 80 87 96 85
69 15 37 95 29
6 45 20 17 36
62 42 1 77 59
25 44 72 35 31
70 73 86 89 97
81 88 82 99 13
53 87 2 29 47
36 94 48 95 65
96 42 92 61 60
86 33 83 52 12
32 4 52 54 24
28 77 58 80 16
62 82 59 6 66
63 72 91 41 29
36 22 68 0 31
38 58 51 77 26
80 5 90 30 20
33 14 54 53 0
76 74 63 84 15
45 73 41 29 69
28 31 47 97 58
69 7 86 40 57
45 1 11 84 54
29 9 95 93 88
12 5 79 76 77
93 7 60 75 12
49 64 20 46 10
3 23 76 42 47
9 22 6 34 87
41 37 66 45 48 | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
93 7 60 75 12
49 64 20 46 10
3 23 76 42 47
9 22 6 34 87
41 37 66 45 48
9 53 64 37 83
89 43 91 30 36
39 22 69 79 42
31 28 55 40 54
7 24 44 84 46
81 75 15 89 31
11 13 12 5 10
94 80 22 68 3
27 60 42 65 58
40 82 17 92 73
16 40 98 33 41
79 72 2 77 86
14 32 85 74 50
11 49 62 56 9
69 20 12 19 60
95 72 61 54 92
10 0 1 84 99
88 62 13 18 86
89 59 60 29 78
55 98 27 91 87
58 37 49 43 76
14 3 65 13 2
92 20 6 73 5
96 53 82 95 99
15 83 80 26 11
51 71 56 58 95
59 84 46 54 94
8 7 49 62 83
47 92 32 31 65
48 44 57 25 20
5 3 26 90 14
61 16 44 4 0
49 1 52 82 54
60 77 86 43 87
6 36 73 25 31
32 25 37 18 63
60 65 35 24 34
52 94 12 77 47
99 83 2 30 74
58 38 17 75 56
77 88 70 22 39
4 14 86 99 50
5 79 2 78 16
34 46 83 58 13
71 74 21 76 66
25 15 99 79 68
59 95 82 22 53
0 70 85 73 67
36 10 66 6 32
1 51 52 40 4
29 49 64 26 18
56 28 9 7 99
20 2 74 71 39
81 94 55 75 16
52 45 35 66 11
42 68 76 37 34
0 41 86 19 59
7 46 49 30 88
74 80 24 50 29
96 78 67 61 26
45 96 11 99 44
87 95 32 77 64
8 31 80 4 34
24 91 90 16 60
13 29 63 67 59
15 55 0 52 54
58 45 62 66 85
91 19 32 16 92
93 59 8 22 2
98 33 31 17 84
28 49 63 81 69
30 45 46 90 26
4 76 94 93 24
15 16 18 86 62
2 98 89 44 67
32 35 11 1 38
86 36 70 24 95
59 94 71 99 40
48 64 91 25 57
29 76 68 88 58
45 81 50 20 68
85 91 49 38 9
27 0 58 8 10
59 1 88 19 89
23 29 61 99 12
74 50 41 83 4
33 34 88 23 14
89 39 98 75 37
26 73 80 71 44
52 53 48 84 85
47 35 98 73 9
61 4 71 91 58
65 40 63 36 86
12 30 69 46 2
6 17 23 32 74
84 87 59 58 65
30 53 7 98 48
71 28 1 77 56
36 88 52 64 89
90 37 94 26 39
25 75 32 48 6
49 7 74 50 62
68 51 72 12 10
94 37 97 69 91
73 9 67 18 1
51 96 71 44 0
97 52 1 77 11
90 9 15 76 24
68 6 57 40 98
47 31 94 82 49
48 31 26 77 14
94 93 27 2 82
11 83 85 9 8
90 69 4 16 22
5 62 29 57 30
59 46 82 13 53
71 58 67 2 28
73 52 30 97 12
95 34 51 32 38
62 81 5 15 74
82 10 58 84 67
92 5 66 25 83
90 76 21 26 69
39 63 42 11 53
23 61 80 99 48 | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
82 10 58 84 67
92 5 66 25 83
90 76 21 26 69
39 63 42 11 53
23 61 80 99 48
8 13 49 63 83
26 48 50 53 43
1 39 95 60 99
96 7 35 94 10
24 44 65 31 46
87 17 72 71 81
35 56 4 99 59
96 90 37 23 86
34 73 18 19 78
41 10 43 92 80
29 7 37 40 70
72 10 85 74 76
36 9 13 73 82
4 65 49 77 42
75 24 84 78 39
29 6 94 59 38
99 55 8 66 85
14 43 25 92 67
49 33 87 39 44
9 61 24 90 75
45 35 78 56 24
53 38 34 92 55
20 44 90 33 83
54 95 71 87 13
40 43 85 88 68
32 80 59 34 22
18 9 12 15 55
85 60 37 64 92
35 39 26 90 50
52 67 58 87 8
90 96 40 14 61
34 33 80 22 38
59 94 3 6 4
0 71 25 1 20
30 57 48 31 10
50 14 40 48 83
85 80 29 60 2
92 59 86 99 57
46 7 89 66 75
98 6 45 97 51
13 17 0 57 5
29 68 52 11 59
78 63 94 88 89
35 54 74 18 2
28 65 86 1 30
57 46 44 86 62
43 89 81 34 13
32 51 9 6 35
29 52 84 8 88
26 21 17 75 85
14 87 26 22 30
65 78 98 6 60
42 99 19 71 11
68 27 48 52 62
51 1 54 37 74
76 69 37 49 61
20 91 14 31 11
54 40 67 71 15
73 64 85 80 62
5 10 3 51 7
63 90 54 46 17
16 5 4 56 33
39 41 8 87 80
14 77 26 47 70
15 48 6 10 76
96 95 0 42 56
3 87 92 18 60
51 7 38 4 91
41 33 80 43 66
61 32 57 84 10
8 64 76 78 17
55 74 68 47 29
46 84 49 58 93
52 26 32 11 33
24 42 98 27 43
14 19 27 93 16
23 32 74 73 67
68 38 2 22 76
6 12 94 15 77
64 62 34 3 37
Some thoughts about design decision I made and why I made them. Let me know if you think I should have made them different and why: | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, object-oriented, programming-challenge, c++20
using the 'factory' method Create: I wanted the list of numbers inside the BingoCard to be const, but that disallows to read it from std::cin in the constructor. Alternatively, I could remove the const, and put the Create-code inside the constructor.
'hit' array as a member: originally, I modified the numbers on the bingo card to -1 to declare them 'drawn', but that felt poor. The BingoCard should not lose information by getting its numbers overwritten. It worked with the -1 though.
min/max calculation: I considered using stuff from <algorithm>, but I need more than the min/max values themselves; I also need their indexes. I don't see how I could use them at all.
Answer:
HasBingo works too hard. A hit may create a bingo only along the row and/or column of the square it hits. There is no reason to test all of them.
This observation hints that you may want to have 10 match counts (one per row, and one per column), and declare bingo when one of them reaches 5.
Representing a card as an std::map<int, square> would let you find the hit much faster than scanning the entire card over and over again.
DrawNumbers does not belong to BingoCard. Consider iterating over the drawn number first, along the lines of:
for (auto n: numbers) {
for (auto b: boards) {
auto hit = b[n];
if (hit == b.end() {
continue;
}
if (b.hasBingo(hit) {
....
}
}
}
The code assumes that a card consists of unique numbers, and the drawn numbers are also unique. However, the problem statement doesn't specify this. A prudent program must take it into an account. | {
"domain": "codereview.stackexchange",
"id": 42706,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, programming-challenge, c++20",
"url": null
} |
c++, beginner, simulation, game-of-life
Title: Conway's Game of Life in C++ with a Board Struct
Question: I made the game of Life in C++ for a highschool class project. The website we're using doesn't have an autograder for C++, and my programming teacher doesn't really know how to program... so I'd love some external feedback! While I believe this simulation works, I'm not sure about the quality of the code. I tried making it as readable and fluid as possible, but I'm new to C++. Let me know how "C++" this code is, and about any pitfalls I may have dug myself into.
I'm unsure what version of C++ this website uses, but I believe its pre-C++11? (Due to a lack of smart pointers.)
I highly reccomend running it on the website here: https://codehs.com/sandbox/drakepickett/game-of-life
p.s. - I added console clearing and such just as a cheeky experiment to make it look nice. Not sure how safe console clearing with my method is :)
Thank you very much!
Here is the raw code:
#include "util.h"
#include <vector>
#include <chrono>
#include <thread>
using namespace std; | {
"domain": "codereview.stackexchange",
"id": 42707,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, simulation, game-of-life",
"url": null
} |
c++, beginner, simulation, game-of-life
struct Board
{
int BOARD_SIZE;
char liveCell;
char deadCell;
vector<vector<char> > cells;
void populateBoard()
{
int numLive = readInt(1, BOARD_SIZE*BOARD_SIZE, "Please enter number of active cells between 1 and " + to_string(BOARD_SIZE*BOARD_SIZE)+ ": ");
for (int i = 0; i < numLive; i++)
{
int x, y;
while (true)
{
x = randInt(0, this->BOARD_SIZE-1);
y = randInt(0, this->BOARD_SIZE-1);
if (this->cells[x][y] == this->deadCell) break;
}
this->cells[x][y] = this->liveCell;
}
}
Board(int size, char liveCell, char deadCell)
{
this->BOARD_SIZE = size;
this->liveCell = liveCell;
this->deadCell = deadCell;
for (int i = 0; i < this->BOARD_SIZE; i++)
{
vector<char> row;
for (int j = 0; j < this->BOARD_SIZE; j++)
{
row.push_back(this->deadCell);
}
this->cells.push_back(row);
}
populateBoard();
}
int getNumNeighbors(int row, int column)
{
int numNeighbors = 0;
vector<int> xRange;
vector<int> yRange;
if (row > 0) yRange.push_back(-1);
yRange.push_back(0);
if (row < this->cells.size()-1) yRange.push_back(1);
if (column > 0) xRange.push_back(-1);
xRange.push_back(0);
if (column < this->cells.size()-1) xRange.push_back(1);
for (int y : yRange)
{
for (int x : xRange)
{
if (x == 0 && y == 0) continue;
//cout <<"Y: " << row << " | Row: " << row+y << " _ X: " << column << " | Column: " << column + x << endl;
if (this->cells[row+y][column+x] == this->liveCell) numNeighbors++;
//cout << "We made it!" << endl; | {
"domain": "codereview.stackexchange",
"id": 42707,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, simulation, game-of-life",
"url": null
} |
c++, beginner, simulation, game-of-life
//cout << "We made it!" << endl;
}
}
return numNeighbors;
}
void update()
{
vector<vector<char> > b = this->cells;
for (int i = 0; i < this->BOARD_SIZE; i++)
{
for(int j = 0; j < this->BOARD_SIZE; j++)
{
int numNeighbors = getNumNeighbors(i, j);
if (this->cells[i][j] == this->liveCell && !(numNeighbors == 2 || numNeighbors == 3)) b[i][j] = this-> deadCell;
if (this->cells[i][j] == this->deadCell && numNeighbors == 3) b[i][j] = this->liveCell;
}
}
this->cells = b;
}
void print()
{
for (int i = 0; i < this->BOARD_SIZE; i++)
{
for (int j = 0; j < this->BOARD_SIZE; j++)
{
cout << this->cells[i][j] << " ";
}
cout << endl;
}
}
}; | {
"domain": "codereview.stackexchange",
"id": 42707,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, simulation, game-of-life",
"url": null
} |
c++, beginner, simulation, game-of-life
void cls()
{
using namespace std::chrono_literals;
this_thread::sleep_for(1000ms);
std::cout << "\x1B[2J\x1B[H";
}
int main()
{
Board board(15, 'X', '-');
int numIterations = readInt(0, 1000, "Run how many iterations? (0-1000): ");
for (int i = 0; i < numIterations; i++)
{
cls();
cout << "Iteration " << i << endl;
board.print();
board.update();
}
cls();
cout <<"Final Board" << endl;
board.print();
return 0;
}
Answer:
It is a good idea to list headers in alphabetical order, this enables searching for the reader. Also user-defined headers can be separated from global ones.
2.BOARD_SIZE, dead and alive can be consts. As these are not changed once the object is initialized.
Loops to initialize are not required. You can write like:
vector<vector> (BOARD_SIZE,vector(BOARD_SIZE,DEAD));
Also,the boolean logic of determining the fate of each cell can be enclosed in a function.
bool shouldDie(int row,int col) {
return (this->cells[row][col] == this->liveCell && !(numNeighbors == 2 || numNeighbors == 3));
} | {
"domain": "codereview.stackexchange",
"id": 42707,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, simulation, game-of-life",
"url": null
} |
python, python-3.x, linux
Title: A Python script to install a number of useful programs and packages on a fresh Linux-based device
Question: I work with Linux-based devices, and, both at work and in my personal life, it's necessary to wipe these devices every so often - sometimes as frequently as multiple times per week. In this context, it's obviously very useful to have some sort of script which reinstalls a suite of useful software.
For the past couple of years I've made do with a Shell script, but, since GitHib decided to encourage the use of access tokens ever more strongly, I switched to using Python. Setting up Git is one of the script's most crucial actions. Other responsibilities:
Upgrading Python as required.
Installing a number of useful packages via APT.
Cloning and installing some of my own repositories.
I'm going to post the code for the script's core class below. If you want to run the script yourself, you can download the full repo - it's only a few files - here. But beware that it will start trying to install stuff!
The core class:
"""
This code defines a class which installs the various packages and repositories
required on this computer.
"""
# Standard imports.
import os
import pathlib
import shutil
import subprocess
import urllib.parse
# Local imports.
from git_credentials import set_up_git_credentials, \
DEFAULT_PATH_TO_GIT_CREDENTIALS, DEFAULT_PATH_TO_PAT, \
DEFAULT_USERNAME as DEFAULT_GIT_USERNAME, DEFAULT_EMAIL_ADDRESS
# Local constants.
DEFAULT_OS = "ubuntu"
DEFAULT_TARGET_DIR = str(pathlib.Path.home())
DEFAULT_PATH_TO_WALLPAPER_DIR = \
os.path.join(DEFAULT_TARGET_DIR, "hmss/wallpaper/")
##############
# MAIN CLASS #
############## | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
##############
# MAIN CLASS #
##############
class HMSoftwareInstaller:
""" The class in question. """
# Class constants.
CHROME_DEB = "google-chrome-stable_current_amd64.deb"
CHROME_STEM = "https://dl.google.com/linux/direct/"
EXPECTED_PATH_TO_GOOGLE_CHROME_COMMAND = "/usr/bin/google-chrome"
GIT_URL_STEM = "https://github.com/"
MISSING_FROM_CHROME = ("eog", "nautilus")
OTHER_THIRD_PARTY = ("gedit-plugins", "inkscape")
SUPPORTED_OSS = set(("ubuntu", "chrome-os", "raspian", "linux-based"))
WALLPAPER_STEM = "wallpaper_t"
WALLPAPER_EXT = ".png"
def __init__(
self,
this_os=DEFAULT_OS,
target_dir=DEFAULT_TARGET_DIR,
thunderbird_num=None,
path_to_git_credentials=DEFAULT_PATH_TO_GIT_CREDENTIALS,
path_to_pat=DEFAULT_PATH_TO_PAT,
git_username=DEFAULT_GIT_USERNAME,
email_address=DEFAULT_EMAIL_ADDRESS,
path_to_wallpaper_dir=DEFAULT_PATH_TO_WALLPAPER_DIR
):
self.this_os = this_os
self.target_dir = target_dir
self.thunderbird_num = thunderbird_num
self.path_to_git_credentials = path_to_git_credentials
self.path_to_pat = path_to_pat
self.git_username = git_username
self.email_address = email_address
self.path_to_wallpaper_dir = path_to_wallpaper_dir
self.failure_log = []
def check_os(self):
""" Test whether the OS we're using is supported. """
if self.this_os in self.SUPPORTED_OSS:
return True
return False
def move_to_target_dir(self):
""" Change into the directory where we want to install stuff. """
os.chdir(self.target_dir) | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def set_up_git(self):
""" Install Git and set up a personal access token. """
install_result = install_via_apt("git")
if not install_result:
return False
pat_result = \
set_up_git_credentials(
username=self.git_username,
email_address=self.email_address,
path_to_git_credentials=self.path_to_git_credentials,
path_to_pat=self.path_to_pat
)
if not pat_result:
return False
return True
def install_google_chrome(self):
""" Ronseal. """
if (
check_command_exists("google-chrome") or
self.this_os == "chrome-os"
):
return True
chrome_url = urllib.parse.urljoin(self.CHROME_STEM, self.CHROME_DEB)
chrome_deb_path = "./"+self.CHROME_DEB
download_process = subprocess.run(["wget", chrome_url])
if download_process.returncode != 0:
return False
if not install_via_apt(chrome_deb_path):
return False
os.remove(chrome_deb_path)
return True | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def change_wallpaper(self):
""" Change the wallpaper on the desktop of this computer. """
if not os.path.exists(self.path_to_wallpaper_dir):
return False
if self.thunderbird_num:
wallpaper_filename = (
self.WALLPAPER_STEM+
str(self.thunderbird_num)+
self.WALLPAPER_EXT
)
else:
wallpaper_filename = "default.jpg"
wallpaper_path = \
os.path.join(self.path_to_wallpaper_dir, wallpaper_filename)
if self.this_os == "ubuntu":
arguments = [
"gsettings",
"set",
"org.gnome.desktop.background",
"picture-uri",
"file:///"+wallpaper_path
]
elif self.this_os == "raspbian":
arguments = ["pcmanfm", "--set-wallpaper", wallpaper_path]
else:
return False
result = run_with_indulgence(arguments)
return result
def make_git_url(self, repo_name):
""" Make the URL pointing to a given repo. """
suffix = self.git_username+"/"+repo_name+".git"
result = urllib.parse.urljoin(self.GIT_URL_STEM, suffix)
return result | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def install_own_repo(
self,
repo_name,
dependent_packages=None,
installation_arguments=None
):
""" Install a custom repo. """
if os.path.exists(repo_name):
print("Looks like "+repo_name+" already exists...")
return True
if dependent_packages:
for package_name in dependent_packages:
if not install_via_apt(package_name):
return False
arguments = ["git", "clone", self.make_git_url(repo_name)]
if not run_with_indulgence(arguments):
return False
os.chdir(repo_name)
if installation_arguments:
if not run_with_indulgence(arguments):
os.chdir(self.target_dir)
return False
os.chdir(self.target_dir)
return True
def install_kingdom_of_cyprus(self):
""" Install the Kingdom of Cyprus repo. """
repo_name = "kingdom-of-cyprus"
dependent_packages = ("sqlite", "sqlitebrowser", "nodejs", "npm")
result = \
self.install_own_repo(
repo_name,
dependent_packages=dependent_packages
)
return result
def install_chancery(self):
""" Install the Chancery repos. """
repo_name = "chancery"
if not self.install_own_repo(repo_name):
return False
repo_name_b = "chancery-b"
installation_arguments_b = ("sh", "install_3rd_party")
result = \
self.install_own_repo(
repo_name_b,
installation_arguments=installation_arguments_b
)
return result
def install_hmss(self):
""" Install the HMSS repo. """
result = self.install_own_repo("hmss")
return result | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def install_hgmj(self):
""" Install the HGMJ repo. """
repo_name = "hgmj"
installation_arguments = ("sh", "install_3rd_party")
result = \
self.install_own_repo(
repo_name,
installation_arguments=installation_arguments
)
return result
def install_other_third_party(self):
""" Install some other useful packages. """
result = True
for package in self.OTHER_THIRD_PARTY:
if not install_via_apt(package):
result = False
if self.this_os == "chrome-os":
for package in self.MISSING_FROM_CHROME:
if not install_via_apt(package):
result = False
return result
def run_essentials(self):
""" Run those processes which, if they fail, we will have to stop
the entire program there. """
print("Checking OS...")
if not self.check_os():
self.failure_log.append("Check OS")
return False
print("Updating and upgrading...")
if not update_and_upgrade():
self.failure_log.append("Update and upgrade")
return False
print("Upgrading Python...")
if not upgrade_python():
self.failure_log.append("Upgrade Python")
return False
print("Setting up Git...")
if not self.set_up_git():
self.failure_log.append("Set up Git")
return False
return True | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def run_non_essentials(self):
""" Run the installation processes. """
result = True
print("Installing Google Chrome...")
if not self.install_google_chrome():
self.failure_log.append("Install Google Chrome")
result = False
print("Installing HMSS...")
if not self.install_hmss():
self.failure_log.append("Install HMSS")
print("Installing Kingdom of Cyprus...")
if not self.install_kingdom_of_cyprus():
self.failure_log.append("Install Kingdom of Cyprus")
result = False
print("Installing Chancery repos...")
if not self.install_chancery():
self.failure_log.append("Install Chancery repos")
result = False
print("Installing HGMJ...")
if not self.install_hgmj():
self.failure_log.append("Install HGMJ")
result = False
print("Installing other third party...")
if not self.install_other_third_party():
self.failure_log.append("Install other third party")
result = False
print("Changing wallpaper...")
if not self.change_wallpaper():
self.failure_log.append("Change wallpaper")
# It doesn't matter too much if this fails.
return result
def print_outcome(self, passed, with_flying_colours):
""" Print a list of what failed to the screen. """
if passed and with_flying_colours:
print("Installation PASSED with flying colours!")
return
if passed:
print("Installation PASSED but with non-essential failures.")
else:
print("Installation FAILED.")
print("\nThe following items failed:\n")
for item in self.failure_log:
print(" * "+item)
print(" ") | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def run(self):
""" Run the software installer. """
print("Running His Majesty's Software Installer...")
get_sudo()
self.move_to_target_dir()
if not self.run_essentials():
print("\nFinished.\n\n")
self.print_outcome(False, False)
return False
with_flying_colours = self.run_non_essentials()
print("\nComplete!\n")
self.print_outcome(True, with_flying_colours)
return True
####################
# HELPER FUNCTIONS #
####################
def get_sudo():
""" Get superuser privileges. """
print("I'm going to need superuser privileges for this...")
subprocess.run(
["sudo", "echo", "Superuser privileges: activate!"],
check=True
)
def run_with_indulgence(arguments, show_output=False):
""" Run a command, and don't panic immediately if we get a non-zero
return code. """
if show_output:
print("Running subprocess.run() with arguments:")
print(arguments)
process = subprocess.run(arguments)
else:
process = subprocess.run(arguments, stdout=subprocess.DEVNULL)
if process.returncode == 0:
return True
return False
def run_apt_with_argument(argument):
""" Run APT with an argument, and tell me how it went. """
arguments = ["sudo", "apt-get", argument]
result = run_with_indulgence(arguments)
return result
def check_against_dpkg(package_name):
""" Check whether a given package is on the books with DPKG. """
result = run_with_indulgence(["dpkg", "--status", package_name])
return result
def check_command_exists(command):
""" Check whether a given command exists on this computer. """
if shutil.which(command):
return True
return False | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
def install_via_apt(package_name, command=None):
""" Attempt to install a package, and tell me how it went. """
if not command:
command = package_name
if check_command_exists(command):
return True
arguments = ["sudo", "apt-get", "--yes", "install", package_name]
result = run_with_indulgence(arguments)
return result
def update_and_upgrade():
""" Update and upgrade the existing software. """
if not run_apt_with_argument("update"):
return False
if not run_apt_with_argument("upgrade"):
return False
if not install_via_apt("software-properties-common"):
return False
return True
def pip3_install(package):
""" Run `pip3 install [package]`. """
if run_with_indulgence(["pip3", "install", package]):
return True
return False
def upgrade_python():
""" Install PIP3 and other useful Python hangers-on. """
result = True
if not install_via_apt("python3-pip"):
result = False
if not pip3_install("pylint"):
result = False
if not pip3_install("pytest"):
result = False
return result
Answer: The nuclear option
it's necessary to wipe these devices every so often - sometimes as frequently as multiple times per week
Having a script like this is useful, because reproducible environments are useful; so long as you're not relying on it to cover over other problems. Your two scenarios:
At work: we were manufacturing embedded Linux devices, and we needed to be absolutely sure that each new software release would work install properly on untouched hardware.
That's a great application of a setup script like this.
At home: my laptop's a Chromebook with a Linux VM; every few months, I run into a problem in which it's quicker just to delete the VM and start again. | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
Fine-ish, so long as you understand what went wrong and were able to learn from it before nuking your OS.
Code
CHROME_DEB seems like a strange choice. You're on Ubuntu, so why not just install it from the repo?
You should be able to infer most of EXPECTED_PATH_TO_GOOGLE_CHROME_COMMAND from the result of a which.
set(("ubuntu", "chrome-os", "raspian", "linux-based")) should just be {"ubuntu", "chrome-os", "raspian", "linux-based"}.
The kind of rote repetition for member initialisation seen in your __init__ can be mostly eliminated by use of a @dataclass.
self.failure_log = [] implies that you're logging to memory. This is risky: if your process crashes, won't you lose your logs? Consider instead using the standard logging module and logging to a file.
This:
if self.this_os in self.SUPPORTED_OSS:
return True
return False
should just be
return self.this_os in self.SUPPORTED_OSS
Avoid newline-escapes like in pat_result = \, which can just be
pat_result = set_up_git_credentials(
username=self.git_username,
email_address=self.email_address,
path_to_git_credentials=self.path_to_git_credentials,
path_to_pat=self.path_to_pat
)
This:
if not pat_result:
return False
return True
can just be
return bool(pat_result)
This use of subprocess:
download_process = subprocess.run(["wget", chrome_url])
if download_process.returncode != 0:
return False | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
python, python-3.x, linux
should be replaced with subprocess.check_call. This will, rather than a boolean failure indicator, raise an exception - which you should also be doing. Use exceptions for failure states instead of boolean returns. Your "essential failures" should be represented by exceptions allowed to unwind the stack, and your "non-essential failures" should be logged in an except.
Replace calls to os.path.exists etc. with calls to the pathlib alternatives.
Your install_own_repo is curious. You accept a list of dependent packages required before installation of repo_name. This betrays a lack of proper packaging. Your own repos, when written properly, should build debs that express their own dependencies, so that you can just install the top-level package and the dependencies will be pulled in automatically. The alternative to making your own debs is to express dependencies in a distutils setup.py, which is preferable if all of the dependencies are pure Python. | {
"domain": "codereview.stackexchange",
"id": 42708,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, linux",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
Title: C# Tool to Generate MS Word Document Mailbox List From MS Excel | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
Question: There is now a Follow up question to this question.
Abstract
The VBA solution didn't work on the clients computer because Office 2010 Starter Edition doesn't support VBA. I decided to try a C# solution instead. The portion of the tool presented in this question is the interface to the Excel interop library which allows access to Microsoft excel files. There is also a Microsoft Word interop interface that is not presented in this question. The full source code for this project including the UI can be found in my GitHub repository.
The portion of the application that is presented here opens an excel workbook file, finds the worksheets within the workbook and copies the worksheet with
the apartment complex tenants into a DataTable. The user can then edit the data in the tenant data, adding, editing or deleting tenants and print or save lists of tenants for each building to Microsoft Word Documents. The edits are stored in the program until the user clicks a button in the UI to save them or exits the application. Each edit is applied separately when the data is saved to reduce the amount of time to save the updates. At the time of each edit the DataTable is updated for future edits, but each edit is stored in a list of updates.
A sanitized CSV version of the excel worksheet is presented at the bottom of the question. I don't have all the real data myself, but the sanitized version is used in testing and works fine.
Questions and Issues
The excel worksheet contains 178 rows of data with 23 columns. This takes approximately 8 seconds to load (measured within the program in debugging code that has been removed). This function is where the 8 seconds elapse:
private void AddTenantDataToTenantTable(Excel.Range TenantDataRange,
ref DataTable tenantTable, int headerLine, int firstColumn)
{
int columnCount = TenantDataRange.Columns.Count;
int rowcount = TenantDataRange.Rows.Count; | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
int rowcount = TenantDataRange.Rows.Count;
// This loop needs to be optimized, it takes almost 8 seconds
for (int row = headerLine + 1; row <= rowcount; row++)
{
DataRow tenantData = tenantTable.NewRow();
for (int column = firstColumn; column <= columnCount; column++)
{
tenantData[column - firstColumn] =
Convert.ToString(TenantDataRange.Cells[row, column].Value2);
}
tenantTable.Rows.Add(tenantData);
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
}
I'd appreciate any and all help with optimizing that loop for performance.
I'm also interested in the maintainability, naming consistency, reducing any cyclic complexity or object coupling. I've started using Visual Studio 2019 analytic tools, but I don't necessarily agree with some of the maintainability stats.
The Code:
The excel interface is presented first, any classes included in the code are presented after that.
CExcelInteropMethods.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Windows;
using Excel = Microsoft.Office.Interop.Excel;
namespace RentRosterAutomation
{
// Provides the interface between the rest of the program and Microsoft excel
class CExcelInteropMethods
{
// Excel objects
private Excel.Application xlApp;
private Excel.Workbook xlWorkbook;
private Excel.Worksheet tenantRoster;
// Classes written for this project
private CPropertyComplex complex;
private List<CApartment> TenantUpdates; // Stored updates to be written
// by save button or program exit
private bool worksheetChanged;
private string tenantRosterName;
private DataTable localTenantRoster; // Local copy of excel worksheet
private const int ApartmentColumn = 0;
private const int TenantLastNameColumn = 3;
private const int CoTenantLastNameColumn = 5;
public CPropertyComplex Complex { get { return complex; } }
public bool AlreadyOpenOtherApp { get; private set; }
public bool HaveEditsToSave { get { return (TenantUpdates.Count > 0); } }
public string WorkbookName { get; set; } | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
public CExcelInteropMethods(string workBookName, string workSheetName)
{
worksheetChanged = false;
WorkbookName = workBookName;
tenantRosterName = workSheetName;
TenantUpdates = new List<CApartment>();
try
{
AlreadyOpenOtherApp = false;
if (!string.IsNullOrEmpty(WorkbookName))
{
AlreadyOpenOtherApp = WorkSheetIsOpenInOtherApp(WorkbookName);
if (!AlreadyOpenOtherApp)
{
GetExcelDataAndReportProgress();
ConstructComplexAndReport();
CloseWorkbookExitExcel();
}
}
}
catch (Exception e)
{
string emsg = "CExcelInteropMethods Constructor failed while building Complex:" + e.Message;
MessageBox.Show(emsg);
}
}
public void SaveEditsCloseWorkbookExitExcel()
{
if (worksheetChanged)
{
SaveWorkBookEdits();
}
CloseWorkbookExitExcel();
}
public void CloseWorkbookExitExcel()
{
if (xlWorkbook == null || xlApp == null)
{
return;
}
xlWorkbook.Close();
xlWorkbook = null;
xlApp.Quit();
xlApp = null;
}
public List<string> GetSheetNames()
{
List<string> sheetNames = new List<string>();
StartExcelOpenWorkbook(false);
if (xlWorkbook == null)
{
return null;
}
int SheetCount = xlWorkbook.Sheets.Count;
for (int i = 1; i <= SheetCount; ++i)
{
string sheetname = xlWorkbook.Sheets[i].Name;
sheetNames.Add(sheetname);
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
return sheetNames;
}
public void PreferencesUpdated(CUserPreferences preferences)
{
WorkbookName = preferences.RentRosterFile;
tenantRosterName = preferences.RentRosterSheet;
StartExcelOpenWorkbook(true);
}
public CMailboxListData GetMailboxData(CBuilding building)
{
CMailboxListData mailboxData = new CMailboxListData(building);
List<int> apartmentNumbers = building.ApartmentNumbers;
foreach (int aptNo in apartmentNumbers)
{
mailboxData.addApartmentData(new CApartment(aptNo));
}
return mailboxData;
}
public void DeleteTenant(int apartmentNumber)
{
CRenter tenant = new CRenter();
TenantUpdates.Add(new CApartment(apartmentNumber, tenant));
worksheetChanged = UdateTenantDataTable(apartmentNumber, tenant);
}
public void AddEditTenant(int apartmentNumber, CRenter tenant)
{
TenantUpdates.Add(new CApartment(apartmentNumber, tenant));
worksheetChanged = UdateTenantDataTable(apartmentNumber, tenant);
}
public CRenter GetTenant(int apartmentNumber)
{
CRenter tenant = null;
try
{
DataTable lTenantRoster = GetLocalTenantRoster();
if (localTenantRoster != null)
{
string searchString = "UnitNo = '" + apartmentNumber.ToString() + "'";
DataRow[] aptTenantData = lTenantRoster.Select(searchString);
tenant = FillTenantFromDataRow(aptTenantData);
}
}
catch (Exception e)
{
MessageBox.Show("Exception in CExcelInteropMethods::GetTenant(): " + e.Message);
}
return tenant;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
return tenant;
}
private void ConstructComplexAndReport()
{
if (localTenantRoster == null)
{
return;
}
List<CBuildingAndApartment> buildingAndApartments;
Form_CurrentProgressStatus statusReport = new Form_CurrentProgressStatus();
statusReport.MessageText = "Constructing Apartment Complex Data.";
statusReport.Show();
buildingAndApartments = CreateBuildingAndApartmentsList();
complex = new CPropertyComplex("Anza Victoria Apartments, LLC", buildingAndApartments);
statusReport.Close();
}
private void GetExcelDataAndReportProgress()
{
Form_CurrentProgressStatus statusReport = new Form_CurrentProgressStatus();
statusReport.MessageText =
"Starting Excel and Loading Tenant Data From Excel.";
statusReport.Show();
StartExcelOpenWorkbook(false);
localTenantRoster = GetLocalTenantRoster();
statusReport.Close();
}
// Creates data for a single tenant that can be edited from
// the local data table.
private CRenter FillTenantFromDataRow(DataRow[] aptTenantData)
{
CRenter tenant = new CRenter(); | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
tenant.LastName = aptTenantData[0].Field<string>("Last");
tenant.FirstName = aptTenantData[0].Field<string>("First");
tenant.CoTenantLastName = aptTenantData[0].Field<string>("Add OCC Last");
tenant.HomePhone = aptTenantData[0].Field<string>("Ph #");
tenant.CoTenantFirstName = aptTenantData[0].Field<string>("Add OCC First");
tenant.RentersInsurancePolicy = aptTenantData[0].Field<string>("Renters Ins");
tenant.LeaseStart = aptTenantData[0].Field<string>("Lease Start");
tenant.LeaseEnd = aptTenantData[0].Field<string>("Lease End");
tenant.Email = aptTenantData[0].Field<string>("Email");
return tenant;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
return tenant;
}
// Updates the local version of the data in the application.
private bool UdateTenantDataTable(int apartmentNumber, CRenter tenant)
{
bool updated = false;
try
{
DataTable lTenantRoster = GetLocalTenantRoster();
string searchString = "UnitNo = '" + apartmentNumber.ToString() + "'";
DataRow[] aptTenantData = lTenantRoster.Select(searchString);
DataRow currentApartment = aptTenantData[0];
currentApartment.BeginEdit();
currentApartment["First"] = tenant.FirstName;
currentApartment["Last"] = tenant.LastName;
currentApartment["Add OCC Last"] = tenant.CoTenantLastName;
currentApartment["Add OCC First"] = tenant.CoTenantFirstName;
currentApartment["Ph #"] = tenant.HomePhone;
currentApartment["Renters Ins"] = tenant.RentersInsurancePolicy;
currentApartment["Lease Start"] = tenant.LeaseStart;
currentApartment["Lease End"] = tenant.LeaseEnd;
currentApartment["Email"] = tenant.Email;
currentApartment.EndEdit();
updated = true;
}
catch (Exception e)
{
MessageBox.Show("Exception in CExcelInteropMethods::updateDataTable(): " + e.Message);
}
return updated;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
return updated;
}
// Updates a row of data in the excel file
private void UpdateColumnData(CApartment rowEdit, List<string> columnNames)
{
CRenter tenant = rowEdit.renter;
Excel.Range currentRow = FindRowInWorkSheetForUpdate(rowEdit.ApartmentNumber);
UpdateColumn(currentRow, "Last", tenant.LastName, columnNames);
UpdateColumn(currentRow, "First", tenant.FirstName, columnNames);
UpdateColumn(currentRow, "Add OCC First", tenant.CoTenantFirstName, columnNames);
UpdateColumn(currentRow, "Add OCC Last", tenant.CoTenantLastName, columnNames);
UpdateColumn(currentRow, "Ph #", tenant.HomePhone, columnNames);
UpdateColumn(currentRow, "Renters Ins", tenant.RentersInsurancePolicy, columnNames);
UpdateColumn(currentRow, "Lease Start", tenant.LeaseStart, columnNames);
UpdateColumn(currentRow, "Lease End", tenant.LeaseEnd, columnNames);
UpdateColumn(currentRow, "Email", tenant.Email, columnNames);
}
private DataTable GetLocalTenantRoster()
{
DataTable tenantRosterDt = localTenantRoster;
if (tenantRosterDt == null)
{
int headerRow = 1;
int firstColumn = 1;
tenantRosterDt = ReadExcelIntoDatatble(headerRow, firstColumn);
}
return tenantRosterDt;
}
private void StartExcelOpenWorkbook(bool showErrorMessage)
{
if (xlApp != null && xlWorkbook != null)
{
return;
}
if (string.IsNullOrEmpty(WorkbookName))
{
if (showErrorMessage)
{
MessageBox.Show("Please update your preferences by adding the excel file that contains the tenant roster");
}
return;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
if (xlApp == null)
{
xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
}
if (xlWorkbook == null)
{
xlWorkbook = xlApp.Workbooks.Open(WorkbookName);
}
}
private void OpenTenantRosterWorkSheet()
{
try
{
if (!string.IsNullOrEmpty(tenantRosterName))
{
StartExcelOpenWorkbook(true);
List<string> sheetNames = GetSheetNames();
bool exists = sheetNames.Any(x => x.Contains(tenantRosterName));
if (!exists)
{
MessageBox.Show("The workbook " + WorkbookName + " does not contain the worksheet " + tenantRosterName);
tenantRoster = null;
}
else
{
tenantRoster = xlWorkbook.Worksheets[tenantRosterName];
}
}
}
catch (Exception e)
{
localTenantRoster = null;
string eMsg = "Function CExcelInteropMethods.openTenantRosterWorkSheet() failed: " + e.Message;
MessageBox.Show(eMsg);
}
}
// To enhance performance the excel worksheet is read once into a local
// DataTable.
private DataTable ReadExcelIntoDatatble(int HeaderLine, int ColumnStart)
{
try
{
StartExcelOpenWorkbook(true);
OpenTenantRosterWorkSheet();
if (tenantRoster == null)
{
return null;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
Excel.Range TenantDataRange = tenantRoster.UsedRange;
DataTable tenantTable = CreateDataTableAddColumns(TenantDataRange,
HeaderLine, ColumnStart);
AddTenantDataToTenantTable(TenantDataRange, ref tenantTable,
HeaderLine, ColumnStart);
// We don't need access to the data in excel while the edits
// are being made or the word documents are generated.
CloseWorkbookExitExcel();
return tenantTable;
}
catch (Exception ex)
{
string eMsg = "In ReadExcelToDatatble error: " + ex.Message;
MessageBox.Show(ex.Message);
return null;
}
}
private DataTable CreateDataTableAddColumns(Excel.Range TenantDataRange,
int headerLine, int firstColumn)
{
DataTable tenantTable = new DataTable();
int columnCount = TenantDataRange.Columns.Count;
for (int column = firstColumn; column <= columnCount; column++)
{
tenantTable.Columns.Add(Convert.ToString
(TenantDataRange.Cells[headerLine, column].Value2), typeof(string));
}
return tenantTable;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
return tenantTable;
}
private void AddTenantDataToTenantTable(Excel.Range TenantDataRange,
ref DataTable tenantTable, int headerLine, int firstColumn)
{
int columnCount = TenantDataRange.Columns.Count;
int rowcount = TenantDataRange.Rows.Count;
// This loop needs to be optimized, it takes almost 8 seconds
for (int row = headerLine + 1; row <= rowcount; row++)
{
DataRow tenantData = tenantTable.NewRow();
for (int column = firstColumn; column <= columnCount; column++)
{
tenantData[column - firstColumn] =
Convert.ToString(TenantDataRange.Cells[row, column].Value2);
}
tenantTable.Rows.Add(tenantData);
}
}
private void SaveWorkBookEdits()
{
if (!HaveEditsToSave)
{
return;
}
string eSaveMsg = "Can't save edits to " + WorkbookName;
try
{
Form_CurrentProgressStatus SaveStatus = new Form_CurrentProgressStatus();
SaveStatus.MessageText = "Saving updated tenants and apartments to Excel.";
SaveStatus.Show();
StartExcelOpenWorkbook(false);
OpenTenantRosterWorkSheet();
xlApp.Visible = false;
xlApp.DisplayAlerts = false; | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
if (tenantRoster == null)
{
MessageBox.Show(eSaveMsg + " can't open the sheet " + tenantRosterName);
return;
}
List<string> columnNames = GetColumnNames();
foreach (CApartment edit in TenantUpdates)
{
UpdateColumnData(edit, columnNames);
}
xlWorkbook.Save();
SaveStatus.Close();
TenantUpdates.Clear();
}
catch (Exception ex)
{
string exSaveMsg = eSaveMsg + " : " + ex.Message;
MessageBox.Show(eSaveMsg);
}
}
private Excel.Range FindRowInWorkSheetForUpdate(int apartmentNumber)
{
Excel.Range currentRow = null;
object oMissing = Missing.Value;
try
{
Excel.Range UnitNoColumn = GetUnitColumn();
if (UnitNoColumn != null)
{
currentRow = UnitNoColumn.Find(apartmentNumber.ToString(), oMissing,
Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
oMissing, oMissing);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in CExcelInteropMethods::getRowNumberForSave(): " +
ex.Message);
}
return currentRow;
}
void UpdateColumn(Excel.Range currentRow, string columnName, string newValue,
List<string> columnNames)
{
int columnNumber = GetColumnNumber(columnName, columnNames);
currentRow.Cells[1, columnNumber] = newValue;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
// Get the apartment unit column for searching.
private Excel.Range GetUnitColumn()
{
Excel.Range UnitColumn = null;
try
{
string headerName = "UnitNo";
Excel.Range headerRow = tenantRoster.UsedRange.Rows[1];
foreach (Excel.Range cel in headerRow.Cells)
{
if (cel.Text.ToString().Equals(headerName))
{
UnitColumn = tenantRoster.Range[cel.Address, cel.End[Excel.XlDirection.xlDown]];
return UnitColumn;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in CExcelInteropMethods::GetUnitColumn(): " +
ex.Message);
}
return UnitColumn;
}
private int GetColumnNumber(string columnName, List<string> columnNames)
{
int columnNumber = 1;
foreach (string name in columnNames)
{
if (name.Equals(columnName))
{
return columnNumber;
}
columnNumber++;
}
return columnNumber;
}
private List<string> GetColumnNames()
{
List<string> columnNames = new List<string>();
try
{
Excel.Range headerRow = tenantRoster.UsedRange.Rows[1];
foreach (Excel.Range cell in headerRow.Cells)
{
columnNames.Add(cell.Text);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in CExcelInteropMethods::GetColumnNames(): " +
ex.Message);
}
return columnNames;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
return columnNames;
}
private List<CBuildingAndApartment> CreateBuildingAndApartmentsList()
{
if (localTenantRoster == null)
{
return null;
}
List<CBuildingAndApartment> buildingAndApartments = new List<CBuildingAndApartment>();
int LastDataRow = localTenantRoster.Rows.Count;
for (int row = 0; row < LastDataRow; row++)
{
buildingAndApartments.Add(CreateBuildAndApartmentFromDataRow(row));
}
return buildingAndApartments;
}
private CBuildingAndApartment CreateBuildAndApartmentFromDataRow(int row)
{
DataRow dataRow = localTenantRoster.Rows[row];
string streetAddress = dataRow.Field<string>("Street 1").ToString();
string apartmentNumString = dataRow.Field<string>("UnitNo").ToString();
int apartmentNumber;
Int32.TryParse(apartmentNumString, out apartmentNumber);
int firstSpace = streetAddress.IndexOf(' ');
string streetNumber = streetAddress.Substring(0, firstSpace);
int buildingNumber;
Int32.TryParse(streetNumber, out buildingNumber);
CBuildingAndApartment currentApt = new CBuildingAndApartment(buildingNumber,
apartmentNumber, streetAddress);
return currentApt;
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
// Check if there is any instance of excel open using the workbook.
private bool WorkSheetIsOpenInOtherApp(string workBook)
{
Excel.Application TestOnly = null;
bool isOpened = true;
// There are 2 possible exceptions here, GetActiveObject will throw
// an exception if no instance of excel is running, and
// workbooks.get_Item throws an exception if the sheetname isn't found.
// Both of these exceptions indicate that the workbook isn't open.
try
{
TestOnly = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
int lastSlash = WorkbookName.LastIndexOf('\\');
string fileNameOnly = WorkbookName.Substring((lastSlash + 1));
TestOnly.Workbooks.get_Item(fileNameOnly);
TestOnly = null;
}
catch (Exception)
{
isOpened = false;
if (TestOnly != null)
{
TestOnly = null;
}
}
return isOpened;
}
}
}
CPropertyComplex.cs
using System;
using System.Collections.Generic;
using System.Windows;
namespace RentRosterAutomation
{
// Contains all the information about the apartment complex (5 buildings)
class CPropertyComplex
{
private string propertyName;
private List<int> allApartmentNumbers;
private List<CBuilding> buildingList = new List<CBuilding>(); | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
public string PropertyName { get { return propertyName; } }
public List<CBuilding> Buildings { get; private set; }
public List<string> BuildingAddressList { get; private set; }
public List<int> StreetNumbers { get; private set; }
public List<int> AllApartmentNumbers { get { return allApartmentNumbers; } }
public int MinApartmentNumber { get; private set; }
public int MaxApartmentNumber { get; private set; }
public CPropertyComplex(string PropertyName, List<CBuildingAndApartment> bldsAntApts)
{
propertyName = PropertyName;
BuildingAddressList = new List<string>();
allApartmentNumbers = new List<int>();
StreetNumbers = new List<int>();
CreateBuildingList(bldsAntApts);
foreach (CBuilding building in Buildings)
{
BuildingAddressList.Add(building.FullStreetAddress);
allApartmentNumbers.AddRange(building.ApartmentNumbers);
}
allApartmentNumbers.Sort();
MinApartmentNumber = allApartmentNumbers[0];
MaxApartmentNumber = allApartmentNumbers[allApartmentNumbers.Count - 1];
}
public CBuilding GetBuilding(int streetNumber)
{
CBuilding building;
building = buildingList.Find(x => x.AddressStreetNumber == streetNumber);
return building;
}
public CBuilding GetBuilding(string streetNumber)
{
int iStreetNumber = 0; | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
try
{
if (Int32.TryParse(streetNumber, out iStreetNumber))
{
return GetBuilding(iStreetNumber);
}
else
{
MessageBox.Show("Non Numeric string passed into CBuilding::GetBuilding().");
return null;
}
}
catch (Exception)
{
return null;
}
}
public string FindBuildingByApartment(int apartmentNumber)
{
string buildingAddress = null;
foreach (CBuilding building in Buildings)
{
buildingAddress = building.BuildingFromApartment(apartmentNumber);
if (!string.IsNullOrEmpty(buildingAddress))
{
return buildingAddress;
}
}
return buildingAddress;
}
private void CreateBuildingList(List<CBuildingAndApartment> buildingAptList)
{
buildingList = new List<CBuilding>();
string streetName = "Anza Avenue";
foreach (CBuildingAndApartment entry in buildingAptList)
{
CBuilding found = buildingList.Find(x => x.AddressStreetNumber == entry.building);
if (found != null)
{
found.AddApartmentNumber(entry.apartment);
}
else
{
CBuilding newBuilding = new CBuilding(entry.building, streetName);
newBuilding.AddApartmentNumber(entry.apartment);
buildingList.Add(newBuilding);
}
}
foreach (CBuilding building in buildingList)
{
building.SortApartMentNumbers();
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
foreach (CBuilding building in buildingList)
{
StreetNumbers.Add(building.AddressStreetNumber);
}
Buildings = buildingList;
}
}
}
CRenter.cs
namespace RentRosterAutomation
{
public class CRenter
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string CoTenantLastName { get; set; }
public string CoTenantFirstName { get; set; }
public string Email { get; set; }
public string HomePhone { get; set; }
public string RentersInsurancePolicy { get; set; }
public string LeaseStart { get; set; }
public string LeaseEnd { get; set; }
public CRenter()
{
FirstName = "";
LastName = "";
CoTenantLastName = "";
CoTenantFirstName = "";
Email = "";
HomePhone = "";
RentersInsurancePolicy = "";
LeaseStart = "";
}
public CRenter(string lastName, string homePhone)
{
LastName = lastName;
HomePhone = homePhone;
FirstName = "";
CoTenantLastName = "";
CoTenantFirstName = "";
Email = "";
RentersInsurancePolicy = "";
LeaseStart = "";
}
public string MailboxListOccupantEntry()
{
string fullTenantNameString = LastName;
if (!string.IsNullOrEmpty(CoTenantLastName))
{
fullTenantNameString = fullTenantNameString + " // " + CoTenantLastName;
}
return fullTenantNameString;
}
public string mergedName()
{
return (!string.IsNullOrEmpty(FirstName)) ? FirstName + " " + LastName : LastName;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
}
}
CApartment.cs
namespace RentRosterAutomation
{
class CApartment
{
private CExcelInteropMethods excelInteropMethods = Program.excelInteropMethods;
public int ApartmentNumber { get; private set; }
public CRenter renter { get; private set; }
public CApartment(int apartmentNumber)
{
ApartmentNumber = apartmentNumber;
renter = excelInteropMethods.GetTenant(apartmentNumber);
}
public CApartment(int apartmentNumber, CRenter Renter)
{
ApartmentNumber = apartmentNumber;
renter = Renter;
}
}
}
CMailboxListData.cs
using System.Collections.Generic;
namespace RentRosterAutomation
{
// This class contains the data necessary to print a mailbox tenant list,
// Each building in the complex contains 3 floors of apartments. The documnets
// generated by Microsoft Word have 3 columns of data, one for each floor.
class CMailboxListData
{
public int AddressStreetNumber { get; private set; }
public List<CApartment> FirstFloor { get; private set; }
public List<CApartment> SecondFloor { get; private set; }
public List<CApartment> ThirdFloor { get; private set; }
public CMailboxListData(int addressStreetNumber)
{
AddressStreetNumber = addressStreetNumber;
}
public CMailboxListData(CBuilding building)
{
AddressStreetNumber = building.AddressStreetNumber;
FirstFloor = new List<CApartment>();
SecondFloor = new List<CApartment>();
ThirdFloor = new List<CApartment>();
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
public void addApartmentData(CApartment apartment)
{
if (apartment.ApartmentNumber >= 200 && apartment.ApartmentNumber < 300)
{
SecondFloor.Add(apartment);
}
else if (apartment.ApartmentNumber >= 300)
{
ThirdFloor.Add(apartment);
}
else
{
FirstFloor.Add(apartment);
}
}
}
}
CBuildingAndApartment.cs
namespace RentRosterAutomation
{
// One of these is contructed for each apartment in the complex (5 buildings, 177 apartments).
// The list is used during the construction of the apartment complex object
class CBuildingAndApartment
{
public int building;
public int apartment;
public string fullStreetAddress;
public CBuildingAndApartment(int streetNumber, int Apartment, string FullStreetAddress)
{
building = streetNumber;
apartment = Apartment;
fullStreetAddress = FullStreetAddress;
}
}
}
CBuilding.cs
using System.Collections.Generic;
namespace RentRosterAutomation
{
// Represents one building in the apartment Complex
class CBuilding
{
private List<int> aptNumbers;
public int AddressStreetNumber { get; private set; }
public string FullStreetAddress { get; private set; }
public List<int> ApartmentNumbers { get { return aptNumbers; } }
public CBuilding(int addressStreetNumber, string StreetName, List<int> apartmentNumbers)
{
AddressStreetNumber = addressStreetNumber;
FullStreetAddress = addressStreetNumber.ToString() + " " + StreetName;
aptNumbers = apartmentNumbers;
aptNumbers.Sort();
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
public CBuilding(int addressStreetNumber, string StreetName)
{
AddressStreetNumber = addressStreetNumber;
FullStreetAddress = addressStreetNumber.ToString() + " " + StreetName;
aptNumbers = new List<int>();
}
public void AddApartmentNumber(int apartmentNumber)
{
if (!aptNumbers.Contains(apartmentNumber))
{
aptNumbers.Add(apartmentNumber);
}
}
public void SortApartMentNumbers()
{
aptNumbers.Sort();
}
public bool IsApartmentInThisBuildin(int apartmentNumber)
{
return aptNumbers.Contains(apartmentNumber);
}
public string BuildingFromApartment(int apartmentNumber)
{
return (IsApartmentInThisBuildin(apartmentNumber)) ? FullStreetAddress : null;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
Input Data
UnitNo,Unit Type,First,Last,Add OCC First,Add OCC Last,# of people,Ph #,Email,Parking,Renters Ins,Original Rent,Old Rent,Increase,Inc. Date,New,Lease Start,Lease End,Street 1,City,State,Zip,Refridgerator
101,,FName1,LastName1,,,,(XXX)XXX-XXXX,(YYY)XYZ-ZZZZ FNLastName1@AnyOrg.org,,AAA 10/20/2016,,,,,,10/20/2016,12/31/2024,20809 Anza Ave.,HomeTown,XX,xxxxx,
102,,FName2,LastName2,,,,(XXX)XXX-XXXX,FLastName2@hotmail.com,,AAA 12/25/2017,,,,,,2/3/1981,,20809 Anza Ave.,HomeTown,XX,xxxxx,
103,,FName3,LastName3,,,,(XXX)XXX-XXXX,(ABC)XYZ-DEFG,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
104,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
105,,FName5,LastName5,,,,(XXX)XXX-XXXX,GobbleGoop@ANYMAIL.ORG,,12/31/2017,,,,,,12/30/2017,,20809 Anza Ave.,HomeTown,XX,xxxxx,
106,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
107,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
108,,FName8,LastName8,XXXX,XX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
109,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
110,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
111,,FName11,LastName11,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
112,,FName12,LastName12,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
113,,FName13,LastName13,XXXX,LastName,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
114,,FName14,LastName14,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
115,,FName15,LastName15,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
116,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
117,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
118,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
118,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
119,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
120,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
121,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
122,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
123,,FName3,LastName3,XXXX,LastName16,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
124,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
125,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
126,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
127,,LongFirstName,LongLastName,,,,(XXX)XXX-XXXX,,,SF 6/10/2019,,,,,,6/11/2019,12/31/2023,20829 Anza Ave.,HomeTown,XX,xxxxx,
128,,AnEvenLongerFirstName,AnEvenLongerLastName,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
129,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
130,,FName0,LastName0,XXXX,Tenant2Name,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
131,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
132,,FName2,LongLastName2Added,XXXX,Tenant2LongNameAdded,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
133,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
134,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
135,,FName5,LastName5,XXXX,XX,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
136,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
140,,,,,,,,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
141,,FName1,LastName1,XXXX,XXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
142,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
142,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
143,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
144,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
145,,FName5,LastName5,XXXX,XXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
146,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
147,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
148,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
149,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
150,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
151,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
152,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
153,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
154,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
155,,FName5,LastName5,XXXX,XXXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
156,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
157,,FName7,LastName7,XXXX,XXX,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
158,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
159,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
160,,FName0,LastName0,XXXX,XXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
161,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
162,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
163,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
164,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
164,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
165,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
166,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
167,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
168,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
169,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
170,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
171,,FName1,LastName1,XXXX,XXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
172,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
201,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
202,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
203,,FName3,LastName3,,,,(XXX)XXX-XXXX,aagarwal@hotmail.com,,ALLS 8/23/2015,,,,,,8/23/2015,,20809 Anza Ave.,HomeTown,XX,xxxxx,
204,,FName4,LastName4,XXXX,XXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
205,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
206,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
207,,FName7,LastName7,XXXX,XXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
208,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
209,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
210,,FName0,LastName0,XXXX,XXXXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
211,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
212,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
213,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
214,,,,,,,,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
214,,,,,,,,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
215,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
216,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
217,,FName7,LastName7,XXXX,CCDDFFGG,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
218,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
219,,,,,,,,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
220,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
221,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
222,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
223,,FName3,LastName3,XXXX,ABCDEFG,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
224,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
225,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
226,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
227,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
228,,FName8,LastName8,XXXX,XXX,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
229,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
230,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
231,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
232,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
233,,,,,,,,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
234,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
235,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
236,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
241,,,,,,,,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
241,,,,,,,,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
242,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
243,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
244,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
245,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
246,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
247,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
248,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
249,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
250,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
251,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
252,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
253,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
254,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
255,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
256,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
257,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
258,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
259,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
260,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
261,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
262,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
263,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
264,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
264,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
265,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
266,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
267,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
268,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
269,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
270,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
271,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
272,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
302,,FName2,LastName2,XXXX,XXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
303,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
304,,FName4,LastName4,XXXX,XXXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
305,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
308,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
309,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
310,,FName0,LastName0,XXXX,XXXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
311,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20809 Anza Ave.,HomeTown,XX,xxxxx,
322,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
323,,FName3,LastName3,XXXX,XXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
324,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
325,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
328,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
329,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
329,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
330,,FName0,LastName0,XXXX,XXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
331,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20829 Anza Ave.,HomeTown,XX,xxxxx,
338,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
339,,FName9,LastName9,XXXX,XXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
340,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
341,,,,,,,,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
344,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
345,,FName5,LastName5,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
346,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
347,,FName7,LastName7,,,,(XXX)XXX-XXXX,,,,,,,,,,,20909 Anza Ave.,HomeTown,XX,xxxxx,
350,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
351,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
352,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
353,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
356,,FName6,LastName6,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
357,,FName7,LastName7,XXXX,XXX,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
358,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
359,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20929 Anza Ave.,HomeTown,XX,xxxxx,
362,,FName2,LastName2,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
363,,FName3,LastName3,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
364,,FName4,LastName4,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
365,,FName5,LastName5,XXXX,XXXXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
365,,FName5,LastName5,XXXX,XXXXXXXX,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
368,,FName8,LastName8,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
369,,FName9,LastName9,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
370,,FName0,LastName0,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx,
371,,FName1,LastName1,,,,(XXX)XXX-XXXX,,,,,,,,,,,20939 Anza Ave.,HomeTown,XX,xxxxx, | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
Answer: I managed to speed up reading the tenant data by making a single interop call to get all the data from the range and then iterating through that
private void AddTenantDataToTenantTable(Range TenantDataRange,
ref System.Data.DataTable tenantTable, int headerLine, int firstColumn)
{
int columnCount = TenantDataRange.Columns.Count;
int rowcount = TenantDataRange.Rows.Count;
var values = TenantDataRange.Value2;
// This loop needs to be optimized, it takes almost 8 seconds
for (int row = headerLine + 1; row <= rowcount; row++)
{
DataRow tenantData = tenantTable.NewRow();
for (int column = firstColumn; column <= columnCount; column++)
{
tenantData[column - firstColumn] =
//Convert.ToString(TenantDataRange.Cells[row, column].Value2);
Convert.ToString(values[row, column]);
}
tenantTable.Rows.Add(tenantData);
}
}
individual calls to Range.Cells[] are slow and making a separate call for each cell in the rows*cols block was the problem.
You can probably do the same for CreateDataTableAddColumns() although it is probably not a big performance hit at the moment.
Other Areas
Error Handling
An error which occurs when reading the tenant data can cause an orphaned instance of Excel
private System.Data.DataTable ReadExcelIntoDatatble(int HeaderLine, int ColumnStart)
{
try
{
StartExcelOpenWorkbook(true);
OpenTenantRosterWorkSheet();
if (tenantRoster == null)
{
return null;
}
Range TenantDataRange = tenantRoster.UsedRange;
System.Data.DataTable tenantTable = CreateDataTableAddColumns(TenantDataRange,
HeaderLine, ColumnStart);
AddTenantDataToTenantTable(TenantDataRange, ref tenantTable,
HeaderLine, ColumnStart); | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
// We don't need access to the data in excel while the edits
// are being made or the word documents are generated.
CloseWorkbookExitExcel();
return tenantTable;
}
catch (Exception ex)
{
string eMsg = "In ReadExcelToDatatble error: " + ex.Message;
MessageBox.Show(ex.Message);
return null;
}
}
Say we have an error in AddTenantDataToTenantTable(), then we drop down to the exception handler skipping past the CloseWorkbookExitExcel() call which leaves the excel instance running in background. This call should be in a finally block so that it is called whether we have an exception or not.
Coupling
There is an amount of coupling between parts of the system which do not need to know about each other.
The MessageBox() calls limit the places where CExcelInteropMethods and CPropertyComplex can be used. I would push for propagating the exceptions upwards to a higher level and reporting them there or, injecting an interface for reporting the exceptions which can have an implementation which calls MessageBox. With the current code, Automated Unit Testing error conditions for CExcelInteropMethods is a problem.
A CExcelInteropMethods instance in CApartment is iffy at the best of times but a hardcoded reference to an instance in Program heavily impacts reusability and maintenance.
Chained Constructors
public CBuilding(int addressStreetNumber, string StreetName, List<int> apartmentNumbers)
{
AddressStreetNumber = addressStreetNumber;
FullStreetAddress = addressStreetNumber.ToString() + " " + StreetName;
aptNumbers = apartmentNumbers;
aptNumbers.Sort();
}
public CBuilding(int addressStreetNumber, string StreetName)
{
AddressStreetNumber = addressStreetNumber;
FullStreetAddress = addressStreetNumber.ToString() + " " + StreetName;
aptNumbers = new List<int>();
} | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
c#, performance, excel, cyclomatic-complexity
If we change the format for the FullStreetAddress, then it needs to be changed in two places - Maintainability issue. We should chain the constructors
public CBuilding(int addressStreetNumber, string StreetName)
: this(addressStreetNumber, StreetName, new List<int>())
{
}
public CBuilding(int addressStreetNumber, string StreetName, List<int> apartmentNumbers)
{
AddressStreetNumber = addressStreetNumber;
FullStreetAddress = addressStreetNumber.ToString() + " " + StreetName;
aptNumbers = apartmentNumbers;
aptNumbers.Sort();
}
or, perhaps, use a default parameter
public CBuilding(int addressStreetNumber, string StreetName, List<int> apartmentNumbers = null)
{
AddressStreetNumber = addressStreetNumber;
FullStreetAddress = addressStreetNumber.ToString() + " " + StreetName;
aptNumbers = apartmentNumbers ?? new List<int>();
aptNumbers.Sort();
}
either way, we cut down the number of places where updates need to be made.
Naming
The recommendation for class naming in C# is to not use a C prefix.
The recommendation for parameters names is to use camelCasing. | {
"domain": "codereview.stackexchange",
"id": 42709,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, excel, cyclomatic-complexity",
"url": null
} |
angular-2+, electron
Title: Should I use standalone service for angular custom APP_INITIALIZER
Question: I'm working on a Angular Electron application where we display loading screen while the application is starting up. This means we have to do couple of BE requests and only remove the loader when we receive desired answers. We only read data in those calls, there are no write calls there.
Everything works but the INITIALIZER keeps growing in complexity and gains more and more deps with every request from Product Owner. This it's current state:
// app-init.ts
export function initApp(
healthService: HealthService, // Spring health - retryWithBackOff to handle BE not running
sseService: SseService, // Opens SSE channel
clientService: ClientService, // Project specific
resultService: ResultsService, // Project specific
loggerService: LoggerService, // self explanatory
messageService: MessageService // helps to propagate status messages to loader screen
): () => Promise<any> {
// ...
}
// app.module.ts
{
provide: APP_INITIALIZER,
useFactory: initApp,
multi: true,
deps: [HealthService, SseService, ClientService, ResultsService, LoggerService, MessageService],
},
My questions is, wouldn't it be better to create one use only service, to execute initial requests within the APP_INITIALIZER? I know this goes against the DRY principle but I see a benefit here. Plus all our services and models are generated from API, we just run an npm command to update them. This should keep the good pretty stable.
It would look like this:
// app-init.ts
export function initApp(
initService: InitService, // Would group Health + Project specific services
sseService: SseService, // Opens SSE channel
loggerService: LoggerService, // self explanatory
messageService: MessageService // helps to propagate status messages to loader screen
): () => Promise<any> {
// ...
} | {
"domain": "codereview.stackexchange",
"id": 42710,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "angular-2+, electron",
"url": null
} |
angular-2+, electron
// app.module.ts
{
provide: APP_INITIALIZER,
useFactory: initApp,
multi: true,
deps: [InitService, SseService, LoggerService, MessageService],
},
If the need for a new Project Specific service call would arise, we would just add it to InitService. This would prevent INITIALIZER deps from growing although it would introduce duplicity of some calls.
Is it a good idea? Or is there a better way I'm not aware of? | {
"domain": "codereview.stackexchange",
"id": 42710,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "angular-2+, electron",
"url": null
} |
angular-2+, electron
Answer: My personal point of view:
All "Best Practices" like "Do not repeat yourself" (DRY), "Single Responsibility Principle" (SRP), "You aint gonna need it" (YAGNI) and all the others are quite important and should always be considered. But not always applied. :-)
Especially because some of them contradict each other in certain cases.
My approach based on my coding goals:
Humans loves to seperate information into chunks.
Humans can normally catch between 5 and 10 chunks in one glance (7 is a good value).
(by the way, thats the reason why long numbers, like the IBAN or the ISBN are splitted like "DE44 1234 5678 9123 45" because its much easier to work with than with "DE4412345678912345")
Because of that reason i try to have not to many code chunks together.
If i have less then 7 services which i need at the initialisation, it would be kind of okay for me to call them directly.
If it gets more i would start to group.
Beside that, from a pure reading perspective, do i need the information that the all those services are needed at startup? Does it give me any additional value, if i am not specificley interested in the startup behavior?
I think not.
Therefore it would be totally fine for me to create one "InitApplicationService" which then orchestrates a bunch of specific services.
Because as a reader, then i see "ahhh there is some stuff that is done at initialisation" but if i am not really interested in that, my eyes can directly move on to the relevant stuff.
If i am interested, i do the additional click and look inside that service.
The same logic i apply to other places. Like if statements.
if(cage size = L && cage.stability > 50 && cage.contains(water) && cage.contains(food)){ ... }
against
if( isCageForLions(cage) ) { ... } | {
"domain": "codereview.stackexchange",
"id": 42710,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "angular-2+, electron",
"url": null
} |
angular-2+, electron
against
if( isCageForLions(cage) ) { ... }
Easier to read and if really want to know what is relevant for a lion cage, then i look into the method.
Long story short, i produce boilerplate code, which does not have any functional value. But it makes the code easier to read and easier to understand. Which is an important value by itself in my eyes.
Also in my experience, when i group things, i have to think hard for a good group name. And quite often that gives me a few more insight into the grouped elements as well. | {
"domain": "codereview.stackexchange",
"id": 42710,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "angular-2+, electron",
"url": null
} |
rust
Title: Rust calculator
Question: To learn some rust I decided to write a simple calculator. This calculator can take a string in the form of 1+2*3/4-5, and calculate the result. It does so while keeping the order of operations in mind (*/ before +-).
I came up with the following:
/// Token containing either a number or an operation. Never both.
#[derive(Debug, PartialEq)]
enum Token {
NUMBER(i64),
/// Operation being one of +/*-
OPERATION(char),
}
impl Token {
pub fn from_string(string: &str) -> Result<Self, &str> {
let number = string.parse::<i64>().ok();
if number.is_some() {
Ok(Token::NUMBER(number.unwrap()))
} else {
match string.chars().nth(0) {
Some(c) => Ok(Token::OPERATION(c)),
None => Err("Can't parse token from empty string."),
}
}
}
}
/// Tokenizes the given string. Splits numbers from non-numbers. Returns a vector of tokens.
fn tokenize(sum: &str) -> Vec<Token> {
let mut parts: Vec<String> = Vec::new();
let mut prev_is_number = false;
for c in sum.chars() {
if c.is_numeric() != prev_is_number {
prev_is_number = c.is_numeric();
parts.push(String::new());
}
parts.last_mut().unwrap().push(c);
}
let mut tokens: Vec<Token> = Vec::new();
for token in parts {
tokens.push(Token::from_string(&token).expect(&format!("Failed to parse {}", token)));
}
prev_is_number = false;
for token in &tokens {
let is_number = match token {
Token::NUMBER(..) => true,
_ => false
};
assert_ne!(prev_is_number,
is_number
); // Assert numbers always followed by tokens and otherwise.
prev_is_number = is_number;
}
return tokens;
} | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
return tokens;
}
/// Solves the multiplications and divisions in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place.
/// e.g. 1+2*3 returns 1+6.
fn solve_multiply_divide(tokens: &Vec<Token>) -> Vec<Token> {
let mut prev_number: Option<i64> = None;
let mut prev_operation: Option<char> = None;
let mut result: Vec<Token> = Vec::new();
for token in tokens {
match token {
Token::NUMBER(number) => {
match prev_number {
None => {
prev_number = Some(*number);
},
Some(unwrapped_prev_number) => {
match prev_operation {
Some('*') => {
prev_number = Some(unwrapped_prev_number * number);
},
Some('/') => {
prev_number = Some(unwrapped_prev_number / number);
},
_ => {panic!("Found two numbers after each other without operator in between. Incorrect token sequence supplied.")}
}
prev_operation = None;
}
}
}
Token::OPERATION(operation) => {
if *operation == '*' || *operation == '/' {
prev_operation = Some(*operation);
} else {
if prev_number.is_some() {
result.push(Token::NUMBER(prev_number.unwrap()));
}
result.push(Token::OPERATION(*operation));
prev_number = None;
prev_operation = None;
}
}
}
}
if prev_number.is_some() {
result.push(Token::NUMBER(prev_number.unwrap()));
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
return result;
}
/// Solves the plus and minus in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place.
/// e.g. 1+2*3 returns 3*3
fn solve_plus_minus(tokens: &Vec<Token>) -> Vec<Token> {
let mut prev_number: Option<i64> = None;
let mut prev_operation: Option<char> = None;
let mut result: Vec<Token> = Vec::new();
for token in tokens {
match token {
Token::NUMBER(number) => {
match prev_number {
None => {
prev_number = Some(*number);
},
Some(unwrapped_prev_number) => {
match prev_operation {
Some('+') => {
prev_number = Some(unwrapped_prev_number + number);
},
Some('-') => {
prev_number = Some(unwrapped_prev_number - number);
},
_ => {panic!("Found two numbers after each other without operator in between. Incorrect token sequence supplied.")}
}
prev_operation = None;
}
}
}
Token::OPERATION(operation) => {
if *operation == '+' || *operation == '-' {
prev_operation = Some(*operation);
} else {
if prev_number.is_some() {
result.push(Token::NUMBER(prev_number.unwrap()));
}
result.push(Token::OPERATION(*operation));
prev_number = None;
prev_operation = None;
}
}
}
}
if prev_number.is_some() {
result.push(Token::NUMBER(prev_number.unwrap()));
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
return result;
}
/// Solves a given equation.
pub fn solve(sum: &str) -> Result<i64, &str> {
let tokens = tokenize(sum);
let tokens_multiplied_divided = solve_multiply_divide(&tokens);
let tokens_plus_minus = solve_plus_minus(&tokens_multiplied_divided);
assert_eq!(tokens_plus_minus.len(), 1);
match tokens_plus_minus.first().unwrap() {
Token::NUMBER(result) => Ok(*result),
_ => Err("Could not solve. Invalid equation?")
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Returns the vector of tokens for 1+2*3/4-5
fn get_test_tokens() -> Vec<Token> {
return vec![
Token::NUMBER(1),
Token::OPERATION('+'),
Token::NUMBER(2),
Token::OPERATION('*'),
Token::NUMBER(3),
Token::OPERATION('/'),
Token::NUMBER(4),
Token::OPERATION('-'),
Token::NUMBER(5),
];
}
#[test]
fn test_tokenize() {
assert_eq!(tokenize("1+2*3/4-5"), get_test_tokens());
}
#[test]
fn test_multiply_divide() {
assert_eq!(
solve_multiply_divide(&get_test_tokens()),
[
Token::NUMBER(1),
Token::OPERATION('+'),
Token::NUMBER(2 * 3 / 4),
Token::OPERATION('-'),
Token::NUMBER(5),
]
)
}
#[test]
fn test_solve() {
match solve("1+2*3/4-5") {
Ok(-3) => assert!(true),
Ok(number) => assert!(false, "wrong answer: {}", number),
Err(error) => assert!(false, "got an error: {}", error)
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
One problem that I do have with this code is the overlap between solve_multiply_divide and solve_plus_minus, I feel like these could be merged somehow but I haven't figured out how yet.
I'm coming from a C++ background, which could shine through in this code. How could I improve my code and make it adhere more to a rust way of thinking, instead of c++?
Answer:
One problem that I do have with this code is the overlap between
solve_multiply_divide and solve_plus_minus, I feel like these could be
merged somehow but I haven't figured out how yet.
This can be done by introducing a more general function solve_bin_ops. You will then run into some limitations of match which you can solve by using if instead. Like this:
/// Solves the multiplications and divisions in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place.
/// e.g. 1+2*3 returns 1+6.
fn solve_multiply_divide(tokens: &Vec<Token>) -> Vec<Token> {
solve_bin_ops(tokens, ('*', i64::wrapping_mul), ('/', i64::wrapping_div))
}
/// Solves the plus and minus in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place.
/// e.g. 1+2*3 returns 3*3
fn solve_plus_minus(tokens: &Vec<Token>) -> Vec<Token> {
solve_bin_ops(tokens, ('+', i64::wrapping_add), ('-', i64::wrapping_sub))
}
fn solve_bin_ops(
tokens: &Vec<Token>,
op1: (char, fn(i64, i64) -> i64),
op2: (char, fn(i64, i64) -> i64),
) -> Vec<Token> {
let mut prev_number: Option<i64> = None;
let mut prev_operation: Option<char> = None;
let mut result: Vec<Token> = Vec::new(); | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
let mut result: Vec<Token> = Vec::new();
for token in tokens {
match token {
Token::NUMBER(number) => match prev_number {
None => {
prev_number = Some(*number);
}
Some(unwrapped_prev_number) => {
if prev_operation == Some(op1.0) {
prev_number = Some(op1.1(unwrapped_prev_number, *number));
} else if prev_operation == Some(op2.0) {
prev_number = Some(op2.1(unwrapped_prev_number, *number));
} else {
panic!("Found two numbers after each other without operator in between. Incorrect token sequence supplied.")
}
prev_operation = None;
}
},
Token::OPERATION(operation) => {
if *operation == op1.0 || *operation == op2.0 {
prev_operation = Some(*operation);
} else {
if prev_number.is_some() {
result.push(Token::NUMBER(prev_number.unwrap()));
}
result.push(Token::OPERATION(*operation));
prev_number = None;
prev_operation = None;
}
}
}
}
if prev_number.is_some() {
result.push(Token::NUMBER(prev_number.unwrap()));
}
result
} | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
result
}
I've slightly changed the binary operators here, by specifying what should happen in the case of overflow. To recover the behavior of your original code, which will panic on overflow in debug mode (since you haven't specified what you want to happen in that case), but wrap in release mode, do this:
/// Solves the multiplications and divisions in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place.
/// e.g. 1+2*3 returns 1+6.
fn solve_multiply_divide(tokens: &Vec<Token>) -> Vec<Token> {
solve_bin_ops(tokens, ('*', <i64 as std::ops::Mul>::mul), ('/', <i64 as std::ops::Div>::div))
}
/// Solves the plus and minus in the given token vector. Returns a vector of tokens that were not solved, with the solved parts in-place.
/// e.g. 1+2*3 returns 3*3
fn solve_plus_minus(tokens: &Vec<Token>) -> Vec<Token> {
solve_bin_ops(tokens, ('+', <i64 as std::ops::Add>::add), ('-', <i64 as std::ops::Sub>::sub))
}
Introducing explicit grouping (using parentheses is customary) into the language you accept (for example (3+4)*2) will probably change your design quite a bit... | {
"domain": "codereview.stackexchange",
"id": 42711,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
vb.net, windows, installer, powerpoint
Title: Reliably setting keys in Windows Registry for a VBA addin
Question: We have a PowerPoint VBA addin which is installed using an MSI installer written with WIX (Windows Installer XML).
For the addin to be picked up (for all users) by PowerPoint, name-value pairs need to be added to this registry key in HKLM: SOFTWARE\Microsoft\Office\[POWERPOINT_VERSION_NUMBER]\PowerPoint\AddIns\OurAddinName, where [POWERPOINT_VERSION_NUMBER] has the form 14.0, 16.0 etc. The addin works with PowerPoint 2007 and greater (i.e. >=12.0).
To get the right version number, the installer had been looking here: PowerPoint.Application\CurVer in HKCR. This gives a value like PowerPoint.Application.16. However (as of January 2022), the value of CurVer does not seem to be reliable. One of my machines has it as PowerPoint.Application.11 and on another it's PowerPoint.Application.16. Both have the same recent version of PowerPoint (Version 2111 Build 16.0.14701.20240). Both machines have a single version of Office.
Where CurVer is giving the incorrect value for computing the right key to register the addin, this creates a couple of problems:
When a user uninstalls the addin, the registry key for the path to the addin does not get deleted (it's trying to remove HKLM\SOFTWARE\Microsoft\Office\11.0\PowerPoint\AddIns\OurAddinName rather than HKLM\SOFTWARE\Microsoft\Office\16.0\PowerPoint\AddIns\OurAddinName), so thereafter when the user opens PowerPoint they will get an error message about not being able to find the addin.
When a user tries to install the addin, they will get an error message saying that their version of PowerPoint is too old.
My working solution | {
"domain": "codereview.stackexchange",
"id": 42712,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vb.net, windows, installer, powerpoint",
"url": null
} |
vb.net, windows, installer, powerpoint
My working solution
Inspect HKLM\SOFTWARE\Microsoft\Office\ClickToRun\Configuration\VersionToReport instead of CurVer
Inspect HKCR\PowerPoint.Application\CurVer if VersionToReport not available (maybe it might not be available on older installs? Some of our customers' organisations have very old installs of Office)
Store the version found here in the registry - under an entry for our software - so the right location can always be found for an uninstall
Using WIX and vb.net, it looks like this:
Get the registry values:
<Property Id="CTR_POWERPOINT_VERSION" Secure="yes">
<RegistrySearch Id="RegPowerPointVersion"
Root="HKLM"
Key="SOFTWARE\Microsoft\Office\ClickToRun\Configuration"
Name="VersionToReport"
Type="raw">
</RegistrySearch>
</Property>
<Property Id="CURVER_POWERPOINT_VERSION" Secure="yes">
<RegistrySearch Id="RegCurVerPowerPointVersion"
Root="HKCR"
Key="PowerPoint.Application\CurVer"
Type="raw">
</RegistrySearch>
</Property>
<Property Id="RECORDED_POWERPOINT_VERSION" Secure="yes">
<RegistrySearch Id="RegRecordedPowerPointVersion"
Root="HKLM"
Key="SOFTWARE\OurCompany\OurAddinName"
Name="powerpoint_version"
Type="raw">
</RegistrySearch>
</Property>
Make available for custom actions:
<CustomAction Id="SetPowerPointVersionProperty"
Property="CTR_POWERPOINT_VERSION"
HideTarget="no"
Value="[CTR_POWERPOINT_VERSION]"/>
<CustomAction Id="SetCurVerPowerPointVersionProperty"
Property="CURVER_POWERPOINT_VERSION"
HideTarget="no"
Value="[CURVER_POWERPOINT_VERSION]"/>
<CustomAction Id="SetRecordedPowerPointVersionProperty"
Property="RECORDED_POWERPOINT_VERSION"
HideTarget="no"
Value="[RECORDED_POWERPOINT_VERSION]"/> | {
"domain": "codereview.stackexchange",
"id": 42712,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vb.net, windows, installer, powerpoint",
"url": null
} |
vb.net, windows, installer, powerpoint
Process with vb.net:
Dim versionToUse As String
versionToUse = Regex.Match(Me.session("RECORDED_POWERPOINT_VERSION"), "[0-9]+").Value
' Note, when updating the addin, this is always done by doing an uninstall
' followed by an install - so in the uninstall phase RECORDED_POWERPOINT_VERSION
' will have something in it, and in the install phase it will be empty.
If versionToUse = vbNullString Then
versionToUse = Regex.Match(Me.session("CTR_POWERPOINT_VERSION"), "[0-9]+").Value
End If
If versionToUse = vbNullString Then
versionToUse = Regex.Match(Me.session("CURVER_POWERPOINT_VERSION"), "[0-9]+").Value
End If
Me.session("POWERPOINT_VERSION_NUMBER") = versionToUse & ".0"
Set the registry values (all also repeated on WOW6432Node):
<RegistryKey Root="HKLM"
Key="SOFTWARE\Microsoft\Office\[POWERPOINT_VERSION_NUMBER]\PowerPoint\AddIns\MyAddinName">
<RegistryValue Name="AutoLoad"
Action="write"
Value="1"
Type="integer"
KeyPath="yes"/>
<RegistryValue Name="Path"
Action="write"
Value="[APPLICATIONFOLDER]our-addin.ppam"
Type="string"
KeyPath="no"/>
</RegistryKey>
And record the location in a registry location for our addin:
<RegistryKey Root="HKLM"
Key="SOFTWARE\OurCompany\OurAddinName">
<RegistryValue Name="powerpoint_version"
Action="write"
Value="[POWERPOINT_VERSION_NUMBER]"
Type="string"
KeyPath="no"/>
</RegistryKey>
How does this look?
Answer: I have similar code in VBA to pull the version. It's much more simple because I can pull the version from the running application itself. It knows it's own version and doesn't care what arbitrary values exist in the registry. You could do this from VB.NET using office interop code.
First you need add a reference | {
"domain": "codereview.stackexchange",
"id": 42712,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vb.net, windows, installer, powerpoint",
"url": null
} |
vb.net, windows, installer, powerpoint
In Solution Explorer, right-click your project's name and then click
Add Reference. The Add Reference dialog box appears.
On the Assemblies page, select Microsoft.Office.Interop.PowerPoint in the Component Name list. If you do not see the assemblies,
you may need to ensure they are installed and displayed. See How to:
Install Office Primary Interop Assemblies.
Click OK.
Then you need to import the assembly you referenced:
Imports Microsoft.Office.Interop.PowerPoint
Then you can pull the version like this:
Public Function GetPowerPointVersion As String
Dim CurVer As String
Using thisPowerPoint As New Microsoft.Office.Interop.PowerPoint.Application()
CurVer = thisPowerPoint.Version
thisPowerPoint.Quit
End Using
Return CurVer
End Function | {
"domain": "codereview.stackexchange",
"id": 42712,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vb.net, windows, installer, powerpoint",
"url": null
} |
c#, asynchronous, wpf, socket, tcp
Title: Resilient & Stable TCP Server Polling
Question: I am looking for feedback to perfect my code developed for WPF in terms of speed, stability and resiliency. My code is supposed to handle synchronous status polling as well as asynchronous Commands to numerous TCP servers (more than 20). I am using a BlockingCollection to funnel these Polls & Commands and using the APM Pattern for Socket Communication. Please review.
ManualResetEvent connect = new ManualResetEvent(false);
ManualResetEvent send = new ManualResetEvent(false);
ManualResetEvent receive = new ManualResetEvent(false);
BlockingCollection<string[]> cmd_Queue = new BlockingCollection<string[]>();
...
Task.Run(() => TCP_Comms());
... | {
"domain": "codereview.stackexchange",
"id": 42713,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, wpf, socket, tcp",
"url": null
} |
c#, asynchronous, wpf, socket, tcp
void TCP_Comms()
{
while (true)
{
while (wifi_state)
{
string[] frame = cmd_Queue.Take(); // string[] { IP, Command }
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
client.BeginConnect(frame[0], port, new AsyncCallback(Connect_Callback), client);
if (!connect.WaitOne(timeout_Millis)) //1000ms
{
Debug("Connection timeout");
}
else
{
data = Encoding.ASCII.GetBytes(frame[1]);
client.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(Send_Callback), client);
if (!send.WaitOne(timeout_Millis))
{
Debug("Send timeout");
}
else
{
var response = new byte[client.ReceiveBufferSize];
client.BeginReceive(response, 0, response.Length, SocketFlags.None, new AsyncCallback(Receive_Callback), client);
if (!receive.WaitOne(timeout_Millis))
{
Debug("Receive timeout");
}
else
{
string response_data = Encoding.ASCII.GetString(response, 0, response.Length);
Debug("Response Received: " + response_data);
}
}
}
}
catch (SocketException ex)
{
Debug("Comms Error: " + ex.Message);
} | {
"domain": "codereview.stackexchange",
"id": 42713,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, wpf, socket, tcp",
"url": null
} |
c#, asynchronous, wpf, socket, tcp
Debug("Comms Error: " + ex.Message);
}
connect.Reset();
send.Reset();
receive.Reset();
client.Close();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42713,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, wpf, socket, tcp",
"url": null
} |
c#, asynchronous, wpf, socket, tcp
void Connect_Callback(IAsyncResult ar)
{
try
{
client.EndConnect(ar.AsyncState as Socket);
connect.Set();
}
catch (Exception ex)
{
Debug("Connect Error: " + ex.Message);
}
}
void Send_Callback(IAsyncResult ar)
{
try
{
client.EndSend(ar.AsyncState as Socket);
Debug("Send Success");
send.Set();
}
catch (Exception ex)
{
Debug("Send Error: " + ex.Message);
}
}
void Receive_Callback(IAsyncResult ar)
{
try
{
client.EndReceive(ar.AsyncState as Socket);
Debug("Receive Success");
receive.Set();
}
catch (Exception ex)
{
Debug("Recieve Error: " + ex.Message);
}
}
Answer: The APM Pattern is old school. I would suggest using the TAP extensions that are built in now. Can still use Task.Run as it takes a Func Task as one of the method overloads.
I would also change the timeout to be a TimeSpan they are easier to read and change instead of having to think in milliseconds.
private TimeSpan timeout = TimeSpan.FromSeconds(1);
while true is always a code smell for me. I don't know how this is running but if converting it to run as a service the services have a shutdown event. What I would recommend is changing the method signature of TCP_Comms to be
async Task TCP_Comms(CancellationToken cancellationToken)
and instead of while true have the while check the cancellationtoken
while (!cancellationToken.IsCancellationRequested)
If right now you don't need a way to break out of the loop when calling Task.Run can just pass in a default CancellationToken
Task.Run(() => TCP_Comms(CancellationToken.None)); | {
"domain": "codereview.stackexchange",
"id": 42713,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, wpf, socket, tcp",
"url": null
} |
c#, asynchronous, wpf, socket, tcp
This will allow later an option to pass in a cancellation token that does get cancelled when the app is shutting down by replacing CancellationToken.None with a token that gets cancelled when the app is shutting down.
There is a lot of code in the loop. I would recommend breaking them out into smaller methods or local functions, depending on the version of c# you are using.
For example on connecting/sending/receiving can break out each code into it's own set of code like the following. These are a local functions so has access the the variables of cancellationtoken and client socket. If want a methods would need to pass them along.
async Task<bool> Connect(string host, int port)
{
// using Task.Delay to have a timeout on the Connection
var completedTask = await Task.WhenAny(
client.ConnectAsync(host, port),
Task.Delay(timeout, cancellationToken));
// await here to throw any exception this task might have been completed with
try
{
await completedTask;
}
catch (Exception ex)
{
Debug("Connect Error: " + ex.Message);
return false;
}
// timeout hit first
if (!client.Connected)
{
Debug("Connection timeout");
client.Close();
return false;
}
return true;
}
async Task<bool> Send(byte[] command)
{
// Create a CancellationTokenSource to timeout the sendasync
using var tokenSource = new CancellationTokenSource(timeout);
try
{
await client.SendAsync(command, SocketFlags.None, tokenSource.Token);
}
catch (TaskCanceledException)
{
Debug("Send timeout");
return false;
}
catch (Exception ex)
{
Debug("Send Error: " + ex.Message);
return false;
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 42713,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, wpf, socket, tcp",
"url": null
} |
c#, asynchronous, wpf, socket, tcp
return true;
}
async Task<string> Receive(int bufferSize)
{
var buffer = new byte[bufferSize];
// Create a CancellationTokenSource to timeout the receiveasync
using var tokenSource = new CancellationTokenSource(timeout);
try
{
await client.ReceiveAsync(buffer, SocketFlags.None, tokenSource.Token);
var response = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
Debug("Response Received: " + response);
return response;
}
catch (TaskCanceledException)
{
Debug("Receive timeout");
return null;
}
catch (Exception ex)
{
Debug("Receive Error: " + ex.Message);
return null;
}
}
Now the code for each event that happens in the code is it's own set of code and logging.
Now makes the main inner loop look similar to
while (wifi_state)
{
string[] frame = cmd_Queue.Take(); // string[] { IP, Command }
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
if (await Connect(frame[0], port))
{
var data = Encoding.ASCII.GetBytes(frame[1]);
if (await Send(data))
{
var response = await Receive(client.ReceiveBufferSize);
}
}
}
catch (SocketException ex)
{
Debug("Comms Error: " + ex.Message);
}
client.Close();
Warning I didn't run/test this code as I don't have all your code or a server setup to send and receive messages This is just used as an example of how using the TAP and restructuring the code into smaller functions/methods will help make it read easier and will be more up-to-date and I personally feel easier to maintain by anyone coming afterwards. | {
"domain": "codereview.stackexchange",
"id": 42713,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, wpf, socket, tcp",
"url": null
} |
c++, template, c++20
Title: callable_traits implementation
Question: Update: there are new versions of this code: v2 is posted here, v3 is posted here and v4 is posted here
Goal: implement traits that for anything callable return its arity, return type and the argument types. Since pointers to data members are also callable, those should be handled (and be considered 0-arity).
Code below, try here. Questions i have:
How to make a nice compiler error message when passing a type that is not callable (such as int at the bottom of the testing code)? These come in at template <typename T> struct callable_traits : callable_traits<decltype(&std::decay_t<T>::operator())>, but i did not manage to test for existence of an operator() or so, so that a static_assert can be issued.
See usage inside a function in useInFunc() in the testing code. On MSVC, i need to do traits::template arg<0> instead of traits::arg<0> (typename before isn't necessary there on MSVC, but GCC requires that in turn so thats why that's there). Its a bit unwieldy to have to add the template (because its a dependent type?). Is there a way to avoid that? In general, i wonder why i need to add the typename when used inside the function but not in main for GCC, and why the template for MSVC...
I assume this does not work with overloaded functions. Can we catch that, or extend this to make it work?
#pragma once
// derived and extended from https://github.com/kennytm/utils/blob/master/traits.hpp
// and https://stackoverflow.com/a/28213747
#include <tuple>
#include <type_traits>
// get at operator() of any struct/class defining it (this includes lambdas)
template <typename T>
struct callable_traits : callable_traits<decltype(&std::decay_t<T>::operator())>
{}; | {
"domain": "codereview.stackexchange",
"id": 42714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, c++20",
"url": null
} |
c++, template, c++20
#define SPEC(cv,unused) \
/* handle anything with a function-like signature */ \
template <typename R, typename... Args> \
struct callable_traits<R(Args...) cv> \
{ \
using arity = std::integral_constant<std::size_t, sizeof...(Args) >; \
\
using result_type = R; \
\
template <std::size_t i> \
using arg = typename std::tuple_element<i, std::tuple<Args...,void>>::type; \
}; \
/* handle pointers to data members */ \
template <typename C, typename R> \
struct callable_traits<R C::* cv> \
{ \
using arity = std::integral_constant<std::size_t, 0 >; \
\
using result_type = R; \
\
template <std::size_t i> \
using arg = typename std::tuple_element<i, std::tuple<void>>::type; \
}; \
/* handle pointers to member functions, all possible iterations of reference and noexcept */ \ | {
"domain": "codereview.stackexchange",
"id": 42714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, c++20",
"url": null
} |
c++, template, c++20
/* handle pointers to member functions, all possible iterations of reference and noexcept */ \
template <typename C, typename R, typename... Args> \
struct callable_traits<R(C::*)(Args...) cv> : public callable_traits<R(Args...)> {};\
template <typename C, typename R, typename... Args> \
struct callable_traits<R(C::*)(Args...) cv &> : public callable_traits<R(Args...)> {};\
template <typename C, typename R, typename... Args> \
struct callable_traits<R(C::*)(Args...) cv &&> : public callable_traits<R(Args...)> {};\
template <typename C, typename R, typename... Args> \
struct callable_traits<R(C::*)(Args...) cv noexcept> : public callable_traits<R(Args...)> {};\
template <typename C, typename R, typename... Args> \
struct callable_traits<R(C::*)(Args...) cv & noexcept> : public callable_traits<R(Args...)> {};\
template <typename C, typename R, typename... Args> \
struct callable_traits<R(C::*)(Args...) cv && noexcept> : public callable_traits<R(Args...)> {}; | {
"domain": "codereview.stackexchange",
"id": 42714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, c++20",
"url": null
} |
c++, template, c++20
// cover all const and volatile permutations
SPEC(, )
SPEC(const, )
SPEC(volatile, )
SPEC(const volatile, )
// handle pointers to free functions
template <typename R, typename... Args>
struct callable_traits<R(*)(Args...)> : public callable_traits<R(Args...)> {};
testing code:
void test(int)
{
}
template <typename Func>
void useInFunc(Func)
{
using traits = callable_traits<Func>;
static_assert(std::is_same_v<const char*, typename traits::result_type>, "");
static_assert(std::is_same_v<const int&, typename traits::template arg<0>>, "");
}
struct tester
{
void yolo(char)
{
}
std::string field;
};
int main(int argc, char **argv)
{
auto lamb = [](const int& in_) noexcept {return "ret"; };
using traits = callable_traits<decltype(lamb)>;
static_assert(std::is_same_v<const char*, traits::result_type>, "");
static_assert(std::is_same_v<const int&, traits::arg<0>>, "");
useInFunc(lamb);
using traits2 = callable_traits<decltype(&test)>;
static_assert(std::is_same_v<void, traits2::result_type>, "");
static_assert(std::is_same_v<int, traits2::arg<0>>, "");
using traits3 = callable_traits<decltype(&tester::yolo)>;
static_assert(std::is_same_v<void, traits3::result_type>, "");
static_assert(std::is_same_v<char, traits3::arg<0>>, "");
using traits4 = callable_traits<decltype(&tester::field)>;
static_assert(std::is_same_v<std::string, traits4::result_type>, "");
static_assert(std::is_same_v<void, traits4::arg<0>>, "");
using traits5 = callable_traits<std::add_rvalue_reference_t<decltype(lamb)>>;
static_assert(std::is_same_v<const char*, traits5::result_type>, "");
static_assert(std::is_same_v<const int&, traits5::arg<0>>, "");
using traits6 = callable_traits<std::add_lvalue_reference_t<decltype(lamb)>>;
static_assert(std::is_same_v<const char*, traits6::result_type>, "");
static_assert(std::is_same_v<const int&, traits6::arg<0>>, ""); | {
"domain": "codereview.stackexchange",
"id": 42714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, c++20",
"url": null
} |
c++, template, c++20
/*using traits7 = callable_traits<int>;
static_assert(std::is_same_v<const char*, traits7::result_type>, "");
static_assert(std::is_same_v<const int&, traits7::arg<0>>, "");*/
return 0;
}
Answer: Missing support for some types of callables
It fails to compile if you try to get the callable traits of a freestanding function that is noexcept. This is easy to fix by adding:
template <typename R, typename... Args> \
struct callable_traits<R(Args...) cv noexcept>: public callable_traits<R(Args...) cv> {}; \
As mentioned by Jarod42, your code also doesn't handle variadic functions. In the StackOverflow post you referenced in the code, this answer shows one way to add support for that.
Don't append void to the tuple
There should be no need to append void to the tuple you want to get an element's type of. Just write:
template <std::size_t i> \
using arg = typename std::tuple_element<i, std::tuple<Args...>>::type; \
Callers should use arity to check if the function takes any parameters.
Why check for data members?
I don't understand why there is an overload that matches pointers to data members. Those aren't callable, so I would remove that template overload.
Make arity a value
Instead of making arity a type, consider making it a value, like so:
static constexpr auto arity = sizeof...(Args);
This avoids the need to add ::value after it.
Could the macro be avoided?
It would be nice if you didn't need a macro to be able to handle cv-qualifications of functions. There is also some duplication to handle both regular and noexcept functions. Perhaps it can be done by having a four-stage approach:
Get the actual callable. If passed a (pointer to member) function, just return it as-is. If it is a functor, return its operator().
Remove cv-qualifiers and noexcept.
If it is a pointer to member variable, return the function type, otherwise return it as is.
Provide traits of the final non-cv a non-noexcept function type. | {
"domain": "codereview.stackexchange",
"id": 42714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, c++20",
"url": null
} |
c++, template, c++20
This might not be easy. In particular, there is no std::remove_noexcept, so you might have to implement that yourself.
Handling overloaded functions
There is no way you can do that unless you already know the types of arguments and the cv-qualification. Otherwise, the compiler cannot resolve the overload. And if you do know the arguments, you can just use std::invoke_result to get the only missing piece of information (which is the return type).
Why the seemingly unnecessary need for template and typename
Indeed, sometimes the compiler cannot know up front if an identifier refers to a type, variable or function. When parsing the template definition, it has not instantiated the template. So it cannot know for sure what std::tuple_element<i, std::tuple<Args...>>::type is going to be. You remove that ambiguity by adding typename in front of it. Similarly you might need to add template in some places if the compiler would not be able to deduce that, but it seems a shortcoming of the version of MSVC you are using in this case. | {
"domain": "codereview.stackexchange",
"id": 42714,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, c++20",
"url": null
} |
c#, performance, ms-word
Title: Saving and/or Printing a Word Document From C#
Question: This is the Microsoft Word portion of the application described in this question. It is considerably simpler than the excel portion of the project. Any classes not defined in this question can be found in the excel question. The full source code for this project including the UI can be found in my GitHub repository.
This portion simply generates a word document and then can save it to a file or print it.
CWordInteropMethods.cs
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using Word = Microsoft.Office.Interop.Word;
namespace RentRosterAutomation
{
// Each building in the complex contains 3 floors of apartments. The documnets
// generated by Microsoft Word have 3 columns of data, one for each floor.
// Prints and or saves a Microsoft Word Document for each building.
class CWordInteropMethods
{
private string defaultSaveFolder;
private object oMissing = Missing.Value;
private object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
public CWordInteropMethods(CUserPreferences inPreferences)
{
defaultSaveFolder = inPreferences.DefaultSaveDirectory;
}
public bool CreateMailistPrintAndOrSave(string documentName, CMailboxListData mailboxdata,
bool addDateToDocName, bool addDateToTitle, bool save, bool print
)
{
bool docGenerated = true;
if (string.IsNullOrEmpty(documentName))
{
return false;
}
string fullFilePathName = FullFilePath(documentName, addDateToDocName);
Word.Application wordApp = new Word.Application(); | {
"domain": "codereview.stackexchange",
"id": 42715,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, ms-word",
"url": null
} |
c#, performance, ms-word
Word.Application wordApp = new Word.Application();
try
{
Word.Document wordDoc = new Word.Document();
wordApp.Visible = false;
wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
FormatDocMargins(ref wordDoc, wordApp);
AddTitleToMailBoxList(ref wordDoc, mailboxdata.AddressStreetNumber, addDateToTitle);
AddTenantTableToMailBoxList(ref wordDoc, mailboxdata, wordApp);
object DoNotSaveChanges = PrintAndOrSave(wordDoc, save, print, fullFilePathName);
wordDoc.Close(ref DoNotSaveChanges, ref oMissing, ref oMissing);
}
catch (Exception e)
{
string eMsg = "An error occurred while generating the Word Document for "
+ documentName + " : " + e.Message;
docGenerated = false;
MessageBox.Show(eMsg);
}
wordApp.Quit();
return docGenerated;
}
private object PrintAndOrSave(Word.Document wordDoc, bool save, bool print, string fullFilePathName)
{
object DoNotSaveChanges = oMissing;
if (print)
{
wordDoc.PrintOut();
}
if (save)
{
SaveFile(wordDoc, fullFilePathName);
}
else
{
DoNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
}
return DoNotSaveChanges;
}
private void AddTitleToMailBoxList(ref Word.Document wordDoc, int addressNumber, bool addDateToTitle)
{
object oMissing = Missing.Value; | {
"domain": "codereview.stackexchange",
"id": 42715,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, ms-word",
"url": null
} |
c#, performance, ms-word
Word.Paragraph MailboxListTitle = wordDoc.Content.Paragraphs.Add(ref oMissing);
MailboxListTitle.Range.Text = addressNumber.ToString();
MailboxListTitle.Range.Font.Size = 78;
MailboxListTitle.Range.Font.Bold = 1;
MailboxListTitle.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
MailboxListTitle.SpaceAfter = 0;
MailboxListTitle.Range.InsertParagraphAfter();
if (addDateToTitle)
{
DateTime todaysDate = DateTime.Today;
Word.Paragraph todaysDatePara = wordDoc.Content.Paragraphs.Add(ref oMissing);
todaysDatePara.Range.Text = todaysDate.ToString("MM/dd/yyyy");
todaysDatePara.Range.Font.Size = 7;
todaysDatePara.Range.Bold = 0;
todaysDatePara.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
todaysDatePara.SpaceAfter = 5;
todaysDatePara.Range.InsertParagraphAfter();
}
}
// Table is 2 columns for first and second floors, 1 column
// merged for third floor
private void AddTenantTableToMailBoxList(ref Word.Document wordDoc,
CMailboxListData mailboxData, Word.Application wordApp)
{
object oMissing = Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
int rowCount = (mailboxData.FirstFloor.Count > mailboxData.SecondFloor.Count) ?
mailboxData.FirstFloor.Count : mailboxData.SecondFloor.Count;
int maxDoubleColumn = rowCount;
rowCount += mailboxData.ThirdFloor.Count;
rowCount += 1; // One empty row between third floor column and upper colums
Word.Table tenantTable = CreateAndFormatTenatTable(rowCount, maxDoubleColumn,
wordDoc, wordApp); | {
"domain": "codereview.stackexchange",
"id": 42715,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, ms-word",
"url": null
} |
c#, performance, ms-word
FillFloor1Stand2Nd(mailboxData, maxDoubleColumn, ref tenantTable);
FillThirdFloor(mailboxData, maxDoubleColumn, wordApp, ref tenantTable);
}
private void FillThirdFloor(CMailboxListData mailboxData, int maxDoubleColumn, Word.Application wordApp, ref Word.Table tenantTable)
{
int row = maxDoubleColumn + 2;
List<CApartment> ThirdFloor = mailboxData.ThirdFloor;
for (int i = 0; i < ThirdFloor.Count; i++)
{
Word.Cell currentCell = tenantTable.Cell(row, 1);
tenantTable.Rows[row].Cells[1].Merge(tenantTable.Rows[row].Cells[2]);
currentCell.LeftPadding = wordApp.InchesToPoints((float)2.5);
AssignCellValueAndFormat(ref currentCell, MailBoxListEntry(ThirdFloor, i));
row++;
}
}
private void FillFloor1Stand2Nd(CMailboxListData mailboxData, int maxDoubleColumn, ref Word.Table tenantTable)
{
List<CApartment> FirstFloor = mailboxData.FirstFloor;
List<CApartment> SecondFloor = mailboxData.SecondFloor;
int firstFloorCount = FirstFloor.Count;
int secondFloorCount = SecondFloor.Count;
int row = 1;
for (; row <= maxDoubleColumn; row++)
{
if (row <= firstFloorCount)
{
Word.Cell currentCell = tenantTable.Cell(row, 1);
AssignCellValueAndFormat(ref currentCell, MailBoxListEntry(FirstFloor, row - 1));
}
if (row <= secondFloorCount)
{
Word.Cell currentCell = tenantTable.Cell(row, 2);
AssignCellValueAndFormat(ref currentCell, MailBoxListEntry(SecondFloor, row - 1));
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, ms-word",
"url": null
} |
c#, performance, ms-word
}
private Word.Table CreateAndFormatTenatTable(int rowCount, int maxDoubleColumn,
Word.Document wordDoc, Word.Application wordApp)
{
Word.Table tenantTable;
Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
tenantTable = wordDoc.Tables.Add(wrdRng, rowCount, 2, ref oMissing, ref oMissing);
tenantTable.Range.Font.Size = (maxDoubleColumn < 14) ? 18 : 16;
tenantTable.Range.Font.Bold = 1;
tenantTable.Range.Font.Name = "Arial";
tenantTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowLeft;
tenantTable.Columns.SetWidth(wordApp.InchesToPoints((float)3.25), Word.WdRulerStyle.wdAdjustSameWidth);
return tenantTable;
}
private void AssignCellValueAndFormat(ref Word.Cell currentCell, string cellValue)
{
currentCell.Range.Text = cellValue;
currentCell.WordWrap = true;
currentCell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
}
private string MailBoxListEntry(List<CApartment> apartments, int row)
{
string mbListEntry = apartments[row].ApartmentNumber.ToString();
mbListEntry += " " + apartments[row].renter.MailboxListOccupantEntry();
return mbListEntry;
}
private string FullFilePath(string documentName, bool addDateToFileName)
{
string fileToSave = defaultSaveFolder + "\\" + documentName;
if (addDateToFileName)
{
DateTime todaysDate = DateTime.Today;
string dtNoSlash = todaysDate.ToString("MMddyyyy");
fileToSave += "_" + dtNoSlash;
}
fileToSave += ".docx";
return fileToSave;
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, ms-word",
"url": null
} |
c#, performance, ms-word
return fileToSave;
}
private void SaveFile(Word.Document wordDoc, string documentName)
{
if (!string.IsNullOrEmpty(defaultSaveFolder))
{
object oMissing = Missing.Value;
object newfile = documentName;
wordDoc.SaveAs(ref newfile, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
}
else
{
wordDoc.Save();
}
}
private void FormatDocMargins(ref Word.Document wordDoc, Word.Application wordApp)
{
wordDoc.PageSetup.TopMargin = wordApp.InchesToPoints((float)0.375);
wordDoc.PageSetup.LeftMargin = wordApp.InchesToPoints((float)1);
wordDoc.PageSetup.RightMargin = wordApp.InchesToPoints((float)1);
wordDoc.PageSetup.BottomMargin = wordApp.InchesToPoints((float)0.375);
}
}
}
CUserPreferences.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace RentRosterAutomation
{
// Reads and writes the user preferences file.
public class CUserPreferences
{
private CPrintSavePreference.PrintSave printSaveValue;
private CPrintSavePreference printSavePreference;
private Dictionary<int, string> FieldNameByIndex;
private Dictionary<string, int> IndexFromFieldName;
private const int fileVersion = 1;
private bool preferenceFileExists = false;
private bool preferenceFileRead = false; | {
"domain": "codereview.stackexchange",
"id": 42715,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, ms-word",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.