text stringlengths 1 2.12k | source dict |
|---|---|
c++, image, template, classes, variadic
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::divides<>{});
return *this;
}
friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default;
friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default;
friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 += input2;
}
friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 -= input2;
}
friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2)
{
return multiplies(input1, input2);
}
friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2)
{
return multiplies(input2, input1);
}
#ifdef USE_BOOST_SERIALIZATION | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
#ifdef USE_BOOST_SERIALIZATION
void Save(std::string filename)
{
const std::string filename_with_extension = filename + ".dat";
// Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c
std::ofstream ofs(filename_with_extension, std::ios::binary);
boost::archive::binary_oarchive ArchiveOut(ofs);
// write class instance to archive
ArchiveOut << *this;
// archive and stream closed when destructors are called
ofs.close();
}
#endif
private:
std::vector<std::size_t> size;
std::vector<ElementT> image_data;
template<typename... Args>
void checkBoundary(const Args... indexInput) const
{
constexpr std::size_t n = sizeof...(Args);
if(n != size.size())
{
throw std::runtime_error("Dimensionality mismatched!");
}
std::size_t parameter_pack_index = 0;
auto function = [&](auto index) {
if (index >= size[parameter_pack_index])
throw std::out_of_range("Given index out of range!");
parameter_pack_index = parameter_pack_index + 1;
};
(function(indexInput), ...);
}
};
template<typename T, typename ElementT>
concept is_Image = std::is_same_v<T, Image<ElementT>>;
}
Full Testing Code
The full testing code:
// An Updated Multi-dimensional Image Data Structure with Variadic Template Functions in C++
// Developed by Jimmy Hu
#include <algorithm>
#include <cassert> // for assert
#include <chrono> // for std::chrono::system_clock::now
#include <cmath> // for std::exp
#include <concepts>
#include <execution> // for std::is_execution_policy_v
#include <iostream> // for std::cout
#include <vector>
struct RGB
{
std::uint8_t channels[3];
}; | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
struct RGB
{
std::uint8_t channels[3];
};
using GrayScale = std::uint8_t;
namespace TinyDIP
{
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
}
template<std::size_t index = 1, typename Arg, typename... Args>
constexpr static auto& get_from_variadic_template(const Arg& first, const Args&... inputs)
{
if constexpr (index > 1)
return get_from_variadic_template<index - 1>(inputs...);
else
return first;
}
template<typename... Args>
constexpr static auto& first_of(Args&... inputs) {
return get_from_variadic_template<1>(inputs...);
}
template<std::size_t, typename, typename...>
struct get_from_variadic_template_struct { };
template<typename T1, typename... Ts>
struct get_from_variadic_template_struct<1, T1, Ts...>
{
using type = T1;
};
template<std::size_t index, typename T1, typename... Ts>
requires ( requires { typename get_from_variadic_template_struct<index - 1, Ts...>::type; })
struct get_from_variadic_template_struct<index, T1, Ts...>
{
using type = typename get_from_variadic_template_struct<index - 1, Ts...>::type;
};
template<std::size_t index, typename... Ts>
using get_from_variadic_template_t = typename get_from_variadic_template_struct<index, Ts...>::type;
}
// image.h
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image() = default;
template<std::same_as<std::size_t>... Sizes>
Image(Sizes... sizes): size{sizes...}, image_data((1 * ... * sizes))
{} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
template<std::ranges::input_range Range,
std::same_as<std::size_t>... Sizes>
Image(const Range& input, Sizes... sizes):
size{sizes...}, image_data(begin(input), end(input))
{
if (image_data.size() != (1 * ... * sizes)) {
throw std::runtime_error("Image data input and the given size are mismatched!");
}
}
Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight)
{
size.reserve(2);
size.emplace_back(newWidth);
size.emplace_back(newHeight);
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035
}
Image(const std::vector<std::vector<ElementT>>& input)
{
size.reserve(2);
size.emplace_back(input[0].size());
size.emplace_back(input.size());
for (auto& rows : input)
{
image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten
}
return;
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
template<typename... Args>
constexpr ElementT& at(const Args... indexInput)
{
checkBoundary(indexInput...);
constexpr std::size_t n = sizeof...(Args);
if(n != size.size())
{
throw std::runtime_error("Dimensionality mismatched!");
}
std::size_t parameter_pack_index = 0;
std::size_t image_data_index = 0;
auto function = [&](auto index) {
std::size_t m = 1;
for(std::size_t i = 0; i < parameter_pack_index; ++i)
{
m*=size[i];
}
image_data_index+=(index * m);
parameter_pack_index = parameter_pack_index + 1;
};
(function(indexInput), ...);
return image_data[image_data_index];
}
template<typename... Args>
constexpr ElementT const& at(const Args... indexInput) const
{
checkBoundary(indexInput...);
constexpr std::size_t n = sizeof...(Args);
if(n != size.size())
{
throw std::runtime_error("Dimensionality mismatched!");
}
std::size_t parameter_pack_index = 0;
std::size_t image_data_index = 0;
auto function = [&](auto index) {
std::size_t m = 1;
for(std::size_t i = 0; i < parameter_pack_index; ++i)
{
m*=size[i];
}
image_data_index+=(index * m);
parameter_pack_index = parameter_pack_index + 1;
};
(function(indexInput), ...);
return image_data[image_data_index];
}
constexpr std::size_t getDimensionality() const noexcept
{
return size.size();
}
constexpr std::size_t getWidth() const noexcept
{
return size[0];
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
constexpr std::size_t getHeight() const noexcept
{
return size[1];
}
constexpr auto getSize() noexcept
{
return size;
}
std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
if(size.size() == 1)
{
for(std::size_t x = 0; x < size[0]; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x) << separator;
}
os << "\n";
}
else if(size.size() == 2)
{
for (std::size_t y = 0; y < size[1]; ++y)
{
for (std::size_t x = 0; x < size[0]; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y) << separator;
}
os << "\n";
}
os << "\n";
}
else if (size.size() == 3)
{
for(std::size_t z = 0; z < size[2]; ++z)
{
for (std::size_t y = 0; y < size[1]; ++y)
{
for (std::size_t x = 0; x < size[0]; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y, z) << separator;
}
os << "\n";
}
os << "\n";
}
os << "\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
// Enable this function if ElementT = RGB
void print(std::string separator = "\t", std::ostream& os = std::cout) const
requires(std::same_as<ElementT, RGB>)
{
for (std::size_t y = 0; y < size[1]; ++y)
{
for (std::size_t x = 0; x < size[0]; ++x)
{
os << "( ";
for (std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y).channels[channel_index] << separator;
}
os << ")" << separator;
}
os << "\n";
}
os << "\n";
return;
}
void setAllValue(const ElementT input)
{
std::fill(image_data.begin(), image_data.end(), input);
}
friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs)
{
const std::string separator = "\t";
rhs.print(separator, os);
return os;
}
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::plus<>{});
return *this;
}
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::minus<>{});
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
check_size_same(rhs, *this);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::divides<>{});
return *this;
}
friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default;
friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default;
friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 += input2;
}
friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 -= input2;
}
friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2)
{
return multiplies(input1, input2);
}
friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2)
{
return multiplies(input2, input1);
}
#ifdef USE_BOOST_SERIALIZATION | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
void Save(std::string filename)
{
const std::string filename_with_extension = filename + ".dat";
// Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c
std::ofstream ofs(filename_with_extension, std::ios::binary);
boost::archive::binary_oarchive ArchiveOut(ofs);
// write class instance to archive
ArchiveOut << *this;
// archive and stream closed when destructors are called
ofs.close();
}
#endif
private:
std::vector<std::size_t> size;
std::vector<ElementT> image_data;
template<typename... Args>
void checkBoundary(const Args... indexInput) const
{
constexpr std::size_t n = sizeof...(Args);
if(n != size.size())
{
throw std::runtime_error("Dimensionality mismatched!");
}
std::size_t parameter_pack_index = 0;
auto function = [&](auto index) {
if (index >= size[parameter_pack_index])
throw std::out_of_range("Given index out of range!");
parameter_pack_index = parameter_pack_index + 1;
};
(function(indexInput), ...);
}
};
template<typename T, typename ElementT>
concept is_Image = std::is_same_v<T, Image<ElementT>>;
}
namespace TinyDIP
{
template<typename ElementT>
constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
return x.getWidth() == y.getWidth();
}
template<typename ElementT>
constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
return is_width_same(x, y) && is_width_same(y, z) && is_width_same(x, z);
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
template<typename ElementT>
constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
return x.getHeight() == y.getHeight();
}
template<typename ElementT>
constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
return is_height_same(x, y) && is_height_same(y, z) && is_height_same(x, z);
}
template<typename ElementT>
constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
return is_width_same(x, y) && is_height_same(x, y);
}
template<typename ElementT>
constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
return is_size_same(x, y) && is_size_same(y, z) && is_size_same(x, z);
}
template<typename ElementT>
constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
assert(is_width_same(x, y));
}
template<typename ElementT>
constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
assert(is_width_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
assert(is_height_same(x, y));
}
template<typename ElementT>
constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
assert(is_height_same(x, y, z));
}
template<typename ElementT>
constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
assert_width_same(x, y);
assert_height_same(x, y);
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
template<typename ElementT>
constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z)
{
assert_size_same(x, y);
assert_size_same(y, z);
assert_size_same(x, z);
}
template<typename ElementT>
constexpr void check_width_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
if (!is_width_same(x, y))
throw std::runtime_error("Width mismatched!");
}
template<typename ElementT>
constexpr void check_height_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
if (!is_height_same(x, y))
throw std::runtime_error("Height mismatched!");
}
template<typename ElementT>
constexpr void check_size_same(const Image<ElementT>& x, const Image<ElementT>& y)
{
check_width_same(x, y);
check_height_same(x, y);
}
}
template<typename ElementT>
void multidimensionalImageTest(const size_t size = 5)
{
std::cout << "Test with 1D image:\n";
auto image1d = TinyDIP::Image<ElementT>(size);
image1d.at(0) = 3;
image1d.print();
std::cout << "Test with 2D image:\n";
auto image2d = TinyDIP::Image<ElementT>(size, size);
image2d.setAllValue(1);
image2d.at(0, 1) = 3;
image2d.print();
std::cout << "Test with 3D image:\n";
auto image3d = TinyDIP::Image<double>(size, size, size);
image3d.setAllValue(0);
image3d.at(3, 1, 0) = 4;
image3d.print();
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
multidimensionalImageTest<double>();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
The output of the test code above:
Test with 1D image:
3 0 0 0 0
Test with 2D image:
1 1 1 1 1
3 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Test with 3D image:
0 0 0 0 0
0 0 0 4 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Computation finished at Tue Jan 2 03:25:03 2024
elapsed time: 0.00127554
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
Multi-dimensional Image Data Structure with Variadic Template Functions in C++
What changes has been made in the code since last question?
I am trying to do the excercise of looping over parameter packs with the given structure.
Why a new review is being asked for?
Please review the updated Image template class implementation and all suggestions are welcome. | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
Answer: Apply the techniques you have learned to all of the code
In the past reviews of your questions we have repeatedly stressed that you should simplify the code, reduce code duplication and make it more generic. Those things also usually go hand in hand. However, you are not applying these lessons consistently to all of your code. Next time, a good excercise will be to review your code yourself first, and think about what you might do to improve it. This time, I will just have to repeat myself.
Please don't take this admonishment personally though, you are not the only person doing this, and I probably am guilty of this myself. But I do want to make you aware of this issue so you can improve.
Make everything generic
Here is a good excercise: make everything you see generic where possible. That constructor that takes a std::vector<ElementT> and a bunch of sizes? Make it generic so it handles any number of dimensions. The constructor that takes a std::vector<std::vector<ElementT>>? Make it so it handles an arbitrary number of nested vectors. Why fixate on std::vectors? Make things work for any kind of range. Storing image_data in a vector? Why not make Image so generic the storage type is also just a template parameter, and make it handle custom allocators as well? Those print() functions? Generic! Getting the size of a given dimension? Generic!
Avoid code duplication
Apart from the code you can save by making things more generic, you also have the issue of at(), where you need both a const and non-const version. But you can avoid a lot of duplication there. You can split out the index calculation into a separate function, which will get rid of most of the code duplication. However, you can also have one version call the other and apply a bit of legal const_cast<>()ing, see this StackOverflow question.
Simplify the code | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
Simplify the code
The code to calculate the index is still looking a bit more complex than necessary to me. Every time function() is called, you have a for-loop to calculate m from scratch. However, if you move m out of the lambda's body you don't need that loop.
You also don't need the check for sizeof...(Args), as that is already done by checkBoundary().
Here is a simplified version:
template<typename... Args>
constexpr ElementT const& at(const Args... indexInput) const
{
checkBoundary(indexInput...); | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, image, template, classes, variadic
std::size_t i = 0;
std::size_t stride = 1;
std::size_t position = 0;
auto update_position = [&](auto index) {
position += index * stride;
stride *= size[i++];
};
(update_position(indexInput), ...);
return image_data[position];
} | {
"domain": "codereview.stackexchange",
"id": 45352,
"lm_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++, image, template, classes, variadic",
"url": null
} |
c++, logging
Title: Header only logging library in C++
Question: Source Code
I've attempted to create a simple logging library in cpp. My goal was to make it lightweight to incorporate and easy to add to the codebase.
/**
* @file herrlog.hh
* @author Saphereye
* @brief Header file only logging library
* @version 0.5
* @date 2023-12-30
*
* @copyright Copyright (c) 2023
*/
#pragma once
#include <chrono>
#include <fstream>
#include <iostream>
#include <ostream>
#include <mutex>
/**
* @brief Set of ANSI colors, more can be found here:
* https://gist.github.com/JBlond/2fea43a3049b38287e5e9cefc87b2124
*
*/
#define RESET_COLOR "\033[0m"
#define BOLD_RED_COLOR "\033[1;31m"
#define BOLD_GREEN_COLOR "\033[1;32m"
#define BOLD_YELLOW_COLOR "\033[1;33m"
#define BOLD_BLUE_COLOR "\033[1;34m"
#define BACKGROUND_RED_COLOR "\033[41m"
#define BOLD_WHITE_COLOR "\033[1;37m"
/**
* @brief Enum defining different log types as bit flags.
*
*/
enum class LogType : std::uint8_t {
Trace = 0b000001, // For specific details
Debug = 0b000010, // Temporary debug printing
Info = 0b000100, // General purpose details, e.g. "Program has started"
Error = 0b001000, // For errors, exits the program
Warn = 0b010000, // For reporting warning, the program keeps working
Fatal = 0b100000, // Program exits and produces core dump
All = 0b111111,
None = 0b000000,
};
/**
* @brief Overloading the `|` operator for combining log types.
*
* @param a
* @param b
* @return LogType
*/
LogType operator|(LogType a, LogType b) {
return static_cast<LogType>(static_cast<uint8_t>(a) |
static_cast<uint8_t>(b));
}
/**
* @brief Overloading the `&` operator for checking if a log type is set.
*
* @param a
* @param b
* @return true
* @return false
*/
bool operator&(LogType a, LogType b) {
return static_cast<bool>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b));
} | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
/**
* @brief Logger implementation providing flexible logging capabilities.
*
*/
class Logger {
private:
static LogType log_type;
static std::string output_file_name;
static std::ofstream output_file;
static bool is_output_to_console;
static const char* datetime_format;
static std::mutex log_mutex;
/**
* @brief A recursive function to print the templated arguments passed
*
* @tparam T
* @tparam Rest
* @param stream
* @param format
* @param arg
* @param rest
*/
template <typename T, typename... Rest>
static void print_to_stream(std::ostream& stream, const char* format, T arg,
Rest... rest) {
for (size_t index = 0; format[index] != '\0'; index++) {
if (format[index] == '{' && format[index + 1] == '}') {
stream << arg;
return print_to_stream(stream, format + index + 2, rest...);
}
stream << format[index];
}
}
/**
* @brief Base case for the recursive function
*
* @param stream
* @param format
*/
static void print_to_stream(std::ostream& stream, const char* format) {
for (size_t index = 0; format[index] != '\0'; index++) {
stream << format[index];
}
} | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
/**
* @brief Logs a message with specified details to the console or a file.
*
* @tparam Args
* @param name
* @param color
* @param format
* @param args
*/
template <typename... Args>
static void log(const char* name, const char* color, const char* format,
Args... args) {
auto current_time_point = std::chrono::system_clock::now();
std::time_t current_time =
std::chrono::system_clock::to_time_t(current_time_point);
char time_string[100];
std::strftime(time_string, sizeof(time_string), datetime_format,
std::localtime(¤t_time));
std::lock_guard<std::mutex> lock(Logger::log_mutex);
if (is_output_to_console) {
std::cout << color << "[" << name << " " << time_string << "]"
<< RESET_COLOR << " ";
print_to_stream(std::cout, format, args...);
std::cout << std::endl;
} else {
output_file << "[" << name << " " << time_string << "] ";
print_to_stream(output_file, format, args...);
output_file << "\n";
}
}
/**
* @brief Preventing construction of a new logger object.
*
*/
Logger() = delete;
public:
/**
* @brief Sets the log type, default is LogType::All.
*
* @param log_type
*/
static void set_type(LogType log_type) { Logger::log_type = log_type; }
/**
* @brief Set the output file name object
*
* @param output_file_name
*/
static void set_output_file_name(std::string output_file_name) {
Logger::output_file_name = output_file_name;
is_output_to_console = false;
Logger::output_file = std::ofstream(Logger::output_file_name);
if (Logger::output_file.is_open()) {
Logger::output_file.close();
}
Logger::output_file.open(Logger::output_file_name);
} | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
/**
* @brief Set the datetime format object, default is "%Y-%m-%d %H:%M:%S"
*
* @param datetime_format
*/
static void set_datetime_format(const char* datetime_format) {
Logger::datetime_format = datetime_format;
}
/**
* @brief Logs messages of type trace.
*
* @tparam Args
* @param name
* @param color
* @param format
* @param args
*/
template <typename... Args>
static void trace(const char* format, Args... args) {
if (log_type & LogType::Trace) {
log("TRACE", BOLD_WHITE_COLOR, format, args...);
}
}
/**
* @brief Logs messages of type debug
*
* @tparam Args
* @param name
* @param color
* @param format
* @param args
*/
template <typename... Args>
static void debug(const char* format, Args... args) {
if (log_type & LogType::Debug) {
log("DEBUG", BOLD_BLUE_COLOR, format, args...);
}
}
/**
* @brief Logs messages of type info
*
* @tparam Args
* @param name
* @param color
* @param format
* @param args
*/
template <typename... Args>
static void info(const char* format, Args... args) {
if (log_type & LogType::Info) {
log(" INFO", BOLD_GREEN_COLOR, format, args...);
}
}
/**
* @brief Logs messages of type error. Furthermore closes the output file
* and exits the program.
*
* @tparam Args
* @param name
* @param color
* @param format
* @param args
*/
template <typename... Args>
static void error(const char* format, Args... args) {
if (log_type & LogType::Error) {
log("ERROR", BOLD_RED_COLOR, format, args...);
if (!is_output_to_console) {
output_file.close();
}
exit(EXIT_FAILURE);
}
} | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
/**
* @brief Logs messages of type warning. Doesn't exit the program, just
* notifies the issue.
*
* @tparam Args
* @param format
* @param args
*/
template <typename... Args>
static void warn(const char* format, Args... args) {
if (log_type & LogType::Warn) {
log(" WARN", BOLD_YELLOW_COLOR, format, args...);
}
}
/**
* @brief Logs messages of type fatal. Exits the program and creates a core
* dump.
*
* @tparam Args
* @param format
* @param args
*/
template <typename... Args>
static void fatal(const char* format, Args... args) {
if (log_type & LogType::Fatal) {
log("FATAL", BACKGROUND_RED_COLOR, format, args...);
if (!is_output_to_console) {
output_file.close();
}
abort();
}
}
};
LogType Logger::log_type = LogType::All;
std::string Logger::output_file_name = std::string();
std::ofstream Logger::output_file;
bool Logger::is_output_to_console = true;
const char* Logger::datetime_format = "%Y-%m-%d %H:%M:%S";
std::mutex Logger::log_mutex;
Example Usage
#include "herrlog.hh"
int main() {
Logger::set_output_file_name("test.log"); // The output will be redirected to "test.log"
Logger::trace("This is trace message number 1");
}
Which will write [TRACE 2023-12-31 12:41:09] This is trace message number 1 to the file test.log
Issue/Grievances | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
If the file option is chosen, the script writes to the file every time a logging function is called. My logic was that if it writes all the logs to a temporary buffer and then proceeds to write it to a file at the end of execution, all the logs will be lost in case of premature termination.
Currently, I am using helper methods such as set_output_file_name, set_type and set_datetime_format to set my respective variables. Initially, I had planned to use an init function, which takes all the parameters. But it doesn't cover all cases in which the user wants to give input. I tried the following.
Create all permutations of the function and put default values for each variable. This was a quick and dirty solution, but if I plan to increase variables, this will increase dramatically (O(n!))
I planned on using the boost library's name parameters. However, as I plan to create a single header library, I am unsure how to add that.
Final comments
I would really appreciate your input and suggestions on this and thank you for your time.
Answer: Here are some things that may help you improve your program.
Don't hold a lock that might call external code
Consider this admittedly perverse little program:
#include "herrlog.h"
#include <thread>
using namespace std::chrono_literals;
struct Roadblock {
std::chrono::duration<long> delay = 10s;
};
std::ostream& operator<<(std::ostream& out, const Roadblock& rb) {
std::this_thread::sleep_for(rb.delay);
return out << "What a refreshing sleep!";
}
void countdown(int initial, int identity) {
Roadblock block{1s};
for (int i = initial; i; --i) {
Logger::warn("{}: count = {}, {}", identity, i, block);
}
}
int main() {
Roadblock roadblock{};
Logger::trace("This is trace message number 1");
std::jthread t1(countdown, 10, 1);
std::jthread t2(countdown, 10, 2);
Logger::info("roadblock says \"{}\"", roadblock);
Logger::trace("This is trace message number 2");
} | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
The code right now grabs the mutex and then invokes the inserter for that object. It should be the other way around to minimize the time that the lock is held. Here's a trace of that program with the mutex as is:
[TRACE 2024-01-01 09:37:00] This is trace message number 1
[ WARN 2024-01-01 09:37:00] 1: count = 10, What a refreshing sleep!
[ WARN 2024-01-01 09:37:01] 1: count = 9, What a refreshing sleep!
[ WARN 2024-01-01 09:37:02] 1: count = 8, What a refreshing sleep!
[ WARN 2024-01-01 09:37:03] 1: count = 7, What a refreshing sleep!
[ WARN 2024-01-01 09:37:04] 1: count = 6, What a refreshing sleep!
[ INFO 2024-01-01 09:37:00] roadblock says "What a refreshing sleep!"
[TRACE 2024-01-01 09:37:15] This is trace message number 2
[ WARN 2024-01-01 09:37:00] 2: count = 10, What a refreshing sleep!
[ WARN 2024-01-01 09:37:16] 2: count = 9, What a refreshing sleep!
[ WARN 2024-01-01 09:37:17] 2: count = 8, What a refreshing sleep!
[ WARN 2024-01-01 09:37:18] 2: count = 7, What a refreshing sleep!
[ WARN 2024-01-01 09:37:19] 2: count = 6, What a refreshing sleep!
[ WARN 2024-01-01 09:37:20] 2: count = 5, What a refreshing sleep!
[ WARN 2024-01-01 09:37:21] 2: count = 4, What a refreshing sleep!
[ WARN 2024-01-01 09:37:22] 2: count = 3, What a refreshing sleep!
[ WARN 2024-01-01 09:37:23] 2: count = 2, What a refreshing sleep!
[ WARN 2024-01-01 09:37:24] 2: count = 1, What a refreshing sleep!
[ WARN 2024-01-01 09:37:05] 1: count = 5, What a refreshing sleep!
[ WARN 2024-01-01 09:37:26] 1: count = 4, What a refreshing sleep!
[ WARN 2024-01-01 09:37:27] 1: count = 3, What a refreshing sleep!
[ WARN 2024-01-01 09:37:28] 1: count = 2, What a refreshing sleep!
[ WARN 2024-01-01 09:37:29] 1: count = 1, What a refreshing sleep! | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
In this rewrite, we print instead to a stringstream without a lock and then only grab the lock when we print that string out to either the console or a log file:
template <typename... Args>
static void log(const char* name, const char* color, const char* format,
Args... args) {
auto current_time_point = std::chrono::system_clock::now();
std::time_t current_time =
std::chrono::system_clock::to_time_t(current_time_point);
char time_string[100];
std::strftime(time_string, sizeof(time_string), datetime_format,
std::localtime(¤t_time));
std::stringstream ss;
if (is_output_to_console) {
ss << color << "[" << name << " " << time_string << "]"
<< RESET_COLOR << " ";
} else {
ss << "[" << name << " " << time_string << "] ";
}
print_to_stream(ss, format, args...);
std::lock_guard<std::mutex> lock(Logger::log_mutex);
if (is_output_to_console) {
std::cout << ss.str() << std::endl;
} else {
output_file << ss.str() << '\n';
}
} | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
Now the log is a little more like what we would expect:
[TRACE 2024-01-01 09:42:15] This is trace message number 1
[ WARN 2024-01-01 09:42:15] 2: count = 10, What a refreshing sleep!
[ WARN 2024-01-01 09:42:15] 1: count = 10, What a refreshing sleep!
[ WARN 2024-01-01 09:42:16] 1: count = 9, What a refreshing sleep!
[ WARN 2024-01-01 09:42:16] 2: count = 9, What a refreshing sleep!
[ WARN 2024-01-01 09:42:17] 1: count = 8, What a refreshing sleep!
[ WARN 2024-01-01 09:42:17] 2: count = 8, What a refreshing sleep!
[ WARN 2024-01-01 09:42:18] 1: count = 7, What a refreshing sleep!
[ WARN 2024-01-01 09:42:18] 2: count = 7, What a refreshing sleep!
[ WARN 2024-01-01 09:42:19] 1: count = 6, What a refreshing sleep!
[ WARN 2024-01-01 09:42:19] 2: count = 6, What a refreshing sleep!
[ WARN 2024-01-01 09:42:20] 1: count = 5, What a refreshing sleep!
[ WARN 2024-01-01 09:42:20] 2: count = 5, What a refreshing sleep!
[ WARN 2024-01-01 09:42:21] 1: count = 4, What a refreshing sleep!
[ WARN 2024-01-01 09:42:21] 2: count = 4, What a refreshing sleep!
[ WARN 2024-01-01 09:42:22] 1: count = 3, What a refreshing sleep!
[ WARN 2024-01-01 09:42:22] 2: count = 3, What a refreshing sleep!
[ WARN 2024-01-01 09:42:23] 1: count = 2, What a refreshing sleep!
[ WARN 2024-01-01 09:42:23] 2: count = 2, What a refreshing sleep!
[ INFO 2024-01-01 09:42:15] roadblock says "What a refreshing sleep!"
[TRACE 2024-01-01 09:42:25] This is trace message number 2
[ WARN 2024-01-01 09:42:24] 1: count = 1, What a refreshing sleep!
[ WARN 2024-01-01 09:42:24] 2: count = 1, What a refreshing sleep! | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
c++, logging
Reconsider header-only
The usual expectation of a header-only library is that if I don't invoke anything from it, it should not add any code. However, this puts the LogType operator| and operator& code into the global namespace. Try putting just the #include of this logger into to separate files foo.cpp and bar.cpp and then create a static library from them. You'll find that you end up with two copies and a non-zero length code section for both foo and bar.
Don't use #define constants
We have std::string_view for that, which is type safe. Use that instead.
Reconsider colors
It's not necessarily a problem to make a decision on whether or not to use colors based on whether we're printing to std::cout or not, but one might reasonable want to print instead to std::cerr and may or may not want color there. I'd suggest instead having the user pass a std::ostream& and then provide an independent control for color or not. | {
"domain": "codereview.stackexchange",
"id": 45353,
"lm_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++, logging",
"url": null
} |
python, matplotlib
Title: Colorbar for Matplotlib 3D patch plot
Question: I am trying to make a 3D grid plot in Python using Matplotlib. The grid consists of hexahedral cells (with qudrilateral surfaces). The surfaces should be colored according to their height, that is: the z coordinate. A colorbar should accompany the plot.
Here is an example plotting three surfaces:
from matplotlib import pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
def getFaceMidpointsZ(pc):
a=[]
for i in pc:
v=0
for j in i:
v=v+j[2]
v=v/4.
a.append(v)
return a
def getColors(m,a):
b=m.to_rgba(a)
return [(i[0],i[1],i[2]) for i in b]
fig = plt.figure()
ax = plt.axes(projection='3d')
P=[(0,0,0),(2,0,0),(2,2,0),(0,2,0),(0,2,2),(2,2,2),(0,0,2)]
F=[[0,1,2,3],[2,3,4,5],[0,3,4,6]]
x = [t[0] for t in P]
y = [t[1] for t in P]
z = [t[2] for t in P]
pc=[[P[i] for i in f] for f in F]
fz=getFaceMidpointsZ(pc)
q = Poly3DCollection(pc, linewidths=1)
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array([min(z),max(z)])
m.set_clim(vmin=min(z),vmax=max(z))
q.set_facecolor(getColors(m,fz))
ax.add_collection3d(q)
fig.colorbar(m)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(y),max(y))
ax.set_zlim(min(z),max(z))
ax.view_init(elev=18., azim=-43.)
plt.show()
I am starting to learn Python and Matplotlib, so any comments would be appreciated.
Answer: Coding style
There is an official coding style guide for Python called PEP8. Give it a good read and follow it. For example, the most glaring violations:
Spacing around operators: instead of v=v+j[2], write as v = v + j[2]
For function names, snake_case is preferred over camelCase
Put exactly two blank lines before each function definition | {
"domain": "codereview.stackexchange",
"id": 45354,
"lm_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, matplotlib",
"url": null
} |
python, matplotlib
Coding practices
Don't put code in the global namespace, put inside a function.
This protects you from bad practices like using global variables, whether intentionally or by accident.
For example, you could move all the code current code in the global namespace inside a main function:
def main():
fig = plt.figure()
ax = plt.axes(projection='3d')
P = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0), (0, 2, 2), (2, 2, 2), (0, 0, 2)]
F = [[0, 1, 2, 3], [2, 3, 4, 5], [0, 3, 4, 6]]
# ...
And call the main function like this:
if __name__ == '__main__':
main()
Avoid unused imports:
import numpy as np
Naming
The biggest issue with this code is the naming of variables.
You're overusing single-letter or very short variable names,
and it's hard to guess what is what without searching for where they come from and how they are used.
Simplify
You have many expressions that can be simplified, for example:
# instead of: v = v + j[2]
v += j[2]
# instead of: v = v / 4.
v /= 4. | {
"domain": "codereview.stackexchange",
"id": 45354,
"lm_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, matplotlib",
"url": null
} |
c++, performance, sorting
Title: Fraudulent activity notifications problem from hackerrank
Question: There's a problem on hackerrank called fraudulent activity notifications: given an array of integers and a value k, I'm supposed to increment a counter if the median of the numbers up until k , multiplied by 2 is greater than or equal to the current value being read at k + 1.
So for instance:
given an array: [10, 20, 30, 40, 50] and a value k = 3, the median would be 10 + 20 + 30 / 3
= 20.
So we take the value at k + 1 which is 40, and compare: 40 > median * 2? or 40 >= 40?
Since this is true we increment the counter.
Now, here's my solution:
float GetMedian( std::vector<int> sample_days )
{
auto median = 0.0f;
auto size = sample_days.size();
if( sample_days.size() % 2 == 0 )
{
median = ( sample_days[( size / 2 ) - 1] + sample_days[size / 2] ) / 2.0f;
}
else
{
median = sample_days[( size - 1 ) / 2];
}
return median;
}
int activityNotifications( std::vector<int> expenditure, int d )
{
auto notices = 0;
for( auto i = 0; i + d < expenditure.size(); ++i )
{
std::vector<int> sample_days = { expenditure.begin() + i, expenditure.begin() + d + i};
std::sort( sample_days.begin(), sample_days.end() );
auto median = (GetMedian( sample_days ));
auto current_day = expenditure[d + i];
if( current_day >= std::floor(median * 2.0f) )
++notices;
}
return notices;
}
This works for the first few test cases but after that I'm timing out. Any tips on how I can make this go faster?
Supposedly this problem is in the sorting section, I just don't see how I'd use sort to solve this. I'd appreciate any tips or feedback.
Answer: contract
float GetMedian( std::vector<int> sample_days ) | {
"domain": "codereview.stackexchange",
"id": 45355,
"lm_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, sorting",
"url": null
} |
c++, performance, sorting
Answer: contract
float GetMedian( std::vector<int> sample_days )
This signature is nice enough.
It looks like it describes the API
contract.
We see what caller must present, what will come back,
and the informative GetMedian identifier tells us
what math concept is involved.
Oh, wait!
It turns out that caller is required to only pass in an ordered vector.
The code doesn't check for that, fine, it would turn O(1) into O(N) cost,
makes sense.
But there's no comment advising caller that the only way to
correctly call this routine is to offer sorted integers.
When this median library routine winds up in a separate compilation unit,
some maintenance engineer will inevitably call it incorrectly,
and with no error logged will just blindly trust
the returned float as being correct.
Document how to correctly use this helper.
consistent terms
int activityNotifications( std::vector<int> expenditure, int d )
Please arrange for agreement between the helper's signature and this signature.
std::vector<int> sample_days (plural, unit of time)
std::vector<int> expenditure (singular, unit of currency) | {
"domain": "codereview.stackexchange",
"id": 45355,
"lm_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, sorting",
"url": null
} |
c++, performance, sorting
You probably want expenditure_days instead.
The rest of it looks correct.
(Though it does a lot of work.
It has high compute complexity, leading to contest timeouts.)
algorithm
pqueue
Expenditures are drawn from some arbitrary, unseen distribution.
Size of the D window can potentially be near a quarter million.
You copy and sort that many integers every time,
and since median is a "robust" metric, most recorded expenditures
won't move the median value at all.
Yet we copy and sort to obtain same old value, most of the time.
Surely there must be a better way?
There is!
Enter the "heap", or "priority queue".
Create an empty one.
Keep adding expenditures to it, with at most O(log D) cost each time.
Once you're past D days, also remove a single "expired" expenditure,
again costing O(log D).
Now you can report median in O(1) constant time, just like your current helper.
counting sort
Both N and D can be "large" -- 200k.
But expenditures are limited to non-negative real numbers of no more than $200.
Better, they are integer valued.
So the unknown distribution can produce only 201 distinct values.
Do we have enough RAM to allocate 201 slots?
Yes, we do!
Init the counts array C to zeros.
Each time expenditure E arrives, note it with C[E]++
Once you're past D days, also note that some value X expired, with C[X]--
Compute median in O(201) constant time, that's O(1) time, by scanning C for cumulative sum and ending when you arrive at a sum of D / 2. (Before we're up to D days we end somewhat earlier.) | {
"domain": "codereview.stackexchange",
"id": 45355,
"lm_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, sorting",
"url": null
} |
c++, performance, sorting
So complexity is independent of window size,
and only depends on number of distinct values the distribution can give us.
Recall that "median" means "half the sorted values are to its left"
on the number line, and "half of them are to its right".
We found a "left" cumsum of D / 2.
If we kept going past that particular E index value,
the "right" cumsum would also be D / 2.
By construction, once we're past D days,
the total value of C will always be D.
With each new day we continue to maintain that invariant,
by incrementing a single value and also decrementing a single value.
sparse
If the contest server sets D to, say, 100, the counts array C will necessarily be
on the sparse side, with at least a hundred zeros at all times.
We could potentially get fancier with a sparse representation,
maybe an OrderedMap, to exploit the fact that zeros won't alter the cumsum.
For this problem's max input parameters, with "small" E's,
it probably isn't a net win,
but for some values it would be.
cached index
Given the robust nature of median,
many days the D / 2 index won't change.
It may be helpful to maintain that index,
and manipulate it directly when we increment and when we decrement.
Then we get O(1) time, independent of number of distinct
values in the input distribution (number of C entries).
When debugging an implementation of that optimization,
unit tests should also verify cumsum "the long way" as originally
described above, to ensure that corner cases are properly handled.
alternate datastructures
Let N be number of distinct values the distribution can
possibly produce, and M the number that happen to be
currently "resident", currently showing a non-zero value.
We're interested in this case: M < N < D
When using the OrderedMap described above,
we will delete() a node when its count is decremented to zero,
and all accesses have O(log(M)) cost.
Maybe we could obtain O(1) cost?
Switch to HashMap, and run a doubly linked list through the counter nodes. | {
"domain": "codereview.stackexchange",
"id": 45355,
"lm_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, sorting",
"url": null
} |
c++, performance, sorting
Switch to HashMap, and run a doubly linked list through the counter nodes.
Defer the increment and decrement operations, noting them in temp variables.
Compute cumsum in O(M) time by traversing the (ordered) linked list.
Along the way, we will encounter the nodes that need {inc, dec},
or we will notice that we skipped over a hole where that node should fit.
So perform such an increment by inserting a counter node with value 1,
and thread it into the doubly linked list.
Similarly, if we traverse our way to the node to be decremented
and it goes to zero, unthread it from the list and deallocate it.
Now we have O(M) processing time for each daily entry,
which for some distributions and problem parameter values
will be winning.
For example, rather than bank balances we might be looking at
stock ticker closing prices, and we know ahead of time that
each week's trading tends to be within a narrow restricted band,
so M << N.
Binning might be an attractive approach,
for some distributions.
Suppose expenditures are real numbers,
so N is infinite, or at least close to
2 ** 53.
Divide the $200 range into ten bins of twenty dollars apiece.
Now it's easy to apply the counting trick to the first few
and last few bins, simply to verify that they're not moving the median.
And we have to carefully maintain a pqueue for at least
the bin containing the median, plus maybe a pair of neighboring bins.
When the median shifts out of its current bin we may need to
do an expensive replay of D expenditures to locate its new bin,
which usually but not always will be adjacent.
Frequent bin shifts may also force replays.
The effect of all this is to reduce the value of M,
so we have a conveniently small pqueue that is rapidly traversed.
Of course, an adversary who controls the distribution of expenditures
can always manipulate it to defeat the optimization by putting
all values within a single bin.
For realistic distributions seen by production systems, | {
"domain": "codereview.stackexchange",
"id": 45355,
"lm_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, sorting",
"url": null
} |
c++, performance, sorting
all values within a single bin.
For realistic distributions seen by production systems,
the binning approach likely allows significant resource savings,
even when the distribution is not constrained to small set of integers. | {
"domain": "codereview.stackexchange",
"id": 45355,
"lm_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, sorting",
"url": null
} |
c#, winforms
Title: Is there a more performance-friendly way to check and change the colors of a WinForms app?
Question: I'm a somewhat new programmer developing a WinForms application in C# that has the option to change the theme/colors depending on user input. Due to the complexity of the application and the amount of panels, tabs, and labels that it needs to change the colors of, it ends up being a hassle to constantly keep updating the themes everytime a new input is placed.
Currently, the selected theme is saved via 'Properties' through WinForms, which can be saved and called at anytime. The function to change the theme is here.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedItem == "Dark")
{
Properties.Settings.Default.Theme = "dark";
Main.CheckTheme();
CheckTheme();
Properties.Settings.Default.Save();
}
if (comboBox2.SelectedItem == "Light")
{
Properties.Settings.Default.Theme = "light";
Main.CheckTheme();
CheckTheme();
Properties.Settings.Default.Save();
}
}
Because of this, I am able to call what theme the user is using at anytime, unfortunately I have to create a CheckTheme() function for every single form to actually change the colors of the app, and that ends up cluttering the code up quickly. For example, this is what one of the other form's theme setter looks like. (Yes, this is a separate form from the other example.)
private void frmSettings_Load(object sender, EventArgs e)
{
CheckTheme();
}
public void CheckTheme()
{
if (Properties.Settings.Default.Theme == "light")
{
// tabPages | {
"domain": "codereview.stackexchange",
"id": 45356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms",
"url": null
} |
c#, winforms
foreach (TabPage tp in tabControl1.Controls.OfType<TabPage>())
{ tp.BackColor = Color.WhiteSmoke; }
foreach (TabPage tp in tabControl2.Controls.OfType<TabPage>())
{ tp.BackColor = Color.WhiteSmoke; }
// Labels
foreach (Label lbl in tabPage1.Controls.OfType<Label>())
{ lbl.ForeColor = Color.Black; }
foreach (Label lbl in tabPage3.Controls.OfType<Label>())
{ lbl.ForeColor = Color.Black; }
foreach (Label lbl in tabPage5.Controls.OfType<Label>())
{ lbl.ForeColor = Color.Black; }
foreach (Label lbl in tabPage6.Controls.OfType<Label>())
{ lbl.ForeColor = Color.Black; }
foreach (Label lbl in tabPage7.Controls.OfType<Label>())
{ lbl.ForeColor = Color.Black; }
// Checkboxes
foreach (CheckBox cb in tabPage6.Controls.OfType<CheckBox>())
{ cb.ForeColor = Color.Black; }
foreach (CheckBox cb in tabPage7.Controls.OfType<CheckBox>())
{ cb.ForeColor = Color.Black; } | {
"domain": "codereview.stackexchange",
"id": 45356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms",
"url": null
} |
c#, winforms
// TabPages + TabControls
// tabPage1.BackColor = Color.White;
// tabPage7.BackColor = Color.White;
// tabPage3.BackColor = Color.White;
tabControl2.BackColor = Color.White;
tabControl1.BackColor = Color.White;
// tabPage5.BackColor = Color.White;
// tabPage6.BackColor = Color.White;
// tabPage1.BackColor = Color.White;
// tabPage7.BackColor = Color.White;
// tabPage3.BackColor = Color.White;
tabControl2.BackColor = Color.White;
tabControl1.BackColor = Color.White;
// tabPage5.BackColor = Color.White;
// tabPage6.BackColor = Color.White;
comboBox1.BackColor = Color.WhiteSmoke;
comboBox1.ForeColor = Color.Black;
ExtensionsBox.BackColor = Color.White;
ExtensionsBox.ForeColor = Color.Black;
// listView1.ForeColor = Color.Black;
// listView1.BackColor = Color.GhostWhite;
pictureBox2.Image = Tasks.Properties.Resources.QuickClean_Black;
this.BackColor = Color.FromArgb(250, 250, 250);
}
}
Is there any way to make this more performance-friendly and user friendly? Previously I had tried to rely on a 100ms timer but that tanked the performance of the app by a lot.
Answer: carefully chosen identifier
public void CheckTheme()
That looks more like SetTheme to me, or at least AdjustTheme.
But it's probably too late for a rename at this point in the project.
dictionary
if (Properties.Settings.Default.Theme == "light")
...
{ tp.BackColor = Color.WhiteSmoke; } ...
if (Properties.Settings.Default.Theme == "dark") ... | {
"domain": "codereview.stackexchange",
"id": 45356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms",
"url": null
} |
c#, winforms
Clearly the conditionals work fine,
at the expense of duplicating the "visit all the nodes" code.
Consider putting Color.WhiteSmoke into a Dictionary entry
that has "light" (rather than "dark") in its key.
Then you could unconditionally just assign a color.
remembering previously applied updates
Do keep track of the most recently applied theme,
so you can skip redundant assignments the next time if nothing changed.
Think of it as a cache hit.
traversal
To better conform to the
single responsibility
principle, this code is crying out for application of
Visitor Pattern.
Each display element should expose an interface
so a visitor can recursively visit embedded display elements.
That would let you add a cleanly separated Styler
which visits elements and adjusts theme colors as needed.
common styles
Every single display element appears to have specific
theme colors that are hard-coded.
We need a better representation for that.
And then a small styling algorithm could traverse all elements,
compute new color, and apply it.
Think about the class attribute attached to <div>
and other HTML display elements.
Putting same class name on several elements
lets the CSS styling engine impose consistent theme colors
on elements which the app designer described as being similar.
You want each of your current display elements to be able to
report similar attributes, in order to simplify the logic
of your Styler when it visits each element. | {
"domain": "codereview.stackexchange",
"id": 45356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, winforms",
"url": null
} |
python
Title: Parsing PDFs into Python structures
Question: Take a resume (or “CV” outside of the US) and return all the text within it in a formatted way. Right now the below script outputs it to a txt file.
I used this guide as inspiration and have looked to improve on it, by using slightly saner control flow and functions. Although the script works as intended, there are quite a lot of things that smell very bad.
Bad Things:
Horrendous main()
Kind of crazy looping (lots of nested indentations which is usually a bad sign).
2D structures and LOTS of lists (again! A bad sign).
No use of yield so materialising a lot in memory.
No use of @dataclass/NamedTuple (I feel like I should be modelling the PDFPage at least).
Could this be vectorised?
Converting it to an object-oriented design seems like a OK idea.
Dumb statements like using pass and if table_in_page == -1
PEP8 Violations
I am lacking creativity to get this to an elegant solution and thought I would add it here to see if there are any fresh minds that want to rework it.
The Code
from typing import Any, Optional
import pdfplumber
from pdfminer.high_level import extract_pages
from pdfminer.layout import LTPage, LTTextContainer, LTChar
def text_extraction(element: LTTextContainer) -> tuple[str, list[str]]:
"""
Extracts text and unique formats (font names and sizes) from a given element.
Parameters:
element (LTTextContainer): The element from which text and formats are extracted.
Returns:
tuple[str, list[str]]: A tuple containing the extracted text and a list of unique formats.
"""
line_text = element.get_text()
line_formats = set()
for text_line in element:
if isinstance(text_line, LTTextContainer):
for character in text_line:
if isinstance(character, LTChar):
format_info = f"{character.fontname}, {character.size}"
line_formats.add(format_info) | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
format_per_line = list(line_formats)
return line_text, format_per_line
def extract_table(pdf_path: str, page_num: int, table_num: int) -> Optional[list[list[str]]]:
"""
Extracts a specified table from a given page of a PDF document.
Parameters:
pdf_path (str): The file path of the PDF document.
page_num (int): The page number from which to extract the table.
table_num (int): The index of the table on the page to extract.
Returns:
Optional[list[list[str]]]: A 2D list representing the extracted table, or None if an error occurs.
"""
try:
with pdfplumber.open(pdf_path) as pdf:
# Check if the page number is valid
if page_num < 0 or page_num >= len(pdf.pages):
raise ValueError("Page number out of range.")
table_page = pdf.pages[page_num]
tables = table_page.extract_tables()
# Check if the table number is valid
if table_num < 0 or table_num >= len(tables):
raise ValueError("Table number out of range.")
return tables[table_num]
except Exception as e:
print(f"An error occurred: {e}")
return None
def table_converter(table: list[list[str]]) -> str:
"""
Converts a 2D table into a string format, where each cell is separated by '|'
and each row is on a new line. Newline characters in cells are replaced with spaces,
and None values are converted to the string 'None'.
Parameters:
table (list[list[str]]): The 2D table to convert.
Returns:
str: The string representation of the table. | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Returns:
str: The string representation of the table.
Example usage:
table = [['Name', 'Age'], ['Alice', '23'], ['Bob', None]]
print(table_converter(table))
"""
converted_rows = []
for row in table:
cleaned_row = [
item.replace('\n', ' ') if item is not None else 'None'
for item in row
]
converted_rows.append('|' + '|'.join(cleaned_row) + '|')
return '\n'.join(converted_rows)
def is_element_inside_any_table(element, page: LTPage, tables: list[Any]) -> bool:
"""
Checks whether a given element is inside any of the tables on a PDF page.
Parameters:
element: The element to check.
page (LTPage): The PDF page.
tables (List[Any]): A list of tables, where each table is an object with a bounding box.
Returns:
bool: True if the element is inside any of the tables, False otherwise.
"""
x0, y0up, x1, y1up = element.bbox
page_height = page.bbox[3]
# Transform coordinates
y0, y1 = page_height - y1up, page_height - y0up
for table in tables:
tx0, ty0, tx1, ty1 = table.bbox
# Check if element bbox is inside table bbox
if tx0 <= x0 < x1 <= tx1 and ty0 <= y0 < y1 <= ty1:
return True
return False
def find_table_for_element(element, page: LTPage, tables: list[Any]) -> Optional[int]:
"""
Finds the index of the table that a given element is inside on a PDF page.
Parameters:
element: The element to check.
page (LTPage): The PDF page.
tables (list[Any]): A list of tables, where each table is an object with a bounding box.
Returns:
Optional[int]: The index of the table that contains the element, or None if not found.
"""
x0, y0up, x1, y1up = element.bbox
page_height = page.bbox[3]
# Transform coordinates
y0, y1 = page_height - y1up, page_height - y0up | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
for i, table in enumerate(tables):
tx0, ty0, tx1, ty1 = table.bbox
if tx0 <= x0 < x1 <= tx1 and ty0 <= y0 < y1 <= ty1:
return i # Return the index of the table
return None
def process_tables(tables, pdf_path, pagenum, text_from_tables):
# Extracting the tables of the page
for table_num in range(len(tables)):
# Extract the information of the table
table = extract_table(pdf_path, pagenum, table_num)
# Convert the table information in structured string format
table_string = table_converter(table)
# Append the table string into a list
text_from_tables.append(table_string)
def process_text_element(element, page_text, line_format, page_content):
# Check if the element is text element
if isinstance(element, LTTextContainer):
# Use the function to extract the text and format for each text element
(line_text, format_per_line) = text_extraction(element)
# Append the text of each line to the page text
page_text.append(line_text)
# Append the format for each line containing text
line_format.append(format_per_line)
page_content.append(line_text)
return line_format, page_content
def main(filepath: str) -> None:
pdf = open(filepath, 'rb')
text_per_page = {}
# We extract the pages from the PDF
for pagenum, page in enumerate(extract_pages(filepath)):
# Initialize the variables needed for the text extraction from the page
page_text = []
line_format = []
text_from_images = []
text_from_tables = []
page_content = []
# Initialize the number of the examined tables
table_in_page = -1
pdf = pdfplumber.open(pdf_path)
page_tables = pdf.pages[pagenum]
tables = page_tables.find_tables()
if len(tables) != 0:
table_in_page = 0
process_tables(tables, filepath, pagenum, text_from_tables) | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
process_tables(tables, filepath, pagenum, text_from_tables)
# Find all the elements
page_elements = [(element.y1, element) for element in page._objs]
# Sort all the element as they appear in the page
page_elements.sort(key=lambda a: a[0], reverse=True)
# Find the elements that composed a page
for i, component in enumerate(page_elements):
# Extract the element of the page layout
element = component[1]
# Check the elements for tables
if table_in_page == -1:
pass
else:
if is_element_inside_any_table(element, page, tables):
table_found = find_table_for_element(element, page,tables)
if table_found == table_in_page and table_found is not None:
page_content.append(text_from_tables[table_in_page])
page_text.append('table')
line_format.append('table')
table_in_page += 1
# Pass this iteration because the content of this element was extracted from the tables
continue
if not is_element_inside_any_table(element, page, tables):
line_format, page_content = process_text_element(element, page_text, line_format, page_content)
# Add the list of list as value of the page key
text_per_page[f'Page_{pagenum}'] = [page_text, line_format, text_from_images, text_from_tables, page_content]
# Close the pdf file object
pdf.close()
# For now just write to file.
result = ''.join(text_per_page['Page_0'][4])
with open("/path/to/processed-resume.pdf.txt", "w") as text_file:
text_file.write(result)
# TODO: this needs a lot of refinement.
if __name__ == "__main__":
pdf_path = '/path/to/any/test-resume.pdf'
main(pdf_path) | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Answer: Self-analysis
The analysis of your own code is pretty accurate, which is a great start
Style
This code follows PEP8 guidelines for the most part, which is also great
Docstrings
The docstrings are helpful, but some of them are missing. I would argue
that specifying the types in the docstrings is not a good idea, as they are usually not checked by static type checkers (like mypy). There is no need to duplicate this information, as it is easy to miss when updating a function signature. If a documentation must be generated, modern tools use the type annotations and display them anyway.
In table_converter, the Example usage: section should be called Example:, as specified in the Google docstring styleguide. A real doctest should also be implemented: this is a free unit test, and the documentation cannot drift from the implementation anymore:
"""
Example:
>>> table = [['Name', 'Age'], ['Alice', '23'], ['Bob', None]]
>>> print(table_converter(table))
|Name|Age|
|Alice|23|
|Bob|None|
""" | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Typing
Using type annotations is great, but it's not more informative than comments or docstrings
if not checked with a static type checker like mypy. For example, the table parameter of table_converter should be annotated with list[list[str | None]]. mypy also detects
that in process_tables, table can be None, and therefore should not be injected into table_converter.
Also, a lot of them are missing or not precise enough (Any). It is particularly helpful for the gentle reader (and for mypy) to annotate empty collections ([], {}, set()) or optional variables (my_var: int | None = None) at their instantiation.
Duplication
The functions is_element_inside_any_table and find_table_for_element are duplicated: the use-case of is_element_inside_any_table can be achieved with find_table_for_element. If a boolean function is really needed, a simple wrapper around find_table_for_element would be enough.
Functions design
Some function interfaces are hard to follow.
text_extraction should not return line_text, as it complexifies its signature, and the caller can easily and independently call element.get_text() if needed.
find_table_for_element takes a whole LTPage as an input, but only uses its height, which is a violation of the principle of least knowledge. This makes this function harder to test. Also, this function does two thing:
converting from one system of coordinates to the other, and then finding the table. It could probably be split in two parts.
process_tables has a poorly informative name, and mainly takes low-level arguments, except for pdf_path. text_from_tables could simply be initialized as an empty list inside the function and then returned instead of being passed as an input argument. Also, there is no need to provide whole Tables, the length of the list is enough. | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
In process_text_element, page_text is modified during the execution of the function like line_format and page_content, but is not returned. This function should either not return anything, or return the data that it actually produced. The fact that three arguments out of the four are mutated show that a data structure is probably missing.
Variable in global scope
The pdf_path variable polutes the global scope, and there are conflicts with some of your pdf_path local variables (not a big deal here, but still a smell). It should be integrated to the main function, that should not take any arguments. A high level function that take paths (input and output) could be extracted from the main function if needed.
Managing IO
The input PDF is opened multiple times, and sometimes at the heart of the logic of the script, which sometimes make the code hard to follow. Ideally, I/O should be managed at the start/end of the script to fill/read from a properly defined data structure. When it is not possible to do that (memory constraints for example), I/O should be encapsulated (Using a class or functools.partial / Callable) and injected gracefully in the logic.
Also, in the main function the pdf = open(filepath, 'rb') statement does not achieve anything, as pdf is never used before being overwritten by pdf = pdfplumber.open(pdf_path). File openings should be handled with context managers when possible (with keyword).
When opening a file in write text mode, an encoding should be specified:
with open("/path/to/processed-resume.pdf.txt", "w", encoding="utf-8") as text_file:
... | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Use of two libraries
Using two libraries to interact with PDFs instead of one can lead to problems that are visible here: multiple file openings, data structure conversions... Sticking to a single one can help a lot. pdfplumber depends on pdfminer.six, but it does not really help here. Have you considered only using pdfplumber to deal with the tables and the text? (See this issue)
Exceptions
In extract_tables, raising exceptions and catching them immediatly in the same function does not seem right. Catching Exception is usually not a good idea, and in this case, the None returned is not even handled in process_tables.
Lack of data structures
This line clearly shows that a data structure is lacking:
text_per_page[f'Page_{pagenum}'] = [page_text, line_format, text_from_images, text_from_tables, page_content]
The type of the variables in the list are heterogeneous, and the list has always the same size.
Another clue is the presence of a magic number to access the data here:
result = ''.join(text_per_page['Page_0'][4])
Using Page_{pagenum} as keys makes things too complicated for an internal data structure. Why not using a simple list instead of a dictionary?
Overcomplicated sorting
This part can be simplified:
page_elements = [(element.y1, element) for element in page._objs]
# Sort all the element as they appear in the page
page_elements.sort(key=lambda a: a[0], reverse=True)
# Find the elements that composed a page
for i, component in enumerate(page_elements):
# Extract the element of the page layout
element = component[1]
i and enumerate are not needed
_objs is a private member of page and should not be accessed. Iterating over page actually yields the same thing, and is less likely to break in a next release of pdfminer
Storing a list of tuples is not needed
page_elements = sorted(page.objects, key=lambda elem: elem.y1, reverse=True)
for element in page_elements:
... | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Comments
Some of the comments are not that informative:
# Extract the information of the table
table = extract_table(pdf_path, pagenum, table_num)
# Convert the table information in structured string format
table_string = table_converter(table)
# Append the table string into a list
text_from_tables.append(table_string)
Focusing on proper naming and type annotations is probably more helpful.
Parallelization
Before introducing parallelization, a profiling should be performed (with cProfile for example) to see where the main bottleneck is.
Refactor
Here is an attempt of refactor. mypy 1.8.0 passes in strict mode on python 3.11 (Windows).
A simple PDF file available here has been used to verify that the behavior has not changed too much.
from typing import Optional, Iterable, NamedTuple, Sequence, Iterator
import pdfplumber
from pdfminer.high_level import extract_pages
from pdfminer.layout import LTPage, LTTextContainer, LTChar, LTComponent
from pdfminer.utils import Rect
from pdfplumber.page import Page
from pdfplumber.table import Table
class TextElement(NamedTuple):
"""A data structure to store elements extracted from a PDF file,
formatted as text
"""
text: str
text_format: list[str] | str
content: str
class LTTextTable(LTComponent):
"""A container to hold the text of a PDF table"""
def __init__(self, text: str, bbox: Rect) -> None:
super().__init__(bbox)
self.text = text
def __contains__(self, item: object) -> bool:
"""Returns ``True`` if the bounding box of the provided
item is entirely contained in this instance
"""
if isinstance(item, LTComponent):
return (
self.x0 <= item.x0
and self.y0 <= item.y0
and self.x1 > item.x1
and self.y1 > item.y1
)
raise NotImplementedError | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
def extract_text_formats(element: LTTextContainer[LTComponent]) -> list[str]:
"""
Extracts the unique formats (font names and sizes) from a given element.
Parameters:
element: The element from which the formats are extracted.
Returns:
A list of unique formats.
"""
line_formats = set()
for text_line in element:
if isinstance(text_line, LTTextContainer):
for character in text_line:
if isinstance(character, LTChar):
format_info = f"{character.fontname}, {character.size}"
line_formats.add(format_info)
return list(line_formats)
def format_table(table: list[list[str | None]]) -> str:
"""
Converts a 2D table into a string format, where each cell is separated by '|'
and each row is on a new line. Newline characters in cells are replaced with spaces,
and None values are converted to the string 'None'.
Parameters:
table: The 2D table to convert.
Returns:
The string representation of the table.
Example:
>>> t = [['Name', 'Age'], ['Alice', '23'], ['Bob', None]]
>>> print(format_table(t))
|Name|Age|
|Alice|23|
|Bob|None|
"""
converted_rows = []
for row in table:
cleaned_row = [
item.replace("\n", " ") if item is not None else "None" for item in row
]
converted_rows.append("|" + "|".join(cleaned_row) + "|")
return "\n".join(converted_rows)
def convert_to_text_table(table: Table) -> LTTextTable:
"""Convert a ``pdfplumber`` Table to a ``pdfminer`` format
Parameters:
table: the table to convert | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Parameters:
table: the table to convert
Returns:
an object that contains the text of the table and its bounding box
"""
x0, y0_down, x1, y1_down = table.bbox
page_y_max = table.page.bbox[3]
return LTTextTable(
text=format_table(table.extract()),
bbox=(x0, page_y_max - y1_down, x1, page_y_max - y0_down),
)
def find_table_for_element(
bbox: LTComponent,
bboxes_to_test: Iterable[LTTextTable],
) -> Optional[int]:
"""
Finds the index of the table that a given element is inside on a PDF page.
Parameters:
bbox: The bounding box of the element to consider
bboxes_to_test: An iterable of bounding boxes to test.
Returns:
The index of the bounding box that contains the element, or None if not found.
"""
for i, bbox_to_test in enumerate(bboxes_to_test):
if bbox in bbox_to_test:
return i
return None
def extract_text_from_page(
lt_page: LTPage, text_tables: Sequence[LTTextTable]
) -> Iterator[TextElement]:
"""Iterate through a PDF page to extract the text and the tables
Parameters:
lt_page: The page from which the text should be extracted
text_tables: The tables that are contained in this page | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Returns:
An iterator that yields the sorted text elements contained in this page
"""
page_elements = sorted(lt_page, key=lambda elem: elem.y1, reverse=True)
table_in_page = 0
for element in page_elements:
table_index = find_table_for_element(element, text_tables)
if table_index is None and isinstance(element, LTTextContainer):
line_text = element.get_text()
format_per_line = extract_text_formats(element)
yield TextElement(text=line_text, text_format=format_per_line, content=line_text)
continue
if table_index == table_in_page:
text_table = text_tables[table_index]
yield TextElement(
text="table",
text_format="table",
content=text_table.text,
)
table_in_page += 1
def iter_pdf_pages(
pages: Iterable[Page], lt_pages: Iterable[LTPage]
) -> Iterator[list[TextElement]]:
"""
Iterate through PDF pages from two iterators, and convert them to text. The iterator is
exhausted as soon as one of the input is exhausted.
Parameters:
pages: An iterable of pdfplumber ``Page`` instances.
lt_pages: An iterable of pdfminer ``LTPage`` instances.
Returns:
An iterator that yields a list of text elements for each page
"""
for page, lt_page in zip(pages, lt_pages):
tables: list[Table] = page.find_tables()
text_tables = [convert_to_text_table(table) for table in tables]
yield list(extract_text_from_page(lt_page, text_tables))
def convert_pdf(filepath: str, output_path: str) -> None:
"""
Extract the text and the tables from a PDF file and the data to an output text file | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
python
Parameters:
filepath: Input path to a PDF
output_path: Path to the .txt file to generate
"""
pages = extract_pages(filepath)
with pdfplumber.open(filepath) as pdf:
text_per_page = list(iter_pdf_pages(pdf.pages, pages))
result = "".join(element.content for element in text_per_page[0])
with open(output_path, "w", encoding="utf-8") as text_file:
text_file.write(result)
def main() -> None:
filepath = r"/path/to/any/test-resume.pdf"
output_path = r"/path/to/processed-resume.pdf.txt"
convert_pdf(filepath, output_path)
if __name__ == "__main__":
main() | {
"domain": "codereview.stackexchange",
"id": 45357,
"lm_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",
"url": null
} |
c++, security, http, windows, https
Title: Reading a date from the start of a text webpage from github to determine if the program is fully updated
Question: #define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <wininet.h>
const char thisVersionDate[] = "2024-01-05";
bool isMostRecentVersion(HINTERNET* hInternet, HINTERNET* hConnection, HINTERNET* hData) {
char currentVersionDate[sizeof(thisVersionDate)] = {};
*hInternet = InternetOpenA(
"wininet_test",
INTERNET_OPEN_TYPE_PRECONFIG,
nullptr,
nullptr,
0
);
if (*hInternet == nullptr) {
printf("error when using InternetOpenA: %d\n", GetLastError());
return false;
}
*hConnection = InternetConnectA(
*hInternet,
"raw.githubusercontent.com",
INTERNET_DEFAULT_HTTPS_PORT,
nullptr,
nullptr,
INTERNET_SERVICE_HTTP,
0,
0
);
if (*hConnection == nullptr) {
printf("error when using InternetConnectA: %d\n", GetLastError());
return false;
}
*hData = HttpOpenRequestA(
*hConnection,
nullptr,
"/speedrun-program/amnesia_load_screen_tool/main/amnesia_settings.txt",
nullptr,
nullptr,
nullptr,
INTERNET_FLAG_SECURE,
0
);
if (*hData == nullptr) {
printf("error when using HttpOpenRequestA: %d\n", GetLastError());
return false;
}
if (!HttpSendRequestA(*hData, nullptr, 0, nullptr, 0)) {
printf("error when using HttpSendRequestA: %d\n", GetLastError());
return false;
} | {
"domain": "codereview.stackexchange",
"id": 45358,
"lm_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++, security, http, windows, https",
"url": null
} |
c++, security, http, windows, https
// windows API documentation says to call this in a loop
DWORD bytesReadThisLoop = 0;
DWORD totalBytesRead = 0;
while (
totalBytesRead < sizeof(currentVersionDate) - 1
&& InternetReadFile(*hData, ¤tVersionDate[totalBytesRead], sizeof(currentVersionDate) - 1 - totalBytesRead, &bytesReadThisLoop)
&& bytesReadThisLoop != 0) {
totalBytesRead += bytesReadThisLoop;
}
if (totalBytesRead < sizeof(currentVersionDate) - 1) {
printf("couldn't determine the date of the most recent version using InternetReadFile: %d\n", GetLastError());
return false;
}
bool isMostRecentVersion = (strncmp(thisVersionDate, currentVersionDate, sizeof(currentVersionDate) - 1) == 0);
if (strncmp(thisVersionDate, currentVersionDate, sizeof(currentVersionDate) - 1) != 0) {
printf("a newer version from %s is available\nthis version's date: %s\n", currentVersionDate, thisVersionDate);
return false;
}
return true;
}
int main() {
HINTERNET hInternet = nullptr;
HINTERNET hConnection = nullptr;
HINTERNET hData = nullptr;
// resources acquired:
// hInternet (1)
// hConnection (2)
// hData (3)
if (isMostRecentVersion(&hInternet, &hConnection, &hData)) {
printf("this is the most recent version\n");
}
if (hData != nullptr) {
InternetCloseHandle(hData); // hData released (3)
}
if (hConnection != nullptr) {
InternetCloseHandle(hConnection); // hConnection released (2)
}
if (hInternet != nullptr) {
InternetCloseHandle(hInternet); // hInternet released (1)
}
return 0;
}
I'm writing a program in C++ for, and I'd like it to be able to check if it's fully updated. My idea is to have it read some text from a webpage on github representing the date of the most recent version. It can then compare the date on github to its own date. | {
"domain": "codereview.stackexchange",
"id": 45358,
"lm_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++, security, http, windows, https",
"url": null
} |
c++, security, http, windows, https
Answer: Overall, the code is structured and easy to follow. Some of the remarks below can probably be ignored in the context of this small program, they only become more important when dealing with a larger codebase, they are still something worth being aware of.
Use Of Pointer Parameters
Some of your functions use pointer arguments. These are then dereferenced without checking the pointer values against null first. At the very least, use assert(). Better perhaps would be to use references, which implicitly can not be null. Even better would be to return values from the functions (e.g. isMostRecentVersion()), maybe using tuples to return multiple values.
Use Of WinAPI *A Functions
These legacy functions (from the DOS-derived Windows versions) convert their parameters internally before calling the according *W functions (which are Unicode-capable). I'd generally prefer the non-legacy versions.
sizeof With Redundant Parentheses
There are two ways to use sizeof, as sizeof (type) or as sizeof object. The latter doesn't require any parentheses.
Not Using Exceptions
There is a lot of code which logs an error with some context info and then returns false to signal failure. This is bad for multiple reasons: | {
"domain": "codereview.stackexchange",
"id": 45358,
"lm_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++, security, http, windows, https",
"url": null
} |
c++, security, http, windows, https
The return value slot is occupied. This means you can't use it to return the actual results of the function to the caller and that you have to use pointers/references (see above) to convey those results. Note that you could use std::optional<> to either return a falsy value or actual results.
The context info is only logged to stdout. That means that the calling function only sees success/failure but doesn't receive any info why something failed. If you wanted to use this function in a UI, you'd first have to intercept stdout in order to present the error to the user. If you wanted to handle specific errors (e.g. using one resource by default but with a fallback when that resource is not available), you couldn't do so easily.
You end up with repeated error-checking code in the calling function as well, which is tedious to read and write.
You can't distinguish the case that you don't have the latest version from the case that determining the version failed. Both are signalled using return false.
Use Of Manual Resource Management
Just as raw pointers with manual memory management are a bad idea, use of raw HINTERNET handles are. Using a smart handle to encapsulate this handle and to reliably release the resource it represent is a better approach, also known as RAII.
Returning Unused Resources From isMostRecentVersion()
The function allocates resources and assigns them to output values. However, these output values are never really used by the calling code, they are only deallocated. Keep that inside the function. Also, use RAII for that (see above).
Nitpicks | {
"domain": "codereview.stackexchange",
"id": 45358,
"lm_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++, security, http, windows, https",
"url": null
} |
c++, security, http, windows, https
I guess this code has a very restricted scope. Otherwise, is most recent version begets the question "what?". I'd normally expect some kind of parameter telling the function what or where to check the version.
The location where to check a version is provided by some hardcoded inline constants, which are like "Magic Numbers". The currentVersionDate constant does this much better.
"a newer version from %s is available", the "from" doesn't make sense in that message. | {
"domain": "codereview.stackexchange",
"id": 45358,
"lm_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++, security, http, windows, https",
"url": null
} |
c++, algorithm, strings, string-processing
Title: Z-Function/ Algorithms on strings. C++
Question: The problem:
Given a string s. For each i from 1 to |s|, find the number of occurrences of its prefix of length i in the string.
Input:
The first line of input contains an integer q (1≤q≤10⁵) — the number of datasets in the test.
Each dataset consists of a string s. The length of the string s is from 1 to 10⁶ characters. The string consists exclusively of lowercase Latin alphabet letters.
The sum of the lengths of strings s across all q datasets in the test does not exceed 10⁶.
Output:
For each dataset, output |s| integers c1, c2, ..., c|s|, where c[i] is the number of occurrences of the prefix of length i in the string s.
Example
Input:
5
abacaba
eeeee
abcdef
ababababa
kekkekkek
Output:
4 2 2 1 1 1 1
5 4 3 2 1
1 1 1 1 1 1
5 4 4 3 3 2 2 1 1
6 3 3 2 2 2 1 1 1
The task must be solved exclusively using the Z-function, and the total time for a string of length 10⁶ characters should not exceed 2 seconds.
My solution looks like this:
#include <iostream>
#include <string>
#include <vector>
std::vector<int> ZFunc(const std::string& s) {
const int sz = s.size();
std::vector<int> z(sz, 0);
for (int i = 1, l = 0, r = 0; i != sz; ++i) {
if (r >= i)
z[i] = std::min(z[i - l], r - i + 1);
while (z[i] + i < sz && s[i + z[i]] == s[z[i]])
z[i]++;
if (z[i] > r - i + 1) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
int main() {
int n;
std::cin >> n;
std::vector<std::vector<int>> res(n);
for (int k = 0; k != n; ++k) {
std::string s;
std::cin >> s;
res[k].resize(s.size(), 1);
std::vector<int> z = ZFunc(s);
for (int i = 1; i != z.size(); ++i) {
while (z[i]--)
res[k][z[i]]++;
}
}
for (const auto& ivec : res) {
for (int i : ivec)
std::cout << i << " ";
std::cout << std::endl;
} | {
"domain": "codereview.stackexchange",
"id": 45359,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, string-processing",
"url": null
} |
c++, algorithm, strings, string-processing
return 0;
}
Its only issue is that I am exceeding the allowed time on tests, and I do not know how to optimize this algorithm. I suspect that the problem lies in strings of the form aaaaaa...aaabcd, where the number of identical characters is quite large, causing the algorithm to have a complexity of O(n²).
Algorithm Description:
The essence of the proposed algorithm is as follows: we find the Z-function for each string. The i-th value of the Z-function represents the length of the matching prefix and substring at position i. More about the Z-function can be found here.
For each string, a prefix of length i occurs at least once, so initially, res[k].resize(s.size(), 1); is set to 1 for all prefixes of the string.
Since the task is to specify, for all i from 1 to |s|, the number of occurrences of a prefix of length i in the string s, when we look at a non-zero value of the Z-function at position i, it means that the prefix of length z[i] matches the substring of length z[i], starting at position i. This means we have found at least one more occurrence for all substrings of the prefix of length i.
For example:
s = abacaba
z = 0010301
When we reach i = 2, z[i] = 1, we can confidently increment the result res[0]++, as s[2]=s[0]='a'. We have found the first occurrence of the prefix of length 1. Next, z[4]=3, which means we have found a match for the prefix 'aba', including 'a', 'ab', and 'aba'. Therefore, for prefixes of length 3, 2, and 1, we add +1.
This is done in the following lines:
while (z[i]--)
res[k][z[i]]++;
Answer: Instead of doing the one by one addition, we shall calculate cumulative sums. Let vector<int> freqs(s.length(), 0) be the frequencies of the prefixes lengths
for (int len : z) {
if (len > 0)
++freqs[len - 1];
}
freqs.back() = 1; | {
"domain": "codereview.stackexchange",
"id": 45359,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, string-processing",
"url": null
} |
c++, algorithm, strings, string-processing
We explicitly set freqs.back() = 1 because z[0] is always 0 instead of being equal to the word length.
If there exists a prefix of length N there also exist prefixes of lengths 1, ..., N - 1. This observation gives us the following cumulative sums
for (int i = freqs.size() - 1; i >= 1; --i)
freqs[i - 1] += freqs[i];
And the answer is freqs.
Use std::cout << '\n'; instead of std::cout << std::endl; since performance is the issue. The latter flushes the output buffer on each call.
Formally speaking, the code std::min(z[i - l], r - i + 1); may implicate an undefined behavior. This version of std::min has const-reference parameters and returns a const-reference which is potentially dangling.
We may omit the index k since it is used merely for iteration,
for (auto& ans : res) {
...
} | {
"domain": "codereview.stackexchange",
"id": 45359,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, string-processing",
"url": null
} |
error-handling, kotlin, language-design
Title: Kotlin: scoped functions with try/catch support
Question: I'm working with Kotlin for some time. Compared to Java it's more concise. Still it has some legacy inherited from Java. For example the try-catch-construct. Though it has been upgraded from a statement in Java to an expression in Kotlin, it's still some kind bulky in writing, assuming we stick to the officially mentioned code formatter and the code conventions regarding the control flow statements.
Then a rather short
fun dayOfWeek() : DayOfWeek {
return try { DayOfWeek.of("1".toInt()) }
catch (e: NumberFormatException) { logAntThrow(e) }
catch (e: DateTimeException) { logAntThrow(e) }
}
becomes a bulky
fun dayOfWeek() : DayOfWeek {
return try {
DayOfWeek.of("1".toInt())
} catch (e: NumberFormatException) {
logAntThrow(e)
} catch (e: DateTimeException) {
logAntThrow(e)
}
}
and breaks the code flow.
Trying to follow the design of Kotlin's run and let I wrote this draft:
data class Try<T, B : (T) -> R, R>(
private val it: T,
private val block: B,
private val exceptionHandler: Map<KClass<Exception>, (e: Exception) -> R> = emptyMap()
) : () -> R {
fun <E : Exception> on(e: KClass<E>, handleException: (e: E) -> R): Try<T, B, R> =
copy(exceptionHandler = (exceptionHandler.toMap() + (e to handleException)) as Map<KClass<Exception>, (e: Exception) -> R>)
override fun invoke(): R {
return try {
block(it)
} catch (e: Exception) {
(exceptionHandler[e::class] ?: throw e)(e)
}
}
}
typealias TryRun<T, R> = Try<T, T.() -> R, R>
typealias TryLet<T, R> = Try<T, (T) -> R, R>
fun <T, R> T.tryRun(block: T.() -> R): TryRun<T, R> = TryRun(this, block)
fun <T, R> T.tryLet(block: (T) -> R): TryLet<T, R> = TryLet(this, block)
Motivation: | {
"domain": "codereview.stackexchange",
"id": 45360,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, kotlin, language-design",
"url": null
} |
error-handling, kotlin, language-design
Motivation:
Declaring TryRun and TryLet makes the use cases explicit. Additionally it defines the generic type parameter B of Try and provides thus an easier way to use than Try itself.
I choose to declare a function named on rather than catch. In my opinion it reads better within the code flow. It implies the fact of catching an Exception but shifts the focus on the corresponding behavior.
The declaration of on provides a usage following the builder pattern. But it doesn't change the internal state, it creates every time a new Try instance and thus doesn't use side-effects.
Using the invoke operator we can finish the building process without calling an additional named function. Everything in between is the parametrization of this call.
Some examples following the code conventions on wrapping chained calls and lambdas.
fun main() {
// succeeds - only happy path
"1".tryLet { DayOfWeek.of(it.toInt()) }()
.let { println("Day Of Week is: $it") }
"1".tryRun { DayOfWeek.of(toInt()) }()
.let { println("Day Of Week is: $it") }
// succeeds - provding two cases of exception handling
"5".tryRun { DayOfWeek.of(toInt()) }
.on(NumberFormatException::class) {
log(it)
DayOfWeek.MONDAY
}.on(DateTimeException::class) {
log(it)
DayOfWeek.MONDAY
}()
.let { println("Day Of Week is: $it") }
// fails with DateTimeException - (re)throws the exception
"0".tryRun { DayOfWeek.of(toInt()) }()
.let { println("Day Of Week is: $it") }
// fails with DateTimeException - returns SUNDAY as default value
"0".tryLet { DayOfWeek.of(it.toInt()) }
.on(NumberFormatException::class) {
log(it)
DayOfWeek.SUNDAY
}.on(DateTimeException::class) {
log(it)
DayOfWeek.SUNDAY
}()
.let { println("Day Of Week is : $it") } | {
"domain": "codereview.stackexchange",
"id": 45360,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, kotlin, language-design",
"url": null
} |
error-handling, kotlin, language-design
// fails with NumberFormatException - returns null as default value
"five".tryLet { DayOfWeek.of(it.toInt()) }
.on(NumberFormatException::class) {
log(it)
null
}.on(DateTimeException::class) {
log(it)
null
}()
.let { println("Day Of Week is : $it") }
// fails with NumberFormatException - explicitly re-throws the exception
"six".tryLet { DayOfWeek.of(it.toInt()) }
.on(NumberFormatException::class) {
logAntThrow(it)
}.on(DateTimeException::class) {
logAntThrow(it)
}()
.let { println("Day Of Week is : $it") }
}
fun log(entry: Any) = println(entry)
fun logAntThrow(e: Exception): Nothing {
log(e)
throw e
}
This is a draft and intended for first feedback. It is e.g. missing support for the finally case and doesn't take inheritance into account determining an exception handler.
Any hints / ideas ?
Answer: Consider options
You should consider looking at Kotlin's existing runCatching and the Arrow library's either.
A lot of what you are trying to accomplish already exists either built-in inside Kotlin or in a popular library.
Your code
I think that this code feels weird:
"0".tryRun { DayOfWeek.of(toInt()) }()
.let { println("Day Of Week is: $it") }
And it is clearer to write it as one of the following:
runCatching { DayOfWeek.of("0") }.fold(onSuccess = { println(it) }, onFailure = { throw it })
runCatching { DayOfWeek.of("0") }.onSuccess { println(it) }.getOrThrow() | {
"domain": "codereview.stackexchange",
"id": 45360,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, kotlin, language-design",
"url": null
} |
error-handling, kotlin, language-design
Additionally, your code creates a bit of overhead by creating instances of Try and multiple Map instances for every tryRun/tryLet that you do.
Multi-catch
I notice that all your catch statements seem to do the same thing at the moment, if that will be the case then you might want to consider catching a more generic exception. Even if you want to handle exceptions differently, you could get some inspiration from an article on how you would do multi-catch in Kotlin using the when-statement.
Side-note
As a side note, I think that your comparison of "Then a rather short" ... "becomes a bulky" is a bit unfair, as the first example (the "rather short" one) also doesn't match any Java coding conventions that I am familiar with. | {
"domain": "codereview.stackexchange",
"id": 45360,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, kotlin, language-design",
"url": null
} |
algorithm, swift, ios, caesar-cipher, swiftui
Title: Caesar Cipher in Swift (iOS-app)
Question: I have implemented the Caesar Cipher in Swift and incorporated it into an iOS-app.
I guess it's formally correct. Please see the attached images, which show how the usage of the app is meant. | {
"domain": "codereview.stackexchange",
"id": 45361,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, ios, caesar-cipher, swiftui",
"url": null
} |
algorithm, swift, ios, caesar-cipher, swiftui
Here's the relevant code:
struct ContentView: View {
@State var input = ""
@State var output = ""
@State var shift = 1
@State var hasSubmitted = false
var body: some View {
VStack {
Text("Caesar Cipher").font(.title)
Form {
Section("Text to Encrypt/Decrypt") {
TextField("Text to Encrypt/Decrypt", text: $input)
.lineLimit(2)
.disabled(hasSubmitted)
.textInputAutocapitalization(.never)
}
Section("Shift") {
Picker("Digits", selection: $shift) {
ForEach(1...25, id: \.self) { digit in
Text("\(digit)")
}
}
}
Section("Submit") {
HStack {
if hasSubmitted {
Spacer()
Button("Reset") {
input = ""
output = ""
hasSubmitted = false
shift = 1
}.buttonStyle(.borderedProminent)
Spacer()
} else {
Spacer()
ChoiceButton(caption: "Encrypt",
input: $input,
output: $output,
hasSubmitted: $hasSubmitted) { index, count in
(index + shift) % count
}
Spacer()
ChoiceButton(caption: "Decrypt",
input: $input,
output: $output, | {
"domain": "codereview.stackexchange",
"id": 45361,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, ios, caesar-cipher, swiftui",
"url": null
} |
algorithm, swift, ios, caesar-cipher, swiftui
output: $output,
hasSubmitted: $hasSubmitted) { index, count in
((index - shift) + count) % count
}
Spacer()
}
}
}
Section("Encrypt/Decrypt Result") {
Text(output).bold()
}
}
}
.padding()
}
} | {
"domain": "codereview.stackexchange",
"id": 45361,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, ios, caesar-cipher, swiftui",
"url": null
} |
algorithm, swift, ios, caesar-cipher, swiftui
struct ChoiceButton: View {
var caption: String
let alphabet = ["a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x",
"y", "z"]
@Binding var input: String
@Binding var output: String
@Binding var hasSubmitted: Bool
var algo: (Int, Int) -> Int
var body: some View {
Button(caption) {
guard input.isEmpty == false else {
return
}
let lInput = input.lowercased()
hasSubmitted = true
output = ""
for char in lInput {
let index = alphabet.firstIndex(of: String(char))
if let index = index {
let shiftedIndex = algo(index, alphabet.count)
output = "\(output)\(alphabet[shiftedIndex])"
} else {
output = "\(output)\(char)"
}
}
}.buttonStyle(.bordered)
}
}
Any feedback according the naming, form, algorithm, closure-usage, state-handling, app-implementation in general is welcomed.
Looking forward to reading your comments and answers.
Answer: My main point of criticism is that the encryption logic is in the view, actually in two views: the ContentView contains the code to shift one index forward or backward, and the ChoiceButton contains the code to apply that to strings. This should be factored out into a separate function
func caesar(input: String, shift: Int) -> String {
// ...
} | {
"domain": "codereview.stackexchange",
"id": 45361,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, ios, caesar-cipher, swiftui",
"url": null
} |
algorithm, swift, ios, caesar-cipher, swiftui
which makes things much clearer and simpler. It also allows to add unit test for the encryption function.
Even better, this refactoring makes the ChoiceButton obsolete: we can replace
ChoiceButton(caption: "Encrypt",
input: $input,
output: $output,
hasSubmitted: $hasSubmitted) { index, count in
(index + shift) % count
}
Spacer()
ChoiceButton(caption: "Decrypt",
input: $input,
output: $output,
hasSubmitted: $hasSubmitted) { index, count in
((index - shift) + count) % count
}
by
Button("Encrypt") {
hasSubmitted = true
output = caesar(input: input, shift: shift)
}
.buttonStyle(.bordered)
.disabled(input.isEmpty)
Spacer()
Button("Decrypt") {
hasSubmitted = true
output = caesar(input: input, shift: -shift)
}
.buttonStyle(.bordered)
.disabled(input.isEmpty) | {
"domain": "codereview.stackexchange",
"id": 45361,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, ios, caesar-cipher, swiftui",
"url": null
} |
algorithm, swift, ios, caesar-cipher, swiftui
The .disabled(input.isEmpty) replaces your test for an empty input field. In addition, it makes it visible to the user whether the buttons are active or not.
The encryption code itself can also be simplified a bit. If we declare alphabet as an array of Character then alphabet.firstIndex() can be called without casting the argument to a string. The encryption operation is a map: each character is mapped to a new character, therefore I would write it as such.
The function then looks like this:
func caesar(input: String, shift: Int) -> String {
let alphabet: [Character] = ["a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x",
"y", "z"]
let count = alphabet.count
return String(input.lowercased().map { char in
if let index = alphabet.firstIndex(of: char) {
let shiftedIndex = (index + shift + count) % count
return alphabet[shiftedIndex]
} else {
return char
}
})
}
Some more thoughts:
There is repeated information in the user interface, e.g. "Text to Encrypt/Decrypt" both as section header and as placeholder string. I would use only one or the other. Also a section header "Submit" above the Encrypt and Decrypt button is not necessary.
It looks better if the form is embedded in a NavigationView with a .navigationTitle, instead of a VStack:
var body: some View {
NavigationView {
Form {
// ...
}
.navigationTitle("Caesar Cipher")
}
} | {
"domain": "codereview.stackexchange",
"id": 45361,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, ios, caesar-cipher, swiftui",
"url": null
} |
c++, template-meta-programming
Title: (C++) Template code for adding tagging types to add additional context
Question: Below is a piece of template code which allows for adding a Tag to structure or class types.
#include <type_traits>
#include <concepts>
//Source: https://stackoverflow.com/questions/31171682/type-trait-for-copying-cv-reference-qualifiers
// Copies the const and volatile qualifiers from T to U;
// Example copy_cv< const double, float >::type == const float
template<typename T,typename U>
struct copy_cv
{
private:
using R = std::remove_reference_t<T>;
using U1 = std::conditional_t<std::is_const<R>::value, std::add_const_t<U>, U>;
using U2 = std::conditional_t<std::is_volatile<R>::value, std::add_volatile_t<U1>, U1>;
public:
using type = U2;
};
// Checks if a type is basicly the same as another ( ignoring const and volatile )
template< typename cvrefT, typename T >
concept basicly = std::is_same_v< std::remove_cvref_t< cvrefT >, T >;
// Checks if a type is a parent ( inheritance ) of another type
template< typename Base, typename Child >
concept parent_of = std::derived_from< Child, Base >;
// Code for converting between a tagged type and its base type
template< template<typename> typename Tag, typename Base >
struct TagConversion
{
template< basicly< Base > U >
static typename copy_cv< U, Tag< Base > >::type && Convert( U && u ){ return ( typename copy_cv< U, Tag< Base > >::type && ) u; }
template< parent_of< Base > T >
explicit(false) operator T & () { return reinterpret_cast< T & >( *this ); }
};
// Combination of conversion + inheritance( to allow access to methods )
template< template<typename> typename Tag, typename Base >
struct TagProxy: public TagConversion< Tag, Base >, public Base {};
// Convenience method to quickly tag a type
template< template<typename> typename Tag, typename Base >
auto && Convert( Base && base ){ return Tag< typename std::remove_cvref_t< Base > >::Convert( base ); } | {
"domain": "codereview.stackexchange",
"id": 45362,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
For example this could be used in the context of rendering where a point can be specified in world, screen, uv, camera, etc coordinates.
Example:
template< typename T >
struct WorldSpace: TagProxy< WorldSpace, T > {};
template< typename T >
struct ScreenSpace: TagProxy< ScreenSpace, T > {};
/// ======================================================== ///
struct Point
{
double x;
double y;
};
// With Context
ScreenSpace< Point > ToScreenSpace( WorldSpace< Point > const & inPoint )
{
return Convert< ScreenSpace >( Point{ inPoint.x * 2, inPoint.y * 2 } );
}
This would avoid passing coordinates to a function which are defined in the wrong target space by having the code not compile.
My Questions:
I know of the limitation that this cannot be used with types such as int ( as you cannot derive from them ). But are there any other potential issues that I haven't spotted yet
From my limited experiments, I would suspect that code using these templates and plain code is compiled to the same binary. Thus resulting in no performance overhead. But I'm not sure.
Could I give a nice error if a user tries to make WorldSpace<int>?
Could I enforce that an Tag ( such as WorldSpace ) does not "extend" the class ( i.e. has member variables )?
Any other improvements are also welcome
Answer: Missing test suite
You have a very basic example, but are you sure your code handles all the edge cases you want it to handle? And do they all make sense?
For example, the following does not compile:
volatile Point point{1, 2};
auto tagged_point = Convert<WorldSpace>(point);
It works if you remove volatile. The following does compile:
const Point point{1, 2};
auto tagged_point = Convert<WorldSpace>(point); | {
"domain": "codereview.stackexchange",
"id": 45362,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
But while you went to great lengths to copy the cv qualifiers, the resulting tagged_point is not const. This is because cv qualifiers don't really make sense when you return something by value; after all, the caller can always copy them into some variable with different qualifications.
The interface is confusing
It's easy to create a new Point:
Point point{1, 2};
But how do you create a WorldSpace<Point>? I think most people would try this first:
WorldSpace<Point> world_point{1, 2};
But that doesn't compile, and your compiler will probably say something like "initializer must be brace-enclosed", which is not a very helpful error message as you did write braces there. The actual problem is that you don't have enough braces; it only compiles when you write this:
WorldSpace<Point> world_point{{{}, {1, 2}}};
That does not look very great though. So to keep your sanity, you can instead use Convert<>() to create a new tagged object:
auto world_point = Convert<WorldSpace>(Point{1, 2});
But now you are conflating adding a tag with changing a tag. I would create two functions, one with unconditionally adds a tag to a type, and another which just changes the outer tag. So consider:
auto world_point = add_tag<WorldSpace>(Point{1, 2});
auto screen_point = convert_tag<ScreenSpace>(world_point);
And make it so the following will fail to compile:
auto screen_point = convert_tag<ScreenSpace>(Point{1, 2}); | {
"domain": "codereview.stackexchange",
"id": 45362,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
But even better, make it look more like the standard library, and consider naming it make_tagged<>() and tag_cast<>().
Avoid unnecessary moves and copies
While your code will move objects where possible, a move still might have some overhead. It also requires that the object is movable. Even better would be to avoid that entirely. That might not be possible if you want to convert tagged objects, but tagging can be useful even if you never convert them. If you can make a make_tagged<>() function that constructs the inner object in-place, you will get the best performance, and at the same time also allow for objects that are neither copyable nor movable. Consider being able to write:
auto world_point = add_tag<WorldSpace, Point>(1, 2);
Consider not using inheritance
Using inheritance gives you a way to transparently access the inner object. However, you will run into issues. You've already discovered that you can't use it with things like int. You also can't use it with classes that are marked final. There might be other corner cases where it will fail to work as expected. A much safer approach would be to avoid inheritance, and just store the inner object as a member variable, and overload operator*() and operator->() to let the user access it, just like you would for things like std::unique_ptr<>, std::optional<> and so on.
Answers to your questions
I know of the limitation that this cannot be used with types such as int ( as you cannot derive from them ). But are there any other potential issues that I haven't spotted yet
I already mentioned some of those above, although there might be other issues I haven't spotted either.
From my limited experiments, I would suspect that code using these templates and plain code is compiled to the same binary. Thus resulting in no performance overhead. But I'm not sure. | {
"domain": "codereview.stackexchange",
"id": 45362,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
Just compile it and look at the assembly output! Note that while the size of the tagged object is the same as the untagged object, there might be subtle issues that cause differences in performance. For example, depending on the inner object, the compiler might not be able to optimize away conversions. On the other hand, types with different tags cannot alias each other, so using tags might actually improve performance in some cases.
Could I give a nice error if a user tries to make WorldSpace<int>?
You can use either a requires clause that checks for std::is_class<Base>, or add a static_assert() declaration that does the same. The latter allows for adding a custom error message, but a requires clause might be preferred as it will trigger earlier (with the static_assert() it will complain the error is inside the TagProxy<> template, whereas with the requires it will say the error is at the point where somebody wants to create a WorldSpace<int>).
Could I enforce that an Tag ( such as WorldSpace ) does not "extend" the class ( i.e. has member variables )?
You can use std::is_empty<Tag> to check that the size of the tag is zero bytes. However, this still allows for member functions, and also there are ways to create variables that have a size of zero, so it's not failsafe. There is no way in C++ to check that it has no members at all.
However, even if the Tag has members, they are not exposed at all in the resulting tagged class, since you never actually derive directly from Tag, nor have a Tag as a member object. It's only part of the type as a template parameter. | {
"domain": "codereview.stackexchange",
"id": 45362,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming",
"url": null
} |
python, datetime, comparative-review, time
Title: Subtract two lap times (m:ss:fff)
Question: I have two lap time strings I need to subtract, the format is minutes, seconds, milliseconds. This is to compare a new world record time to the previous holder's time. The result will always be positive.
Example input:
x = "1:09.201"
y = "0:57.199"
# 12.002
I have two working solutions, but I'm not sure I'm content. Am I able to make this better, shorter, cleaner, or more readable?
1st solution:
from datetime import datetime, time, timedelta
def getTimeDifference(t1, t2):
wrTime = convertTimeString(t1)
wrTime = datetime(2000, 1, 1,
minute=wrTime["minutes"],
second=wrTime["seconds"],
microsecond=wrTime["milliseconds"]*1000
)
previousWrTime = convertTimeString(t2)
previousWrTime = datetime(2000, 1, 1,
minute=previousWrTime["minutes"],
second=previousWrTime["seconds"],
microsecond=previousWrTime["milliseconds"]*1000
)
current, prev = wrTime.timestamp(), previousWrTime.timestamp()
difference = round(prev - current, 3)
return difference
def convertTimeString(time):
time = time.replace(":", " ").replace(".", " ").split()
try:
converted = {
"minutes": int(time[0]),
"seconds": int(time[1]),
"milliseconds": int(time[2])
}
except IndexError:
print("Index error occured when formatting time from scraped data")
return converted
x = "1:09.201"
y = "0:57.199"
print(getTimeDifference(y, x))
2nd solution:
from datetime import datetime, time, timedelta | {
"domain": "codereview.stackexchange",
"id": 45363,
"lm_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, comparative-review, time",
"url": null
} |
python, datetime, comparative-review, time
2nd solution:
from datetime import datetime, time, timedelta
# Takes two m:ss.fff time strings
# Example: 1:
def getTimeDifference(t1, t2):
wrTime = convertTimeString(t1)
time1 = timedelta(
minutes=wrTime["minutes"],
seconds=wrTime["seconds"],
milliseconds=wrTime["milliseconds"])
previousWrTime = convertTimeString(t2)
time2 = timedelta(
minutes=previousWrTime["minutes"],
seconds=previousWrTime["seconds"],
milliseconds=previousWrTime["milliseconds"])
diff = time2 - time1
formatted = f"{diff.seconds}.{int(diff.microseconds/1000):>03}"
return formatted # 0.000 seconds
def convertTimeString(time):
time = time.replace(":", " ").replace(".", " ").split()
try:
converted = {
"minutes": int(time[0]),
"seconds": int(time[1]),
"milliseconds": int(time[2])
}
except IndexError:
print("Index error occured when formatting time from scraped data")
return converted
x = "1:09.201"
y = "0:57.199"
print(getTimeDifference(y, x))
``` | {
"domain": "codereview.stackexchange",
"id": 45363,
"lm_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, comparative-review, time",
"url": null
} |
python, datetime, comparative-review, time
return converted
x = "1:09.201"
y = "0:57.199"
print(getTimeDifference(y, x))
```
Answer: Figure out what your requirements are; your two variations actually perform different operations: the first one returns the difference as a float of seconds, the second one as a formatted string. I'd argue the best format for a time difference is a timedelta instance, and factor out the formatting code.
Use the standard library when you can. In this case, you can easily parse any string into a datetime object using datetime.strptime as long as you know the string format. This is likely more robust than your own implementation, more concise, and easier to understand when reading code.
You can subtract two datetime objects directly to get the resulting timedelta, no need to manually build timedelta's before performing arithmetic.
Include type hints to your function's signature, to make it clear that it expects strings and returns a float/string/timedelta (depending on implementation). You could also document it with a docstring, but I feel like it might not be necessary with type hints.
There is no built-in method for formatting timedelta, so your formatting code is about as good as it gets.
You don't use datetime.time, so you should remove that import.
With this in mind, you can achieve your requirements with very few lines of code:
from datetime import datetime, timedelta
TIME_FORMAT = '%M:%S.%f'
def get_time_difference(t1: str, t2:str) -> timedelta:
return (datetime.strptime(t1, TIME_FORMAT)
- datetime.strptime(t2, TIME_FORMAT))
def format_difference(difference: timedelta) -> str:
sign = '-' if difference.days < 0 else ''
if difference.days < 0:
difference = - difference
return f'{sign}{difference.seconds}.{difference.microseconds//1000:03}'
if __name__ == '__main__':
print(format_difference(get_time_difference('1:09.201', '0:57.199'))) | {
"domain": "codereview.stackexchange",
"id": 45363,
"lm_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, comparative-review, time",
"url": null
} |
python, datetime, comparative-review, time
if __name__ == '__main__':
print(format_difference(get_time_difference('1:09.201', '0:57.199')))
Edit: as pointed out in the comments, formatting can be simplified a lot by using the total_seconds method of the timedelta class:
def format_difference(difference: timedelta) -> str:
return f'{difference.total_seconds():.3f}'
Now that all functionality is implemented with simple calls to standard library methods, the relevance of wrapping them in helper functions such as these is questionable, I'll let you decide depending on your actual use case. | {
"domain": "codereview.stackexchange",
"id": 45363,
"lm_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, comparative-review, time",
"url": null
} |
java, stream, lambda
Title: Find all line numbers of prefix duplicates with streams
Question: All line indices of lines from a text that begin with the same line prefix should be found. The prefixes and the corresponding line numbers should be returned. Streams and lambdas should be used as techniques if possible.
The format of a line is always as follows:
anyText_anyText_number_number
where anyText_anyText is the prefix, and one line has at least 7 chars.
For example:
a_b_0_1
c_d_5_8
c_d_9_3
b_d_1_12
should return {c_d=[2, 3]}.
The prefixes (here c_d) could be any text (inclusive additional underscores, but without newlines...).
This is my try:
public static void main(final String[] args) {
String s = """
a_b_0_1
c_d_5_8
c_d_9_3
b_d_1_12""";
Map<String, List<Integer>> duplicates = s.lines()
.collect(Collectors.groupingBy(l -> l.substring(0, IntStream.range(0, l.length())
.map(i -> l.length() - i - 1)
.filter(i -> l.charAt(i) == '_')
.skip(1)
.findFirst()
.orElse(0))))
.entrySet()
.stream()
.filter(e -> e.getValue()
.size() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
.stream()
.map(e1 -> {
LineNumberReader lnr = new LineNumberReader(new StringReader(s));
return lnr.lines()
.filter(l -> l.equals(e1))
.map(l -> lnr.getLineNumber())
.findFirst()
.orElse(0);
})
.toList()));
System.out.println(duplicates); // print all duplicates line numbers
} | {
"domain": "codereview.stackexchange",
"id": 45364,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, stream, lambda",
"url": null
} |
java, stream, lambda
System.out.println(duplicates); // print all duplicates line numbers
}
Could this code be simplified?
Answer: First off, the description of your code is quite unclear and leaves things out. In your comment you mention "at least 3 characters followed by an underscore", however that is not what your code does. I'm basing my review on what the code does, not the description.
I think your biggest problem is fixating on using Stream, because Java Stream lacks several features that would be helpful in this scenario, for example a zipWithIndex method and tuples in order to handle more than a single value at a time.
The part that extracts the prefix is especially convoluted. At the very least it should be extracted to its own method. If I understand it correctly, it considers everything before the last two underscores the prefix.
The most straight forward way to this would be the split the string at the underscores, remove the last two items and rejoin the items with underscores. Unfortunately Standard Java lacks methods the remove the last n elements of a Stream or a List. I don't think this can be be done sensibly with Stream. I would do something like this:
private static String prefix(String text) {
List<String> sections = Arrays.asList(text.split("_"));
return String.join("_", sections.subList(0, sections.size() - 2));
}
One big problem is that you only take a String with line breaks as an input, due to the convoluted way to find the line numbers with LineNumberReader in the end. An input in form of a List would be more appropriate. For this - and for reviews like this one - it would be helpful to put the central code into a well defined method.
As I suggested above, with a tuple (or alternatively a custom class, or in my case a record) this would be much easier:
public static void main(final String[] args) {
String s = """
a_b_0_1
c_d_5_8
c_d_9_3
b_d_1_12"""; | {
"domain": "codereview.stackexchange",
"id": 45364,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, stream, lambda",
"url": null
} |
java, stream, lambda
System.out.println(findDuplicatePrefixes(s.lines().toList()));
}
private static record Line(int lineNumber, String text) {}
private static Map<String, List<Integer>> findDuplicatePrefixes(List<String> lines) {
return IntStream.range(0, lines.size())
.mapToObj(i -> new Line(i + 1, lines.get(i)))
.collect(groupingBy(
l -> prefix(l.text()),
mapping(Line::lineNumber, toList())
)).entrySet()
.stream()
.filter(e -> e.getValue().size() > 1)
.collect(toMap(Entry::getKey, Entry::getValue));
} | {
"domain": "codereview.stackexchange",
"id": 45364,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, stream, lambda",
"url": null
} |
c#, enum
Title: BOOL×BOOL→ENUM mapping
Question: Does this part look clean enough? Any suggestions on how to make it cleaner?
if (isCheck)
{
if (isStuck)
{
return GameState.Mate;
}
else
{
return GameState.Check;
}
}
else
{
if (isStuck)
{
return GameState.Stalemate;
}
else
{
return GameState.Ok;
}
}
Answer: I'd use a decision table here:
GameState[,] decisionTable = new GameState[2,2];
decisionTable[0,0] = GameState.Ok;
decisionTable[0,1] = GameState.Stalemate;
decisionTable[1,0] = GameState.Check;
decisionTable[1,1] = GameState.Mate;
return decisionTable[Convert.ToInt32(isCheck), Convert.ToInt32(isStuck)];
From Code Complete 2nd Edition, Chapter 19: General Control Issues, page 431:
Use decision tables to replace complicated conditions
Sometimes you have a complicated test involving several variables. It can be helpful to use a decision table to perform the test rather than using ifs or cases. A decision-table lookup is easier to code initially, having only a couple of lines of code and no tricky control structures. This minimization of complexity minimizes the opportunity for mistakes. If your data changes, you can change a decision table without changing the code; you only need to update the contents of the data structure. | {
"domain": "codereview.stackexchange",
"id": 45365,
"lm_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#, enum",
"url": null
} |
c++, strings, reinventing-the-wheel, floating-point
Title: Calculate the maximum number of decimal places with which all floating point numbers can be represented in a range in C++
Question: I'm looking for a function in C++ that can determine, how accurate all floating point numbers in a given range can be represented as strings, without the use of e.g. boost library, etc.
Please take a look at my code and tell me how it can be improved.
#include <iostream>
#include <cmath>
#include <cfloat>
/**
* Calculates the scale of a given string.
*
* @param str the string to calculate the scale of
*
* @return the scale of the string
*
* @throws None
*/
int get_scale_of(const std::string &str)
{
int scale = 0;
for (int i = str.length() - 1; i >= 0; i--)
{
if (str[i] != '0')
{
break;
}
scale++;
}
return str.length() - str.find('.') - scale - 1;
}
/**
* Calculates the maximum precision in the range of floating-point numbers.
*
* @param min The minimum value of the range.
* @param max The maximum value of the range.
*
* @return The maximum precision in the range.
*
* @throws None.
*/
int get_max_precision_in_range_for_float(const int min, const int max)
{
int precision = 100;
float f = min;
while (f < max)
{
float n = std::nextafter(f, FLT_MAX);
std::string s1 = std::to_string(f);
std::string s2 = std::to_string(n);
while (s1 == s2)
{
n = std::nextafter(n, FLT_MAX);
s2 = std::to_string(n);
}
int p = std::max(get_scale_of(s1), get_scale_of(s2));
if (p < precision)
{
precision = p;
// Debug outputs:
std::cout << "s1 = " << s1 << "\n";
std::cout << "s2 = " << s2 << "\n";
}
f = n;
}
return precision;
} | {
"domain": "codereview.stackexchange",
"id": 45366,
"lm_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, reinventing-the-wheel, floating-point",
"url": null
} |
c++, strings, reinventing-the-wheel, floating-point
int main(int argc, char const *argv[])
{
// Some examples:
std::cout << get_max_precision_in_range_for_float(1, 2) << " digits accuracy\n";
std::cout << get_max_precision_in_range_for_float(7, 8) << " digits accuracy\n";
std::cout << get_max_precision_in_range_for_float(500000, 600000) << " digits accuracy\n";
return 0;
}
Answer: Precision vs digits
While the decimal representation of a floating point number might result in a certain number of digits, that's not the same as the precision of the floating point number itself. Only some of them are significant digits. In fact, also some of the digits that appear before the decimal point can be significant digits.
It's easy to mistake the number of digits for precision, but we should try to avoid that. Your function might still be useful as it is, but then it should be renamed. Maybe get_max_decimal_representation_digits_in_range_for_float()? That's awfully long though, maybe get_max_decimals_in_range() would be better.
Converting floating point numbers to strings
You are using std::to_string() to convert floating point numbers to strings. However, by default this will always limit the number of digits after the decimal separator to 6, regardless of how large or small that number is.
floats have a precision of 23 bits, which is almost 7 decimal digits. To represent the value of a float in decimal notation exactly, you might even need more digits than that. You can use std::to_chars() to do that.
Improve the interface
Despite the name mentioning float, the two arguments are ints. What if I want to know the max number of decimals in the range 0.1 to 0.2? Or from 1.0e41 to 1.0e42? What about doubles? I would take the parameters as floating point numbers. And to make it also handle doubles, make it a template:
template<typename T>
int get_max_decimals_in_range(const T min, const T max)
{
int precision = 100;
T f = min;
while (f < max) {
…
}
return precision;
} | {
"domain": "codereview.stackexchange",
"id": 45366,
"lm_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, reinventing-the-wheel, floating-point",
"url": null
} |
c++, strings, reinventing-the-wheel, floating-point
Also consider that there are several ways to convert floating point values to strings. Instead of hardcoding which method to use, you can let the caller pass in the conversion function they want tested, or use a default function if they don't provide anything. It could look like:
template<typename T>
int get_max_decimals_in_range(const T min, const T max,
std::function<std::string(T)> convert = [](T value){
return std::to_string(value);
})
{
…
std::string s1 = convert(f);
std::string s2 = convert(n);
…
}
And then call it like:
std::cout << get_max_decimals_in_range<float>(1, 2) << " digits accuracy\n";
Runtime
Your program will run for a long time. It will do about \$2^{23}\$ string conversions and comparisons to check the maximum number of decimals in the range of 1 to 2. But that's a lot of wasted time, as std::to_string() is capped at 6 decimals, and you reach that number after just a few iterations of your loops. So there is a lot of potential for optimization here. Even better:
You don't need string conversion
The smallest difference between consecutive floating point numbers in the given range is std::nextafter(min, max) - min. In binary, that difference is of the form 0.000…001. So you can use std::log2() of that to get how many binary digits there are after the decimal point. From that you can in principle calculate the number of decimal digits you need. I'll leave that as an excercise for the reader. | {
"domain": "codereview.stackexchange",
"id": 45366,
"lm_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, reinventing-the-wheel, floating-point",
"url": null
} |
python
Title: OpenAI API: Return structured data from text input
Question: Given a txt input which represents extracted resume (or “CV” outside of the US) data, pass the text to an AI model and return a JSON version of the original input.
I have created the below script, which tries to prompt gpt3-turbo in order to process and return the JSON.
As well as the usual review, I am also looking for any guidance on the below list:
Is a GPT even needed to achieve this?
If so is the gpt3-turbo model ideal for this sort of work?
Can I prompt GPT any better to achieve high confidence scoring?
How could I improve the standardisation of the response so that in the case we get an unexpected field, it doesn't explode a client
Is there a way to make the processing go faster? I know the bottleneck is the call to OpenAI - can I do anything with my inputs to make it faster?
It's worth noting that the input txt can change in an arbitrary way. It is most likely never the exact same format.
Code
import json
from openai import OpenAI, Stream
from openai.types.chat import ChatCompletion, ChatCompletionChunk
OPENAI_API_KEY = "sk-*"
# Low Temperature (e.g., 0.0 to 0.3)
# A low temperature makes the model's responses more deterministic and conservative.
TEMPERATURE = 0.1
MAX_TOKENS = 2500
RAW_DATA = """
Forename SURNAME
e-mail: professional email address tel: UK landline or mobile
Education and Qualifications
2000-2003
University/Universities
Location; City and Country
Degree and Subject
applicable additional info
Work Experience | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
Work Experience
Sep-07 – Aug-10
Official Company Name
Job title
Please use 3-4 bullets maximum to describe your job function &
City, Country
responsibilities
Concentrate on your achievements, and what you have distinctly
contributed to in each role, using quantitative examples where possible
Examples that may assist you –
“Advised client’s Digital Media division on £3M international expansion,
coordinating a team of 8 analysts during initial research phase”
“Structured and negotiated equipment deal financing including credit
purchases, rentals, and 31 lease contracts worth $745k”
Jun-05 – Sep-07
Official Company Name
Job title
Make sure your work experience comes to life, consider what someone
City, Country
reading your CV would be most interested in
Avoid any negativity or short comings on your CV that may raise the
wrong questions
Try to avoid having your CV read like a job description
Mar-04 – Jun-05
Official Company Name
Job title
Try to ensure your CV is easy to scan, start bullet points with relevant
City, Country
action verbs
You can also include significant relevant voluntary experience in your
work experience if it is applicable
Try to avoid industry jargon that may not be understood
Aug-03 – Mar-04
Official Company Name
Job title
Use past tense for roles you have completed
Please set dates using the abbreviated month and two digits for the year,
City, Country
you must include months as well as years
Make sure your CV is an accurate reflection of you and what you want to
highlight about your experience
Stick to facts you can easily discuss. Avoid subjective comments
Additional Information
Interests:
Concentrate on activities you participate in and are willing to talk about. You
should highlight achievements in those activities. Eg. rather than just listing
‘running’ say ‘running – participated in several marathons, President of the
Oxford Runners Club’ | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
Achievements:
List academic or other achievements here, for example
First Class Honours, Previous University
Study abroad scholarship (selected 3 out of 600 students)
Principal Cellist of London Youth Orchestra
Nationality:
your nationality, dual nationality, and any additional work authorization if
applicable
Languages:
languages other than English and ability level eg. German (fluent)
""" | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
def parse_cv(client: OpenAI) -> ChatCompletion | Stream[ChatCompletionChunk]:
conversation = [
{
"role": "system",
"content": (
"You are a sophisticated resume parser. "
"Your task is to analyze, extract, and structure data from resumes. "
"You should identify and separate key sections such as "
"personal details, professional experience, education, skills, and additional information "
"like certifications or personal projects. "
"For each section, provide structured information in a clear, concise, and organized manner."
)
},
{
"role": "user",
"content": (
"Please parse the following resume and return all data structured as JSON. "
"For each section, include a confidence score indicating your certainty that the information is "
"correctly extracted and true. "
"Focus on accurately identifying and categorizing the data into predefined fields such as name, "
"contact information, work history, educational background, skills, and any other relevant sections. "
"Handle ambiguities or unclear information gracefully, "
"and indicate areas of uncertainty in your confidence scores."
)
},
{
"role": "user",
"content": RAW_DATA
}
]
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=conversation,
max_tokens=MAX_TOKENS,
temperature=TEMPERATURE,
stop=None
)
return response
def gpt_verify() -> ChatCompletion | Stream[ChatCompletionChunk]:
client = OpenAI(api_key=OPENAI_API_KEY)
cv_data = parse_cv(client)
return cv_data | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
if __name__ == "__main__":
result = gpt_verify()
str_result = result.choices[0].message.content
json_result = json.loads(str_result)
print(json_result) | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
Current Output
{
"name": {
"forename": "Forename",
"surname": "SURNAME",
"confidence": 0.9
},
"contact_information": {
"email": "professional email address",
"phone": "UK landline or mobile",
"confidence": 0.8
},
"education": {
"items": [
{
"start_date": "2000",
"end_date": "2003",
"institution": "University/Universities",
"location": "City and Country",
"degree": "Degree and Subject",
"additional_info": "applicable additional info",
"confidence": 0.9
}
]
},
"work_experience": {
"items": [
{
"start_date": "Sep-07",
"end_date": "Aug-10",
"company": "Official Company Name",
"job_title": "Job title",
"responsibilities": [
"Please use 3-4 bullets maximum to describe your job function & responsibilities",
"Concentrate on your achievements, and what you have distinctly contributed to in each role, using quantitative examples where possible",
"Examples that may assist you –",
"“Advised client’s Digital Media division on £3M international expansion, coordinating a team of 8 analysts during initial research phase”",
"“Structured and negotiated equipment deal financing including credit purchases, rentals, and 31 lease contracts worth $745k”"
],
"location": "City, Country",
"confidence": 0.8
},
{
"start_date": "Jun-05",
"end_date": "Sep-07",
"company": "Official Company Name",
"job_title": "Job title",
"responsibilities": [
"Make sure your work experience comes to life, consider what someone reading your CV would be most interested in",
"Avoid any negativity or shortcomings on your CV that may raise the wrong questions",
"Try to avoid having your CV read like a job description"
],
"location": "City, Country",
"confidence": 0.8
}, | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
],
"location": "City, Country",
"confidence": 0.8
},
{
"start_date": "Mar-04",
"end_date": "Jun-05",
"company": "Official Company Name",
"job_title": "Job title",
"responsibilities": [
"Try to ensure your CV is easy to scan, start bullet points with relevant action verbs",
"You can also include significant relevant voluntary experience in your work experience if it is applicable",
"Try to avoid industry jargon that may not be understood"
],
"location": "City, Country",
"confidence": 0.8
},
{
"start_date": "Aug-03",
"end_date": "Mar-04",
"company": "Official Company Name",
"job_title": "Job title",
"responsibilities": [
"Use past tense for roles you have completed",
"Please set dates using the abbreviated month and two digits for the year, you must include months as well as years",
"Make sure your CV is an accurate reflection of you and what you want to highlight about your experience",
"Stick to facts you can easily discuss. Avoid subjective comments"
],
"location": "City, Country",
"confidence": 0.8
}
]
},
"additional_information": {
"interests": "Concentrate on activities you participate in and are willing to talk about. You should highlight achievements in those activities. Eg. rather than just listing ‘running’ say ‘running – participated in several marathons, President of the Oxford Runners Club’",
"achievements": "List academic or other achievements here, for example\nFirst Class Honours, Previous University\nStudy abroad scholarship (selected 3 out of 600 students)\nPrincipal Cellist of London Youth Orchestra",
"nationality": "your nationality, dual nationality, and any additional work authorization if applicable", | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
"languages": "languages other than English and ability level eg. German (fluent)",
"confidence": 0.7
}
} | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
Answer: Current code
The parse_cv function should already take the CV text as an input argument
There should be no variables declared in the global scope to avoid redeclarations and conflicts: everything
under if __name__ == __main__: should be moved to a def main() -> None: function
Data validation
With your current implementation, the LLM model might be inconsistent, and asking it to generate a data
format based on an informal description will make its response impossible to validate and exploit systematically.
Sending a precise data structure to ChatGPT might help it understand what you expect.
You could use simple dataclasses, but a more powerful choice would be to use pydantic
models, that allow you to define data structures, and validate the data before instantiating the classes.
A format could look like this (defined in a file named candidate.py):
import datetime
from typing import Sequence
from pydantic import BaseModel, EmailStr, Field
class Name(BaseModel):
forename: str
surname: str
confidence: float
class ContactInformation(BaseModel):
email: EmailStr
phone: str
confidence: float
class Location(BaseModel):
city: str
country: str
confidence: float
class Period(BaseModel):
start_date: datetime.date = Field(description="The start date of the period, in a YYYY-MM-DD format")
end_date: datetime.date = Field(description="The end date of the period, in a YYYY-MM-DD format")
class EducationItem(BaseModel):
period: Period
institution: str
location: Location
degree: str
additional_info: str
confidence: float
class WorkExperienceItem(BaseModel):
period: Period
company: str
job_title: str
responsibilities: Sequence[str]
location: Location
confidence: float
class AdditionalInformation(BaseModel):
interests: Sequence[str]
achievements: Sequence[str]
nationality: str
languages: Sequence[str]
confidence: float | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
class Candidate(BaseModel):
name: Name
contact_information: ContactInformation
education: Sequence[EducationItem]
work_experience: Sequence[WorkExperienceItem]
additional_information: AdditionalInformation | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
Some fields can be defined as optional to make the validation more flexible to missing information in the resume,
and adding Field descriptions and docstrings might help ChatGPT for the data extraction.
The Candidate model can be instantiated with the following JSON (slightly modified from your version):
{
"name": {"forename": "Forename", "surname": "SURNAME", "confidence": 0.9},
"contact_information": {
"email": "professional@address.uk",
"phone": "UK landline or mobile",
"confidence": 0.8
},
"education": [
{
"period": {"start_date": "2000-09-01", "end_date": "2003-06-01"},
"institution": "University/Universities",
"location": {
"city": "City",
"country": "Country"
},
"degree": "Degree and Subject",
"additional_info": "applicable additional info",
"confidence": 0.9
}
],
"work_experience": [
{
"period": {"start_date": "2007-09-01", "end_date": "2010-08-01"},
"location": {
"city": "City",
"country": "Country"
},
"company": "Official Company Name",
"job_title": "Job title",
"responsibilities": [
"Please use 3-4 bullets maximum to describe your job function & responsibilities"
],
"confidence": 0.8
}
],
"additional_information": {
"interests": ["Table tennis", "Scrabble"],
"achievements": ["Multiple patents", "Academic award"],
"nationality": "your nationality, dual nationality, and any additional work authorization if applicable",
"languages": ["Mandarin", "Javanese", "Cajun"],
"confidence": 0.7
}
}
With the file candidate.py in the same folder:
import json
from pathlib import Path
from .candidate import Candidate | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
python
def parse_cv(cv_text: str) -> str:
candidate_def = Path("candidate.py").read_text(encoding="utf-8")
# candidate_def can be injected in the prompt
...
return json_result
def main() -> None:
cv_text = ...
json_result: str = parse_cv(cv_text)
candidate = Candidate(**json.loads(json_result))
print(candidate.work_experience[0].period.start_date.year)
# 2007
if __name__ == "__main__":
main()
If the JSON is not valid according to the Candidate model, a ValidationError is raised:
from .candidate import Candidate
invalid_json = {
"name": {"forename": "", "surname": "", "confidence": 0.9},
"contact_information": {
"email": "a@b",
"phone": "",
"confidence": 0.8,
},
"education": [],
"work_experience": [],
"additional_information": {
"interests": [],
"achievements": [],
"nationality": "",
"languages": [],
"confidence": 0.7,
},
}
candidate = Candidate(**invalid_json)
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Candidate
# contact_information.email
# value is not a valid email address: The part after the @-sign is not valid. It should have a period. [type=value_error, input_value='a@b', input_type=str]
``` | {
"domain": "codereview.stackexchange",
"id": 45367,
"lm_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",
"url": null
} |
c++, beginner, rock-paper-scissors
Title: Beginner Rock-Paper-Scissors game
Question: As a beginner, this is my second game in C++. It is a very simple rock-paper-scissors game. User or computer wins the game after a given number of rock,paper or scissors matches. I'd appreciate any comment improving or criticising my code in any way. Thanks!
// Rock-Paper-Scissors game
#include <iostream>
#include <random>
#include <chrono>
char getUserInput();
char getCompInput();
void showValue(char x);
void getWinner(char x, char y);
int getScore(char x, char y);
int main()
{
std::cout << "Welcome to Rock-Paper-Scissors Game!\n";
// Ask how many matches to play
int matches;
std::cout << "How many games do you want to play?: \n";
std::cin >> matches;
// check if user enters a valid number
while (matches < 1)
{
std::cout << "Please enter a valid number.\n";
std::cout << "How many games do you want to play? \n";
std::cin >> matches;
}
// Play the game and get the score
int countmatches = 0;
int score = 0;
while (countmatches < matches)
{
char player = getUserInput();
std::cout << "You chose: ";
showValue(player);
char comp = getCompInput();
std::cout << "Computer chose: ";
showValue(comp);
getWinner(player, comp);
score = score + getScore(player, comp);
countmatches++;
}
std::cout << matches << " matches played in total. \n";
// Declare the winner
if (score < 0)
{
std::cout << "YOU LOST THE GAME! \n";
}
else if (score == 0)
{
std::cout << "IT'S A TIE! \n";
}
else
{
std::cout << "YOU WON THE GAME! \n";
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, rock-paper-scissors",
"url": null
} |
c++, beginner, rock-paper-scissors
return 0;
}
// ask for user input
char getUserInput()
{
char userInput{' '};
std::cout << "Rock, paper or scissors? (r-p-s): \n";
std::cin >> userInput;
if (userInput != 'r' && userInput != 'p' && userInput != 's')
{
std::cout << "Please enter a valid character. \n";
std::cout << "Rock, paper or scissors? (r-p-s): \n";
std::cin >> userInput;
}
return userInput;
}
// generate computer's choice using a random number generator
char getCompInput()
{
std::mt19937 mt{static_cast<std::mt19937::result_type>(std::chrono::steady_clock::now().time_since_epoch().count())};
std::uniform_int_distribution randDist{1, 3};
int r = randDist(mt);
switch (r)
{
case 1:
return 'r';
break;
case 2:
return 'p';
break;
case 3:
return 's';
break;
}
return 0;
}
// show choice of r, p or s
void showValue(char x)
{
switch (x)
{
case 'r':
std::cout << "Rock\n";
break;
case 'p':
std::cout << "Paper\n";
break;
case 's':
std::cout << "Scissors\n";
break;
}
}
// find the winner
void getWinner(char x, char y)
{
if ((x == 'r' && y == 'p') || (x == 'p' && y == 's') || (x == 's' && y == 'r'))
{
std::cout << "YOU LOST!\n";
}
else if (x == y)
{
std::cout << "IT'S A TIE!\n";
}
else
{
std::cout << "YOU WON!\n";
}
}
// count score
int getScore(char x, char y)
{
if ((x == 'r' && y == 'p') || (x == 'p' && y == 's') || (x == 's' && y == 'r'))
{
return -1;
}
else if (x == y)
{
return 0;
}
else
{
return 1;
}
}
Answer: Overview
Overall OK.
Your main issue is failure to reset the stream state on failure and assuming your human follows instructions. A bit more work there.
I rather than use a char to hold the state. I would use an enum
enum Throw {Rock, Paper, Scissors}; | {
"domain": "codereview.stackexchange",
"id": 45368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, rock-paper-scissors",
"url": null
} |
c++, beginner, rock-paper-scissors
This will make the code easier to read. Also this matches up to zero/one/two so it makes accessing arrays easier (see below).
Codereview
This looks like a C interface. Did you not want to write a C++ application?
char getUserInput();
char getCompInput();
void showValue(char x);
void getWinner(char x, char y);
int getScore(char x, char y);
When reading data from an untrusted source (always - but most specifically humans), you need to validate that the read worked.
int matches;
// This read assumes that the next character on the
// input stream is a number. If it is not then the
// read will fail (I am not sure if `matches` is set to zero
// on a failure) but I would not make that assumption.
// defensive coding and all.
std::cin >> matches;
// But even if a read failure set matches to zero.
// A read failure will put the stream into an error state.
// Any subsequent read operation will not work until you
// get the stream out of the error state.
while (matches < 1)
The correct way to do this is:
int matches = 0;
std::cout << "How many games do you want to play?: \n"; | {
"domain": "codereview.stackexchange",
"id": 45368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, rock-paper-scissors",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.