text stringlengths 1 2.12k | source dict |
|---|---|
assembly, rags-to-riches, x86
_stringToNumber:
xor eax, eax
jmp .first ; A one-time jump
.digit:
inc esi
lea eax, [rax + rax * 4] ; (Number * 5) * 2 + Newdigit
lea eax, [rdx + rax * 2]
.first:
movzx edx, byte [rsi]
sub edx, '0'
cmp dl, 10
jb .digit ; The only jump in this tight loop
ret
I verified that it is ok for the caller of this subroutine to have RDX trashed.
I removed support for the minus character based on the following quotes from the documentation:
... decimal (0-9) digits may be used to represent a non-negative, decimal constant in the range 0 through 32,767. The use of the minus sign to indicate a negative number is not allowed.
The A-instruction ... is the only means to introduce a (non-negative) numeric value into the computer under program control;
Avoid complicating matters
The setup that you do for rep movsb in _numberToString seems convoluted.
I could simplify the code mostly by anticipating (before the loop) the upcoming rep movsb that will require RCX, RSI, and RDI been setup. No need for an exchange between RSI and RDI, nor another addition of 5 to calculate RCX.
; given a 16-bit number in ax, convert to string in line
; ENTRY:
; eax : number to convert (high word is empty)
; rdi : points to destination buffer
; EXIT:
; rdi : points to past end of written string
; TRASHES:
; rax, rbx, rcx, rdx, rsi
_numberToString:
lea esi, [rdi + 5] ; Past end of the 5-byte buffer
mov ecx, esi
mov ebx, 10
.loopy:
dec esi
xor edx, edx
div ebx
add edx, '0'
mov [rsi], dl
test eax, eax
jnz .loopy
sub ecx, esi
rep movsb
ret | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
Your use of test rax, rax made you insist on 'high 48 bits must be zero'. Writing test eax, eax not only shortens the code but also relaxes this condition to bits 16-31.
I verified that it is ok for the caller of this subroutine to have RAX, RBX, RCX, RDX, and RSI trashed.
Use a data-driven structure
I very much like what you did with this: the Operation struc and the opcode macro.
But seeing that no mnemonic string has more than 4 characters, why did you choose for a string of 8 instead of 4? Couldn't the program benefit from the increased data density? I rewrote the entire program applying everything from this review (and more that I didn't feel like posting about), and I got a 25% reduction of the .data section and a 19% reduction of the .code section.
Who is right and who is wrong?
The nand2tetris document that you link to uses AMD= and MD=, but the wikipedia page that I consulted uses ADM= and DM=. Whom shall I trust? | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
python, edit-distance
Title: Calculate Levenshtein distance between two strings in Python
Question: I need a function that checks how different are two different strings. I chose the Levenshtein distance as a quick approach, and implemented this function:
from difflib import ndiff
def calculate_levenshtein_distance(str_1, str_2):
"""
The Levenshtein distance is a string metric for measuring the difference between two sequences.
It is calculated as the minimum number of single-character edits necessary to transform one string into another
"""
distance = 0
buffer_removed = buffer_added = 0
for x in ndiff(str_1, str_2):
code = x[0]
# Code ? is ignored as it does not translate to any modification
if code == ' ':
distance += max(buffer_removed, buffer_added)
buffer_removed = buffer_added = 0
elif code == '-':
buffer_removed += 1
elif code == '+':
buffer_added += 1
distance += max(buffer_removed, buffer_added)
return distance
Then calling it as:
similarity = 1 - calculate_levenshtein_distance(str_1, str_2) / max(len(str_1), len(str_2))
How sloppy/prone to errors is this code? How can it be improved?
Answer: There is a module available for exactly that calculation, python-Levenshtein. You can install it with pip install python-Levenshtein.
It is implemented in C, so is probably faster than anything you can come up with yourself.
from Levenshtein import distance as levenshtein_distance
According to the docstring conventions, your docstring should look like this, i.e. with the indentation aligned to the """ and the line length curtailed to 80 characters.
def calculate_levenshtein_distance(str_1, str_2):
"""
The Levenshtein distance is a string metric for measuring the difference
between two sequences.
It is calculated as the minimum number of single-character edits necessary to
transform one string into another.
"""
... | {
"domain": "codereview.stackexchange",
"id": 43567,
"lm_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, edit-distance",
"url": null
} |
c++, generics, template-meta-programming, callback
Title: C++ Generic Callback class with removable listeners by unique id
Question: I'm quite new to the STL.
Does this make sense? Is there a better way of removing the listeners instead of using shared_ptr while keeping the code short and simple? Is there something in the STL to replace this?
Class:
template<class ... Arguments>
class Callback
{
using Function = std::function<void(Arguments ...)>;
using FunctionPtr = std::shared_ptr<Function>;
using Functions = std::vector<FunctionPtr>;
public:
FunctionPtr addListener(Function f) {
FunctionPtr fp = std::make_shared<Function>(f);
_functions.push_back(fp);
return fp;
}
void removeListener(FunctionPtr fp){
_functions.erase(std::find(_functions.begin(), _functions.end(), fp));
}
void operator()(Arguments ... args) const{
for (auto & f : _functions)
f.get()->operator()( args ... );
}
private:
Functions _functions;
};
Use case:
int main()
{
Callback<int> callback;
callback.addListener([](int i){
std::cout << "Listener 1 -> Input is " << i << std::endl;
});
auto id = callback.addListener([](int i){
std::cout << "Listener 2 -> Input is " << i << std::endl;
});
callback.addListener([](int i){
std::cout << "Listener 3 -> Input is " << i << std::endl;
});
callback.removeListener(id);
callback(71);
}
Output is:
Listener 1 -> Input is 71
Listener 3 -> Input is 71 | {
"domain": "codereview.stackexchange",
"id": 43568,
"lm_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++, generics, template-meta-programming, callback",
"url": null
} |
c++, generics, template-meta-programming, callback
callback(71);
}
Output is:
Listener 1 -> Input is 71
Listener 3 -> Input is 71
Addendum
One limitation of this approach is that you can't remove or add listeners inside the callback functions since it would break the iteration. What I found is that this limitation is especially annoying when you want something to only trigger once and then be removed.
The easiest solution I found is to simply have a separate list of callbacks that are called once and then removed automatically after the iteration.
Another easy, more generic solution is to copy the listeners container before triggering the callbacks with the obvious performance cost.
Answer: I think it's quite OK like that. Of course that depends on the use case and your goal.
One thing I would definitely change though is to return only a std::weak_ptr from addListener.
Here a few alternative approaches:
replace the std::vector with
a std::set or std::unordered_set and keep the std::weak_ptr as the "ID", or
a std::list and use the iterator as "ID", or
a std::map or std::unordered_map and make up your own ID, maybe just as simple as a static integer counter.
Those all make the removal faster (logarithmic or constant instead of linear). The addition is already and would stay constant (at least amortized).
Also if you want the returned "ID" to be a little more "ID-like" and don't want to use a map you could wrap the std::weak_ptr or the std::list::iterator into an Id class. And if you then want the single member of the Id class to not be accessable by the user make it private and Callback a friend.
Further non question related remarks:
Adding the missing header would have been a good polish for the otherwise good and complete question to make it truly copy&paste&runnable.
You could add a few const/references here and there:
addListener argument can be const&&
removeListener argument can be const&
operator() arguments can be const&
the f in the for loop could also be const | {
"domain": "codereview.stackexchange",
"id": 43568,
"lm_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++, generics, template-meta-programming, callback",
"url": null
} |
c++, generics, template-meta-programming, callback
although it will not always help that much. | {
"domain": "codereview.stackexchange",
"id": 43568,
"lm_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++, generics, template-meta-programming, callback",
"url": null
} |
beginner, php, html, sql
Title: Product list from database to web tables/boxes
Question: I am a self-taught front-end developer, trying to land a job, the PHP and MySQL are quite new to me, since I only watched and did some code through Traversy Media courses.
This is a test project, where I need to build a product list page that pulls data from a database and presents them in tables/boxes. The entries are presented with checkboxes, so you can delete them and add other products from an add product page that I am currently trying to make...
It's functioning as it is, however I am curious whether this can be written more profesionally.
<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=test', 'bork', '123456');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $pdo->prepare('SELECT * FROM skandi Where id=1');
$statementTwo = $pdo->prepare('SELECT * FROM skandi Where id=2');
$statementThree = $pdo->prepare('SELECT * FROM skandi Where id=3');
$statement->execute();
$statementTwo->execute();
$statementThree->execute();
$products = $statement->fetchAll(PDO::FETCH_ASSOC);
$product = $statementTwo->fetchAll(PDO::FETCH_ASSOC);
$productt = $statementThree->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style/normalize.css" />
<link rel="stylesheet" href="style/style.css" />
</head>
<body>
<header>
<h2>Product List</h2>
<nav>
<button class="add-btn" id="addBtn">ADD</button>
<button class="mass-btn" id="delete-product-btn" onclick="removeCheckedCheckboxes()">MASS DELETE</button>
</nav>
</header> | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
beginner, php, html, sql
<section class="product-list-wrapper">
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($products as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Size']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($products as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Size']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($products as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Size']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" /> | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
beginner, php, html, sql
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($products as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Size']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($product as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Weight']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($product as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Weight']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" /> | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
beginner, php, html, sql
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($product as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Weight']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($product as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Weight']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($productt as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Dimension']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" /> | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
beginner, php, html, sql
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($productt as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Dimension']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($productt as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Dimension']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($productt as $i => $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Dimension']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</section>
<footer>
<h2>Scandiweb Test Assignement</h2>
</footer>
<script src="js/main.js"></script>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
beginner, php, html, sql
<script src="js/main.js"></script>
</body>
</html>
Answer: Since the example code shows for each of the 3 product results 4 identical entries, the first step would be to replace the 4 div with a for loop.
And because the structure of the 3 product tables are almost identical – they differ only in one key (namely 'Size', 'Weight', and 'Dimension') –, the second step would be to simplify that into another, outer for loop.
...
// after querying the database:
$all = [ $products, $product, $productt ];
...
// replacement for all 12 divs:
<section class="product-list-wrapper">
<?php foreach ($all as $entry) : ?>
<?php for ($j = 0; $j < 4; $j++) : ?>
<div class="div-box">
<input type="checkbox" class="delete-checkbox" />
<table>
<tbody>
<?php foreach ($entry as $item) : ?>
<tr class="content">
<td><?php echo $item['SKU']; ?> </td>
<td><?php echo $item['Name']; ?> </td>
<td><?php echo $item['Price']; ?> </td>
<td><?php echo $item['Size'] ?? $item['Weight'] ?? $item['Dimension']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endfor; ?>
<?php endforeach; ?>
</section>
...
Edit: Based on @mickmackusa's comment below this could be a way to reduce the three database trips to one:
$statement = $pdo->prepare('SELECT * FROM skandi WHERE id = IN(1, 2, 3)');
$statement->execute();
$products = $statement->fetchAll(PDO::FETCH_ASSOC);
$all = [
array_filter($products, fn($item) => $item['id'] === 1),
array_filter($products, fn($item) => $item['id'] === 2),
array_filter($products, fn($item) => $item['id'] === 3)
]; | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
beginner, php, html, sql
Depending on the count of rows returned from the database, this might be faster or slower. My assumption would be that for very large amount of rows it would be faster to query three times, because database engines excel at filtering, while for smaller amounts of rows, one query with three array_filter calls would be faster. | {
"domain": "codereview.stackexchange",
"id": 43569,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, php, html, sql",
"url": null
} |
c#, entity-framework, lambda
Title: Ordering data by boolean
Question: I have a bit of EF Lambda code which returns a list of data from the db table, then orders by a field called IsDefault
At first, the code was
var listOfData = Db
.TableName
.Where(u => u.UserId == userId)
.OrderBy(u => u.IsDefault)
.ToList();
Which when writing down, sounds correct. However is wrong as this will order by 0 > 1, and True = 1.
So I changed the statement to;
var listOfData = Db
.TableName
.Where(u => u.UserId == userId)
.OrderBy(u => u.IsDefault ? 0 : 1)
.ToList();
However, I could have also written this 2 other ways.
.OrderBy(u => !u.IsDefault)
OR
.OrderByDescending(u => u.IsDefault)
Now in my mind, u.IsDefault ? 0 : 1 reads better, and the other two could be misread as the not wanting the default value first.
What is your view on this?
Answer: I wouldn't use either ordering on the server side because it looks like the ordering only matters for displaying the data. I cannot imagine why it should matter from the programmatic point of view.
Let the client, its view, its display control, or whatever sort the items according to its needs. | {
"domain": "codereview.stackexchange",
"id": 43570,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, entity-framework, lambda",
"url": null
} |
python, python-3.x, geospatial
Title: find closest object via latitude and longitude and haversine distance
Question: Given a pandas data frame containing objects with ids and latitudes and longitudes:
id latitude longitude
0 a 52.617960 1.717728
1 b 51.773427 -4.455351
2 c 52.206543 -4.345786
I would like to find the closest object with a different id in the same data frame resulting in the following data:
closest_id closest_latitude closest_longitude distance id latitude longitude
0 c 52.206543 -4.345786 413.676582 a 52.617960 1.717728
1 c 52.206543 -4.345786 48.741132 b 51.773427 -4.455351
2 b 51.773427 -4.455351 48.741132 c 52.206543 -4.345786
My working (AFIK) but clumsy/rooky/non pythonic attempt can be found below. Any improvement suggestions would be very much welcome.
import pandas as pd
from math import radians, cos, sin, asin, sqrt
def dist(lat1, long1, lat2, long2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, long1, lat2, long2 = map(radians, [lat1, long1, lat2, long2])
# haversine formula
dlon = long2 - long1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# Radius of earth in kilometers is 6371
km = 6371* c
return km
test_data = {'id':['a','b','c'], 'latitude':[52.61796, 51.773427, 52.206543], 'longitude':[1.717728, -4.455351, -4.345786]}
haves = pd.DataFrame(test_data)
def find_nearest(lat, long, id, df):
# guess very inefficient
filter_data = df.copy()
filter_data.drop(filter_data.index[filter_data['id'] == id], inplace = True)
distances = filter_data.apply(lambda row: dist(lat, long, row['latitude'], row['longitude']), axis=1) | {
"domain": "codereview.stackexchange",
"id": 43571,
"lm_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, geospatial",
"url": null
} |
python, python-3.x, geospatial
#print(distances)
dic = dict()
dic['closest_id'] = filter_data.loc[distances.idxmin(), 'id']
dic['closest_latitude'] = filter_data.loc[distances.idxmin(), 'latitude']
dic['closest_longitude'] = filter_data.loc[distances.idxmin(), 'longitude']
dic['distance'] = distances[distances.idxmin()]
#print(dic)
return dic
print(haves)
wants = pd.DataFrame()
for index, row in haves.iterrows():
dic = find_nearest(row['latitude'], row['longitude'], row['id'], haves)
dic['id'] = row['id']
dic['latitude'] = row['latitude']
dic['longitude'] = row['longitude']
wants = wants.append(dic, ignore_index=True)
print(wants) | {
"domain": "codereview.stackexchange",
"id": 43571,
"lm_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, geospatial",
"url": null
} |
python, python-3.x, geospatial
Answer: So, with regards to the code style (naming, spacing, etc.), the code is really not bad.
There's one small thing I'd like to say, when you use an algorithm or a pattern that has a specific name, use it. The function name dist doesn't tell us, users/readers of your code, that you're using the Haversine Distance.
There's nothing bad with using meaningful names, as a matter of fact it's much worst to have code with unclear variable/function names.
So, don't name your function dist, name it haversine_distance. This way, if someone wants to understand what's happening in your code, they'll be able to find it very fast by searching this on the web. You might tell me that you have a comment in your function that says " # haversine formula ", but comments shouldn't be used to describe what's happening it's a last resort.
Now, for the algorithm. It's not clear in your post what amount of data you have. If you have a hundred points, the way to find the closest distance to another point really isn't the same as if you have a billion rows.
If the amount of data you have is very small, your algorithm is most likely "ok".
Now, if you have lots of data, which is a more fun assumption, I think you're not using the full advantages of the libraries offered to you in Python.
What you want is to find, for each element E in the dataset D, another element E' in the same dataset D such as the distance between E and E' is smaller than every other distances for all elements of D except for E itself (because the distance between E and E is zero, duh).
The way to find information on such problems is to look at the nearest neighbors algorithms.
The exact implementation you'll used will vary depending on the amount of data. If you have under maybe 200000 rows, you could consider using the scikit-learn algorithm. Otherwise, Facebook released a Nearest Neighbors algorithm capable of dealing with billions of rows (assuming you have the hardware for it). | {
"domain": "codereview.stackexchange",
"id": 43571,
"lm_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, geospatial",
"url": null
} |
python, python-3.x, geospatial
Say we use the scikit-learn one, mainly because I never used the other one. What's nice about this is we can specify the metric to use to compute the distances. You can use your implementation, or you could use the scipy one!
Starting with the haves dataframe (btw, what does this mean? Maybe that's a sign it should be named otherwise). This is only a draft of the code you should used, I don't guarantee it'll compile, but the idea is there :
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics.pairwise import haversine_distances | {
"domain": "codereview.stackexchange",
"id": 43571,
"lm_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, geospatial",
"url": null
} |
python, python-3.x, geospatial
# First, I'd split the numeric values from the identifiers.
identifiers = haves["id"]
coordinates = haves[['latitude', 'longitude']]
# Adapt the hyperparameters to your needs, you may need to fiddle a bit to find the best ones for your case.
# However, we picked n_neighbors=2 because the first nearest neighbor will always be the element itself.
nn = NearestNeighbors(n_neighbors=2, radius=1.0, algorithm='auto', leaf_size=30, metric=haversine_distances, n_jobs=None)
# Here we give our data to the algorithm. It'll create a data structure made specially to find nearest neighbors, which is pretty much garanteed to be faster than your code unless you have like <100 rows.
nn = nn.fit(coordinates.values)
# Here, we ask the algorithm to find the 2 closest neighbors for each row of the dataframe
distances, nearest_neighbors_row_ids = n.kneighbors(coordinates.values)
# Get the closest neighbor that isn't the row itself.
nearest_neighbors_row_ids = [x[1] for x in nearest_neighbors_row_ids]
#...
Then, all you need to do is regroup the data, but your code does it already and I think your code is alright.
So, I think my main take away from your code is that it's okay, but when you want to optimize your code, the first think you should do is look for an established algorithm that does the job. These algorithms have been written by pros and tested by thousands before you, so they'll work. | {
"domain": "codereview.stackexchange",
"id": 43571,
"lm_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, geospatial",
"url": null
} |
javascript, array, google-apps-script, google-sheets
Title: Replace/remove all diacritics and converting different letters to Latin alphabet in multiple spreadsheet columns (multidimensional array)
Question:
Attention: if you read the question and are going to use the defaultDiacriticsRemovalMap in
the future → I analyzed the name of all professional football athletes
and added some letters that do not exist in the original map, so it is
modified for my use, test it first and see if that way too it's ok for
you!
Currently (the code bellow works) to work with one column or multiple columns I use .join('♠') and after I remove the diacritics and convert the letters to the Latin alphabet, I separate again using .split('♠'), but this causes a slowness in the process, I would like some help to find a more agile method.
Example array collect in spreadsheet via:
var values = sheet.getRange(get_range).getValues();
var diacriticsMap = {};
for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
var letters = defaultDiacriticsRemovalMap[i].letters;
for (var j = 0; j < letters.length; j++) {
diacriticsMap[letters[j]] = defaultDiacriticsRemovalMap[i].base;
}
}
function remove_all_diacritics(sheet_name, get_range, row_set, col_set) {
// var sheet = SpreadsheetApp.getActive().getSheetByName(sheet_name);
// var values = sheet.getRange(get_range).getValues();
var values = [['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], ['æ', 'ø', 'å', 'á'], ['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], ['á', 'á', 'á', 'á'], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ]] | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
var ct = 0;
while (values[ct] && values[ct][0] != "") {
ct++;
}
var values = values.slice(0, ct);
var joiners = [];
for (var i = 0; i < values.length; i++) {
joiners.push([values[i].join('♠')])
}
var new_values = joiners.map(([v]) => [v.toString() != "" ? v.replace(/[^\u0000-\u007E]/g, a => diacriticsMap[a] || a) : ""]);
nv_arrays = [];
for (var i = 0; i < new_values.length; i++) {
nv_arrays.push(new_values[i][0].split('♠'))
}
// sheet.getRange(row_set, col_set, nv_arrays.length, nv_arrays[0].length).setValues(nv_arrays);
console.log(nv_arrays)
} | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
function rad() {
remove_all_diacritics('NoDiacritics', 'A1:D', 1, 6)
}
rad()
<script>
var defaultDiacriticsRemovalMap = [
{'base':'A', 'letters':'\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F\u018F\u0410'},
{'base':'AA','letters':'\uA732'},
{'base':'AE','letters':'\u00C6\u01FC\u01E2'},
{'base':'AO','letters':'\uA734'},
{'base':'AU','letters':'\uA736'},
{'base':'AV','letters':'\uA738\uA73A'},
{'base':'AY','letters':'\uA73C'},
{'base':'B', 'letters':'\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181'},
{'base':'C', 'letters':'\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E'},
{'base':'D', 'letters':'\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0'},
{'base':'DZ','letters':'\u01F1\u01C4'},
{'base':'Dz','letters':'\u01F2\u01C5'},
{'base':'E', 'letters':'\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E\u0415'},
{'base':'F', 'letters':'\u0046\u24BB\uFF26\u1E1E\u0191\uA77B'},
{'base':'G', 'letters':'\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E'},
{'base':'H', 'letters':'\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D'},
{'base':'I', 'letters':'\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197'},
{'base':'J', 'letters':'\u004A\u24BF\uFF2A\u0134\u0248'},
{'base':'K', 'letters':'\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2'},
{'base':'L', 'letters':'\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780'}, | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
{'base':'LJ','letters':'\u01C7'},
{'base':'Lj','letters':'\u01C8'},
{'base':'M', 'letters':'\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C\u041C'},
{'base':'N', 'letters':'\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4'},
{'base':'NJ','letters':'\u01CA'},
{'base':'Nj','letters':'\u01CB'},
{'base':'O', 'letters':'\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C\u041E'},
{'base':'OI','letters':'\u01A2'},
{'base':'OO','letters':'\uA74E'},
{'base':'OU','letters':'\u0222'},
{'base':'OE','letters':'\u008C\u0152'},
{'base':'oe','letters':'\u009C\u0153'},
{'base':'P', 'letters':'\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754'},
{'base':'Q', 'letters':'\u0051\u24C6\uFF31\uA756\uA758\u024A'},
{'base':'R', 'letters':'\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782'},
{'base':'S', 'letters':'\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784'},
{'base':'T', 'letters':'\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786'},
{'base':'Thor','letters':'\u00DE'},
{'base':'TZ','letters':'\uA728'},
{'base':'U', 'letters':'\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244'},
{'base':'V', 'letters':'\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245'},
{'base':'VY','letters':'\uA760'},
{'base':'W', 'letters':'\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72'},
{'base':'X', 'letters':'\u0058\u24CD\uFF38\u1E8A\u1E8C'}, | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
{'base':'X', 'letters':'\u0058\u24CD\uFF38\u1E8A\u1E8C'},
{'base':'Y', 'letters':'\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE'},
{'base':'Z', 'letters':'\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762'},
{'base':'a', 'letters':'\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250\u0259'},
{'base':'aa','letters':'\uA733'},
{'base':'ae','letters':'\u00E6\u01FD\u01E3'},
{'base':'ao','letters':'\uA735'},
{'base':'au','letters':'\uA737'},
{'base':'av','letters':'\uA739\uA73B'},
{'base':'ay','letters':'\uA73D'},
{'base':'b', 'letters':'\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253'},
{'base':'c', 'letters':'\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184\u0441'},
{'base':'d', 'letters':'\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A'},
{'base':'dz','letters':'\u01F3\u01C6'},
{'base':'e', 'letters':'\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD'},
{'base':'f', 'letters':'\u0066\u24D5\uFF46\u1E1F\u0192\uA77C'},
{'base':'g', 'letters':'\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F'},
{'base':'h', 'letters':'\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265'},
{'base':'hv','letters':'\u0195'},
{'base':'i', 'letters':'\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131\u0456'},
{'base':'j', 'letters':'\u006A\u24D9\uFF4A\u0135\u01F0\u0249'}, | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
{'base':'j', 'letters':'\u006A\u24D9\uFF4A\u0135\u01F0\u0249'},
{'base':'k', 'letters':'\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3'},
{'base':'l', 'letters':'\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747'},
{'base':'lj','letters':'\u01C9'},
{'base':'m', 'letters':'\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F'},
{'base':'n', 'letters':'\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5'},
{'base':'nj','letters':'\u01CC'},
{'base':'o', 'letters':'\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275\u00F0'},
{'base':'oi','letters':'\u01A3'},
{'base':'ou','letters':'\u0223'},
{'base':'oo','letters':'\uA74F'},
{'base':'p','letters':'\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755'},
{'base':'q','letters':'\u0071\u24E0\uFF51\u024B\uA757\uA759'},
{'base':'r','letters':'\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783'},
{'base':'s','letters':'\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B'},
{'base':'t','letters':'\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787'},
{'base':'thor','letters':'\u00FE'},
{'base':'tz','letters':'\uA729'},
{'base':'u','letters': '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289\u03CB'},
{'base':'v','letters':'\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C'},
{'base':'vy','letters':'\uA761'}, | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
{'base':'vy','letters':'\uA761'},
{'base':'w','letters':'\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73'},
{'base':'x','letters':'\u0078\u24E7\uFF58\u1E8B\u1E8D'},
{'base':'y','letters':'\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF'},
{'base':'z','letters':'\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763'}
];
</script> | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
Answer:
Use a simple recursive function using Array.map. This maintains the initial structure of the multidimensional array without needing loops and all those array/string manipulations of .join ,.split and .push.
const replace = (v) =>
Array.isArray(v)
? v.map((v) => replace(v))
: String(v).replace(/[^\u0000-\u007E]/g, (a) => diacriticsMap[a] || a);
Use const and let as needed instead of declaring all variables as var. This helps the javascript engine optimize the memory and processing of such variables | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
const defaultDiacriticsRemovalMap = [
{
base: 'A',
letters:
'\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F\u018F\u0410',
},
{ base: 'AA', letters: '\uA732' },
{ base: 'AE', letters: '\u00C6\u01FC\u01E2' },
{ base: 'AO', letters: '\uA734' },
{ base: 'AU', letters: '\uA736' },
{ base: 'AV', letters: '\uA738\uA73A' },
{ base: 'AY', letters: '\uA73C' },
{
base: 'B',
letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181',
},
{
base: 'C',
letters:
'\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E',
},
{
base: 'D',
letters:
'\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0',
},
{ base: 'DZ', letters: '\u01F1\u01C4' },
{ base: 'Dz', letters: '\u01F2\u01C5' },
{
base: 'E',
letters:
'\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E\u0415',
},
{ base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
{
base: 'G',
letters:
'\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E',
},
{
base: 'H',
letters:
'\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D',
},
{
base: 'I',
letters:
'\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197',
},
{ base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
{
base: 'K',
letters:
'\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2',
},
{
base: 'L',
letters: | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
},
{
base: 'L',
letters:
'\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780',
},
{ base: 'LJ', letters: '\u01C7' },
{ base: 'Lj', letters: '\u01C8' },
{
base: 'M',
letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C\u041C',
},
{
base: 'N',
letters:
'\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4',
},
{ base: 'NJ', letters: '\u01CA' },
{ base: 'Nj', letters: '\u01CB' },
{
base: 'O',
letters:
'\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C\u041E',
},
{ base: 'OI', letters: '\u01A2' },
{ base: 'OO', letters: '\uA74E' },
{ base: 'OU', letters: '\u0222' },
{ base: 'OE', letters: '\u008C\u0152' },
{ base: 'oe', letters: '\u009C\u0153' },
{
base: 'P',
letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754',
},
{ base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
{
base: 'R',
letters:
'\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782',
},
{
base: 'S',
letters:
'\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784',
},
{
base: 'T',
letters:
'\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786',
},
{ base: 'Thor', letters: '\u00DE' },
{ base: 'TZ', letters: '\uA728' },
{
base: 'U',
letters:
'\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244',
}, | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
},
{ base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
{ base: 'VY', letters: '\uA760' },
{
base: 'W',
letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72',
},
{ base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
{
base: 'Y',
letters:
'\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE',
},
{
base: 'Z',
letters:
'\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762',
},
{
base: 'a',
letters:
'\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250\u0259',
},
{ base: 'aa', letters: '\uA733' },
{ base: 'ae', letters: '\u00E6\u01FD\u01E3' },
{ base: 'ao', letters: '\uA735' },
{ base: 'au', letters: '\uA737' },
{ base: 'av', letters: '\uA739\uA73B' },
{ base: 'ay', letters: '\uA73D' },
{
base: 'b',
letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253',
},
{
base: 'c',
letters:
'\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184\u0441',
},
{
base: 'd',
letters:
'\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A',
},
{ base: 'dz', letters: '\u01F3\u01C6' },
{
base: 'e',
letters:
'\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD',
},
{ base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
{
base: 'g',
letters:
'\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F',
},
{
base: 'h',
letters: | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
},
{
base: 'h',
letters:
'\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265',
},
{ base: 'hv', letters: '\u0195' },
{
base: 'i',
letters:
'\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131\u0456',
},
{ base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
{
base: 'k',
letters:
'\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3',
},
{
base: 'l',
letters:
'\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747',
},
{ base: 'lj', letters: '\u01C9' },
{ base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
{
base: 'n',
letters:
'\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5',
},
{ base: 'nj', letters: '\u01CC' },
{
base: 'o',
letters:
'\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275\u00F0',
},
{ base: 'oi', letters: '\u01A3' },
{ base: 'ou', letters: '\u0223' },
{ base: 'oo', letters: '\uA74F' },
{
base: 'p',
letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755',
},
{ base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
{
base: 'r',
letters:
'\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783',
},
{
base: 's',
letters:
'\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B',
},
{
base: 't',
letters: | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
},
{
base: 't',
letters:
'\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787',
},
{ base: 'thor', letters: '\u00FE' },
{ base: 'tz', letters: '\uA729' },
{
base: 'u',
letters:
'\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289\u03CB',
},
{ base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
{ base: 'vy', letters: '\uA761' },
{
base: 'w',
letters:
'\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73',
},
{ base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
{
base: 'y',
letters:
'\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF',
},
{
base: 'z',
letters:
'\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763',
},
]; | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
const diacriticsMap = {};
for (let i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
const letters = defaultDiacriticsRemovalMap[i].letters;
for (let j = 0; j < letters.length; j++) {
diacriticsMap[letters[j]] = defaultDiacriticsRemovalMap[i].base;
}
}
function remove_all_diacritics(sheet_name, get_range, row_set, col_set) {
// const sheet = SpreadsheetApp.getActive().getSheetByName(sheet_name);
// const values = sheet.getRange(get_range).getValues();
const values = [
['á', 'á', 'á', ''],
['á', 'b', 'á', 'á'],
['á', 'á', 'á', 'á'],
['á', 'á', 'á', 'á'],
['á', 'á', 'á', 'á'],
['æ', 'ø', 'å', 'á'],
['á', 'á', 'á', 'á'],
['á', 'á', 'á', 'á'],
['á', 'á', 'á', 'á'],
['á', 'á', 'á', 'á'],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
[, , ,],
];
const replace = (v) =>
Array.isArray(v)
? v.map((v) => replace(v))
: String(v).replace(/[^\u0000-\u007E]/g, (a) => diacriticsMap[a] || a);
// sheet.getRange(row_set, col_set, nv_arrays.length, nv_arrays[0].length).setValues(nv_arrays);
console.log(replace(values));
}
function rad() {
remove_all_diacritics('NoDiacritics', 'A1:D', 1, 6);
}
rad(); | {
"domain": "codereview.stackexchange",
"id": 43572,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
Title: Grouping arrays with different lengths to make a single sentValues() for the spreadsheet
Question: Currently I find out which is the biggest array and from it I generate a while loop and I go around errors with try catch:
function stackoverflow() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Ratings Time A');
var menu = [
['Atletico Lanus'],
['1795.72'],
['Atletico Lanus'],
['Independiente Jose Teran'],
['2.83 Fair'],
['2.77 Fair']
];
//Home Team
var home_team = [
['Fernando Monetti (GK)', '53'],
['Braian Aguirre (DF)', '60'],
['Nicolas Pasquini (DF)', '57'],
['Matias Pérez (DF)', '43'],
['Diego Braghieri (DF)', '47'],
['M. Gonzalez (MF)', '23'],
['Raul Loaiza (MF)', '41'],
['Tomas Belmonte (MF)', '62'],
['Lautaro Acosta (ST)', '63'],
['José Sand (ST)', '52']
];
// Away Team
var away_team = [
['Moisés Ramirez (GK)', '61'],
['Richard Schunke (DF)', '68'],
['Luis Segovia (DF)', '65'],
['Willian Vargas (DF)', '57'],
['Mateo Carabajal (DF)', '57'],
['Jhoanner Chavez (DF)', '52'],
['Fernando Gaibor (MF)', '60'],
['Junior Sornoza (MF)', '68'],
['Lorenzo Faravelli (MF)', '69'],
['Jonathan Bauman (ST)', '73'],
['Jaime Ayovi (ST)', '60'],
['Joan Lopez (GK)', '19']
]; | {
"domain": "codereview.stackexchange",
"id": 43573,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
final_array = [];
let i = 0;
let ct = Math.max(menu.length, home_team.length, away_team.length);
while (i < ct) {
try {
var menu_0 = menu[i];
} catch {
var menu_0 = '';
}
try {
var home_team_0 = home_team[i][0];
var home_team_1 = home_team[i][1];
} catch {
var home_team_0 = '';
var home_team_1 = '';
}
try {
var away_team_0 = away_team[i][0];
var away_team_1 = away_team[i][1];
} catch {
var away_team_0 = '';
var away_team_1 = '';
}
final_array.push([
menu_0,
home_team_0,
home_team_1,
'',
away_team_0,
away_team_1,
])
i++;
}
sheet.getRange(3, 1, final_array.length, final_array[0].length).setValues(final_array);
}
This setValues() to the spreadsheet is done to generate this result (note that there is an empty column between home_team and away_team:
I would like a review on this method that I am using to be able to group the lists in order to generate the correct sequence in the array to define in which column each index will be sent.
Answer:
Use const and let as needed instead of declaring all variables as var. This helps the javascript engine optimize the memory and processing of such variables
Practice DRY(Don't Repeat Yourself) principle. You repeat try...catch thrice. You can create a function instead and pass different variables like menu_0 to it.
In this case however, you can
Create a collection array( [menu, home_team, [], away_team];) with the order of arrays you want concatenated.
Create a output array with maximum length of all those arrays(Array(Math.max(...collection.map((a) => a.length))))
Use Array.map and Array.flatMap to concatenate inner arrays from collection | {
"domain": "codereview.stackexchange",
"id": 43573,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
javascript, array, google-apps-script, google-sheets
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function stackoverflowTheMaster() {
// const sheet = SpreadsheetApp.getActive().getSheetByName('Ratings Time A');
const menu = [
['Atletico Lanus'],
['1795.72'],
['Atletico Lanus'],
['Independiente Jose Teran'],
['2.83 Fair'],
['2.77 Fair'],
];
//Home Team
const home_team = [
['Fernando Monetti (GK)', '53'],
['Braian Aguirre (DF)', '60'],
['Nicolas Pasquini (DF)', '57'],
['Matias Pérez (DF)', '43'],
['Diego Braghieri (DF)', '47'],
['M. Gonzalez (MF)', '23'],
['Raul Loaiza (MF)', '41'],
['Tomas Belmonte (MF)', '62'],
['Lautaro Acosta (ST)', '63'],
['José Sand (ST)', '52'],
];
// Away Team
const away_team = [
['Moisés Ramirez (GK)', '61'],
['Richard Schunke (DF)', '68'],
['Luis Segovia (DF)', '65'],
['Willian Vargas (DF)', '57'],
['Mateo Carabajal (DF)', '57'],
['Jhoanner Chavez (DF)', '52'],
['Fernando Gaibor (MF)', '60'],
['Junior Sornoza (MF)', '68'],
['Lorenzo Faravelli (MF)', '69'],
['Jonathan Bauman (ST)', '73'],
['Jaime Ayovi (ST)', '60'],
['Joan Lopez (GK)', '19'],
];
const collection = [menu, home_team, [], away_team];
const output = Array(Math.max(...collection.map((a) => a.length)))
.fill()
.map((_, i) => collection.flatMap((a) => a[i]));
console.log(output);
// sheet
// .getRange(3, 1, final_array.length, final_array[0].length)
// .setValues(final_array);
}
stackoverflowTheMaster();
<!-- https://meta.stackoverflow.com/a/375985/ -->
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script> | {
"domain": "codereview.stackexchange",
"id": 43573,
"lm_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, array, google-apps-script, google-sheets",
"url": null
} |
c++
Title: C++ Graph class (undirected/directed, weighted/unweighted, adj list/adj mat)
Question: I wrote a rudimentary graph class that supports the following eight combinations:
Undirected/directed
Weighted/unweighted
Adj list/Adj matrix implementation
#include <algorithm>
#include <cassert>
#include <cmath>
#include <common.h>
#include <list>
#include <vector>
#include <ranges>
#include <stdexcept>
namespace frozenca::hard {
namespace detail {
template <typename Weight>
struct AdjListDescTrait {
using desc_type = std::pair<index_t, Weight>;
using edges_type = std::vector<std::list<desc_type>>;
static void add_edge(edges_type& edges, index_t src, index_t dst, float weight) {
edges[src].emplace_back(dst, weight);
}
static index_t proj(const desc_type& desc) noexcept {
return desc.first;
}
};
template <>
struct AdjListDescTrait<void> {
using desc_type = index_t;
using edges_type = std::vector<std::list<desc_type>>;
static void add_edge(edges_type& edges, index_t src, index_t dst) {
edges[src].emplace_back(dst);
}
static index_t proj(const desc_type& desc) noexcept {
return desc;
}
};
template <typename Weight>
struct AdjListTrait {
using desc_trait = AdjListDescTrait<Weight>;
using desc_type = desc_trait::desc_type;
using edges_type = desc_trait::edges_type;
using edge_iter_type = std::list<desc_type>::iterator;
using edge_const_iter_type = std::list<desc_type>::const_iterator;
using edge_range_type = std::ranges::subrange<edge_iter_type>;
using const_edge_range_type = std::ranges::subrange<edge_const_iter_type>;
static void resize(edges_type& edges, index_t new_size) {
auto old_size = curr_size(edges);
if (new_size < old_size) {
for (index_t i = 0; i < new_size; ++i) {
std::erase_if(edges[i], [&new_size](const auto& edge_desc) {
return desc_trait::proj(edge_desc) >= new_size;
});
}
}
edges.resize(new_size);
} | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
static index_t curr_size(const edges_type& edges) {
return std::ssize(edges);
}
static edge_range_type get_edges(edges_type& edges, index_t index) {
return edges[index];
}
static const_edge_range_type get_edges(const edges_type& edges, index_t index) {
return edges[index];
}
};
template <typename Weight>
struct AdjMatDescTrait {
using desc_type = Weight;
using edges_type = std::vector<desc_type>;
static void add_edge(edges_type& edges, index_t src, index_t dst, float weight) {
const auto curr_size = static_cast<index_t>(std::sqrt(std::ssize(edges)));
edges[src * curr_size + dst] = weight;
}
};
template <>
struct AdjMatDescTrait<void> {
using desc_type = int;
using edges_type = std::vector<desc_type>;
static void add_edge(edges_type& edges, index_t src, index_t dst) {
const auto curr_size = static_cast<index_t>(std::sqrt(std::ssize(edges)));
edges[src * curr_size + dst] = 1;
}
};
template <typename Weight>
struct AdjMatTrait {
using desc_trait = AdjMatDescTrait<Weight>;
using desc_type = desc_trait::desc_type;
using edges_type = desc_trait::edges_type;
using edge_iter_type = std::vector<desc_type>::iterator;
using edge_const_iter_type = std::vector<desc_type>::const_iterator;
using edge_range_type = std::ranges::subrange<edge_iter_type>;
using const_edge_range_type = std::ranges::subrange<edge_const_iter_type>; | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
static void resize(const edges_type& edges, index_t new_size) {
auto old_size = curr_size(edges);
if (new_size < old_size) {
for (index_t i = 0; i < new_size; ++i) {
for (index_t j = 0; j < new_size; ++j) {
edges[i * new_size + j] = edges[i * old_size + j];
}
}
}
edges.resize(new_size * new_size);
if (new_size > old_size) {
for (index_t i = old_size - 1; i >= 0; --i) {
for (index_t j = old_size - 1; j >= 0; --j) {
edges[i * new_size + j] = edges[i * old_size + j];
edges[i * old_size + j] = 0;
}
}
}
}
static index_t curr_size(const edges_type& edges) {
return static_cast<index_t>(std::sqrt(std::ssize(edges)));
}
static edge_range_type get_edges(edges_type& edges, index_t index) {
auto sz = curr_size(edges);
return {edges.begin() + index * sz, edges.begin() + (index + 1) * sz};
}
static const_edge_range_type get_edges(const edges_type& edges, index_t index) {
auto sz = curr_size(edges);
return {edges.begin() + index * sz, edges.begin() + (index + 1) * sz};
}
};
struct AdjListTraitTag {
template <bool Weighted, typename WeightType>
using edge_trait_type = AdjListTrait<std::conditional_t<Weighted, WeightType, void>>;
};
struct AdjMatTraitTag {
template <bool Weighted, typename WeightType>
using edge_trait_type = AdjMatTrait<std::conditional_t<Weighted, WeightType, void>>;
};
template <bool Directed, bool Weighted, typename WeightType,
typename EdgeTraitTag>
class GraphBase {
public:
using edge_trait = EdgeTraitTag::template edge_trait_type<Weighted, WeightType>;
using edges_type = edge_trait::edges_type;
using edge_iter_type = edge_trait::edge_iter_type;
using edge_const_iter_type = edge_trait::edge_const_iter_type;
private:
edges_type edges_;
[[nodiscard]] bool vertex_large(index_t index) const noexcept {
return index >= size();
} | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
[[nodiscard]] bool vertex_large(index_t index) const noexcept {
return index >= size();
}
[[nodiscard]] bool vertex_small(index_t index) const noexcept {
return index < 0;
}
[[nodiscard]] bool vertex_invalid(index_t index) const noexcept {
return vertex_small(index) || vertex_large(index);
}
public:
void index_check(index_t src, index_t dst) {
auto max_index = max(src, dst);
if (src < 0 || dst < 0) {
throw std::invalid_argument("vertex index is negative");
} else if (vertex_large(max_index)) {
edge_trait::resize(edges_, max_index + 1);
}
}
void add_edge(index_t src, index_t dst, WeightType w) requires (Weighted) {
index_check(src, dst);
edge_trait::desc_trait::add_edge(edges_, src, dst, w);
if constexpr (!Directed) {
edge_trait::desc_trait::add_edge(edges_, dst, src, w);
}
}
void add_edge(index_t src, index_t dst) requires (!Weighted) {
index_check(src, dst);
edge_trait::desc_trait::add_edge(edges_, src, dst);
if constexpr (!Directed) {
edge_trait::desc_trait::add_edge(edges_, dst, src);
}
}
auto edges(index_t src) {
if (vertex_invalid(src)) {
throw std::invalid_argument("vertex does not exist");
}
return edge_trait::get_edges(edges_, src);
}
auto edges(index_t src) const {
if (vertex_invalid(src)) {
throw std::invalid_argument("vertex does not exist");
}
return edge_trait::get_edges(edges_, src);
}
[[nodiscard]] index_t size() const noexcept {
return edge_trait::curr_size(edges_);
}
};
} // namespace detail
template <typename EdgeTraitTag = detail::AdjListTraitTag>
using Graph = detail::GraphBase<false, false, void, EdgeTraitTag>;
template <typename EdgeTraitTag = detail::AdjListTraitTag>
using DiGraph = detail::GraphBase<true, false, void, EdgeTraitTag>; | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
template <typename W = float, typename EdgeTraitTag = detail::AdjListTraitTag>
using WeightedGraph = detail::GraphBase<false, true, W, EdgeTraitTag>;
template <typename W = float, typename EdgeTraitTag = detail::AdjListTraitTag>
using WeightedDiGraph = detail::GraphBase<true, true, W, EdgeTraitTag>;
} // namespace frozenca::hard
Simple function that does topological sort for directed (acyclic, but not checked) graph:
void topological_sort_helper(const hard::WeightedDiGraph<> &g, std::vector<int> &visited,
std::vector<index_t> &top_sort, index_t i) {
visited[i] = true;
for (const auto &[dst, w] : g.edges(i)) {
if (!visited[dst]) {
topological_sort_helper(g, visited, top_sort, dst);
}
}
top_sort.push_back(i);
}
void top_sort(const hard::WeightedDiGraph<>& g) {
std::vector<index_t> top_sort;
auto V = g.size();
std::vector<int> visited(V);
assert(src < V);
for (index_t i = 0; i < V; ++i) {
if (!visited[i]) {
topological_sort_helper(g, visited, top_sort, i);
}
}
}
index_t is just std::ptrdiff_t.
It worked correctly for both adj_list/adj_matrix implementations.
I'm very new to trait-based class design, so I need your advice!
Answer: Compile errors
I had some issues compiling your code. I had to define index_t, but I guess that is expected. One case of max() which should be std::max(). And then there is the assert(src < V) inside top_sort(), but there is no src variable.
Header file location
I noticed you did #include <common.h>. If you include something with angle brackets (<>), then the compiler will search for the file in the standard system directories for header files, and optionally any directories specified using the -I option (for GCC and Clang). If common.h is a local file, you should instead includ using quotes, like so:
#include "common.h" | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
This will look for common.h in the same directory as the source file it's compiling. If indeed common.h is a local file, and only needed to compile your graph library (and not needed by an application that wants to link with your graph library), prefer quotes, as this avoids any ambiguity with a potential common.h file in the header file search path.
If you plan to have common.h be installed such that it's in the standard system header file locations, then consider that a name like common.h is too generic. What if another library also has a common.h? To solve this, make sure the header file is in a directory with a unique name for your library, for example such that you can do:
#include <frozenca/graph/common.h> | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
Don't be afraid of std::vector<bool>
Yes, it's a specialization which has a few issues, but for your use cases (visited and edges_type for adjacency matrices), it's perfectly fine, and much more efficient than std::vector<int>.
Don't use floating point math unnecessarily
For AdjMatDescTrait::add_edge(), you want to know the size of one dimension of the matrix. You store all elements in a 1D vector, so you take the square root of the size. However, this is very inefficient and dangerous: apart from conversion to float and back, floating point operations might not be as precise as you want. In particular, for double precision floating point numbers, integers above \$2^{53}\$ can not be accurately represented. I recommend just storing the width of the matrix as a separate member variable.
Consider allowing zero weights
In the case of an adjacency matrix, you treat a weight of zero is not having an edge. However, that is not always desirable. There are situations where a zero or negative weight can be assigned to existing edges. See also this question.
About the design
It's nice to have 8 different graph types that share the same interface. However, there are a lot of templated trait classes to support having a generic GraphBase, and then you have 4 aliases for specific graph types (and it would have been 8 if you didn't use the EdgeTraitTag template parameter). Adding other traits is going to be a lot of work.
There is also no room for data associated with vertices and edges, apart from their index and weight. What if you want to color your graph? What if vertices are identified by something other than a numerical index? Or maybe the indexing is sparse?
There are much more ways a graph can be stored than your class allows. I would therefore not create a class that stores the graph itself, but rather one that provides a mixin that is useful for providing a standard set of functions for concrete matrix classes. A very simplified example:
template<typename T> | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
template<typename T>
class GraphBase {
void add_edge(typename T::vertex_type src, typename T::vertex_type dst) {
T::edges[src].push_back(dst);
if constexpr (!T::directed) {
T::edges[dst].push_back(src);
}
}
}; | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
struct DiGraphData {
using vertex_type = int;
static constexpr bool directed = true;
std::map<vertex_type, std::deque<vertex_type>> edges;
};
using DiGraph = GraphBase<DiGraphData>;
In this example, all the traits are in DiGraphData, they are no longer scattered among multiple structs. There is a lot of freedom here, for example edges are now stored in a std::map of std::deques, but you can easily change those types. And GraphBase now only has a single template parameter. It can use SFINAE or concepts to determine what properties the data type has. In the example, a static constexpr bool is used as a tag to indicate whether it is a directed or undirected graph. But you can also check in GraphBase whether edges is a container of containers, or a single, flat container, and use that to determine if it's an adjacency list or matrix type graph, and thus how to correctly add a new edge to the graph. | {
"domain": "codereview.stackexchange",
"id": 43574,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
python, edit-distance
Title: Find all pairs of words that differ by one letter
Question: I have a list of words in English. My aim is to find all pairs of words that differ by exactly one letter (i.e. edit distance is 1). For instance: PAY-PLAY, WARM-ARM, WORD-WORK.
The naive algorithm is to compare every word with all other words in the list. I've improved it by noticing that if one word is two letters or more longer than the other word, then they can't differ by exactly one letter. So I first sort the word list by length, then compare every word with words of the same length or longer by one letter.
This is my code:
import nltk
words = ['a', 'abide', 'ability', 'able', 'about', 'above', ...]
words.sort(key=len)
pairs = []
for i, w1 in enumerate(words):
for j, w2 in enumerate(words[i+1:]):
if len(w2) - len(w1) > 1:
break
if nltk.edit_distance(w1, w2) == 1:
pairs.append((w1, w2))
Can it be improved further? It should scale well with the size of word list (I plan to run it with a list of tens of thousands of words).
Answer:
Sorting seems like a overkill. Assigning words to buckets feels more appropriate:
buckets = defaultdict(list)
for word in words:
buckets[len(word)].append(word)
Now all those not-nicely-looking ifs disappear:
for length, words in buckets:
get_pairs_same_length(words)
get_pairs_different_length(words, buckets[length + 1]
I don't think that nltk.edit_distance is a right tool here. You spend too much time calculating large distances between unrelated words. Since you are interested only in distance 1 it may make sense to do it manually:
For the words are of the same length, compare them letter by letter, allowing only one mismatch.
For the length differ by 1, again compare them letter by letter, allowing only one insertion. | {
"domain": "codereview.stackexchange",
"id": 43575,
"lm_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, edit-distance",
"url": null
} |
c++, strings
Title: C++ String utility functions - Code check
Question: I am trying to create a string class without std::string. Just for educational purpose.
So I created some utility functions, and it would be very nice if you guys could take a look at the code for mistakes.
Does anyone see any errors? (probably)
// Includes.
#include <iostream> // for "print()" and "std".
#include <sstream> // for "tostr()".
// Print.
template <typename Arg, typename... Args>
void print(Arg&& arg, Args&&... args) {
std::cout << std::forward<Arg>(arg);
((std::cout << ' ' << std::forward<Args>(args)), ...);
std::cout << std::endl;
}
// Allocate a new array.
template <class T>
T * alloc(
// The new size of the array.
size_t n
) {
T *a;
a = (T *) malloc((n + 1) * sizeof(T));
return a;
}
// Delete.
template <class T>
void del(T *x) {
delete[] x;
x = NULL;
}
// Length.
size_t len(const char* x) {
return ::strlen(x);
}
size_t len(char x) {
if (std::isblank(x)) { return 0; }
return 1;
}
// Cast const char* to char *.
char* strcast(const char* x, size_t n = -1) {
char *s;
if (n == -1) { n = len(x); }
s = alloc<char>(n); // real alloc size afterwards is n + 1
if (n == 0) {
s[0] = '\0';
return s;
}
return strcat(strcpy(s, x), "");
}
// String is null.
// Will cause segmentation fault if x is unallocated [const char x;], when x is [const char *x = ""] it will run.
bool strnull(const char* x) {
return (x == NULL || ! *x);
}
// Safely dump a string.
// Not necessary.
// Will cause segmentation fault if x is [const char x;], when x is [const char *x = ""] it will run.
// const char* strdump(const char* x) {
// return x;
// }
// char* strdump(char* x) {
// return x;
// }
// String equals.
// Will again cause segfault if x / y is unallocated [const char x;].
bool streq(const char* x, const char* y) {
return strcmp(x, y) == 0;
} | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, strings
// Char equals.
// Does not cause segfault if a / b is unallocated [char x].
bool chareq(char a, char b) {
if (std::isspace(a) and std::isspace(b)) { return true; }
return not (a < b) and not (a > b) and a == b;
}
// String from double.
template <class T>
char* tostr(T x) {
std::stringstream ss;
ss << x;
char *y;
y = ss.str().data();
return y;
}
// From string to double.
// Will cause segmentation fault if x is unallocated [const char x;], when x is [const char *x = ""] it will run.
float fromstr(const char* x) {
if (strnull(x)) { return 0; }
return std::atof(x);
}
// Concatenate multiple char*.
// Will cause segmentation fault if x / y is unallocated [const char x;], when x / y is [const char *x = ""] it will run.
char *strconcat(char *x, const char*y) {
size_t xn = strlen(x);
size_t yn = strlen(y);
char *z = alloc<char>(xn + yn);
memcpy(z, x, xn);
memcpy(z + xn, y, yn);
return z;
}
const char *strconcat(const char *x, const char *y) {
size_t xn = strlen(x);
size_t yn = strlen(y);
char *z = alloc<char>(xn + yn);
memcpy(z, x, xn);
memcpy(z + xn, y, yn);
return z;
}
char *strconcat(char *x) { return x; }
const char *strconcat(const char *x) { return x; }
template <class... Args> char *strconcat(char *x, const char *y, Args&&... args) { return strconcat(strconcat(x, y), args...); }
template <class... Args> const char *strconcat(const char *x, const char *y, Args&&... args) { return strconcat(strconcat(x, y), args...); } | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, strings
// Find substring in str.
// Will cause segmentation fault if str / substr is unallocated [const char x;], when str / substr is [const char *x = ""] it will run.
// class npos {
// public:
// size_t m_pos;
// bool found = false;
// npos() {};
// npos(size_t pos) { m_pos = pos; found = true; }
// npos(int pos) { if (pos > 0) { m_pos = pos; found = true; } }
// operator size_t() { return m_pos; }
// };
class nposclass {
public:
size_t m_pos;
nposclass() {}
operator size_t() { return m_pos; }
};
nposclass npos = nposclass();
size_t strfind(char* str, const char* substr) {
char *dest = strstr(str, substr);
if (dest == NULL) { return npos; };
return dest - str;
}
size_t strfind(char* str, const char* substr, size_t start) {
size_t i = strfind(str + start, substr);
if (i != -1) { return start + i; }
return i;
}
// Replace a substring in a string.
// Will cause segmentation fault if str / from / to is unallocated [const char x;], when str / from / to is [const char *x = ""] it will run.
char* strreplace(char* str, const char* from, const char* to, double increaser = 2.0) {
if (strnull(from)) { return str; }
size_t nt = strlen(to); // to size.
size_t nf = strlen(from); // from size.
size_t n = strlen(str); // str size.
size_t mn = n; // max alloc size.
char *result = alloc<char>(mn);
size_t nn = 0; // new size.
while (*str) {
// Found from.
if (strstr(str, from) == str) {
// Check resize.
if (nn + nt > mn) {
mn = (nn + nt) * increaser;
char *a = alloc<char>(mn);
memcpy(a, result, nn);
delete[] result; result = NULL;
result = a;
}
// Add to.
memcpy(&result[nn], to, nt);
nn += nt;
str += nf;
}
// Add current char.
else { result[nn++] = *str++; }
}
result[nn] = '\0';
return result;
} | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, strings
// Testing.
// Test code produces the warnings "ISO C++11 does not allow conversion from string literal to 'char *'", but that will be fixed by creating a string object.
int main() {
// strcast.
const char* x = "Hello";
char *y = strcast(x);
print("strcast:",y);
// strnull.
const char* x0 = "s ";
const char* x1 = "";
print("len: 2 ==>",strnull(x0));
print("len: 0 ==>", strnull(x1));
// len.
print("strnull: 0 ==>",strnull(x0));
print("strnull: 1 ==>", strnull(x1));
// streq.
print("streq: 0 ==>",streq(x0, x1));
print("streq: 1 ==>", streq(x1, x1));
// chareq.
char c;
print("chareq: 0 ==>", chareq('a', 'b'));
print("chareq: 1 ==>",chareq('a', 'a'));
print("chareq: 0 ==>",chareq('a', c));
// tostr.
char * y0 = tostr<double>(1.1);
print("tostr: 1.1 ==>", y0);
// fromstr.
double d0 = fromstr("1.1");
print("fromstr: 1.1 ==>", d0);
// Strconcat.
const char *x2 = "Hello";
x2 = strconcat(x2, " World!", " Howdy!");
print("strconcat: Hello World! Howdy =", x2);
char *y1 = "Hello";
y1 = strconcat(y1, " World!", " Howdy!");
print("strconcat: Hello World! Howdy =", y1);
// strfind.
print("strfind: 4 ==>", strfind("Hello World!", "o"));
print("strfind: 7 ==>", strfind("Hello World!", "o", 5));
print("strfind: 1 ==>", strfind("Hello World!", "?") == npos);
print("strfind: 0 ==>", strfind("Hello World!", "?") == 10);
// strreplace.
print("strreplace: Hello Universe! ==>", strreplace("Hello World!", "World", "Universe"));
print("strreplace: Hello! ==>", strreplace("Hello World!", " World", ""));
print("strreplace: Hello World! ==>", strreplace("Hello World!", "", ""));
return 0;
}
``` | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, strings
return 0;
}
```
Answer: Renaming built-in functions
If you are writing these functions for your own education, then I don't think you should be using built-in functions to implement them.
size_t len(const char* x) {
return ::strlen(x);
}
This could be written without any library functions as a for-loop using your len(char) function (if that's how you want to define the length of your string).
Similarly, these functions also merely rename language built-ins:
alloc just calls malloc() with nearly the same arguments (it should call new, see below).
del just calls delete[]
strfind just calls strstr()
fromstr just calls std::atof
You should be trying to write your functions without using the language's built-in functions so you can discover how they work. This does not apply to such low-level functions as malloc and delete[], but all functions operating on strings are doable.
Write your more complex functions in terms of the simpler functions you've written. You only use your len() function once and call strlen() everywhere else.
// String from double.
template <class T>
char* tostr(T x) {
std::stringstream ss;
ss << x;
char *y;
y = ss.str().data();
return y;
} | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, strings
Since ss.str() creates a std::string, this seems to go against the goals of this code.
Another problem with tostr() above: the char array returned by .data() is not null-terminated, so it can't be used with most string functions. You should use .c_str().
And another problem: you are returning the data from a temporary string that will be destroyed at the end of the function. When I run your code, I get the line: tostr: 1.1 ==> ⁿ⌡». I ran it again and got this: tostr: 1.1 ==> 4≈§☺<►. The function returns a pointer to destroyed data. You need to allocate space for the resulting string, store the pointer to that data in y, copy the new data to that pointer, and then return that pointer to the explicitly allocated data (that is, y).
Undefined behavior
Your alloc and del cannot be used together. Memory allocated with malloc must be deleted by calling free. The operator delete should only be used with pointers allocated with new. Mixing up these operators leads to undefined behavior, which means the compiler makes no guarantees about what the resulting program will do. Since this is C++, use new and delete.
class nposclass {
public:
size_t m_pos;
nposclass() {}
operator size_t() { return m_pos; }
};
The member m_pos is never assigned a value. Using the class like this is undefined behavior and may or may not function correctly.
Similary, char c in main() is never assigned a value.
Non-compiling code
If you want a function to be able to take a string literal as an argument, then it must take a const char*, not a char*. String literals cannot be modified. This is also why you cannot call strreplace on a string literal in the final lines of your main() function.
Functions like strfind should take const char* because a function that searches a string should not modify the string.
Other bits
// strnull.
const char* x0 = "s ";
const char* x1 = "";
print("len: 2 ==>",strnull(x0));
print("len: 0 ==>", strnull(x1)); | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, strings
You probably meant to test len() here, right?
The function strcast() is not really a cast. It creates a copy of a string. It should be renamed to reflect this behavior.
In your chareq() function, what does not (a < b) and not (a > b) and a == b accomplish that a == b doesn't?
Also, even though and, not, and or are synonyms for &&, !, and ||, respectively, they are very rarely used by C++ programmers. Using these words will cause some programmers to wonder if they opened a Python source file by mistake. :)
In many of your functions, spaces are treated specially, either by not being counted in the length of a char as in len(char) or by any space character being equal to any other space character--as in chareq(char, char). This should be documented somewhere in the code as a comment. | {
"domain": "codereview.stackexchange",
"id": 43576,
"lm_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++, strings",
"url": null
} |
c++, datetime, c++20, constrained-templates
Title: Constraining a templated method to accept any integral std::chrono::time_point
Question: Recently I was writing a class that had overloaded read methods for various data types. One of the sets of types I wanted to handle were integral std::chrono::time_points. For this I wrote the following code:
// Return a timestamp from a chunk at a given offset as if from an
// integer in network byte order
template <IsTimePoint T>
requires std::integral<typename T::rep>
[[nodiscard]] T read(length_t offset = 0) const {
return T{typename T::duration{read<typename T::rep>(offset)}};
}
Elsewhere I included a concept for matching time_point types:
template <typename T>
concept IsTimePoint =
requires {
typename T::clock;
typename T::duration;
typename T::rep;
typename T::period;
requires std::chrono::is_clock_v<typename T::clock>;
requires std::same_as<T,
std::chrono::time_point<typename T::clock,
std::chrono::duration<typename T::rep,
typename T::period>>>;
};
The code works. My question is whether this was a good way to solve this problem or whether there is a simpler solution that I have overlooked. Part of the reason for this project is for me to learn C++20, but I often worry that I might be using new techniques because they are new rather than because they are the right tool for the job.
Answer: It seems there is a simpler solution. Shamelessly stolen from this post:
template<class, template<class...> class>
static constexpr bool is_specialization = false;
template<template<class...> class T, class... Args>
static constexpr bool is_specialization<T<Args...>, T> = true;
template<class T>
concept IsTimePoint = is_specialization<T, std::chrono::time_point>; | {
"domain": "codereview.stackexchange",
"id": 43577,
"lm_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++, datetime, c++20, constrained-templates",
"url": null
} |
c++, datetime, c++20, constrained-templates
template<class T>
concept IsTimePoint = is_specialization<T, std::chrono::time_point>;
On the other hand, consider whether you really want to have the low-level function read() construct values of these high-level types. The calling code has to know what the type is of the integer that it reads, then it can construct an appropriate std::chrono::time_point from it itself. | {
"domain": "codereview.stackexchange",
"id": 43577,
"lm_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++, datetime, c++20, constrained-templates",
"url": null
} |
python, pandas
Title: Performance issue on updating a Pandas DataFrame with Series based on DateRange
Question: I have two Pandas data frames: one with Daily data and one with Weekly data.
I want to add the weekly data to each row of the daily data for each group of column A.
For example, for each row on the daily data frame from 2022/07/04 to 2022/07/09, I want to add the weekly data from 2022/07/04 for each group of column A and so on.
The code below reproduces the desired result:
Generate the data
import pandas as pd
import numpy as np
def generate_df(date_range):
tf_dict = []
for A in range(0,4000):
for d in date_range:
tf_dict.append({"A":A,
**{f"B_{i}":np.random.randint(0,10) for i in range(1,250)},
"datadate": d})
return pd.DataFrame(tf_dict)
# Daily Dataframe
daily_range = pd.date_range(start='1/1/2022', end='2/15/2022', freq='D')
df_daily = generate_df(daily_range)
# Weekly Dataframe
weekly_range = pd.date_range(start='1/1/2022', end='2/15/2022', freq='W')
df_weekly = generate_df(weekly_range)
df_weekly = df_weekly.add_prefix("higher_tf_")
Note that I took a range of 4000 for A for simplification. But with real data, A is close to 8000
Create the date range on the weekly data frame so it makes it easier to filter on the daily data frame
dfs = []
for i, dfg in df_weekly.groupby("higher_tf_A"):
dfg = dfg.sort_values("higher_tf_datadate")
dfg["higher_tf_next_date"] = dfg["higher_tf_datadate"].shift(-1)
dfs.append(dfg)
df_weekly = pd.concat(dfs)
(I added the next date to the previous row, so I have a date range on the same row)
For each weekly data, create a mask grouping on 'A' and the date range. Then update the daily rows with the weekly data. | {
"domain": "codereview.stackexchange",
"id": 43578,
"lm_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, pandas",
"url": null
} |
python, pandas
%%time
for index, row in df_weekly.iterrows():
mask = (df_daily["A"]==row["higher_tf_A"]) & \
(df_daily['datadate'] >= row['higher_tf_datadate']) & \
(df_daily['datadate'] < row['higher_tf_next_date'])
df_daily.loc[mask, row.index] = row.values
Results of %%time:
CPU times: user 1min 59s, sys: 4.34 s, total: 2min 3s Wall time: 2min 4s
How can I improve the last code to decrease execution time?
Note that the timeframes can change (e.g. Hourly and daily, minutes and hours, ...)
Answer: Broadly speaking, you've missed two of the most important mantras in Pandas:
Don't use loops. No, seriously. Don't use loops.
There's a thing for that.
Your generate_df is very slow. Replace it with a two-dimensional random matrix initialisation in one pass. Certainly A, and probably datadate should be index levels and not columns. There should probably also be an index level for B producing a dataframe with a triple-level index and one column, but that's beyond the scope of this question.
Don't use m/d/yyyy format; use ISO 8601.
Don't build up a dfs list only to call concat on it, don't call iterrows, and don't do manual date range comparisons. Make one call to merge_asof.
Don't use np.random.randint; that's deprecated.
Suggested
import pandas as pd
import numpy as np
from numpy.random import default_rng
rand = default_rng(seed=0)
def generate_df(
freq: str,
start: str = '2022-01-01', end: str = '2022-02-15',
n_a_vals: int = 4000, n_b_cols: int = 250,
) -> pd.DataFrame:
date_range = pd.date_range(start=start, end=end, freq=freq, name='datadate')
index = pd.MultiIndex.from_product((
pd.Series(data=np.arange(n_a_vals), name='A'),
date_range,
))
return pd.DataFrame(
rand.integers(size=(len(index), n_b_cols), low=0, high=10),
columns=[f'B_{i}' for i in range(n_b_cols)],
index=index,
)
df_daily = generate_df(freq='D')
df_weekly = generate_df(freq='W') | {
"domain": "codereview.stackexchange",
"id": 43578,
"lm_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, pandas",
"url": null
} |
python, pandas
df_daily = generate_df(freq='D')
df_weekly = generate_df(freq='W')
merged = pd.merge_asof(
left=df_daily.sort_values('datadate'),
right=df_weekly.sort_values('datadate'),
by='A', on='datadate',
suffixes=('', '_higher_tf'),
).set_index(['A', 'datadate']).sort_index()
print(merged)
Output
B_0 B_1 ... B_248_higher_tf B_249_higher_tf
A datadate ...
0 2022-01-01 8 6 ... NaN NaN
2022-01-02 2 2 ... 4.0 4.0
2022-01-03 0 3 ... 4.0 4.0
2022-01-04 1 7 ... 4.0 4.0
2022-01-05 5 0 ... 4.0 4.0
... ... ... ... ... ...
3999 2022-02-11 7 0 ... 3.0 1.0
2022-02-12 0 5 ... 3.0 1.0
2022-02-13 8 8 ... 5.0 1.0
2022-02-14 5 8 ... 5.0 1.0
2022-02-15 1 9 ... 5.0 1.0
[184000 rows x 500 columns]
Runs in about three seconds. | {
"domain": "codereview.stackexchange",
"id": 43578,
"lm_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, pandas",
"url": null
} |
python, datetime
Title: Formatting timestamps during autumn DST switchover
Question: I've written code that 99.x% of the time does the same thing as
def format(timestamp: datetime) -> str:
return timestamp.strftime("%X")
but follows the German "Sommerzeitverordnung" ("daylight savings time decree") during the hour before and after the autumn switchover.
Die Stunde von 2 Uhr bis 3 Uhr erscheint dabei zweimal. Die erste Stunde (von 2 Uhr bis 3
Uhr mitteleuropäischer Sommerzeit) wird mit 2A und die zweite Stunde (von 2 Uhr bis 3 Uhr mitteleuropäischer
Zeit) mit 2B bezeichnet.
(Sommerzeitverordnung, §2, Abs. 2, Satz 3-4)
Translation (by google translate with minor fixes by me)
The hour from 2 a.m. to 3 a.m. appears twice. The first hour (from 2 a.m. to 3 a.m.
Central European summer time) becomes 2A and the second hour (from 2 a.m. to 3 a.m. Central European
time) is denoted by 2B.
I've written the following pytests
from datetime import datetime
from zoneinfo import ZoneInfo
from timezone_formatting import format
def test_timestamp_without_marker() -> None:
assert "01:59:59" == format(datetime(
year=2022, month=10, day=30, hour=1, minute=59, second=59,
tzinfo=ZoneInfo('Europe/Berlin')))
assert "03:00:00" == format(datetime(
year=2022, month=10, day=30, hour=3, minute=0, second=0,
tzinfo=ZoneInfo('Europe/Berlin')))
def test_timestamp_during_last_hour_before_switchover() -> None:
assert "02A:00:00" == format(datetime(
year=2022, month=10, day=30, hour=2, minute=0, second=0,
fold=0,
tzinfo=ZoneInfo('Europe/Berlin')))
assert "02A:59:59" == format(datetime(
year=2022, month=10, day=30, hour=2, minute=59, second=59,
fold=0,
tzinfo=ZoneInfo('Europe/Berlin'))) | {
"domain": "codereview.stackexchange",
"id": 43579,
"lm_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, datetime",
"url": null
} |
python, datetime
def test_timestamp_during_first_hour_after_switchover() -> None:
assert "02B:00:00" == format(datetime(
year=2022, month=10, day=30, hour=2, minute=0, second=0,
fold=1,
tzinfo=ZoneInfo('Europe/Berlin')))
assert "02B:59:59" == format(datetime(
year=2022, month=10, day=30, hour=2, minute=59, second=59,
fold=1,
tzinfo=ZoneInfo('Europe/Berlin')))
and the following code, which passes the tests:
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
utc = timezone.utc
germany = ZoneInfo("Europe/Berlin")
offset = timedelta(hours=1)
def switchover_letter(timestamp: datetime) -> str:
"""
Returns "A" if timestamp is in the last hour of daylight savings time.
Returns "B" if timestamp is in the first hour of standard time.
Else returns an empty string
"""
utc_timestamp = timestamp.astimezone(utc)
if (utc_timestamp + offset).astimezone(germany).hour == timestamp.hour:
return "A"
if (utc_timestamp - offset).astimezone(germany).hour == timestamp.hour:
return "B"
return ""
def format(timestamp: datetime) -> str:
return (
timestamp.strftime("%H")
+ switchover_letter(timestamp)
+ timestamp.strftime(":%M:%S")
)
But, there are two things that kind of raise red flags for me:
Calling strftime twice on the same timestamp and inserting my own formatting in between seems wrong. Is there a format specifier for strftime I have missed, or is there something else I could do to make this less icky?
Manually doing time manipulation in switchover_letter. I'm reasonably sure that my code is correct, but is it really? Is there a way to do this less manually? Note that doing this without the roundtrip to UTC doesn't work, because "timezone aware timestamp + offset" uses wall time.
Answer: Overall this is well-written.
Don't call a function format; that shadows a built-in. | {
"domain": "codereview.stackexchange",
"id": 43579,
"lm_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, datetime",
"url": null
} |
python, datetime
Answer: Overall this is well-written.
Don't call a function format; that shadows a built-in.
Calling strftime twice on the same timestamp and inserting my own formatting in between seems wrong. Is there a format specifier for strftime I have missed, or is there something else I could do to make this less icky?
Your instincts are correct; prefer instead:
def daylight_savings_format(timestamp: datetime) -> str:
return '{0:%H}{1}:{0:%M:%S}'.format(
timestamp, switchover_letter(timestamp)
)
Or do two passes where you first format a datetime-field string with your middle character and then pass that to strftime, as in
def daylight_savings_format(timestamp: datetime) -> str:
fmt = f'%H{switchover_letter(timestamp)}:%M:%S'
return timestamp.strftime(fmt)
I have a weak preference for the former. | {
"domain": "codereview.stackexchange",
"id": 43579,
"lm_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, datetime",
"url": null
} |
c++, graph, library
Title: Library to represent graphs
Question: I have been working on a library to represent graphs (directed graphs and undirected graphs). I know that there are already many such libraries but I wanted to create my own as a learning exercise.
I have not tested the library extensively so there are likely to be bugs etc. But what I am really interested in is the design of the library - I spent quite a while thinking about the best design for the interface etc.
There is an abstract base class which DiGraph (directed graph) and UDiGraph (undirected graph) inherit from. I have designed as a template so that each Vertex and each Edge can have an associated user supplied object.
Thanks
// Graph.h
#include <map>
#include <set>
#include <stdexcept>
#include <algorithm>
#include <optional>
#ifndef GRAPH_H
#define GRAPH_H
namespace GLib
{
template <class V, class E>
class GraphABC
{
// TYPES/DEFINITIONS
public:
using VertexID = signed int;
protected:
GraphABC(){} // makes class abstract
using EdgeObjectID = unsigned int;
using VertexEdgeMapping = std::multimap<VertexID, EdgeObjectID>;
enum EDGE_OBJECT_CODE {NO_EDGE_OBJECT = -1};
public:
using EdgeIterator = VertexEdgeMapping::const_iterator;
using VertexIterator = typename std::map<VertexID, V>::const_iterator;
//MEMBERS
public:
// vertex member functions
bool vertexExists(VertexID vertex) const
{
return mVertices.count(vertex);
}
V getVertexObject(VertexID vertex) const
{
if (!vertexExists(vertex))
{
throw std::out_of_range("no such vertex");
}
if (!vertexHasObject(vertex))
{
throw std::invalid_argument("vertex has no such object");
}
return mVertices.at(vertex).value();
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
bool vertexHasObject(VertexID vertex) const
{
return mVertices.at(vertex).has_value();
}
VertexIterator verticesBegin() const
{
return mVertices.cbegin();
}
VertexIterator verticesEnd() const
{
return mVertices.cend();
}
GraphABC<V,E>& addVertex(VertexID idForNewVertex, const V& vertexOb)
{
if ( vertexExists(idForNewVertex) )
{
throw std::invalid_argument("ID already exists");
}
mVertices[idForNewVertex] = vertexOb; // create vertex
mEdges.insert(std::pair<VertexID, VertexEdgeMapping>(idForNewVertex, VertexEdgeMapping())); // insert vertex in list of edges (empty by default)
return *this;
}
VertexID addVertex(const V& vertexOb)
{
for(VertexID potentialId = 0; ; ++potentialId)
{
if (mVertices.count(potentialId) == 0)
{
mVertices[potentialId] = vertexOb;
mEdges.insert(std::pair<VertexID, VertexEdgeMapping>(potentialId, VertexEdgeMapping())); // insert vertex in list of edges (empty by default)
return potentialId;
}
}
}
GraphABC<V,E>& addVertex(VertexID idForNewVertex)
{
if (vertexExists(idForNewVertex))
{
throw std::invalid_argument("ID already exists");
}
mVertices[idForNewVertex] = std::nullopt; // no vertex object
mEdges.insert(std::pair<VertexID, VertexEdgeMapping>(idForNewVertex, VertexEdgeMapping())); // insert vertex in list of edges (empty by default)
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
bool setVertexObject(VertexID vertex, const V& vertexOb)
{
if (!vertexExists(vertex))
{
throw std::out_of_range("no such vertex");
}
mVertices[vertex] = vertexOb;
return true;
}
bool deleteVertex(VertexID vertexToDelete)
{
if (!vertexExists(vertexToDelete))
{
throw std::out_of_range("no such vertex");
}
mVertices.erase(vertexToDelete);
mEdges.erase(vertexToDelete); // delete all elements in map where key is vector
for ( auto it = mEdges.begin(); it != mEdges.end(); ++it )
{
it->second.erase(vertexToDelete); // loop through elements of mmap and delete any value which is vector
}
removeRedundantEdgeObjects(); // delete unused edges
return true;
}
EdgeIterator edgesOfVertexBegin(VertexID vertex) const
{
if (!vertexExists(vertex))
{
throw std::out_of_range("no such vertex");
}
return mEdges.at(vertex).cbegin();
}
EdgeIterator edgesOfVertexBegin(VertexID originVertex, VertexID destVertex) const
{
if (!vertexExists(originVertex) || !vertexExists(destVertex))
{
throw std::out_of_range("no such vertex");
}
return mEdges.at(originVertex).lower_bound(destVertex);
}
EdgeIterator edgesOfVertexEnd(VertexID vertex) const
{
if (!vertexExists(vertex))
{
throw std::out_of_range("no such vertex");
}
return mEdges.at(vertex).cend();
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
EdgeIterator edgesOfVertexEnd(VertexID originVertex, VertexID destVertex)
{
if (!vertexExists(originVertex) || !vertexExists(destVertex))
{
throw std::out_of_range("no such vertex");
}
return mEdges.at(originVertex).upper_bound(destVertex);
}
bool edgeObjectExists(EdgeObjectID edgeObjectID) const
{
return mEdgeObjects.count(edgeObjectID);
}
E getEdgeObject(EdgeObjectID edgeObjectID) const
{
if (mEdgeObjects.count(edgeObjectID) == 0)
{
throw std::out_of_range("no such edge object");
}
return mEdgeObjects.at(edgeObjectID);
}
void setEdgeObject(EdgeObjectID edgeObjectID, const E& edgeObject)
{
if (mEdgeObjects.count(edgeObjectID) == 0)
{
throw std::out_of_range("no such edge object");
}
mEdgeObjects[edgeObjectID] = edgeObject;
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
// convenience functions
std::set<VertexID> adjacentVertices(VertexID vertex) const
{
if (!vertexExists(vertex))
{
throw std::out_of_range("no such vertex");
}
std::set<VertexID> adjVertices;
for (auto edgeIt = edgesOfVertexBegin(vertex); edgeIt != edgesOfVertexEnd(vertex); ++edgeIt)
{
adjVertices.insert((*edgeIt).first);
}
return adjVertices;
}
std::set<VertexID> adjacentVertices(VertexID vertex, std::function<bool (VertexID)> evalFunc)
{
if (!vertexExists(vertex))
{
throw std::out_of_range("no such vertex");
}
std::set<VertexID> adjVertices;
for (auto edgeIt = edgesOfVertexBegin(vertex); edgeIt != edgesOfVertexEnd(vertex); ++edgeIt)
{
if ( evalFunc( (*edgeIt).first ) )
{
adjVertices.insert((*edgeIt).first);
}
}
return adjVertices;
}
protected:
std::map<VertexID, VertexEdgeMapping> mEdges;
std::map<EdgeObjectID, E> mEdgeObjects;
std::map< VertexID, std::optional<V> > mVertices;
EdgeObjectID addEdgeObject(const E& e)
{
for (EdgeObjectID potentialID = 0; ;++potentialID)
{
if (mEdgeObjects.count(potentialID) == 0)
{
mEdgeObjects[potentialID] = e;
return potentialID;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
size_t removeRedundantEdgeObjects() // delete any edge objects which are not used in any edges
{
std::set<EdgeObjectID> currentEdgeObjectIDs, edgeObjectIDsInEdges;
for(auto edgeObjectIt = mEdgeObjects.begin(); edgeObjectIt!= mEdgeObjects.end(); ++edgeObjectIt)
{
currentEdgeObjectIDs.insert((*edgeObjectIt).first);
}
for(typename decltype(mEdges)::iterator it = mEdges.begin(); it != mEdges.end(); ++it)
{
for(VertexEdgeMapping::iterator mappingIt = (*it).second.begin(); mappingIt!=(*it).second.begin(); ++mappingIt)
{
if ((*mappingIt).second == NO_EDGE_OBJECT )
{
continue;
}
edgeObjectIDsInEdges.insert((*mappingIt).second);
}
}
std::set<EdgeObjectID> redundantEdgeObjects;
std::set_difference(currentEdgeObjectIDs.begin(), currentEdgeObjectIDs.end(),
edgeObjectIDsInEdges.begin(), edgeObjectIDsInEdges.end(),
std::inserter(redundantEdgeObjects, redundantEdgeObjects.begin()) );
for(EdgeObjectID redundantEdgeID : redundantEdgeObjects)
{
mEdgeObjects.erase(redundantEdgeID);
}
return redundantEdgeObjects.size();
}
};
template <class V, class E>
class DiGraph : public GraphABC <V, E>
{
public:
using VertexID = typename GraphABC<V,E>::VertexID;
using EdgeObjectID = typename GraphABC<V,E>::EdgeObjectID;
using EdgeIterator = typename GraphABC<V,E>::EdgeIterator; | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
DiGraph<V,E>& addEdgeFromTo(VertexID vertex_1, VertexID vertex_2, const E& edgeToAdd)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2) )
{
throw std::out_of_range("vertex does not exist");
}
EdgeObjectID generatedEdgeObjectID = GraphABC<V,E>::addEdgeObject(edgeToAdd);
this->mEdges[vertex_1].insert(std::pair<VertexID, EdgeObjectID> (vertex_2, generatedEdgeObjectID) );
return *this;
}
DiGraph<V,E>& addEdgeFromTo(VertexID vertex_1, VertexID vertex_2, EdgeObjectID edgeIdToUse)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2))
{
throw std::out_of_range("vertex does not exist");;
}
if (this->mEdgeObjects.count(edgeIdToUse) == 0 )
{
throw std::out_of_range("edge object does not exist");
}
this->mEdges[vertex_1].insert(std::pair<VertexID, EdgeObjectID>(vertex_2, edgeIdToUse));
return *this;
}
DiGraph<V,E>& addEdgeFromTo(VertexID vertex_1, VertexID vertex_2)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2) )
{
throw std::out_of_range("vertex does not exist");
}
this->mEdges[vertex_1].insert(std::pair<VertexID, EdgeObjectID>(vertex_2, GraphABC<V,E>::NO_EDGE_OBJECT));
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
size_t deleteAllEdgesFrom(VertexID vertex)
{
if ( !GraphABC<V,E>::vertexExists(vertex) )
{
return false;
}
size_t deletedEdgeCount = this->mEdges[vertex].size();
this->mEdges[vertex].clear(); // use clear not erase - still need key if vector exists
GraphABC<V,E>::removeRedundantEdgeObjects();
return deletedEdgeCount;
}
size_t deleteAllEdgesFromTo(VertexID vertex_1, VertexID vertex_2)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2) )
{
return false;
}
size_t deletedEdgeCount = this->mEdges[vertex_1].erase(vertex_2);
GraphABC<V,E>::removeRedundantEdgeObjects();
return deletedEdgeCount;
}
void deleteEdgeFrom(VertexID vertex, EdgeIterator edgeIt)
{
if ( !GraphABC<V,E>::vertexExists(vertex) )
{
throw std::out_of_range("vertex does not exist");;
}
this->mEdges[vertex].erase(edgeIt);
GraphABC<V,E>::removeRedundantEdgeObjects();
}
private:
};
template <class V, class E>
class UDiGraph : public GraphABC<V,E>
{
public:
using VertexID = typename GraphABC<V,E>::VertexID;
using EdgeObjectID = typename GraphABC<V,E>::EdgeObjectID;
using EdgeIterator = typename GraphABC<V,E>::EdgeIterator; | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
UDiGraph<V,E>& addEdgeBetween(VertexID vertex_1, VertexID vertex_2, const E& edgeToAdd)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2) )
{
throw std::out_of_range("vertex does not exist");
}
EdgeObjectID generatedEdgeObjectID = GraphABC<V,E>::addEdgeObject(edgeToAdd);
// add mirror edges
this->mEdges[vertex_1].insert(std::pair<VertexID, EdgeObjectID> (vertex_2, generatedEdgeObjectID) );
this->mEdges[vertex_2].insert(std::pair<VertexID, EdgeObjectID>(vertex_1, generatedEdgeObjectID));
return *this;
}
UDiGraph<V,E>& addEdgeBetween(VertexID vertex_1, VertexID vertex_2, EdgeObjectID edgeIdToUse)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2))
{
throw std::out_of_range("vertex does not exist");;
}
if (this->mEdgeObjects.count(edgeIdToUse) == 0 )
{
throw std::out_of_range("edge object does not exist");
}
this->mEdges[vertex_1].insert(std::pair<VertexID, EdgeObjectID>(vertex_2, edgeIdToUse));
this->mEdges[vertex_2].insert(std::pair<VertexID, EdgeObjectID>(vertex_1, edgeIdToUse));
return *this;
}
UDiGraph<V,E>& addEdgeBetween(VertexID vertex_1, VertexID vertex_2)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) || !GraphABC<V,E>::vertexExists(vertex_2) )
{
throw std::out_of_range("vertex does not exist");
}
this->mEdges[vertex_1].insert(std::pair<VertexID, EdgeObjectID>(vertex_2, GraphABC<V,E>::NO_EDGE_OBJECT));
this->mEdges[vertex_2].insert(std::pair<VertexID, EdgeObjectID>(vertex_1, GraphABC<V,E>::NO_EDGE_OBJECT));
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
void deleteEdgeFrom(VertexID vertex, EdgeIterator edgeIt)
{
if ( !GraphABC<V,E>::vertexExists(vertex) )
{
throw std::out_of_range("vertex does not exist");;;
}
// store vertex details before deleting
VertexID adjVertex = (*edgeIt).first;
EdgeObjectID eObId = (*edgeIt).second;
// delete outward edge
this->mEdges[vertex].erase(edgeIt);
// delete inward edge
for(EdgeIterator adjVertexEdgeIt = GraphABC<V,E>::edgesOfVertexBegin(adjVertex, vertex); adjVertexEdgeIt != GraphABC<V,E>::edgesOfVertexEnd(adjVertex, vertex); ++adjVertexEdgeIt)
{
if ( (*adjVertexEdgeIt).second == eObId ) // delete mirrored edge with same object ID
{
this->mEdges[adjVertex].erase(adjVertexEdgeIt);
GraphABC<V,E>::removeRedundantEdgeObjects();
return;
}
}
throw std::logic_error("could not find corresponding edge to delete");
}
size_t deleteAllEdgesBetween(VertexID vertex_1, VertexID vertex_2)
{
if ( !GraphABC<V,E>::vertexExists(vertex_1) && !GraphABC<V,E>::vertexExists(vertex_2) )
{
throw std::out_of_range("vertex does not exist");
}
this->mEdges[vertex_1].erase(vertex_2);
size_t deletedEdges = this->mEdges[vertex_2].erase(vertex_1);
GraphABC<V,E>::removeRedundantEdgeObjects();
return deletedEdges;
}
private:
};
}
#endif
// main.cpp
#include <iostream>
#include "Graph.h"
using namespace GLib;
int main()
{
// example of directed graph
DiGraph<std::string, std::string> graph; | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
int main()
{
// example of directed graph
DiGraph<std::string, std::string> graph;
DiGraph<std::string, std::string>::VertexID A = graph.addVertex("A"); // 0
DiGraph<std::string, std::string>::VertexID B = graph.addVertex("B"); // 1
DiGraph<std::string, std::string>::VertexID C = graph.addVertex("C"); // 2
DiGraph<std::string, std::string>::VertexID D = graph.addVertex("D"); // 3
DiGraph<std::string, std::string>::VertexID E = graph.addVertex("E"); // 4
DiGraph<std::string, std::string>::VertexID F = graph.addVertex("F"); // 5
graph.addEdgeFromTo(A, B, "A to B");
graph.addEdgeFromTo(A, C, "A to C");
graph.addEdgeFromTo(C, D, "C to D");
graph.addEdgeFromTo(C, D, "c to d");
graph.addEdgeFromTo(D, E, "D to E");
graph.addEdgeFromTo(D, F, "D to F");
// print all outward edges of C
for (auto it = graph.edgesOfVertexBegin(C); it!=graph.edgesOfVertexEnd(C); ++it)
{
std::cout << graph.getEdgeObject ( (*it).second ) << std::endl;
}
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
Answer: Prefer = default over {}
When you have to explicitly define a constructor (or other special member function) but it shouldn't do anything, prefer = default over {}. See this post for more information why.
Don't use .count() if you only want to know if something exists
count() tries to count all matches, which might take more effort than just checking if there is any match. For a std::map, this might not matter, but for a std::multimap it does. But to avoid any doubt, prefer using find(), or if you can use C++20, use contains().
Consider returning vertices by const reference
If V is a potentially large and/or non-copyable object, returning by value can be problematic. Consider returning by const reference.
Inconsistent and useless return types
It's weird to have two overloads over addVertex(), one returns a VertexID, the other returns a reference to *this. Instead of having addVertex(const V&), consider adding a function that returns an unused VertexID, which can then be used as input for the other overload of addVertex().
Why do setVertexObject() and deleteVertex() return a bool, when they always return true? Either I expect errors to cause false to be returned instead of exceptions being thrown, or the function should return void.
Inconsistent use of at()
Sometimes you use at(), other times you use []. Using at() will cause an exception being thrown if the key cannot be found. If you are checking if vertexExists() anyway, then at() is redundant. Conversely, you can just do:
const V& getVertexObject(VertexID vertex) const
{
return mVertices.at(vertex).value();
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
And at() and value() will throw expections if the vertex ID does not exist or there is no value for that ID, so you don't need to explicitly check for that yourself.
Use -> where appropriate
Instead of (*foo).bar, write the more idiomatic foo->bar.
Use range-for where appropriate
Instead of manually looping with iterators, use range-based for loops where possible. This simplifies your code and leaves less chance for errors. For example:
for (auto& it: mEdges)
{
it.second.erase(vertexToDelete);
}
It becomes even nicer for maps if you use structured bindings:
for (auto& [vertexID, edgeMapping]: mEdges)
{
edgeMapping.erase(vertexToDelete);
}
Also consider making your graph class be usable in range-for loops, by renaming verticesBegin() and verticesEnd() to begin() and end(). Even better, add a member function edgesOfVertex() that returns a const reference to an element of mEdges, so that you can write:
for (auto& [vertexID, edgeID]: graph.edgesOfVertex(C))
{
std::cout << graph.getEdgeObject(edgeID) << '\n';
}
Make use of emplace()
Instead of insert(), consider using emplace() to simplify your code. Instead of:
mEdges.insert(std::pair<VertexID, VertexEdgeMapping>(idForNewVertex, VertexEdgeMapping()));
You can write:
mEdges.emplace(idForNewVertex, VertexEdgeMapping());
Of course you could also just have written:
mEdges[idForNewVertex] = {};
Faster way of finding a free VertexID
In addVertex(const V&), you are linearly searching through mVertices to find an unused ID. If you have never deleted any IDs, this is an \$O(V)\$ operation, where \$V\$ is the number of vertices. However, since it's OK to have holes in the range of used vertex IDs, you can simply look for the highest vertex ID present, and just add one to that:
if (mVertices.empty())
{
potentialID = 0;
}
else
{
potentialID = (mVertices.end() - 1)->first + 1;
} | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
c++, graph, library
Of course you might need to worry about what happens when the ID becomes so large that it doesn't fit in a signed int anymore, in which case you might want to have a fallback to linearly scan for available IDs again.
And this only works when using std::map, as that keeps the elements sorted. Which brings me to:
Consider using std::unordered_map
Most operations don't require that vertices and edges are sorted by their ID. Consider using std::unordered_maps instead, as they have \$O(1)\$ lookups instead of the \$O(\log N)\$ lookup time of std::map.
Do you need so many maps?
You have three maps; one that stores the vertex objects, one that stores edge objects, and one that stores the adjacency information. You have VertexIDs, which are indeed helpful to distinguish vertices, but then you also have EdgeObjectIDs, and those seem redundant to me: edges can already be uniquely identified by two vertex IDs. For undirected graphs, you can use the rule that given two vertex IDs, the unique edge ID is always formed by the lower vertex ID first, then the higher vertex ID.
Consider creating a struct Vertex to pack the vertex object and the set of edges it has:
struct Vertex {
std::optional<V> object;
std::map<VertexID, E> edges;
};
Now you need only a single member variable to hold the whole graph:
std::map<VertexID, Vertex> mVertices; | {
"domain": "codereview.stackexchange",
"id": 43580,
"lm_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++, graph, library",
"url": null
} |
javascript, node.js, file-system
Title: Generate a nested structure based on a list of file paths
Question: I'm currently working on a small application, as a learning exercise for a Javascript novice. I need to generate an object based on a folder structure. Here is an example of the folder structure:
RootFolder/FolderA/FolderB/FileA
RootFolder/FolderA/FolderB/FileB
RootFolder/FolderA/FolderB/FolderC/FileA
RootFolder/FolderA/FolderB/FolderC/FileB
The desired resulting object should have the following structure:
{
RootFolder: {
FolderA: {
FolderB: {
FileA: {},
FileB: {},
FolderC: {
FileA: {},
FileB: {}
}
}
}
}
};
So far I came up with the following code and it seems to be doing the job, but I'm concerned with 'eval' use and generally believe there is a more elegant way of doing it.
module.exports = {
structure: function(structureArray) {
var generatedObject = {};
for (var i = 0; i < structureArray.length; i++) {
var objectElements = '';
var path = (structureArray[i].split('/')).filter(Boolean);
for (var l = 0; l < path.length; l++) {
if (objectElements.indexOf(path[l]) == -1 || path[l].length == 1) {
objectElements += '["' + path[l] + '"]';
}
if (!(eval('generatedObject' + objectElements))) {
eval('generatedObject' + objectElements + '= {}')
}
}
}
return generatedObject;
}
};
structureArray contains full path strings as in the folder structure example above (e.g. 'RootFolder/FolderA/FolderB/FileA')
Answer: You can split each path at / using split and then use reduce() to build that object.
var paths = [
'RootFolder/FolderA/FolderB/FileA',
'RootFolder/FolderA/FolderB/FileB',
'RootFolder/FolderA/FolderB/FolderC/FileA',
'RootFolder/FolderA/FolderB/FolderC/FileB'
] | {
"domain": "codereview.stackexchange",
"id": 43581,
"lm_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, node.js, file-system",
"url": null
} |
javascript, node.js, file-system
var obj = {}
paths.forEach(function(path) {
path.split('/').reduce(function(r, e) {
return r[e] || (r[e] = {})
}, obj)
})
console.log(obj)
Here is how you can use this approach to read some directory and all of its nested content and create object from that. This approach is synchronous.
var fs = require('fs');
var path = require('path');
var p = path.resolve('C:\\your\\path\\here')
var result = {}
function buildObject(startPath) {
var dir = fs.readdirSync(startPath)
dir.forEach(function(e) {
var newPath = path.join(startPath, e)
var stat = fs.statSync(newPath);
if (stat && stat.isDirectory()) buildObject(newPath)
if (stat.isFile()) {
newPath.split('\\').reduce(function(r, a) {
return r[a] || (r[a] = {})
}, result)
}
})
}
buildObject(p)
console.log(result) | {
"domain": "codereview.stackexchange",
"id": 43581,
"lm_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, node.js, file-system",
"url": null
} |
python, python-3.x
Title: Calculating the nth term of a sequence - Python 3.9.5
Question: I decided to try and make a code that can calculate the n-th term of any sequence (any sequence that only contains n^a, sequences like a^n and n! won't work) and calculate the next numbers of the sequence to further my understanding of Python, here it is:
from math import factorial
from fractions import Fraction
class nthTerm:
"""
Calculates the nth term (or stores it) with reasonable accuracy, and allows you
to enter a 'n' value and get the value based on the nth term.
If 'sequence' is set to False, you can input a list with an nth term instead of
a sequence. The list needs to be written the same way as self.calc is if
sequence is set to false so [[3, 2], [1, 1], [2, 0]] would be 3n^2 + n + 2 for example
and the input of that to __init__ would look like: nthTerm([3, 2], [1, 1], [2, 0], sequence = False
"""
def __init__(self, *values, sequence = True):
self.sequence = sequence
self.values = []
if sequence:
#if a sequence was entered
oldValues = values
self.values = values
self.fraction = True # changes the output type in str(self) from fraction to decimal - not implemented yet
self.calc = [] # the n-th term pattern will be saved here
difference = []
while [values[0]] * len(values) != values:
pattern = False
iterCount = 1
while not pattern: # while the differences of the values aren't all the same | {
"domain": "codereview.stackexchange",
"id": 43582,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
differenceLen = len(values) - 1
for n in range(differenceLen):
difference.append(Fraction(values[n+1]) - Fraction(values[n])) # gets the difference of each of the values
pattern = [difference[0]] * differenceLen == difference # checks if all of the values in 'pattern' are equal (if so, then the pattern is found)
if not pattern: # didn't find a pattern with n^x, lets raise the iterCount and try with n^x+1
values = difference
difference = []
iterCount += 1
coefficientOfN = Fraction(difference[0], factorial(iterCount)) # this is essentially difference[0] / factorial(iterCount)
# print(f"{str(coefficientOfN)}n^{iterCount} found in the sequence!") <- for testing
self.calc.append([coefficientOfN, iterCount]) # adds the found pattern to self.calc so it can be used in calculations later on
patternFound = [coefficientOfN * (n ** iterCount) for n in range(1, len(self.values)+1)] # makes a list of the nth term of the found pattern and...
values = []
difference = []
for n in range(len(self.values)):
values.append(Fraction(self.values[n]) - Fraction(patternFound[n])) # ...takes that away from the original values
self.values = values
self.values = list(oldValues)
if values[0] != 0: # if there's a common number in the list that isn't 0 (eg [1,1,1,1,1])
# print(f"{values[0]} found in the equation!") <- for testing
self.calc.append([values[0], 0]) # takes that value away from the list and adds it to the nth term
else: | {
"domain": "codereview.stackexchange",
"id": 43582,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
else:
# sequence not entered, the nth term was entered instead
# the nth term should've been entered in the same way as self.calc stores it:
# as a 2D list: [[3, 2], [1, 1], [2, 0]] for example would be 3n^2 + n + 2
for value in values:
# all of the lists in 'values' should have a length of 2, since they only contain the
# coefficient of n and the power of n
if len(value) != 2:
raise ValueError(f"'{value}' does not have a length of 2, which is required as an input when 'sequence' is set to False.")
powerList = [values[n][1] for n in range(len(values))] #makes a list of all of the powers
# there shouldn't be any repeats in 'powerlist', check for that is below:
# we can do this by converting the list into a set (which gets rid of any duplicate values) and check if the length is erqual to the original list
if len(powerList) != len(set(powerList)):
raise ValueError("Many lists with the same power value inputted.")
# input verification above
self.calc = list(values)
def __repr__(self):
if self.values == [] and not self.sequence: #if sequence was set to False, pretty much.
return self.__str__() #if there aren't any values to output, copy the nth term output from __str__
else:
addString = [str(value) for value in self.values] # turns all values in self.values into strings -
return f"nthTerm({', '.join(addString)})" # - so ''.join can be used on them here | {
"domain": "codereview.stackexchange",
"id": 43582,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
def __str__(self):
# nthTermData[0] = a (coefficient of n)
# nthTermData[1] = b (power of n)
# data is presented like: an^b
addString = ' + '.join(((f"{str(nthTermData[0])}" if nthTermData[0] != 1 or nthTermData[1] == 0 else "") +
("n" if nthTermData[1] > 0 else "") +
(f"^{nthTermData[1]}" if nthTermData[1] > 1 else ""))
for nthTermData in self.calc)
return f"nthTerm({addString})".replace("+ -", "- ")
def calculate(self, n):
"""
Calculates the nth value of the sequence of numbers provided.
"""
if not isinstance(n, int): # if the value of n isn't an integer - since it has to be one
raise ValueError("nthTerm.calculate(n) only accepts integer values of 'n'.")
if n < 1:
raise ValueError(f"'{n}' is not a non-negative integer higher than 0.")
if n - 1 < len(self.values): # value of n being looked for is already in the list values - can just return that
return self.values[n - 1]
else: # value isn't in self.values - calculate it instead
valueOfN = 0
# nthTermData[0] = a (coefficient of n)
# nthTermData[1] = b (power of n)
# data is presented like: an^b
for nthTermData in self.calc:
valueOfN += nthTermData[0] * (n ** nthTermData[1]) # valueOfN += an^b, thats all this is
return int(valueOfN) if valueOfN.denominator == 1 else valueOfN # turns the value into an integer if the denominator is 1 | {
"domain": "codereview.stackexchange",
"id": 43582,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
I've tried to make the code look readable by adding spacing and comments, although I'm not sure if I've overdone it with the comments & spacing. Also, I feel as if there are a lot of optimisations that could be make with this code, but I can't find any.
As for the code itself, I don't think there's any bugs with it (however, my testing wasn't extensive), although I have used some questionable coding practices that I might've been able to avoid.
Is there any optimisation (in terms of readability, efficiency and pythonicity?) that could've been implemented?
EDIT:
here's some ways to use the class:
>>> a = nthTerm(2, 6, 12, 20, 30)
>>> a
nthTerm(2, 6, 12, 20, 30)
>>> str(a)
nthTerm("n^2 + n")
>>> a.calculate(6) #calculates the next term
42
>>> # for adding the nth term directly:
>>> b = nthTerm([4, 2], [3, 1], sequence = False)
>>> # would give an nth term of 4n^2 + 3n^1 (or just 3n)
Answer: So, let's unpack this a bit.
You have a class called 'NthTerm', you can use that to make an nth_term object, which can be used to calculate (with n) the... nth term?
It sounds like your class is mis-named, perhaps it should be 'Sequence', or in this case 'Polynomial'.
Continuing with that renaming, things get a bit easier.
You have two ways of creating a Polynomial, you can fit it to a sequence of values, or you can give the coefficients for the polynomial term directly. You switch between these behaviours by using an optional argument.
That's okay, but why don't we simplify that down a bit more by using an alternate constructor?
We can make the init method always take coefficients, and drop the 'sequence' flag. And then create an alternate constructor 'from_sequence', which works out the coefficients based on the sequence and then gives you a polynomial (by calling the constructor with those coefficients).
@classmethod
def from_sequence(cls, *values):
fitted_coefficients = fit_coefficients(values) # A function with your logic from before
return cls(*fitted_coefficients) | {
"domain": "codereview.stackexchange",
"id": 43582,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
And on the topic of renaming, 'calculate' is very vague, why don't we try calling it 'nth_term'?
Now we have something that looks more like this:
>>> a = Polynomial.from_sequence(2, 6, 12, 20, 30)
>>> a
Polynomial([1, 2], [1, 1])
>>> str(a)
Polynomial("n^2 + n")
>>> a.nth_term(6) #calculates the next term
42
>>> # for making the polynomial directly:
>>> b = Polynomial([4, 2], [3, 1])
>>> # would give a polynomial of 4n^2 + 3n^1 (or just 3n) | {
"domain": "codereview.stackexchange",
"id": 43582,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x, web-scraping, python-requests
Title: Python script to scrape and parse the Stanford Encyclopedia of Philosophy
Question: I wrote the following script to parse an SEP article and call pandoc to convert it to EPUB. I'd love your feedback.
There is no function but I didn't think it was worth adding. Also there is no test to see if the file is executed or imported, but since it is supposed to be an executable this is not a problem in my opinion.
"""
sep2epub
"""
import os
from bs4 import BeautifulSoup
import argparse
import requests
import yaml
# Parse command line arguments
parser = argparse.ArgumentParser("Create an epub file from an article in the Stanford Encyclopedia of Philosophy")
parser.add_argument("id", help="Identifier of the article")
args = parser.parse_args()
URL = "https://plato.stanford.edu/entries/" + args.id
# Request the HTML page and parse it with BeautifulSoup
response = requests.get(URL)
soup = BeautifulSoup(response.text, "html.parser")
article_content = soup.find("div", id="article-content")
article_title = article_content.find("h1").text
article_content.find("div", id="academic-tools").decompose()
article_content.find("div", id="related-entries").decompose()
# Export HTML and metadata
os.makedirs("tmp", exist_ok=True)
with open(f"tmp/{args.id}.html", "w") as f:
f.write(str(article_content))
metadata = {
"title": article_title,
"publisher": "Stanford Encyclopedia of Philosophy",
}
with open("tmp/metadata.yaml", "w") as f:
f.write(yaml.dump(metadata,
explicit_start=True, explicit_end=True))
# Use pandoc to generate the epub file
command = f"pandoc tmp/{args.id}.html"
command += " --metadata-file=tmp/metadata.yaml"
command += f" -o {args.id}.epub"
os.system(command)
Answer: Add a hashbang at the top of your script since it's expected to be executable.
There is no function but I didn't think it was worth adding | {
"domain": "codereview.stackexchange",
"id": 43583,
"lm_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, web-scraping, python-requests",
"url": null
} |
python, python-3.x, web-scraping, python-requests
There is no function but I didn't think it was worth adding
Functions are worth adding: the visual and performance overhead is minimal, it increases self-documentation and testability. For these same reasons you should add a __main__ guard.
Since you only care about the DOM subtree under one element, use a strainer.
Don't create your own temporary directory; use the system one via the tempfile library. If you can guarantee that you're not running on Windows, the usage is slightly easier for an auto-deleted file than if you're running on Windows due to file-sharing permissions issues; but in either case tempfile offers better security, potentially better performance (depending on how the OS maps temporary files), better idempotence and generally a file access pattern more in line with what the operating system expects for temporary data.
There's basically never a good case for calling os.system; use subprocess instead. Use check_call so that it stands a chance of detecting when something goes wrong and throwing an exception from the Python stack.
Don't ignore requests network failures; call raise_for_status().
Suggested
#!/usr/bin/env python3
"""
sep2epub
"""
import os
import subprocess
from tempfile import NamedTemporaryFile
from bs4 import BeautifulSoup
from bs4.element import SoupStrainer
import argparse
import requests
import yaml
def parse_args() -> str:
parser = argparse.ArgumentParser('Create an epub file from an article in the Stanford Encyclopedia of Philosophy')
parser.add_argument('id', help='Identifier of the article')
args = parser.parse_args()
return args.id
def fetch_content(article_id: str) -> tuple[
str, # title
str, # HTML content
]:
url = 'https://plato.stanford.edu/entries/' + article_id
strainer = SoupStrainer(name='div', id='article-content') | {
"domain": "codereview.stackexchange",
"id": 43583,
"lm_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, web-scraping, python-requests",
"url": null
} |
python, python-3.x, web-scraping, python-requests
with requests.get(url, headers={'Accept': 'text/html'}) as response:
response.raise_for_status()
soup = BeautifulSoup(markup=response.text, features='html.parser', parse_only=strainer)
content, = soup.contents
title = content.find('h1').text
for delete_id in ('academic-tools', 'related-entries'):
content.find('div', id=delete_id).decompose()
return title, str(content)
def make_metadata(title: str) -> dict:
return {
'title': title,
'publisher': 'Stanford Encyclopedia of Philosophy',
}
def export(
article_id: str,
content: str,
metadata: dict,
) -> None:
try:
with NamedTemporaryFile(mode='wt', delete=False, suffix='.html', prefix=f'{article_id}-') as html_file, \
NamedTemporaryFile(mode='wt', delete=False, suffix='.yaml', prefix=f'{article_id}-metadata-') as yaml_file:
html_file.write(content)
yaml.dump(data=metadata, stream=yaml_file, explicit_start=True, explicit_end=True)
# Use pandoc to generate the epub file
subprocess.check_call(
(
'/usr/bin/pandoc',
html_file.name,
'--metadata-file', yaml_file.name,
'-o', f'{article_id}.epub',
), shell=False
)
finally:
os.unlink(html_file.name)
os.unlink(yaml_file.name)
def main() -> None:
article_id = parse_args()
title, content = fetch_content(article_id)
export(article_id, content, metadata=make_metadata(title))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43583,
"lm_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, web-scraping, python-requests",
"url": null
} |
c, unit-testing, cmake
Title: Astronomical calculations in C for python bindings
Question: I've started teaching myself c/c++ with the intent of being able to writing python bindings to c code. I have a c library used for astronomical calculations given a date lat lon and some other parameters.
In my implementation, I use a date range to run a start stop step for loop over the astronomical calcs (I don't actually call them).
src/core.h
#ifndef CORE_H_ // include guard
#define CORE_H_
#ifdef __cplusplus
extern "C" {
#endif
int** array_from_date_range(unsigned int* start_day,
unsigned int* end_day,
unsigned int interval);
unsigned int julian_day(int year, int month, int day);
#ifdef __cplusplus
}
#endif
#endif // CORE_H_
src/core.c
#include "core.h"
#include <stdlib.h>
#include "array.h"
const int MONTHS_IN_YEAR = 12;
const double AVG_DAYS_PER_MONTH = 30.6001;
const double AVG_DAYS_PER_YEAR = 365.25;
const double GREGORIAN_CALENDAR =
1582 + 10 / MONTHS_IN_YEAR + 15 / AVG_DAYS_PER_YEAR;
/*calculate julian day*/
unsigned int julian_day(int year, int month, int day) {
double jd, gc_cor, margin;
if (month < 3) {
year -= 1;
month += MONTHS_IN_YEAR;
}
gc_cor = 0;
// date is greater than the GERGORIAN_CALENDAR value apply a correction
if ((year + month / 12 + day / AVG_DAYS_PER_YEAR) >= GREGORIAN_CALENDAR) {
margin = (double)((int)(year / 100));
gc_cor = 2 - margin + (double)((int)(margin / 4));
}
//
if (year >= 0) {
jd = (double)((int)(AVG_DAYS_PER_YEAR * year)) +
(double)((int)(AVG_DAYS_PER_MONTH * (month + 1.0))) + day + 1720994.5 +
gc_cor;
} else {
jd = (double)((int)(AVG_DAYS_PER_YEAR * year - 0.75)) +
(double)((int)(AVG_DAYS_PER_MONTH * (month + 1.0))) + day + 1720994.5 +
gc_cor;
}
return jd;
} | {
"domain": "codereview.stackexchange",
"id": 43584,
"lm_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, unit-testing, cmake",
"url": null
} |
c, unit-testing, cmake
int** array_from_date_range(unsigned int* start_day,
unsigned int* end_day,
unsigned int interval) {
unsigned int jd0, jd1, jdx;
jd0 = julian_day(start_day[0], start_day[1], start_day[2]);
jd1 = julian_day(end_day[0], end_day[1], end_day[2]);
if(!interval)interval=1;
int n = (int)floor((jd1 - jd0)/interval);
int** arr = allocate_array(n, 5);
int count=0, i ;
for (i = 0; i < n; i++) {
jdx = jd0 +count;
arr[i][0] = jdx; // int function(jdx, *pyargs)
arr[i][1] = jdx; // int function(jdx, *pyargs)
arr[i][2] = jdx; // int function(jdx, *pyargs)
arr[i][3] = jdx; // int function(jdx, *pyargs)
arr[i][4] = jdx; // int function(jdx, *pyargs)
count = i + interval;
}
return arr;
free_array(arr, n);
}
The // int function(jdx, *pyargs) is just a placeholder my intent is to return a 2d array into pandas dataframe. Something along these lines...
pd.DataFrame(array_from_date_range((2022,1,1),(2022,1,15),0,**kwargs),columns=['jdate',...]).set_index('jdate')`
src/array.h
#ifndef ARRAY_H_ // include guard
#define ARRAY_H_
#ifdef __cplusplus
/**/
extern "C" {
#endif
int** allocate_array(int Rows, int Cols);
void free_array(int** board, int Rows);
#ifdef __cplusplus
}
#endif
#endif // ARRAY_H_
src/array.c
#include <stdlib.h>
int** allocate_array(int nRows, int nCols) {
// allocate Rows rows, each row is a pointer to int
int** arr = (int**)malloc(nRows * sizeof(int*));
int row;
// for each row allocate Cols ints
for (row = 0; row < nRows; row++) {
arr[row] = (int*)malloc(nCols * sizeof(int));
}
return arr;
}
void free_array(int** arr, int nRows) {
int row;
// first free each row
for (row = 0; row < nRows; row++) {
free(arr[row]);
}
// Eventually free the memory of the pointers to the rows
free(arr);
} | {
"domain": "codereview.stackexchange",
"id": 43584,
"lm_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, unit-testing, cmake",
"url": null
} |
c, unit-testing, cmake
I am using a cmake and google test
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
#
project(cproject)
set(CMAKE_CXX_STANDARD 14)
# ##############################################################################
# Python
# ##############################################################################
find_package(Python 3.10 REQUIRED Interpreter Development NumPy)
find_package(PythonLibs REQUIRED)
# ##############################################################################
# Source lib
# ##############################################################################
add_library(core SHARED src/core.c src/array.c)
target_link_libraries(core PUBLIC Python::NumPy)
# ##############################################################################
# GTest
# ##############################################################################
enable_testing()
find_package(GTest CONFIG REQUIRED)
add_executable(
core_test
src/tests/core_test.cc
src/tests/array_test.cc
)
target_link_libraries(core_test PUBLIC core ${PYTHON_LIBRARIES} GTest::gtest GTest::gtest_main )
add_test(UnitTests core_test)
# ##############################################################################
# Installation
# ##############################################################################
set(CMAKE_INSTALL_PREFIX /usr/local/src)
install(TARGETS core DESTINATION ${CMAKE_INSTALL_PREFIX})
src/tests/core_tests.cc
#include "../core.h"
#include <Python.h>
#include <limits.h>
#include "gtest/gtest.h"
namespace CORE {
TEST(Array2D, ArrTest) {
unsigned int start_day[3] = {2022, 1, 1};
unsigned int end_day[3] = {2022, 1, 15};
int** arr = array_from_date_range(start_day, end_day, 1);
ASSERT_EQ(arr[0][0], 2459580);
ASSERT_EQ(arr[1][0], 2459581);
int** arr2 = array_from_date_range(start_day, end_day, 2);
ASSERT_EQ(arr2[0][0], 2459580);
ASSERT_EQ(arr2[1][0], 2459582);
}
TEST(JulianDay, JdTest) {
unsigned int jd = julian_day(2022, 1, 1);
ASSERT_EQ(jd, 2459580);
} | {
"domain": "codereview.stackexchange",
"id": 43584,
"lm_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, unit-testing, cmake",
"url": null
} |
c, unit-testing, cmake
TEST(JulianDay, JdTest) {
unsigned int jd = julian_day(2022, 1, 1);
ASSERT_EQ(jd, 2459580);
}
} // namespace CORE
edit:
I caught an error with my step | {
"domain": "codereview.stackexchange",
"id": 43584,
"lm_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, unit-testing, cmake",
"url": null
} |
c, unit-testing, cmake
Answer: General Observations
Caveats, I am a C and C++ programmer, I don't know python or Google tests at all. I also don't know much about astronomy or converting Gregorian dates to Julian dates.
While some compilers accept the .cc file extension for C++, a more common file extension for C++ is .cpp.
The tests should be written in 2 languages, neither one is C++. The unit tests should be written in C and integration tests should be written in python. There is no reason to use C++.
The tests are not complete, unit tests should include negative path testing as well as positive path testing. Negative path testing is where you force errors into the unit test to see what the code does, it is necessary for writing robust that won't fail when users do the wrong thing. Testing arrays of lengths 1 or 2 are also not enough, I would use at least a year, and possibly a decade as a test unit. This will also allow you to do performance testing.
Compiler Warnings
I haven't compiled the code however, there should be a warning message for the function array_from_date_range(). The function free_array() will never be called because it is after the return statement. In both C and C++ the return statement indicates that there will be no more processing in that function.
I suggest that when you compile C or C++ source code you use the -Wall switch to catch all possible errors in the code.
Memory Leaks
This code is going to leak memory since the arrays are never deallocated as mentioned above in the Compiler Warnings section. You also don't want to delete the allocated memory before you use it.
Test for Possible Memory Allocation Errors | {
"domain": "codereview.stackexchange",
"id": 43584,
"lm_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, unit-testing, cmake",
"url": null
} |
c, unit-testing, cmake
Test for Possible Memory Allocation Errors
In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB).
Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).
To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL.
Convention When Using Memory Allocation in C
When using malloc(), calloc() or realloc() in C a common convention is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes. | {
"domain": "codereview.stackexchange",
"id": 43584,
"lm_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, unit-testing, cmake",
"url": null
} |
c++, performance, stack, math-expression-eval
Title: Infix to Postfix Converter in C++
Question: I have written a program to convert an infix expression to postfix with the help of infix2postfix() function. Please review my code and suggest ways to make it simpler and more readable.
Code:
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int isOperator(char x)
{
return (x == '-' || x == '+' || x == '/' || x == '*');
}
int precedenceOperator(char x)
{
if (x == '+' || x == '-')
{
return 1;
}
else if (x == '/' || x == '*')
{
return 2;
}
return 0;
}
string infix2Postfix(string infix)
{
int i = 0;
stack<char> lobby;
string postfix;
if (infix.size() == 0)
{
return "";
}
while (infix[i] != '\0')
{
if (!isOperator(infix[i]))
{
postfix = postfix + infix[i];
i++;
}
else
{
while (!lobby.empty() && precedenceOperator(infix[i]) <= precedenceOperator(lobby.top()))
{
postfix += lobby.top();
lobby.pop();
}
lobby.push(infix[i]);
i++;
}
}
while (!lobby.empty())
{
postfix = postfix + lobby.top();
lobby.pop();
}
return postfix;
}
Implementation:
int main()
{
string infix;
cout << "WELCOME TO INFIX TO POSTFIX CONVERTER: " << endl;
cout << "Enter your Infix Expression: ";
getline(cin, infix);
string postfix = infix2Postfix(infix);
cout << "The Postfix Expression is : " << postfix << endl;
return 0;
}
Logic:
We create a string variable that will hold our postfix expression. Now, start iterating over our infix string. If we receive an operand, concatenate it to the postfix string. Else if we encounter an operator, proceed with the following steps: | {
"domain": "codereview.stackexchange",
"id": 43585,
"lm_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, stack, math-expression-eval",
"url": null
} |
c++, performance, stack, math-expression-eval
Keep in account the operator and its relative precedence. (We have 4 operators where '/' and '*' hold more precedence than '+' and '-')
If either the stack is empty or its topmost operator has lower relative precedence, push this operator inside the stack.
Else, keep popping operators from the stack and concatenate them to the postfix expression until the topmost operator becomes weaker in precedence relative to the current operator.
If we reach the EOE, pop out every element from the stack, if there is any, and concatenate them as well.
Answer: std::getline is defined in the include <string>, which you do not have, so the code doesn't compile for me.
Don't do using namespace std; see https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice.
int isOperator(char x) should be a bool since it is a logical test.
int precedenceOperator(char x) should be called operatorPrecedence(), otherwise it sounds like an operator type (operatorPlus, operatorMinus, operatorPrecedence).
I would change these lines:
if (infix.size() == 0)
{
return "";
}
while (infix[i] != '\0')
{
To:
for(int i = 0; i < infix.size(); i++){
The redundant empty test is removed, the definition of i is moved to where it is first needed and scoped as needed. The intent is clear.
If you do not do that then the 2 i++ are redundant; just one at the end of that while is needed.
Even better is the more modern:
for(char ch : infix)
{
if (!isOperator(ch))
{
Etc, replacing all infix[i] by ch.
cout << endl is generally considered a bad idea nowadays, use cout << '\n' instead. | {
"domain": "codereview.stackexchange",
"id": 43585,
"lm_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, stack, math-expression-eval",
"url": null
} |
c++, performance, stack, math-expression-eval
Comments on logic:
In a comment you stated that it is correct that "12+3" and "1+23" both produce 123+.
I 100% disagree. The usual purpose of an infix to postfix handler is to create input to a calculation engine. Putting 123+ into a calculation engine will never produce 15 or 24 (the correct answers to the input). This whole problem stems from you treating this as a simple string problem rather than a deeper (and more interesting) problem of parsing. I suggest that you go the whole way and add a postfix calculator after the conversion. You will end up with a better solution.
Ie, you should see IO like this:
WELCOME TO INFIX TO POSTFIX CONVERTER:
Enter your Infix Expression: 1 + 23
Converted is : 1, 23, +
Result: 24
You never declare any input invalid, for example "1+5 /" is returned as "15 /+". Instead of nonsense in produces nonsense out, you should produce an error. Again a deeper parsing would fix this.
You do not reject characters that are not whitespace, digits or operators. | {
"domain": "codereview.stackexchange",
"id": 43585,
"lm_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, stack, math-expression-eval",
"url": null
} |
c++, console, winapi
Title: A C++ WinAPI program for changing the process priority classes via PIDs
Question: (See the next iteration .)
I have this program (call it, for example, prioset.exe), that asks for two command line arguments: (1) the target process PID, (2) a priority class selector in the range 0...5 (as specified in the WinAPI docs, where 0 stands for idle priority class, and 5 for real-time priority class.
My main concern is whether we can pass to dwDesiredAccess of OpenProcess more restricted flags than PROCESS_ALL_ACCESS.
Here's the code:
#include <Windows.h>
#include <iostream>
#include <sstream>
#include <string>
using std::wcout;
using std::wcerr;
using std::wstringstream;
static void MyPrintHelp();
static void MyAttemptToChangeProcessPriorityClass(DWORD pid,
DWORD priorityClass);
static bool MyCheckPriorityClassSelection(DWORD priorityClassSelection);
static DWORD MyConvertPriorityClassSelectionToFlag(DWORD priorityClassSelection);
int wmain(int argc, const wchar_t** args) {
if (argc != 3) {
MyPrintHelp();
return 0;
}
DWORD pid;
DWORD priorityClassSelection;
wstringstream wss;
wss << args[1] << L" " << args[2];
wss >> pid;
if (wss.fail() || wss.eof()) {
wcerr << L"Error: bad PID (" << args[1] << L"\n";
return EXIT_FAILURE;
}
wss >> priorityClassSelection;
if (wss.fail()) {
wcerr << L"Error: bad priority class selector (" << args[2] << L")\n";
return EXIT_FAILURE;
}
if (!MyCheckPriorityClassSelection(priorityClassSelection)) {
wcerr << L"Error: bad priority class selection: "
<< priorityClassSelection
<< L". Must be between 0 and 5, inclusively.\n";
return EXIT_FAILURE;
}
MyAttemptToChangeProcessPriorityClass(
pid,
MyConvertPriorityClassSelectionToFlag(
priorityClassSelection));
} | {
"domain": "codereview.stackexchange",
"id": 43586,
"lm_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++, console, winapi",
"url": null
} |
c++, console, winapi
static void MyPrintHelp() {
wcout << L"prioset.exe PID PRIORITY\n";
}
static std::wstring GetLastErrorAsString(DWORD errorMessageId)
{
LPWSTR messageBuffer = nullptr;
size_t size = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorMessageId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) &messageBuffer, 0, NULL);
//Copy the error message into a std::string.
std::wstring message(messageBuffer, size);
//Free the Win32's string's buffer.
LocalFree(messageBuffer);
return message;
}
static void MyAttemptToChangeProcessPriorityClass(DWORD pid, DWORD priorityClass) {
HANDLE processHandle =
::OpenProcess(PROCESS_ALL_ACCESS,
false,
pid);
if (processHandle == NULL) {
wcout << L"Error: could not open a process with PID " << pid << "\n";
return;
}
DWORD oldPriorityClass = GetPriorityClass(processHandle);
if (oldPriorityClass == 0) {
DWORD errorCode = ::GetLastError();
wcerr << L"Error: "
<< GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
return;
}
if (!::SetPriorityClass(processHandle, priorityClass)) {
DWORD errorCode = GetLastError();
wcerr << L"Error: "
<< GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
return;
}
DWORD newPriorityClass = GetPriorityClass(processHandle); | {
"domain": "codereview.stackexchange",
"id": 43586,
"lm_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++, console, winapi",
"url": null
} |
c++, console, winapi
DWORD newPriorityClass = GetPriorityClass(processHandle);
if (newPriorityClass == 0) {
DWORD errorCode = ::GetLastError();
wcerr << L"Error: "
<< GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
return;
}
::CloseHandle(processHandle);
if (newPriorityClass == priorityClass) {
wcout << L"Successfully changed the priority class from "
<< oldPriorityClass
<< L" to "
<< newPriorityClass
<< L"\n";
} else {
wcout << L"Could not change the priority class from "
<< oldPriorityClass
<< L" to "
<< priorityClass
<< L" Instead, "
<< newPriorityClass
<< L" is used as a new priority class.\n";
}
}
static bool MyCheckPriorityClassSelection(DWORD priorityClassSelection) {
return priorityClassSelection >= 0 || priorityClassSelection < 6;
}
static DWORD MyConvertPriorityClassSelectionToFlag(
DWORD priorityClassSelection) {
switch (priorityClassSelection) {
case 0:
return IDLE_PRIORITY_CLASS;
case 1:
return BELOW_NORMAL_PRIORITY_CLASS;
case 2:
return NORMAL_PRIORITY_CLASS;
case 3:
return ABOVE_NORMAL_PRIORITY_CLASS;
case 4:
return HIGH_PRIORITY_CLASS;
case 5:
return REALTIME_PRIORITY_CLASS;
default:
throw L"Bad priority class selection.";
}
}
```
Answer: Some remarks.
The error reporting is not consistent:
Most error messages go to standard error (which is good), but some go to standard output.
Most invalid input causes the program to exit with EXIT_FAILURE (which is good), but failures in MyAttemptToChangeProcessPriorityClass() make the program terminate normally. | {
"domain": "codereview.stackexchange",
"id": 43586,
"lm_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++, console, winapi",
"url": null
} |
c++, console, winapi
An error in the integer to priority conversion throws a C++ exception.
According to the documentation it suffices to call OpenProcess() with
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SET_INFORMATION
You have two separate functions MyCheckPriorityClassSelection() which checks the range of the (integer) input, and MyConvertPriorityClassSelectionToFlag() which converts that integer to a priority value. That bears a risk if additional priorities are introduced.
I would combine that into a single function which returns a priority value or indicates an error. | {
"domain": "codereview.stackexchange",
"id": 43586,
"lm_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++, console, winapi",
"url": null
} |
php, pdo
Title: Wrap INSERT statements to PDO transaction (PHP OOP)
Question: so Im trying to wrap SQL INSERT statements to PDO transaction in PHP OOP. I don't know if I'm doing it right and this is the best/easiest way to do it.
So what is important for me is:
There can be multiple(unpredictable) INSERT statement (which will be in loop in the final code)
I want to wrap all of these queries to transaction and commit(execute) only at the end of the code (after loop in final code)
And of course in PHP OOP.
My code looks like this right now:
class.inc.php
class MyQuery {
protected $DB_CONN;
private $DB_insert_query;
public function __construct($DB_CONN) {
$this->PDO_CONN = $DB_CONN->DB_CONN();
}
public function insert_query($insert_query) {
$this->DB_insert_query = $insert_query;
}
public function commit() {
try {
$this->PDO_CONN->beginTransaction();
foreach ($this->DB_insert_query as $query) {
$stmt = $this->PDO_CONN->prepare($query["query"]);
$stmt->execute($query["params"]);
}
$this->PDO_CONN->commit();
}
catch (PDOException $e) {
$this->PDO_CONN->rollBack();
error_log("Error occurred. Error message: " . $e->getMessage() . ". File: " . $e->getFile() . ". Line: " . $e->getLine(), 0);
}
if ($stmt->rowCount()) {
return true;
} else {
return false;
}
}
}
insert.php
$DB_CONN = new DataBase;
$myQuery = new MyQuery($DB_CONN);
$insert_query[] = array("query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => array(":name" => "Name Test", ":text" => "Text Test")
);
$myQuery->insert_query($insert_query);
$insert_query[] = array("query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => array(":name" => "Another Name", ":text" => "Another Text")
);
$myQuery->insert_query($insert_query); | {
"domain": "codereview.stackexchange",
"id": 43587,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, pdo",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.