text stringlengths 1 2.12k | source dict |
|---|---|
c++, algorithm, recursion, template, c++20
/* recursive_find_if template function implementation with unwrap level
*/
template<std::size_t unwrap_level, class T, class Proj = std::identity,
recursive_projected_invocable<unwrap_level, Proj, T> UnaryPredicate>
constexpr auto recursive_find_if(T&& value, UnaryPredicate&& p, Proj&& proj = {}) {
if constexpr (unwrap_level > 0)
{
return std::ranges::find_if(value, [&](auto& element) {
return recursive_find_if<unwrap_level - 1>(element, p, proj);
}) != std::ranges::end(value);
}
else
{
return std::invoke(p, std::invoke(proj, value));
}
}
/* recursive_find_if_not template function implementation with unwrap level
*/
template<std::size_t unwrap_level, class T, class Proj = std::identity,
recursive_projected_invocable<unwrap_level, Proj, T> UnaryPredicate>
constexpr auto recursive_find_if_not(T&& value, UnaryPredicate&& p, Proj&& proj = {}) {
if constexpr (unwrap_level > 0)
{
return std::ranges::find_if(value, [&](auto& element) {
return recursive_find_if_not<unwrap_level - 1>(element, p, proj);
}) != std::ranges::end(value);
}
else
{
return !std::invoke(p, std::invoke(proj, value));
}
}
// recursive_any_of template function implementation with unwrap level
template<std::size_t unwrap_level, class T, class Proj = std::identity,
recursive_projected_invocable<unwrap_level, Proj, T> UnaryPredicate>
constexpr auto recursive_any_of(T&& value, UnaryPredicate&& p, Proj&& proj = {})
{
return recursive_find_if<unwrap_level>(value, p, proj);
}
// recursive_none_of template function implementation with unwrap level
template<std::size_t unwrap_level, class T, class Proj = std::identity,
recursive_projected_invocable<unwrap_level, Proj, T> UnaryPredicate>
constexpr auto recursive_none_of(T&& value, UnaryPredicate&& p, Proj&& proj = {})
{
return !recursive_any_of<unwrap_level>(value, p, proj);
} | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c++, algorithm, recursion, template, c++20
template<std::ranges::input_range T>
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(std::ranges::cbegin(input), std::ranges::cend(input), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range T>
requires (std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
// recursive_transform_reduce template function implementation
template<std::size_t unwrap_level, class Input, class T, class UnaryOp = std::identity, class BinaryOp = std::plus<T>>
requires(recursive_invocable<unwrap_level, UnaryOp, Input>)
constexpr auto recursive_transform_reduce(const Input& input, T init = {}, const UnaryOp& unary_op = {}, const BinaryOp& binop = std::plus<T>())
{
if constexpr (unwrap_level > 0)
{
return std::transform_reduce(std::ranges::begin(input), std::ranges::end(input), init, binop, [&](auto& element) {
return recursive_transform_reduce<unwrap_level - 1>(element, init, unary_op, binop);
});
}
else
{
return std::invoke(binop, init, std::invoke(unary_op, input));
}
} | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c++, algorithm, recursion, template, c++20
// recursive_transform_reduce template function implementation with execution policy
template<std::size_t unwrap_level, class ExecutionPolicy, class Input, class T, class UnaryOp = std::identity, class BinaryOp = std::plus<T>>
requires(recursive_invocable<unwrap_level, UnaryOp, Input>&&
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>)
constexpr auto recursive_transform_reduce(ExecutionPolicy execution_policy, const Input& input, T init = {}, const UnaryOp& unary_op = {}, const BinaryOp& binop = std::plus<T>())
{
if constexpr (unwrap_level > 0)
{
return std::transform_reduce(
execution_policy,
std::ranges::begin(input),
std::ranges::end(input),
init,
binop,
[&](auto& element) {
return recursive_transform_reduce<unwrap_level - 1>(execution_policy, element, init, unary_op, binop);
});
}
else
{
return std::invoke(binop, init, std::invoke(unary_op, input));
}
}
// recursive_size template function implementation
template<class T> requires (!std::ranges::range<T>)
constexpr auto recursive_size(const T& input)
{
return std::size_t{1};
}
template<std::ranges::range Range> requires (!(std::ranges::input_range<std::ranges::range_value_t<Range>>))
constexpr auto recursive_size(const Range& input)
{
return std::ranges::size(input);
}
template<std::ranges::range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_size(const Range& input)
{
return std::transform_reduce(std::ranges::begin(input), std::ranges::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
}
template<typename T>
concept is_recursive_sizeable = requires(T x)
{
recursive_size(x);
}; | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c++, algorithm, recursion, template, c++20
template<typename T>
concept is_recursive_sizeable = requires(T x)
{
recursive_size(x);
};
// Copy from https://stackoverflow.com/a/37264642/6667035
#ifndef NDEBUG
# define M_Assert(Expr, Msg) \
__M_Assert(#Expr, Expr, __FILE__, __LINE__, Msg)
#else
# define M_Assert(Expr, Msg) ;
#endif
void __M_Assert(const char* expr_str, bool expr, const char* file, int line, const char* msg)
{
if (!expr)
{
std::cerr << "Assert failed:\t" << msg << "\n"
<< "Expected:\t" << expr_str << "\n"
<< "Source:\t\t" << file << ", line " << line << "\n";
abort();
}
}
void recursive_transform_reduce_tests()
{
auto test_vectors_1 = n_dim_container_generator<1, int, std::vector>(1, 3);
// basic usage case
M_Assert(recursive_transform_reduce<1>(test_vectors_1, 0) == 3, "Basic usage case failed");
// basic usage case with execution policy
M_Assert(recursive_transform_reduce<1>(std::execution::par, test_vectors_1, 0) == 3,
"Basic usage case with execution policy failed");
// test case with unary operation
M_Assert(recursive_transform_reduce<1>(
test_vectors_1,
0,
[&](auto&& element) { return element + 1; }) == 6,
"Test case with unary operation failed");
// test case with unary operation, execution policy
M_Assert(recursive_transform_reduce<1>(
std::execution::par,
test_vectors_1,
0,
[&](auto&& element) { return element + 1; }) == 6,
"Test case with unary operation, execution policy failed");
// test case with unary operation and binary operation
M_Assert(recursive_transform_reduce<1>(
test_vectors_1,
1,
[&](auto&& element) { return element + 1; },
[&](auto&& element1, auto&& element2) { return element1 * element2; }) == 8,
"Test case with unary operation and binary operation failed"); | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c++, algorithm, recursion, template, c++20
// test case with unary operation, binary operation and execution policy
M_Assert(recursive_transform_reduce<1>(
std::execution::par,
test_vectors_1,
1,
[&](auto&& element) { return element + 1; },
[&](auto&& element1, auto&& element2) { return element1 * element2; }) == 8,
"Test case with unary operation, binary operation and execution policy failed");
auto test_string_vector_1 = n_dim_container_generator<1, std::string, std::vector>("1", 3);
// test case with std::string
M_Assert(recursive_transform_reduce<1>(test_string_vector_1, std::string("")) == "111",
"Test case with std::string failed");
// test case with std::string, execution policy
M_Assert(recursive_transform_reduce<1>(
std::execution::par,
test_string_vector_1, std::string("")) == "111",
"Test case with std::string, execution policy failed");
// test case with std::string, unary operation
M_Assert(recursive_transform_reduce<1>(
test_string_vector_1,
std::string(""),
[&](auto&& element) { return element + "2";}) == "121212",
"Test case with std::string, unary operation failed");
// test case with std::string, unary operation, execution policy
M_Assert(recursive_transform_reduce<1>(
std::execution::par,
test_string_vector_1,
std::string(""),
[&](auto&& element) { return element + "2";}) == "121212",
"Test case with std::string, unary operation, execution policy failed");
std::cout << "All tests passed!\n";
return;
} | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c++, algorithm, recursion, template, c++20
std::cout << "All tests passed!\n";
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_transform_reduce_tests();
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 EXIT_SUCCESS;
}
The output of the test code above:
All tests passed!
Computation finished at Sat Mar 2 10:36:27 2024
elapsed time: 0.00234773
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++ and
recursive_invocable and recursive_project_invocable Concept Implementation in C++
What changes has been made in the code since last question?
I am trying to implement another version recursive_transform_reduce function which takes unwrap_level as an input in this post.
Why a new review is being asked for?
Please review the implementation of recursive_transform_reduce template function and its tests.
Answer: Incorrect handling of the init parameter
Given this piece of code:
std::vector<int> foo = {2, 3, 4, 5};
std::cout << recursive_transform_reduce<1>(foo, 1) << '\n';
I expect the output to be equal to 1 + 2 + 3 + 4 + 5, or 15. However, this will print 19, because you apply the value of init for every element you visit. The first thing to fix is the non-recursive case, it should simply be:
if constexpr (unwrap_level > 0) {
…
}
else
{
return std::invoke(unary_op, input);
} | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c++, algorithm, recursion, template, c++20
This will then result in the correct output for the example I gave. But it still results in the wrong output for more nested containers.
Note that your test cases don't catch this because you yourself thought the wrong behavior was the correct one. One way that could maybe have been avoided is if you had added a test that compares the output of recursive_transform_reduce<1>() with the output of std::transform_reduce() on the same container. | {
"domain": "codereview.stackexchange",
"id": 45544,
"lm_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, recursion, template, c++20",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
Title: Consolidating GNU C's and C23's attributes
Question: C23 has introduced attribute specifier sequences. Consequently, the header below attempts to conditionally define macros for these sequences (for my own use cases). In cases where a compiler does not yet support them but does support GNU C's attributes, the macros will expand to utilize GNU C's attributes, provided equivalent attributes exist. Otherwise, they will expand to nothing.
It also provides the definitions for nullptr and nullptr_t for versions prior to C2X/C23, and some other GNU C attributes.
#ifndef ATTRIB_H
#define ATTRIB_H 1
/* C2x/C23 or later? */
#if defined(__STDC__) && defined(__STDC_VERSION__) && \
(__STDC_VERSION__ >= 202000L) \
#include <stddef.h> /* nullptr_t */
#else
#define nullptr (void *)0
typedef void * nullptr_t;
#endif /* nullptr/nullptr_t */
/*
* Some notes:
* 1) All attributes that take an optional or variable number of arguments will
* have two versions; one of the form `attr`, and one of the form `attrex`.
* The latter shall expect one or more arguments.
* 2) The attributes that have no equivalent in GNU C shall be replaced with
* nothing except for `__maybe_unused__`, which would expand to `unused`.
* GNU C doesn't have `__reproducible__` or `__unsequenced__`, yet one may
* be interested in looking at `pure` - which is more relaxed than
* `__reproducible__` - and `const` - which is more strict than
* `__unsequenced__`.
*
* References:
* https://en.cppreference.com/w/c/language/attributes
* https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
*/ | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
#if defined(__has_c_attribute)
/* Every standard attribute whose name is of form `attr` can be also
* spelled as __attr__ and its meaning is not changed. All attributes
* are specified with leading pairs of underscores, to avoid that they
* macro-expand in case that the user had a macro with the same name.
*/
#if __has_c_attribute(__maybe_unused__)
#define ATTRIB_MAYBE_UNUSED [[__maybe_unused__]]
#endif /* __maybe_unused__ */
#if __has_c_attribute(__deprecated__)
/* Since __deprecated__ and __no_discard__ takes an optional parameter,
* we define two versions of it.
*/
#define ATTRIB_DEPRECATED [[__deprecated__]]
#define ATTRIB_DEPRECATEDEX(reason) [[__deprecated__(#reason]]
#endif /* __deprecated__ */
#if __has_c_attribute(__fallthrough__)
#define ATTRIB_FALLTHROUGH [[__fallthrough__]]
#endif /* __fallthrough__ */
#if __has_c_attribute(__nodiscard__)
#define ATTRIB_NODISCARD [[__nodiscard__]]
#define ATTRIB_NODISCARDEX(reason) [[__nodiscard__(#reason)]
#endif /* __nodiscard__ */
#if __has_c_attribute(__unsequenced__)
#define ATTRIB_UNSEQUENCED [[__unsequenced__]]
#endif /* __unsequenced__*/ | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
#if __has_c_attribute(__reproducible__)
#define ATTRIB_REPRODUCIBLE [[__reproducible__]]
#endif /* __reproducible__*/
#elif defined(__GNUC__) || defined(__clang__)
/* GNU C doesn't have a __maybe_unused__ attribute, but it has unused. */
#define ATTRIB_MAYBE_UNUSED __attribute__((unused))
#define ATTRIB_DEPRECATED __attribute__((deprecated))
#define ATTRIB_DEPRECATEDEX(reason) __attribute__(deprecated(#reason))
#define ATTRIB_FALLTHROUGH __attribute__((fallthrough))
/* GNU C doesn't have a __nodiscard__ attribute, but has warn_unused_result,
* but that doesn't take an optional argument, and raises a diagnostic message
* even after being casted to void, so we do not define it.
* GCC doesn't have __reproducible__ and __unsequenced__.
*/
#define ATTRIB_NODISCARD /* If only. */
#define ATTRIB_NODISCARD(stream) /* If only. */
#define ATTRIB_UNSEQUENCED /* If only. */
#define ATTRIB_REPRODUCIBLE /* If only. */
#else
#define ATTRIB_MAYBE_UNUSED /* If only. */
#define ATTRIB_DEPRECATED /* If only. */
#define ATTRIB_DEPRECATEDEX(reason) /* If only. */
#define ATTRIB_FALLTHROUGH /* If only. */
#define ATTRIB_NODISCARD /* If only. */
#define ATTRIB_NODISCARD(stream) /* If only. */
#define ATTRIB_UNSEQUENCED /* If only. */
#define ATTRIB_REPRODUCIBLE /* If only. */
#endif /* __has_c_attribute || __GNUC__ || __clang__ */ | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
#if defined(__GNUC__) || defined(__clang__)
/* To indicate that an allocation function both satisfies the nonaliasing
* property and has a deallocator associated with it, both the plain form
* ot the attribute and the one with the deallocator must be used.
*
* Note that this attribute is not accepted on inline functions.
*/
#define ATTRIB_MALLOC __attribute__(malloc)
#define ATTRIB_MALLOCEX(...) __attribute__(malloc, malloc (__VA_ARGS__))
#define ATTRIB_PRINTF_LIKE(n, m) __attribute__((format(printf, n, m)))
#define ATTRIB_FORMAT(func, n, m) __attribute__((format(func, n, m)))
#define ATTRIB_COLD __attribute__((cold))
#define ATTRIB_CONST __attribute__((const))
#define ATTRIB_HOT __attribute__((hot))
#define ATTRIB_PURE __attribute__((pure))
#define ATTRIB_NONNULL __attribute__((nonnull))
#define ATTRIB_NONNULLEX(...) __attribute__((nonnull(__VA_ARGS__)
#define ATTRIB_NULL_TERMINATED __attribute__((null_terminated_string_arg))
#define ATTRIB_NULL_TERMINATEDEX(...) __attribute__((null_terminated_string_arg(__VA_ARGS__)))
#define ATTRIB_UNAVAILABLE __attribute__((unavailable))
#define ATTRIB_UNAVAILABLEEX(reason) __attribute__((unavailable(#reason)))
#define ATTRIB_UNUSED __attribute__((unusued))
#define ATTRIB_USED __attribute__((used))
#define ATTRIB_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#define ATTRIB_RETURNS_NONNULL __attribute__((returns_nonnull))
#define ATTRIB_ALWAYS_INLINE static inline __attribute__((always_inline))
#define ATTRIB_NOINLINE __attribute__((noinline))
#else | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
#define ATTRIB_NOINLINE __attribute__((noinline))
#else
#define ATTRIB_MALLOC /* If only. */
#define ATTRIB_MALLOCEX(...) /* If only. */
#define ATTRIB_PRINTF_LIKE(n, m) /* If only. */
#define ATTRIB_FORMAT(func, n, m) /* If only. */
#define ATTRIB_COLD /* If only. */
#define ATTRIB_CONST /* If only. */
#define ATTRIB_HOT /* If only. */
#define ATTRIB_PURE /* If only. */
#define ATTRIB_NONNULL /* If only. */
#define ATTRIB_NONNULLEX(...) /* If only. */
#define ATTRIB_NULL_TERMINATED /* If only. */
#define ATTRIB_NULL_TERMINATEDEX(...) /* If only. */
#define ATTRIB_UNAVAILABLE /* If only. */
#define ATTRIB_UNAVAILABLEEX(reason) /* If only. */
#define ATTRIB_UNUSED /* If only. */
#define ATTRIB_USED /* If only. */
#define ATTRIB_WARN_UNUSED_RESULT /* If only. */
#define ATTRIB_RETURNS_NONNULL /* If only. */
#define ATTRIB_ALWAYS_INLINE /* If only. */
#define ATTRIB_NOINLINE /* If only. */
#endif /* __GNUC__ || __clang__ */ | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
#if defined(__GNUC__) || defined(__clang__)
#define likely(x) __builtin_expect((!!x), 1)
#define unlikely(x) __builtin_expect((!!x), 0)
#else
#define likely(x) (!!x)
#define unlikely(x) (!!x)
#endif /* __GNUC__ || __clang__ */
#endif /* ATTRIB_H */
Review Request:
How well does attrib.h accomplish the goal of using C23's and GNU specific attributes portably?
Answer: For any attribute that has either a standard version or a GCC/Clang extension, the separate #if clauses need to be #if/#elif blocks, This lets the header work either on any C23 compiler that supports the extension, or in GCC and Clang even if they do not have C23 enabled. These should also be a default #else clause that defines the macro as /**/ (which expands to a single whitespace token), so that the code will still compile portably on all compilers.
Intel’s ICX/ICPX is another compiler I often use that supports GCC and Clang attributes. You might also want to add support for MSVC __declspec.
You probably also want to support your header being included in a C++ program, with __cpp_attributes and __has_cpp_attribute.
A similar macro I frequently use to support tail recursion is:
#if __clang__ || __INTEL_LLVM_COMPILER
# define MUSTTAIL __attribute__((musttail))
#else
# define MUSTTAIL /**/
#endif
Which lets me write MUSTTAIL return foo(bar); on all compilers, and have it compile as a no-op on those that do not support it. An updated version that works on GCC, Clang, ICX and MSVC:
#if defined(__has_c_attribute)
# if __has_c_attribute(clang::musttail)
# define MUSTTAIL [[clang::musttail]]
# endif
#elif defined(__has_cpp_attribute)
# if __has_cpp_attribute(clang::musttail)
# define MUSTTAIL [[clang::musttail]]
# endif
#endif
#if !defined(MUSTTAIL) && (__clang__ || __INTEL_LLVM_COMPILER)
# define MUSTTAIL __attribute__((musttail))
#endif
#if !defined(MUSTTAIL)
# define MUSTTAIL /**/
#endif | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, portability, gcc, c-preprocessor, c23
#if !defined(MUSTTAIL)
# define MUSTTAIL /**/
#endif
Which would be much nicer if compilers other than GCC supported #if defined(__has_c_attribute) && __has_c_attribute(foo)
What you currently have leaves attributes undefined if an implementation defines __has_c_attribute, but not that attribute. This is unlikely, since you only use it for standard attributes, but that will not hold as more are added.
Any compiler that supports this probably also supports the GCC extension __has__attribute, which works with either C or C++. | {
"domain": "codereview.stackexchange",
"id": 45545,
"lm_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, portability, gcc, c-preprocessor, c23",
"url": null
} |
c, strings, io, library, portability
Title: A small header-only input output library
Question: The library (inspired by stb libraries) attempts to provide some commonly used functions (reading a file into memory, determining the size of a file) that are missing from the C standard library portably (for my own use cases).
Code:
#ifndef IO_H
#define IO_H
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
/*
* To use, do this:
* #define IO_IMPLEMENTATION
* before you include this file in *one* C file to create the implementation.
*
* i.e. it should look like:
* #include ...
* #include ...
*
* #define IO_IMPLEMENTATION
* #include "io.h"
* ...
*
* To make all functions have internal linkage, i.e. be private to the source
* file, do this:
* #define `IO_STATIC`
* before including "io.h".
*
* i.e. it should look like:
* #define IO_IMPLEMENTATION
* #define IO_STATIC
* #include "io.h"
* ...
*
* You can #define IO_MALLOC, IO_REALLOC, and IO_FREE to avoid using malloc(),
* realloc(), and free(). Note that all three must be defined at once, or none.
*/
#ifndef IO_DEF
#ifdef IO_STATIC
#define IO_DEF static
#else
#define IO_DEF extern
#endif /* IO_STATIC */
#endif /* IO_DEF */
#if defined(__GNUC__) || defined(__clang__)
#define ATTRIB_NONNULL(...) __attribute__((nonnull (__VA_ARGS__)))
#define ATTRIB_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
#define ATTRIB_NONNULL(...) /* If only. */
#define ATTRIB_WARN_UNUSED_RESULT /* If only. */
#endif /* defined(__GNUC__) || define(__clang__) */ | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
/*
* Reads the file pointed to by `stream` to a buffer and returns it.
* The returned buffer is a null-terminated string.
* If `nbytes` is not NULL, it shall hold the size of the file.
*
* Returns NULL on memory allocation failure. The caller is responsible for
* freeing the returned pointer.
*/
IO_DEF char *io_read_file(FILE *stream,
size_t *nbytes) ATTRIB_NONNULL(1) ATTRIB_WARN_UNUSED_RESULT;
/*
* Splits a string into a sequence of tokens. The `delim` argument
* specifies a set of bytes that delimit the tokens in the parsed string.
* If `ntokens` is not NULL, it shall hold the amount of total tokens.
*
* Returns an array of pointers to the tokens, or NULL on memory allocation
* failure. The caller is responsible for freeing the returned pointer.
*/
IO_DEF char **io_split_by_delim(char *s, const char *delim,
size_t *ntokens) ATTRIB_NONNULL(1, 2) ATTRIB_WARN_UNUSED_RESULT;
/*
* Splits a string into lines.
* A wrapper around `io_split_by_delim()`. It calls the function with "\n" as
* the delimiter.
*
* Returns an array of pointers to the tokens, or NULL on memory allocation
* failure. The caller is responsible for freeing the returned pointer.
*/
IO_DEF char **io_split_lines(char *s,
size_t *nlines) ATTRIB_NONNULL(1) ATTRIB_WARN_UNUSED_RESULT; | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
/*
* Reads the next line from the stream pointed to by `stream`. The returned line
* is null-terminated and does not contain a newline, if one was found.
*
* The memory pointed to by `size` shall contain the length of the
* line (including the terminating null character). Else it shall contain 0.
*
* Upon successful completion a pointer is returned and the size of the line is
* stored in the memory pointed to by `size`, otherwise NULL is returned and
* `size` holds 0.
*
* `fgetline()` does not distinguish between end-of-file and error; the routines
* `feof()` and `ferror()` must be used to determine which occurred. The
* function also returns NULL on a memory-allocation failure.
*
* Although a null character is always supplied after the line, note that
* `strlen(line)` will always be smaller than the value is `size` if the line
* contains embedded null characters.
*/
IO_DEF char *io_read_line(FILE *stream, size_t *size) ATTRIB_NONNULL(1,
2) ATTRIB_WARN_UNUSED_RESULT;
/*
* `size` must be a non-null pointer. On success, the function assigns `size`
* with the number of bytes read and returns true, or returns false elsewise.
*
* Note: The file can grow between io_fsize() and a subsequent read.
*/
IO_DEF bool io_fsize(FILE *stream, size_t *size) ATTRIB_NONNULL(1, 2);
/*
* Writes `lines` to the file pointed to by `stream`.
*
* On success, it returns true, or false elsewise.
*/
IO_DEF bool io_write_lines(FILE *stream, size_t nlines,
char *lines[const static nlines]) ATTRIB_NONNULL(1, 3);
/*
* Writes nbytes from the buffer pointed to by `data` to the file pointed to
* by `stream`.
*
* On success, it returns true, or false elsewise.
*/
IO_DEF bool io_write_file(FILE *stream, size_t nbytes,
const char data[static nbytes]) ATTRIB_NONNULL(1, 3);
#endif /* IO_H */
#ifdef IO_IMPLEMENTATION | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
#endif /* IO_H */
#ifdef IO_IMPLEMENTATION
#if defined(IO_MALLOC) && defined(IO_REALLOC) && defined(IO_FREE)
// Ok.
#elif !defined(IO_MALLOC) && !defined(IO_REALLOC) && !defined(IO_FREE)
// Ok.
#else
#error "Must define all or none of IO_MALLOC, IO_REALLOC, and IO_FREE."
#endif
#ifndef IO_MALLOC
#define IO_MALLOC(sz) malloc(sz)
#define IO_REALLOC(p, sz) realloc(p, sz)
#define IO_FREE(p) free(p)
#endif
#include <stdlib.h>
#include <string.h>
#include <string.h>
#define CHUNK_SIZE INT64_C(1024 * 8)
#define TOKEN_CHUNK_SIZE INT64_C(1024 * 2)
IO_DEF char *io_read_file(FILE *stream, size_t *nbytes)
{
static const size_t page_size = CHUNK_SIZE;
char *content = NULL;
size_t len = 0;
for (size_t rcount = 1; rcount; len += rcount) {
void *const tmp = IO_REALLOC(content, len + page_size);
if (!tmp) {
IO_FREE(content);
return content = NULL;
}
content = tmp;
rcount = fread(content + len, 1, page_size - 1, stream);
if (ferror(stream)) {
IO_FREE(content);
return content = NULL;
}
}
if (nbytes) {
*nbytes = len;
}
content[len] = '\0';
return content;
}
IO_DEF char **io_split_by_delim(char *s, const char *delim, size_t *ntokens)
{
char **tokens = NULL;
const size_t chunk_size = TOKEN_CHUNK_SIZE;
size_t capacity = 0;
size_t token_count = 0;
while (*s) {
if (token_count >= capacity) {
char **const tmp = IO_REALLOC(tokens,
sizeof *tokens * (capacity += chunk_size));
if (!tmp) {
IO_FREE(tokens);
return NULL;
}
tokens = tmp;
}
tokens[token_count++] = s;
s = strpbrk(s, delim);
if (s) {
*s++ = '\0';
}
}
if (ntokens) {
*ntokens = token_count;
}
return tokens;
} | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
if (ntokens) {
*ntokens = token_count;
}
return tokens;
}
IO_DEF char **io_split_lines(char *s, size_t *nlines)
{
return io_split_by_delim(s, "\n", nlines);
}
IO_DEF char *io_read_line(FILE *stream, size_t *size)
{
const size_t page_size = BUFSIZ;
size_t count = 0;
size_t capacity = 0;
char *line = NULL;
for (;;) {
if (count >= capacity) {
char *const tmp = realloc(line, capacity += page_size);
if (!tmp) {
free(line);
return NULL;
}
line = tmp;
}
int c = getc(stream);
if (c == EOF || c == '\n') {
if (c == EOF) {
if (feof(stream)) {
if (!count) {
free(line);
return NULL;
}
/* Return what was read. */
break;
}
free(line);
return NULL;
} else {
break;
}
} else {
line[count] = (char) c;
}
++count;
}
/* Shrink line to size if possible. */
void *tmp = realloc(line, count + 1);
if (tmp) {
line = tmp;
}
line[count] = '\0';
*size = ++count;
return line;
} | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
/*
* Reasons to not use `fseek()` and `ftell()` to compute the size of the file:
*
* Subclause 7.12.9.2 of the C Standard [ISO/IEC 9899:2011] specifies the
* following behavior when opening a binary file in binary mode:
*
* >> A binary stream need not meaningfully support fseek calls with a whence
* >> value of SEEK_END.
*
* In addition, footnote 268 of subclause 7.21.3 says:
*
* >> Setting the file position indicator to end-of-file, as with
* >> fseek(file, 0, SEEK_END) has undefined behavior for a binary stream.
*
* For regular files, the file position indicator returned by ftell() is useful
* only in calls to fseek. As such, the value returned may not be reflect the
* physical byte offset.
*
* Reasons to not use other non-standard functions:
* 1) fseeko()/ftello() - Not specified in the C Standard, and have the same
* problem as the method above.
*
* 2) fstat()/stat() - Not specified in the C standard. POSIX specific.
* 3) _filelength()/_filelengthi64()/GetFileSizeEx() - Not specified in the C
* Standard. Windows
* specific.
* As such, we read the file in chunks, which is the only portable way to
* determine the size of a file.
*
* Yet this is highly inefficient. We could use some #ifdefs and revert to
* platform-specific functions.
*/
IO_DEF bool io_fsize(FILE *stream, size_t *size)
{
/* TODO:
*
* #if defined(_WIN32)
* Windows also supports fileno(), struct stat, and fstat() as _fileno(),
* _fstat(), and struct _stat.
*
* #ifdef _WIN32
* #define fstat _fstat
* #define fileno _fileno
* #define stat _stat
* #endif
*
* But which version to use? See:
* learn.microsoft/en-us/cpp/c-runtime-library/reference/fstat-fstat32-fstat64-fstati64-fstat32i64-fstat64i32?view=msvc-170
* #elif defined(__unix__) || defined(__linux__) et cetera
* struct stat st;
* | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
* #elif defined(__unix__) || defined(__linux__) et cetera
* struct stat st;
*
* if (fstat(fileno(stream), st) == 0) {
* return st.size;
* }
* return -1?
*
* }
* #else
* Fall back to the default and read it in chunks.
* #endif
*/
size_t rcount = 0;
char chunk[CHUNK_SIZE]; | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
while ((rcount = fread(chunk, 1, CHUNK_SIZE, stream)) > 0) {
*size += rcount;
}
return !ferror(stream);
}
IO_DEF bool io_write_lines(FILE *stream, size_t nlines,
char *lines[const static nlines])
{
for (size_t i = 0; i < nlines; ++i) {
if (fprintf(stream, "%s\n", lines[i]) < 0) {
return false;
}
}
return true;
}
IO_DEF bool io_write_file(FILE *stream, size_t nbytes,
const char data[static nbytes])
{
size_t nwritten = fwrite(data, 1, nbytes, stream);
if (nwritten != nbytes || ferror(stream)) {
return false;
}
return true;
}
#undef CHUNK_SIZE
#undef TOKEN_CHUNK_SIZE
#endif /* IO_IMPLEMENTATION */
And here's how it can be used:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define IO_IMPLEMENTATION
#define IO_STATIC
#include "io.h"
int main(int argc, char **argv)
{
if (argc == 2) {
FILE *fp = fopen(argv[1], "rb");
assert(fp);
size_t nbytes = 0;
char *const fbuf = io_read_file(fp, &nbytes);
assert(fbuf);
assert(io_write_file(stdout, nbytes, fbuf));
rewind(fp);
size_t size = 0;
bool rv = io_fsize(fp, &size);
assert(rv);
printf("Filesize: %zu.\n", size);
rewind(fp);
/* size_t nlines = 0; */
/* char **lines = io_split_lines(fbuf, &nlines); */
/* assert(lines); */
/* assert(io_write_lines(stdout, nlines, lines)); */
size_t ntokens = 0;
char **tokens = io_split_by_delim(fbuf, " \f\n\r\v\t", &ntokens);
assert(tokens);
assert(io_write_lines(stdout, ntokens, tokens));
free(fbuf);
free(tokens);
/* free(lines); */
fclose(fp);
}
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
Review Request:
Are there any bugs or undefined/implementation-defined behavior in the code? Are there any edge cases where the functions would leak memory?
Where would restrict be suitable to use?
General coding comments, style, bad practices, et cetera.
Answer: There is a lot to review here.
Power-of-2 read size in io_read_line()
Since it looks like code is trying to use a power-of-2 page_size, Lets fread() read a power-of-2 bytes
// IO_REALLOC(content, len + page_size)
// ...
// rcount = fread(content + len, 1, page_size - 1, stream);
IO_REALLOC(content, len + page_size + 1)
...
rcount = fread(content + len, 1, page_size, stream);
OR
Just allocate in a power of 2 increment and perform, when needed, a IO_REALLOC() at the end to accommodate the append null character.
OR
Just allocate in a power of 2 increment and always perform a "right-size" IO_REALLOC() at the end to accommodate the exact size needed.
O() of io_read_line() and io_read_line()
Rather than grow allocation linearly by capacity += page_size, use a geometric growth. I like 0, 1, 3, 7, 15 ... SIZE_MAX or capacity = capacity*2 + 1.
With linear growth code is making O(length) allocations and potentiality incurring O(length*length) time.
With geometric growth, code is making O(ln(length)) allocations and potentiality incurring O(length*ln(length)) time.
Minor: reformat for clarity
Consider putting attributes on following line,
// IO_DEF char *io_read_file(FILE *stream,
// size_t *nbytes) ATTRIB_NONNULL(1) ATTRIB_WARN_UNUSED_RESULT;
IO_DEF char *io_read_file(FILE *stream, size_t *nbytes) //
ATTRIB_NONNULL(1) ATTRIB_WARN_UNUSED_RESULT; | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
Bug: Infinite loop in io_read_file()?
When fread(content + len, 1, page_size - 1, stream); returns 0 due to end-of-file, for (size_t rcount = 1; rcount; len += rcount) iterates endlessly.
Do not assume file error is false before io_read_file()
Similar problem in io_read_line().
// ferror(stream) could be true due to prior stream error.
if (ferror(stream)) {
IO_FREE(content);
return content = NULL;
}
Fix for this and prior bug:
size_t n = page_size - 1; // Or n = page_size (see above).
rcount = fread(content + len, 1, n, stream);
if (rcount < n) {
if (!feof(stream)) {
IO_FREE(content);
return content = NULL;
}
break;
}
*nbytes on error in io_read_line()
IMO, *nbytes should always be set, when nbytes != NULL, even when NULL is returned from the function.
Code may return non-NULL on input error in io_read_line()
This review comment not applicable as even though code was feof(stream) I originally processed that as ferror(stream).
Code has:
if (feof(stream)) {
if (!count) {
free(line);
return NULL;
}
/* Return what was read. */
break;
}
which, IMO, should always return NULL when an input error occurs, not just when count == 0.
Bug: Unsafe re-alloc()
In the following code, should tmp == NULL, line[count] may be beyond prior allocation as count == capacity is possible.
void *tmp = realloc(line, count + 1);
if (tmp) {
line = tmp;
}
line[count] = '\0'; // not safe
Questionable file size
while ((rcount = fread(chunk, 1, CHUNK_SIZE, stream)) > 0) continues to read even when a read error occurs. Read errors are not certainly sticky. The read error flag is sticky.
Better as
IO_DEF bool io_fsize(FILE *stream, size_t *size) {
size_t rcount = 0;
char chunk[CHUNK_SIZE]; | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
c, strings, io, library, portability
// Consider a `rewind()` here
// Depends on what OP wants should stream not be at the beginning.
do {
rcount = fread(chunk, 1, CHUNK_SIZE, stream);
*size += rcount;
} while (rcount == CHUNK_SIZE);
return !ferror(stream);
}
Unsigned constants
Since CHUNK_SIZE and TOKEN_CHUNK_SIZE are use exclusively for sizing, uses size_t math and types.
// #define CHUNK_SIZE INT64_C(1024 * 8)
// #define TOKEN_CHUNK_SIZE INT64_C(1024 * 2)
#define CHUNK_SIZE ((size_t)1024 * 8)
#define TOKEN_CHUNK_SIZE ((size_t)1024 * 2)
Side issue: INT64_C(1024 * 2) make a constant that is at least 64-bit, but I do not think that means the 1024 * 2 is done first using 64-bit math, but with int math. Might be a problem with 1024 * 1024 * 1024 * 2 as that int overflows.
File size versus size_t
There are many systems where file size > SIZE_MAX. Consider using wider math for file size or detect overflow.
Uncomplicate long lines
// char **const tmp = IO_REALLOC(tokens,
// sizeof *tokens * (capacity += chunk_size));
capacity += chunk_size;
char **const tmp = IO_REALLOC(tokens, sizeof *tokens * capacity);
Style: little reason to type the return from realloc()
(Further, I like comparing with == clearer than !=. 'I don't know half of you half ...)
// char **const tmp = IO_REALLOC(tokens, sizeof *tokens * (capacity += chunk_size));
// if (!tmp) {
// IO_FREE(tokens);
// return NULL;
// }
// tokens = tmp;
void *tmp = IO_REALLOC(tokens, sizeof *tokens * (capacity += chunk_size));
if (tmp == NULL) {
IO_FREE(tokens);
return NULL;
}
tokens = tmp;
Note: if (ferror()) can mislead.
I realize now OP's post comes after a recent post. It looks like there is a fair amount of repetition of same issues. | {
"domain": "codereview.stackexchange",
"id": 45546,
"lm_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, io, library, portability",
"url": null
} |
python, python-3.x, classes
Title: Dynamically mapping an API's setting IDs to instance methods using Descriptors
Question: I'm working with an API, where the url can be constructed with setting_ids. To more clearly indicate the functionality of the setting ids I am mapping them to a WriterClass' methods, with relevant names.
In the code below these are method_a to method_c, in the true application this is a list of ~250 settings.
The functionality I desire would access the API for a desired setting through the structure writer_instance.setting_name(value) - returning a to be awaited coroutine.
For this I'm using descriptors, with which I'm still familiarising myself. This is my main motivation for asking this question, to ensure I'm utilising them correctly and as efficiently as possible - and if not, to learn how to do so now and in the future.
Below is code that functionally does what I desire, with placeholder prints instead of code accessing the (private) API.
The Credentials class is a separate class as it's utilised by other Classes which also access the same API.
import asyncio
import httpx
DOMAIN = 'api.mysite.com'
class Credentials:
# In true context this fetches an api_token from database using the serial.
def __init__(self, device_serial: str, api_token):
self.device_serial = device_serial
self._api_token = api_token
self.headers = self.__build_headers()
def __build_headers(self):
headers = {
'Authorization': ('Bearer ' + self._api_token),
'Content-Type': 'application/json',
'Accept': 'application/json',
}
return headers
class MethodDescriptor:
def __init__(self, id):
self._id = id
def __get__(self, instance, owner):
# Using this so that the final method has access to instance variables.
# Not happy with this approach necessarily, but it gets the results I desire.
return BoundMethod(self._id, instance) | {
"domain": "codereview.stackexchange",
"id": 45547,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes",
"url": null
} |
python, python-3.x, classes
class BoundMethod:
def __init__(self, id, instance):
self._id = id
self._instance = instance
async def __call__(self, value):
# placeholder logic for actual API call.
await asyncio.sleep(1) # Simulate work
print(
f"Method called with id={self._id}, {value=}, at url={self._instance.domain} for serial {self._instance.device_serial}")
return f'accessed setting number {self._id}'
class WriterClass:
method_a = MethodDescriptor(1)
method_b = MethodDescriptor(2)
method_c = MethodDescriptor(3)
def __init__(self, credentials: Credentials, client: httpx.AsyncClient):
self.device_serial = credentials.device_serial
self.headers = credentials.headers
self.domain = DOMAIN
self.client = client
# Example usage
async def main():
creds = Credentials("123AA", "API_TOKEN") # API token obtained elsewhere in real code.
async with httpx.AsyncClient() as client:
writer = WriterClass(creds, client)
task1 = asyncio.create_task(writer.method_c("some_str")) # should use __call__ with self._id = 3, value="some_str" and instance vars.
task2 = asyncio.create_task(writer.method_b("12:34"))
task3 = asyncio.create_task(writer.method_a("3700"))
results = await asyncio.gather(task1, task2, task3)
print(results)
if __name__ == '__main__':
asyncio.run(main())
Which returns:
Method called with id=3, value='some_str', at url=api.mysite.com for serial 123AA
Method called with id=2, value='12:34', at url=api.mysite.com for serial 123AA
Method called with id=1, value='3700', at url=api.mysite.com for serial 123AA
['accessed setting number 3', 'accessed setting number 2', 'accessed setting number 1']
As expected. | {
"domain": "codereview.stackexchange",
"id": 45547,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes",
"url": null
} |
python, python-3.x, classes
As expected.
Answer: Use a More Meaningful Name For Your Descriptor Class?
How about renaming your descriptor class from MethodDescriptor to SettingDescriptor? And consider renaming class WriterClass to SettingWriter. I would also use more descriptive names for the descriptor instances themselves. For example:
class SettingWriter:
set_a = SettingDescriptor(1)
set_b = SettingDescriptor(2)
set_c = SettingDescriptor(3)
...
Then your main function becomes:
async def main():
creds = Credentials("123AA", "API_TOKEN") # API token obtained elsewhere in real code.
async with httpx.AsyncClient() as client:
setter = SettingWriter(creds, client)
task1 = asyncio.create_task(setter.set_c("some_str")) # should use __call__ with self._id = 3, value="some_str" and instance vars.
task2 = asyncio.create_task(setter.set_b("12:34"))
task3 = asyncio.create_task(setter.set_a("3700"))
results = await asyncio.gather(task1, task2, task3)
print(results)
Calling a method named set_a seems more descriptive than calling method_a.
The above renaming suggestions are just that -- suggestions. You might be able to find names that are even more descriptive than the ones I quickly came up with due to your greater familiarity with the actual application.
A Simplification to Consider
It seems to me that you can do away with class BoundedMethod if you modify class SettingDescriptor as follows:
class SettingDescriptor:
def __init__(self, id):
self._id = id
def __get__(self, instance, owner):
# Using this so that the final method has access to instance variables.
self._instance = instance
return self | {
"domain": "codereview.stackexchange",
"id": 45547,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes",
"url": null
} |
python, python-3.x, classes
async def __call__(self, value):
# placeholder logic for actual API call.
await asyncio.sleep(1) # Simulate work
print(
f"Method called with id={self._id}, {value=}, at url={self._instance.domain} for serial {self._instance.device_serial}")
return f'accessed setting number {self._id}'
Add Type Hints
Describe what arguments and return values a method/function expects using type hints. For example,
from typing import Type, Callable
...
class SettingDescriptor:
def __init__(self, id: int):
self._id = id
def __get__(self, instance: object, owner: Type) -> Callable:
...
Add Doctsrings Describing What Your Methods Do
For example,
class SettingDescriptor:
...
def __get__(self, instance: object, owner: Type) -> Callable:
"""Returns self, a callable that invokes the API with
the appropriate id and value arguments."""
...
But Is Using Descriptors for This Overkill?
Ultimately, you are just trying to map a property name, which is a string, to an integer that the API you are using requires. For this you could use a dictionary. So what if you just had this instead:
...
class SettingWriter:
property_name_mapping = {
'a': 1,
'b': 2,
'c': 3
}
def __init__(self, credentials: Credentials, client: httpx.AsyncClient):
self.device_serial = credentials.device_serial
self.headers = credentials.headers
self.domain = DOMAIN
self.client = client
async def set(self, property_name: str, value: str) -> str:
id = self.property_name_mapping[property_name]
await asyncio.sleep(1) # Simulate work
print(
f"Method called with id={id}, {value=}, at url={self.domain} for serial {self.device_serial}")
return f'accessed setting number {id}' | {
"domain": "codereview.stackexchange",
"id": 45547,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes",
"url": null
} |
python, python-3.x, classes
# Example usage
async def main():
creds = Credentials("123AA", "API_TOKEN") # API token obtained elsewhere in real code.
async with httpx.AsyncClient() as client:
setter = SettingWriter(creds, client)
task1 = asyncio.create_task(setter.set("c", "some_str"))
task2 = asyncio.create_task(setter.set("b", "12:34"))
task3 = asyncio.create_task(setter.set("a", "3700"))
results = await asyncio.gather(task1, task2, task3)
print(results) | {
"domain": "codereview.stackexchange",
"id": 45547,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes",
"url": null
} |
performance, sql, stackexchange
Title: Show how close a user is to being unsung
Question: So this morning, I decided to create a SEDE query that answers the age-old question "How close am I to being Unsung?" because I recently polished up my first SEDE query and I realized that I had enjoyed learning how to code in SQL.
I have tested that the code works as intended1, however there I would like to know if there is a way I could improve my code's performance in terms of time.
What this does is output the # of accepted answers from the UserId that have 0 score, are accepted, and are not self-answers or community wikis. run online
SELECT
COUNT(a.Id) as [Accepted Answers],
(10 - SUM(CASE WHEN a.Score = 0 THEN 1 ELSE 0 END)) AS [Answers till Unsung]
FROM
Posts q
INNER JOIN
Posts a on a.Id = q.AcceptedAnswerId
WHERE
a.CommunityOwnedDate IS NULL
AND a.OwnerUserId = ##UserId##
AND q.OwnerUserId != ##UserId##
AND a.PostTypeId = 2
My question is: is there anything that I could do to make sure that the query doesn't take as much time to run the first time around? It really doesn't make sense that the code would run slowly the first time when I enter a user ID but not the second time when the info is already cached.
The query returning negative numbers when putting in the IDs of users who have more than 10 accepted answers with a score of 0 is perfectly intentional.
Notes
1Although it was pretty hard to get done as there weren't a lot of sites where the Unsung Hero badge had even been attained. And even then, I had to make sure that there were users who had the badge whose answers had not been upvoted since then.
Answer: I tried it on myself, elapsed time of 136 msec for userid 145459:
https://data.stackexchange.com/codereview/query/1822723/how-close-am-i-to-being-unsung?opt.withExecutionPlan=true#executionPlan
The plan is extremely easy to read.
Nearly all execution nodes show approximately 0% cost,
with an isolated leaf node showing | {
"domain": "codereview.stackexchange",
"id": 45548,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, stackexchange",
"url": null
} |
performance, sql, stackexchange
Clustered Index Scan [PostsWithDeleted].[UIX_PostsWithDe…
Cost: 97%
The estimated to actual row ratio is not too bad: 1716 / 264 == 6.5.
So the planner manages to get it within an order-of-magnitude,
about par for the course,
sufficient for deciding which access path to choose.
Estimated subtree cost at that node is 69, which I guess
is in units of millisecond, reasonably close to the observed 136.
Substantially all of the expense was for dealing
with the a.Id = q.AcceptedAnswerId equi-join,
and it seems entirely appropriate to me.
I see no inefficiencies in that.
a way I could improve my code's [elapsed] time
tl;dr: No, not that I see.
It would be interesting to publish some "hard" instances
of this query.
That is, against a bigger site such as SO, and with a
more prolific user.
Another way to make this a harder query would be to choose
the top ten (or a hundred) users, and produce one result row per user.
cached behavior
Re-running the identical query unsurprisingly shrinks
elapsed time from 136 msec down to 2 msec.
So access to the I/O subsystem accounts for most
of the expense -- CPU cycles to analyze cached rows is trivial cost.
magic number
AND a.PostTypeId = 2
Minimally this warrants a -- comment giving the symbolic name of 2.
Ideally we would JOIN against a third table, to recover 2 from
a symbolic name, at the cost of maybe an extra millisecond.
meaningful identifiers
The result columns enjoy admirable clarity in their
self-explanatory names. | {
"domain": "codereview.stackexchange",
"id": 45548,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, stackexchange",
"url": null
} |
algorithm, datetime, rust, library, time
Title: RANDEVU - Rust crate implementing a simple algorithm I invented
Question: I've created a simple algorithm which I've implemented in Rust and published it as a crate on crates.io.
https://crates.io/crates/randevu
While I do think my code is pretty clean and idiomatic, I would like to know if there are any suggestions on how to improve it further, including tests and documentation. I have some ideas like allowing the user to pass a chrono date/time to the function instead of the function only taking dates as a string. Or making a version that accepts blake3 hashes of object and date (so they can be calculated only once for instances where the function is called many times for a certain object or date).
For those interested in the function and idea behind the algorithm itself, I've tried to explain it the best I can in the README.md (though it might not be relevant for code review).
//! The official Rust implementation of the [RANDEVU](https://github.com/TypicalHog/randevu) algorithm
//!
//! # Example
//! ```rust
//! use randevu::{rdv, utc_date_with_offset};
//!
//! fn main() {
//! let object = "THE_SIMPSONS";
//! let date = utc_date_with_offset(0);
//! let rdv = rdv(object, &date);
//!
//! println!("Object {} has RDV{} today", object, rdv);
//! }
//! ```
use blake3;
use chrono::{TimeDelta, Utc};
/// Returns current UTC DATE `String` in ISO 8601 format (YYYY-MM-DD), with an OFFSET `i64` in days
pub fn utc_date_with_offset(offset: i64) -> String {
(Utc::now() + TimeDelta::days(offset))
.format("%Y-%m-%d")
.to_string()
} | {
"domain": "codereview.stackexchange",
"id": 45549,
"lm_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, datetime, rust, library, time",
"url": null
} |
algorithm, datetime, rust, library, time
/// Returns RDV level `u32` for an OBJECT `&str` on a specific DATE `&str`
///
/// **RDV = number of leading zero bits in blake3(blake3(OBJECT) || blake3(DATE))**
pub fn rdv(object: &str, date: &str) -> u32 {
let mut hasher = blake3::Hasher::new();
hasher.update(blake3::hash(object.as_bytes()).as_bytes());
hasher.update(blake3::hash(date.as_bytes()).as_bytes());
let final_hash = hasher.finalize();
let mut rdv = 0;
for &byte in final_hash.as_bytes() {
rdv += byte.leading_zeros();
if byte != 0 {
break;
}
}
rdv
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rdv_1() {
assert_eq!(rdv("NO_BOILERPLATE", "2024-01-26"), 11);
}
#[test]
fn test_rdv_2() {
assert_eq!(rdv("SHREK_2001", "2024-01-26"), 8);
}
#[test]
fn test_rdv_3() {
assert_eq!(rdv("RANDEVU", "2024-01-26"), 1);
}
#[test]
fn test_rdv_4() {
assert_eq!(rdv("RUST", "2024-01-26"), 0);
}
} | {
"domain": "codereview.stackexchange",
"id": 45549,
"lm_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, datetime, rust, library, time",
"url": null
} |
algorithm, datetime, rust, library, time
#[test]
fn test_rdv_4() {
assert_eq!(rdv("RUST", "2024-01-26"), 0);
}
}
Answer: Naming
The function rdv has a name, that I'd never remember. It's described as number of leading zero bits, but it is never explained where the presumable abbreviation originates from.
offset: i64 is passed to TimeDelta::days. So you should either explain that those are days in the docstring or rename the variable to days, so that the user knows what it does.
Aside from object being a non-descriptive name in general, object: &str is not generic over some type T. It always will be a &str. Since something called an RDV level is being calculated from it, maybe call it target or so. I really don't know since I cannot make sense of rdv() at all.
Get your types early
rdv() should receive date as an appropriate object, not as a string slice. The serialization should be done internally. With the current implementation one can pass in an arbitrary string, that may not meet the function's expectations of a valid date.
E.g. what would you expect x to be in assert_eq!(rdv("NO_BOILERPLATE", "Hello world"), x);?
If you want to make rdv() really generic, as claimed in the README, you could rewrite it to rdv<T: ToString>(target: T, ...)....
Documentation
The contents of the project's README file are misleading.
The algorithms provided are not generic, as noted above.
Nothing is being done on a daily basis - there is no timed automation whatsoever in the code. It just exhibits some date serialization and a spurious hash function. | {
"domain": "codereview.stackexchange",
"id": 45549,
"lm_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, datetime, rust, library, time",
"url": null
} |
python, performance
Title: What could be the more optimised way to get all unique subarray which equals to a target
Question: I am trying to solve Combination Sum II on LeetCode. I was able to derive a recursive solution for the problem but it is not optimised as it only beats 10% of the solutions.
Combination Sum II
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10, 1, 2, 7, 6, 1, 5], target = 8
Output:
[
[1, 1, 6],
[1, 2, 5],
[1, 7],
[2, 6]
]
Example 2:
Input: candidates = [2, 5, 2, 1, 2], target = 5
Output:
[
[1, 2, 2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
def combinationSum2(self, candidates, target):
res = []
def helper(arr,index,curr_sum,ans):
if curr_sum == target:
#ans = sorted(ans)
if ans not in res:
res.append(ans)
return
if len(arr) == index or curr_sum > target:
return
helper(arr,index+1,curr_sum + arr[index],ans +[arr[index]])
while len(arr)-1 > index and arr[index] == arr[index+1]:
index += 1
helper(arr,index+1,curr_sum,ans)
return res
return helper(sorted(candidates),0,0,ans=[])
What could I improve in my code or
how can I optimise it better by following the same recursive approach?
Answer:
First lets clean up your code.
def combination_sum_2(candidates: list[int], target: int) -> list[list[int]]:
def inner(terms: list[int], curr_sum: int, index: int) -> None:
if curr_sum == target:
if terms not in res:
res.append(terms)
return
if index == len(candidates) or target < curr_sum:
return | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
python, performance
if index == len(candidates) or target < curr_sum:
return
inner(terms + [candidates[index]], curr_sum + candidates[index], index + 1)
while index + 1 < len(candidates) and candidates[index] == candidates[index+1]:
index += 1
inner(terms, curr_sum, index + 1)
res: list[list[int]] = []
candidates = list(sorted(candidates))
inner([], 0, 0)
return res
You are wasting time by filtering duplicates within inner rather than once outside inner.
while index + 1 < len(candidates) and candidates[index] == candidates[index+1]:
index += 1
def combination_sum_2(candidates: list[int], target: int) -> list[list[int]]:
def inner(index: int, curr_sum: int, terms: list[int]) -> None:
if curr_sum == target:
if terms not in res:
res.append(terms)
return
if index == len(candidates) or target < curr_sum:
return
inner(index + 1, curr_sum + candidates[index], terms + [candidates[index]])
inner(index + 1, curr_sum, terms)
res: list[list[int]] = []
candidates = list(sorted(set(candidates)))
inner(0, 0, [])
return res
Using recursion for looping is a bad idea in Python.
>>> def loop(n: int) -> int:
... def inner(n: int) -> int:
... if not n:
... return 0
... else:
... return inner(n - 1)
... assert 0 <= n
... return inner(n)
...
>>> loop(1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in loop
File "<stdin>", line 6, in inner
File "<stdin>", line 6, in inner
File "<stdin>", line 6, in inner
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
As such rather than using the FP looping mechanic we should just loop over a range.
if index == len(candidates) or ...:
return
...
inner(terms, curr_sum, index + 1) | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
python, performance
...
inner(terms, curr_sum, index + 1)
def combination_sum_2(candidates: list[int], target: int) -> list[list[int]]:
def inner(terms: list[int], curr_sum: int, index: int) -> None:
if curr_sum == target:
if terms not in res:
res.append(terms)
return
if target < curr_sum:
return
for i in range(index, len(candidates)):
v = candidates[index]
inner(terms + [v], curr_sum + v, i + 1)
res: list[list[int]] = []
candidates = list(sorted(set(candidates)))
inner(0, 0, [])
return res
Given the constraints we can pre-calculate the end index.
When curr_sum is 13 and the target 30 then the max option is 17.
Checking if 18+ sum to 30 is a waste of time.
1 <= candidates[i] <= 50
1 <= target <= 30
We can build an array containing the index of the highest value which can be added to.
Then we use range(index, high_index[target - curr_sum]).
import bisect
def rstretch__index(values: list[int], length: int) -> list[int]:
return [
bisect.bisect(values, i) - 1
for i in range(length)
]
def combination_sum_2(candidates: list[int], target: int) -> list[list[int]]:
def inner(terms: list[int], curr_sum: int, lo: int, hi: int) -> None:
if curr_sum == target:
if terms not in res:
res.append(terms)
return
for i in range(lo, hi):
c = candidates[index]
inner(terms + [c], curr_sum + c, i + 1, high_index[target - curr_sum - c])
res: list[list[int]] = []
amounts = [0] * (target + 1)
for c in candidates:
if c <= target:
amounts[c] += 1
candidates = [i for i, c in enumerate(amounts) if c]
high_index = rstretch__index(candidates, target + 1)
if amounts[target]:
res.append([target])
inner([], 0, 0, len(candidates))
return res
I prefer using Pythons generator functions.
from typing import Iterator | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
python, performance
I prefer using Pythons generator functions.
from typing import Iterator
def combination_sum_2(candidates: list[int], target: int) -> Iterator[tuple[int, ...]]:
def inner(terms: tuple[int, ...], curr_sum: int, lo: int, hi: int) -> Iterator[tuple[int, ...]]:
if curr_sum == target:
yield terms
return
for i in range(lo, hi):
c = candidates[index]
yield from inner(terms + [c], curr_sum + c, i + 1, high_index[target - curr_sum - c])
amounts = [0] * (target + 1)
for c in candidates:
if c <= target:
amounts[c] += 1
candidates = [i for i, c in enumerate(amounts) if c]
high_index = rstretch__index(candidates, target + 1)
yield from inner([], 0, 0, len(candidates))
We can move the if curr_sum == target into the loop by using if amounts[target - curr_sum]. We will need to handle if target is in candidates outside inner too.
def combination_sum_2(candidates: list[int], target: int) -> Iterator[tuple[int, ...]]:
def inner(terms: tuple[int, ...], curr_sum: int, lo: int, hi: int) -> Iterator[tuple[int, ...]]:
for i in range(lo, hi):
v = candidates[i]
curr = curr_sum + v
c = target - curr
if amounts[c] and i <= high_index[c]:
yield terms + (c,)
yield from inner(terms + (v,), curr, i + 1, high_index[target - curr])
amounts = [0] * (target + 1)
for c in candidates:
if c <= target:
amounts[c] += 1
candidates = [i for i, c in enumerate(amounts) if c]
high_index = rstretch__index(candidates, target + 1)
if amounts[target]:
yield (target,)
yield from inner((), 0, 0, len(candidates))
Note: No code in the answer has been validation tested.
Code to make graph:
import bisect
import collections
from typing import Iterator | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
python, performance
Code to make graph:
import bisect
import collections
from typing import Iterator
def test_orig(candidates, target):
res = []
def helper(arr,index,curr_sum,ans):
if curr_sum == target:
#ans = sorted(ans)
if ans not in res:
res.append(ans)
return
if len(arr) == index or curr_sum > target:
return
helper(arr,index+1,curr_sum + arr[index],ans +[arr[index]])
while len(arr)-1 > index and arr[index] == arr[index+1]:
index += 1
helper(arr,index+1,curr_sum,ans)
return res
return helper(sorted(candidates),0,0,ans=[])
# A failed generalization of the 3SUM problem
def nsum(candidates: list[int], target: int) -> Iterator[tuple[int, ...]]:
candidates_seen_: dict[int, list[tuple[list[int], list[int]]]]
candidates_seen: dict[int, list[tuple[list[int], list[int]]]] = {}
for i, c in enumerate(candidates):
if c < target:
candidates_seen.setdefault(c, []).append(([i], [c]))
for _ in range(len(candidates)):
for i in range(len(candidates)):
a = candidates[i]
for j in range(i + 1, len(candidates)):
b = candidates[j]
for (indexes, c) in candidates_seen.get(target - a - b, []):
if j < indexes[0]:
yield a, b, *c
candidates_seen_ = {}
for c, seen in candidates_seen.items():
for (indexes, terms) in seen:
i = indexes[-1]
for j, d in enumerate(candidates[i + 1:], start=i + 1):
if c + d < target:
candidates_seen_.setdefault(c + d, []).append((indexes + [j], terms + [d]))
candidates_seen = candidates_seen_
if not candidates_seen:
break
def test_peil(candidates: list[int], target: int) -> list[tuple[int, ...]]:
return list(nsum(candidates, target)) | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
python, performance
def rstretch__index(values: list[int], length: int) -> list[int]:
return [
bisect.bisect(values, i) - 1
for i in range(length)
]
def nsum2(candidates: list[int], target: int) -> Iterator[tuple[int, ...]]:
def inner(terms: tuple[int, ...], curr_sum: int, lo: int, hi: int) -> Iterator[tuple[int, ...]]:
for i in range(lo, hi):
v = candidates[i]
curr = curr_sum + v
c = target - curr
if amounts[c] and i <= high_index[c]:
yield terms + (c,)
yield from inner(terms + (v,), curr, i + 1, high_index[target - curr])
amounts = [0] * (target + 1)
for c in candidates:
if c <= target:
amounts[c] += 1
candidates = [i for i, c in enumerate(amounts) if c]
high_index = rstretch__index(candidates, target + 1)
if amounts[target]:
yield (target,)
yield from inner((), 0, 0, len(candidates))
def test_peil2(candidates: list[int], target: int) -> list[tuple[int, ...]]:
return list(nsum2(candidates, target))
def nsum3(candidates: list[int], target: int) -> Iterator[tuple[int, ...]]:
amounts = [0] * (target + 1)
for c in candidates:
if c <= target:
amounts[c] += 1
candidates = [i for i, c in enumerate(amounts) if c]
high_index = rstretch__index(candidates, target + 1)
stack: list[tuple[int, Iterator[int], int]] = [(0, iter(range(len(candidates))), 0)]
while stack:
try:
i = next(stack[-1][1])
except StopIteration:
stack.pop()
continue
v = candidates[i]
curr_sum = stack[-1][2] + v
c = target - curr_sum
if amounts[c] and i <= high_index[c]:
s = iter(stack)
next(s, None)
yield tuple(f[0] for f in s) + (c,)
stack.append((i + 1, iter(range(i + 1, high_index[target - curr_sum])), curr_sum)) | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
python, performance
def test_peil3(candidates: list[int], target: int) -> list[tuple[int, ...]]:
return list(nsum3(candidates, target))
import functools
import random
import matplotlib.pyplot
import numpy
import graphtimer
random.seed(42401)
@functools.cache
def args_conv(size: int) -> tuple[list[int], int]:
return random.choices(range(101), k=int(size)), 30
def main():
fig, axs = matplotlib.pyplot.subplots()
axs.set_yscale('log')
axs.set_xscale('log')
(
graphtimer.Plotter(graphtimer.MultiTimer([test_orig, test_peil, test_peil2, test_peil3]))
.repeat(10, 10, numpy.logspace(0, 2, num=50), args_conv=args_conv)
.min()
).plot(axs, x_label='len(nums)')
fig.show()
matplotlib.pyplot.savefig('foo.png')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 45550,
"lm_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, performance",
"url": null
} |
verilog
Title: ALU design for a 16-bit microprocessor
Question: I'm having a hard time figuring out if the code I wrote is purely combinatorial or sequential logic. I'm designing a simple 16-bit microprocessor (will be implemented on a Spartan 6), and I'm new to Verilog, HDL and FPGAs. The code for the microprocessor is complete, but I'm having second thoughts about the best practices behind the code.
I'm aware that since this is the first time coding for me, the code is not up to any standard, but I tried my best.
One of the most important elements is the ALU, and it has been designed like any other person would. It has overflow/underflow detection which I also asked about here, and I quickly wrote some code for it, which may or may not be correct.
But, my question is whether I should be using the non-blocking operator (<=) or blocking operator (=) in the always block for the ALU. I know the standard practice is to use the blocking operator while designing combinatorial circuits versus using the non-blocking one, which is better for sequential circuits.
If I was to use blocking operators in the always block for the ALU, would the synthesized version be slower than if I use non-blocking operators? I plan to use the on-board 100MHz clock on my development board, so I was wondering if the ALU could keep up.
Here's the full code for the ALU:
module alu(clk, rst, en, re, opcode, a_in, b_in, o, z, n, cond, d_out);
// Parameter Definitions
parameter width = 'd16; // ALU Width
// Inputs
input wire clk /* System Clock Input */, rst /* Reset Result Register */, en /* Enables ALU Processing */, re /* ALU Read Enable */;
input wire [4:0] opcode /* 5-bit Operation Code for the ALU. Refer to documentation. */;
input wire signed [width-1:0] a_in /* Operand A Input Port */, b_in /* Operand B Input Port */;
// Outputs | {
"domain": "codereview.stackexchange",
"id": 45551,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "verilog",
"url": null
} |
verilog
// Outputs
output wire z /* Zero Flag Register (Embedded in res_out) */, n /* Negative/Sign Flag Register */;
output reg o /* Overflow/Underflow/Carry Flag Register */;
output reg cond /* Conditional Flag Register */;
output wire [width-1:0] d_out /* Data Output Port */;
// Internals
reg [1:0] chk_oflow /* Check for Overflow/Underflow */;
reg signed [width+width:0] res_out /* ALU Process Result Register */;
// Flag Logic
assign z = ~|res_out; // Zero Flag
assign n = res_out[15]; // Negative/Sign Flag
assign d_out [width-1:0] = res_out [width-1:0]; // Read Port
// Tri-State Read Control
assign d_out [width-1:0] = (re)?res_out [width-1:0]:0; // Assign d_out Port the value of res_out if re is true.
// Overflow/Underflow Detection Block
always@(chk_oflow) begin
if(rst) o <= 1'b0;
else begin
case(chk_oflow) // synthesis parallel-case
2'b00: o <= 1'b0;
2'b01: begin
if(res_out [width:width-1] == (2'b01 || 2'b10)) o <= 1'b1; // Scenario only possible on Overflow/Underflow.
else o <= 1'b0;
end
2'b10: begin
if((res_out[width+width]) && (~res_out [width+width-1:width-1] != 0)) o <= 1'b1; // Multiplication result is negative.
else if ((~res_out[width+width]) && (res_out [width+width-1:width-1] != 0)) o <= 1'b1; // Multiplication result is positive.
else o <= 1'b0;
end
2'b11: o <= 1'b0;
default: o <= 1'b0;
endcase
end
end
// ALU Processing Block | {
"domain": "codereview.stackexchange",
"id": 45551,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "verilog",
"url": null
} |
verilog
always@(posedge clk) begin
if(en && !rst) begin
case(opcode) // synthesis parallel-case
5'b00000: begin
res_out [width-1:0] <= a_in [width-1:0]; // A
end
5'b00001: begin
res_out [width-1:0] <= b_in [width-1:0]; // B
end
5'b00010: begin
res_out [width-1:0] <= a_in [width-1:0] + 1'b1; // Increment A
end
5'b00011: begin
res_out [width-1:0] <= b_in [width-1:0] + 1'b1; // Increment B
end
5'b00100: begin
res_out [width-1:0] <= a_in [width-1:0] - 1'b1; // Decrement A
end
5'b00101: begin
res_out [width-1:0] <= b_in [width-1:0] - 1'b1; // Decrement B
end
5'b00110: begin
chk_oflow <= 2'b01;
res_out [width:0] <= {a_in[width-1], a_in [width-1:0]} + {b_in[width-1], b_in [width-1:0]}; // Add A + B
end
5'b00111: begin
chk_oflow <= 2'b01;
res_out [width:0] <= {a_in[width-1], a_in [width-1:0]} - {b_in[width-1], b_in [width-1:0]}; // Subtract A - B
end
5'b01000: begin
chk_oflow <= 2'b10;
res_out [width+width:0] <= a_in [width-1:0] * b_in [width-1:0]; // Multiply A * B
end
5'b01001: begin
res_out [width-1:0] <= ~a_in [width-1:0]; // One's Complement of A
end
5'b01010: begin
res_out [width-1:0] <= ~b_in [width-1:0]; // One's Complement of B
end
5'b01011: begin
res_out [width-1:0] <= ~a_in [width-1:0] + 1'b1; // Two's Complement of A
end
5'b01100: begin
res_out [width-1:0] <= ~b_in [width-1:0] + 1'b1; // Two's Complement of B
end
5'b01101: begin | {
"domain": "codereview.stackexchange",
"id": 45551,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "verilog",
"url": null
} |
verilog
end
5'b01101: begin
if(a_in [width-1:0] == b_in [width-1:0]) cond <= 1'b1; // Compare A == B, set Conditional Register as result
else cond <= 1'b0;
end
5'b01110: begin
if(a_in [width-1:0] < b_in [width-1:0]) cond <= 1'b1; // Compare A < B, set Conditional Register as result
else cond <= 1'b0;
end
5'b01111: begin
if(a_in [width-1:0] > b_in [width-1:0]) cond <= 1'b1;// Compare A > B, set Conditional Register as result
else cond <= 1'b0;
end
5'b10000: begin
res_out [width-1:0] <= a_in [width-1:0] & b_in [width-1:0]; // Bitwise AND
end
5'b10001: begin
res_out [width-1:0] <= a_in [width-1:0] | b_in [width-1:0]; // Bitwise OR
end
5'b10010: begin
res_out [width-1:0] <= a_in [width-1:0] ^ b_in [width-1:0]; // Bitwise XOR
end
5'b10011: begin
res_out [width-1:0] <= a_in [width-1:0] ~& b_in [width-1:0]; // Bitwise NAND
end
5'b10100: begin
res_out [width-1:0] <= a_in [width-1:0] ~| b_in [width-1:0]; // Bitwise NOR
end
5'b10101: begin
res_out [width-1:0] <= a_in [width-1:0] ~^ b_in [width-1:0]; // Bitwise XNOR
end
5'b10110: begin
res_out [width-1:0] <= {a_in [width-2:0], 1'b0}; // Logical Left Shift A
end
5'b10111: begin
res_out [width-1:0] <= {b_in [width-2:0], 1'b0}; // Logical Left Shift B
end
5'b11000: begin
res_out [width-1:0] <= {1'b0, a_in [width-1:1]}; // Logical Right Shift A
end
5'b11001: begin
res_out [width-1:0] <= {1'b0, b_in [width-1:1]}; // Logical Right Shift B
end
5'b11010: begin | {
"domain": "codereview.stackexchange",
"id": 45551,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "verilog",
"url": null
} |
verilog
end
5'b11010: begin
res_out [width-1:0] <= {a_in [width-1], a_in [width-1:1]}; // Arithmetic Right Shift A
end
5'b11011: begin
res_out [width-1:0] <= {b_in [width-1], b_in [width-1:1]}; // Arithmetic Right Shift B
end
5'b11100: begin
res_out [width-1:0] <= {a_in [width-2:0], a_in [width-1]}; // Rotate Left A
end
5'b11101: begin
res_out [width-1:0] <= {b_in [width-2:0], b_in [width-1]}; // Rotate Left B
end
5'b11110: begin
res_out [width-1:0] <= {a_in [0], a_in [width-1:1]}; // Rotate Right A
end
5'b11111: begin
res_out [width-1:0] <= {b_in [0], b_in [width-1:1]}; // Rotate Right B
end
default: begin
cond <= 1'b0;
res_out [width-1:0] <= 0;
end
end else if(rst) begin
cond <= 1'b0;
chk_oflow <= 2'b0;
res_out [width-1:0] <= 0;
end
end | {
"domain": "codereview.stackexchange",
"id": 45551,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "verilog",
"url": null
} |
verilog
endmodule
There is a good chance I'll reduce the number of operations it performs to reduce the amount of unnecessary operations it does on both A and B, since less operations translates to better RISC performance.
Would a blocking or non-blocking operator be appropriate in this case?
Answer:
non-blocking one, which is better for sequential circuits.
It is not better per-se but it is the correct way to simulate a flip-flop.
Combinatorial
always @* begin
a = b;
Sequential (flip-flop)
always @(posedge clock) begin
a <= b ;
In the examples above nothing would go wrong if you used the wrong type but think about
always @(posedge clock) begin
b <= c ;
a <= b ;
Which is the same as
always @(posedge clock) begin
a <= b ;
b <= c ;
We are specifying a delay line which is c -> b -> a. If we use the wrong type :
always @(posedge clock) begin
b = c ;
a = b ; //=c
We actually get c -> b and c -> a, b does not block and feeds directly into a. Mixing the styles is possible but unless done very carefully bugs can creep in. for the purpose of code review it is best not to mix them so that it is a clear cut case.
Which will give a different result to :
always @(posedge clock) begin
a = b ;
b = c ;
When implying parallel hardware you would not expect an order dependence like this.
Mixing styles, or using the wrong style can lead to RTL vs Gate level mismatch. ie using a <= in a combinatorial section always @* will give the desired result in simulation but synthesis will ignore this and give you the equivalent of =. | {
"domain": "codereview.stackexchange",
"id": 45551,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "verilog",
"url": null
} |
c, generics, stack, library
Title: Generic stack implementation (revision)
Question: The below post is a follow-up of Generic stack implementation.
Below follows a header-only implementation of a generic stack (inspired by stb-libraries, following these guidelines: stb-howto.txt). After incorporating @Coderodde's advice into the code, I am left with:
#ifndef STACK_H
#define STACK_H
/* To use, do this:
* #define STACK_IMPLEMENTATION
* before you include this file in *one* C file to create the implementation.
*
* i.e. it should look like:
* #include ...
* #include ...
*
* #define STACK_IMPLEMENTATION
* #include "stack.h"
* ...
*
* To make all the functions have internal linkage, i.e. be private to the
* source file, do this:
* #define IO_STATIC
* before including "stack.h"
*
* i.e. it should look like:
* #define STACK_IMPLEMENTATION
* #define STACK_STATIC
* #include "stack.h"
* ...
*
* You can define STACK_MALLOC, STACK_REALLOC, and STACK_FREE to avoid using
* malloc(), realloc(), and free().
*/
#ifndef STACK_DEF
#ifdef STACK_STATIC
#define STACK_DEF static
#else
#define STACK_DEF extern
#endif /* STACK_STATIC */
#endif /* STACK_DEF */
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_LLVM_COMPILER)
#define ATTRIB_NONNULL(...) __attribute__((nonnull(__VA_ARGS__)))
#define ATTRIB_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#define ATTRIB_MALLOC __attribute__((malloc))
#else
#define ATTRIB_NONNULL(...) /**/
#define ATTRIB_WARN_UNUSED_RESULT /**/
#define ATTRIB_MALLOC /**/
#endif /* defined(__GNUC__) || defined(__clang__) || defined(__INTEL_LLVM_COMPILER) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct stack Stack; | {
"domain": "codereview.stackexchange",
"id": 45552,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, generics, stack, library",
"url": null
} |
c, generics, stack, library
typedef struct stack Stack;
/*
* Creates a stack with `cap` elements of size `memb_size`.
*
* The stack can only store one type of elements. It does not support
* heterogeneuous types.
*
* Returns a pointer to the stack on success, or NULL on failure to allocate
* memory.
*/
STACK_DEF Stack *stack_create(size_t cap, size_t memb_size)
ATTRIB_WARN_UNUSED_RESULT ATTRIB_MALLOC;
/*
* Pushes an element to the top of the stack referenced by `s`. It automatically
* resizes the stack if it is full.
*
* Whilst pushing an element, there's no need of a cast, as there is an implicit
* conversion to and from a void *.
*
* On a memory allocation failure, it returns false. Else it returns true.
*/
STACK_DEF bool stack_push(Stack *s, const void *data)
ATTRIB_NONNULL(1, 2) ATTRIB_WARN_UNUSED_RESULT;
/*
* Removes the topmost element of the stack referenced by `s` and returns it.
* If the stack is empty, it returns NULL.
*
* The returned element should be casted to a pointer of the type that was
* pushed on the stack, and then dereferenced.
*
* Note that casting to a pointer of the wrong type is Undefined Behavior, and
* so is dereferencing to performing arithmetic on a void *.
*/
STACK_DEF void *stack_pop(Stack *s) ATTRIB_NONNULL(1);
/*
* Returns a pointer to the topmost element of the stack referenced by `s`
* without removing it. If the stack is empty, it returns NULL.
*/
STACK_DEF const void *stack_peek(const Stack *s) ATTRIB_NONNULL(1);
/*
* Returns true if the capacity of the stack referenced by `s` is full, or false
* elsewise.
*/
STACK_DEF bool stack_is_full(const Stack *s) ATTRIB_NONNULL(1);
/*
* Returns true if the count of elements in the stack referenced by `s` is zero,
* or false elsewise.
*/
STACK_DEF bool stack_is_empty(const Stack *s) ATTRIB_NONNULL(1);
/*
* Returns the count of elements in the stack referenced by `s`.
*/
STACK_DEF size_t stack_size(const Stack *s) ATTRIB_NONNULL(1); | {
"domain": "codereview.stackexchange",
"id": 45552,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, generics, stack, library",
"url": null
} |
c, generics, stack, library
/*
* Destroys and frees all memory associated with the stack referenced by `s`.
*/
STACK_DEF void stack_destroy(Stack *s) ATTRIB_NONNULL(1);
#endif /* STACK_H */
#ifdef STACK_IMPLEMENTATION
#if defined(IO_MALLOC) != defined(IO_REALLOC) || defined(IO_REALLOC) != defined(IO_FREE)
#error "Must define all or none of IO_MALLOC, IO_REALLOC, and IO_FREE."
#endif
#ifndef STACK_MALLOC
#define STACK_MALLOC(sz) malloc(sz)
#define STACK_REALLOC(p, sz) realloc(p, sz)
#define STACK_FREE(p) free(p)
#endif
struct stack {
void *data;
size_t size;
size_t cap;
size_t memb_size;
};
STACK_DEF bool stack_is_full(const Stack *s)
{
return s->size == s->cap;
}
STACK_DEF bool stack_is_empty(const Stack *s)
{
return s->size == 0;
}
STACK_DEF const void *stack_peek(const Stack *s)
{
if (stack_is_empty(s)) {
return NULL;
}
return (char *) s->data + (s->size - 1) * s->memb_size;
}
STACK_DEF Stack *stack_create(size_t cap, size_t memb_size)
{
if (cap == 0 || memb_size == 0 || cap > SIZE_MAX / memb_size) {
return NULL;
}
Stack *const s = STACK_MALLOC(sizeof *s);
if (s) {
/* Would it be an improvement to round this up to the nearest
* multiple/power of 2.
*/
size_t total_size = memb_size * cap;
s->data = STACK_MALLOC(total_size);
if (s->data) {
s->cap = cap;
s->size = 0;
s->memb_size = memb_size;
} else {
free(s);
return NULL;
}
}
return s;
}
STACK_DEF bool stack_push(Stack *s, const void *data)
{
if (s->size >= s->cap) {
/* If we cannot allocate geometrically, we shall allocate linearly. */
if (s->cap > SIZE_MAX / 2) {
if (s->cap + BUFSIZ < s->cap) {
return false;
}
s->cap += BUFSIZ;
} else {
s->cap *= 2;
} | {
"domain": "codereview.stackexchange",
"id": 45552,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, generics, stack, library",
"url": null
} |
c, generics, stack, library
if (s->cap > SIZE_MAX / s->memb_size) {
return false;
}
void *const tmp = STACK_REALLOC(s->data, s->cap * s->memb_size);
if (!tmp) {
return false;
}
s->data = tmp;
}
char *const target = (char *) s->data + (s->size * s->memb_size);
memcpy(target, data, s->memb_size);
return !!++s->size;
}
STACK_DEF void *stack_pop(Stack *s)
{
if (stack_is_empty(s)) {
return NULL;
}
--s->size;
void *const top = (char *) s->data + (s->size * s->memb_size);
if (s->size && (s->size <= s->cap / 4)) {
void *const tmp = realloc(s->data, s->cap / 2 * s->memb_size);
if (tmp) {
s->data = tmp;
s->cap /= 2;
}
/* Else do nothing. The original memory is left intact. */
}
return top;
}
STACK_DEF void stack_destroy(Stack *s)
{
STACK_FREE(s->data);
STACK_FREE(s);
}
STACK_DEF size_t stack_size(const Stack *s)
{
return s->size;
}
#endif /* STACK_IMPLEMENTATION */
#ifdef TEST_MAIN
#include <assert.h>
int main(void)
{
/* We could support heterogenuous objects by using void pointers. */
Stack *stack = stack_create(SIZE_MAX - 1000, sizeof (size_t));
assert(!stack);
stack = stack_create(1000, sizeof (int));
assert(stack);
for (int i = 0; i < 150; ++i) {
assert(stack_push(stack, &i));
}
assert(!stack_is_empty(stack));
assert(stack_size(stack) == 150);
assert(*(int *) stack_peek(stack) == 149);
for (int i = 149; i >= 0; i--) {
assert(*(int *) stack_peek(stack) == i);
assert(*(int *) stack_pop(stack) == i);
}
stack_destroy(stack);
return EXIT_SUCCESS;
}
#endif /* TEST_MAIN */ | {
"domain": "codereview.stackexchange",
"id": 45552,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, generics, stack, library",
"url": null
} |
c, generics, stack, library
#endif /* TEST_MAIN */
Review Request:
What I am mainly interested in are my new overflow checks and reallocation strategy, namely in stack_create(), stack_push(), and stack_pop().
Other comments are also welcome.
Edit:
This is how it can be used:
#define GSTACK_IMPLEMENTATION // Include the implementation as well
#define GSTACK_STATIC // Make all functions static
#define TEST_MAIN // Include a sample main() function
Answer: Name space
Code is taking up stack, stack_..., Stack, STACK_....
I can foresee user code collisions as "stack" is very common.
Consider something like gstack, gstack_..., GSTACK_... and not gStack.
... an improvement to round this up ...
/* Would it be an improvement to round this up to the nearest
* multiple/power of 2. */
No. Rounding up makes sense only if you understand STACK_MALLOC() better than the implementer of STACK_MALLOC().
Really going to test this well?
Do you really want linear growth of say a BUFSIZ of 4k when SIZE_MAX is 264 - 1?
Instead when geometric growth not possible either:
Fail.
Use SIZE_MAX/memb_size to simplify testing. Fail if above that.
I'd go for the first.
Why 4?
Magic numbers vs named constants.
if (s->size && (s->size <= s->cap / 4)) { deserves explanation.
Unclear why !!
As the return type is bool, why !!? What benefit do you see?
// return !!++s->size;
return ++s->size;
Why define IO_STATIC?
* To make all the functions have internal linkage, i.e. be private to the
* source file, do this:
* #define IO_STATIC
* before including "stack.h"
Where are IO_... defined?
Code is for a generic stack type. Does it compile with a generic C compiler?
#if defined(IO_MALLOC) != defined(IO_REALLOC) || defined(IO_REALLOC) != defined(IO_FREE)
#error "Must define all or none of IO_MALLOC, IO_REALLOC, and IO_FREE." | {
"domain": "codereview.stackexchange",
"id": 45552,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, generics, stack, library",
"url": null
} |
c, generics, stack, library
1 .h file vs. a .c and .h file
This .h file brings in various #include <....h> files that would not be needed with classic .c, .h file approach.
#include <stdio.h>
#include <string.h>
#include <stdint.h>
Unclear why code always includes <stdio.h>, <stdint.h>.
[Edit]
Tolerate stack_destroy(NULL)
As free(NULL) is OK, allow stack_destroy(). This simplifies caller's clean-up code.
STACK_DEF void stack_destroy(Stack *s) {
if (s) { // Add condition
STACK_FREE(s->data);
STACK_FREE(s);
}
} | {
"domain": "codereview.stackexchange",
"id": 45552,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, generics, stack, library",
"url": null
} |
java, stream, lazy
Title: Implementation of java.util.stream.Stream (and friends) that reads lines from the internet without requiring you to manage the resources
Question: This streams lines of information over the internet using BufferedReader::lines.
However, what makes this special (and thus, extraordinarily complicated imo) is that ALL resource management is done internally -- the end user does not need to handle the resources at all.
So, no try-with-resources, no try-catch-finally, none of that. The user can fearlessly use this stream (or at least, as fearlessly as they can use any other non-resource stream). | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
As a result, I would like this review to focus on making sure my claim is as bullet proof as I make it out to be. Priority #1 is to make sure that this implementation cannot leak resources.
Other than that, I want the obvious things like correctness/efficiency/readability/maintainability/etc.
One potential pain point that I want to highlight -- I chose to open a connection to the URL at the last possible moment -- during terminal operations. However, that technically makes certain introspective operations a little dubious. For example, isParallel. As is, I am opening a connection to the internet just to check if my stream is parallel. I don't know how terrible that is, but I also don't see a better way to work around that pain point. Special attention to this method would be appreciated.
And finally, you may be wondering what maniac would go to such lengths when we have TWR (try with resources).
The reason why is because forgetting to do TWR is not a compiler error nor a compiler warning. And I am leading a team of (entry-level) devs to handle a fairly lofty personal project. To make their lives a little easier, I wanted to build something that wouldn't leak. Hence, this monstrosity was created.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.IntSummaryStatistics;
import java.util.Iterator;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.*;
import java.util.stream.*;
public class StreamLinesOverInternet<T>
implements Stream<T>
{ | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public class StreamLinesOverInternet<T>
implements Stream<T>
{
private final Supplier<Stream<T>> encapsulatedStream;
public static void main(final String[] args)
{
final String url =
//THIS IS A >5 GIGABYTE FILE
"https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv"
;
final Stream<String> linesFromCsv = StreamLinesOverInternet.stream(url);
//Grabs the first 10 lines from the CSV File
linesFromCsv
.limit(10)
.forEach(System.out::println)
;
//Normally, a file this size would take several seconds, if not minutes, to download, and then process.
//But, because we are processing data as soon as we fetch it, we can short-circuit once we have as much
//as we need. This is thanks to java.util.Stream, java.io.InputStream, and java.io.BufferedReader.
//In the above example, we are streaming lines from the CSV File. So, once the Stream has determined
//it can terminate early because it has enough info to correctly evaluate (called short-circuiting),
//the Stream closes the BufferedReader, which in turn, closes the other resources.
}
private StreamLinesOverInternet(final Supplier<Stream<T>> encapsulatedStream)
{
Objects.requireNonNull(encapsulatedStream);
this.encapsulatedStream = encapsulatedStream;
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public static StreamLinesOverInternet<String> stream(final URI uri)
{
Objects.requireNonNull(uri);
final URL url;
try
{
url = uri.toURL();
}
catch (final Exception exception)
{
throw new IllegalStateException(exception);
}
final Supplier<Stream<String>> stream =
() ->
{
try
{
final InputStream inputStream = url.openStream();
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
final Stream<String> encapsulatedStream =
bufferedReader
.lines()
.onClose
(
() ->
{
try
{
bufferedReader.close(); | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
System.out.println("CLOSED THE BUFFERED READER");
}
catch (final Exception exception)
{
throw new IllegalStateException(exception);
}
}
)
;
return encapsulatedStream;
}
catch (final Exception exception)
{
throw new IllegalStateException(exception);
}
}
;
return new StreamLinesOverInternet<>(stream);
}
public static StreamLinesOverInternet<String> stream(final String uriString)
{
Objects.requireNonNull(uriString);
if (uriString.isBlank())
{
throw new IllegalArgumentException("uri cannot be blank!");
}
try
{
final URI uri = new URI(uriString);
return stream(uri);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
private
static
<A, B, C>
C
convertStream
(
final Supplier<A> currentStreamSupplier,
final Function<A, ? extends B> function,
final Function<Supplier<B>, C> constructor
)
{
Objects.requireNonNull(currentStreamSupplier);
Objects.requireNonNull(function);
Objects.requireNonNull(constructor);
final Supplier<B> nextStreamSupplier =
() ->
{
final A currentStream = currentStreamSupplier.get();
final B nextStream = function.apply(currentStream);
return nextStream;
}
;
return constructor.apply(nextStreamSupplier);
}
private <U> StreamLinesOverInternet<U> continueStreamSafely(final Function<Stream<T>, Stream<U>> function)
{
return
convertStream
(
this.encapsulatedStream,
function,
StreamLinesOverInternet::new
)
;
}
private <U> U terminateWithValueSafely(final Function<Stream<T>, U> function)
{
try
(
final Stream<T> stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(function);
return function.apply(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
private void terminateSafely(final Consumer<Stream<T>> consumer)
{
try
(
final Stream<T> stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(consumer);
consumer.accept(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
@Override
public Optional<T> findAny()
{
return this.terminateWithValueSafely(Stream::findAny);
}
@Override
public Optional<T> findFirst()
{
return this.terminateWithValueSafely(Stream::findFirst);
}
@Override
public boolean noneMatch(final Predicate<? super T> predicate)
{
return this.terminateWithValueSafely(stream -> stream.noneMatch(predicate));
}
@Override
public boolean allMatch(final Predicate<? super T> predicate)
{
return this.terminateWithValueSafely(stream -> stream.allMatch(predicate));
}
@Override
public boolean anyMatch(final Predicate<? super T> predicate)
{
return this.terminateWithValueSafely(stream -> stream.anyMatch(predicate));
}
@Override
public long count()
{
return this.terminateWithValueSafely(Stream::count);
}
@Override
public Optional<T> max(final Comparator<? super T> comparator)
{
return this.terminateWithValueSafely(stream -> stream.max(comparator));
}
@Override
public Optional<T> min(final Comparator<? super T> comparator)
{
return this.terminateWithValueSafely(stream -> stream.min(comparator));
}
@Override
public <R, A> R collect(final Collector<? super T, A, R> collector)
{
return this.terminateWithValueSafely(stream -> stream.collect(collector));
}
@Override
public <R> R collect(final Supplier<R> supplier, final BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
{
return this.terminateWithValueSafely(stream -> stream.collect(supplier, accumulator, combiner));
}
@Override
public <U> U reduce(final U identity, final BiFunction<U,? super T,U> accumulator, final BinaryOperator<U> combiner)
{
return this.terminateWithValueSafely(stream -> stream.reduce(identity, accumulator, combiner));
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
@Override
public Optional<T> reduce(final BinaryOperator<T> accumulator)
{
return this.terminateWithValueSafely(stream -> stream.reduce(accumulator));
}
@Override
public T reduce(final T identity, final BinaryOperator<T> accumulator)
{
return this.terminateWithValueSafely(stream -> stream.reduce(identity, accumulator));
}
@Override
public <A> A[] toArray(final IntFunction<A[]> generator)
{
return this.terminateWithValueSafely(stream -> stream.toArray(generator));
}
@Override
public Object[] toArray()
{
return this.terminateWithValueSafely(Stream::toArray);
}
@Override
public void forEachOrdered(final Consumer<? super T> action)
{
this.terminateSafely(stream -> stream.forEachOrdered(action));
}
@Override
public void forEach(final Consumer<? super T> action)
{
this.terminateSafely(stream -> stream.forEach(action));
}
@Override
public StreamLinesOverInternet<T> skip(final long n)
{
return this.continueStreamSafely(stream -> stream.skip(n));
}
@Override
public StreamLinesOverInternet<T> limit(final long maxSize)
{
return this.continueStreamSafely(stream -> stream.limit(maxSize));
}
@Override
public StreamLinesOverInternet<T> peek(final Consumer<? super T> action)
{
return this.continueStreamSafely(stream -> stream.peek(action));
}
@Override
public StreamLinesOverInternet<T> sorted(final Comparator<? super T> comparator)
{
return this.continueStreamSafely(stream -> stream.sorted(comparator));
}
@Override
public StreamLinesOverInternet<T> sorted()
{
return this.continueStreamSafely(Stream::sorted);
}
@Override
public StreamLinesOverInternet<T> distinct()
{
return this.continueStreamSafely(Stream::distinct);
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
@Override
public DoubleVersion flatMapToDouble(final Function<? super T, ? extends DoubleStream> function)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.flatMapToDouble(function),
DoubleVersion::new
)
;
}
@Override
public LongVersion flatMapToLong(final Function<? super T, ? extends LongStream> function)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.flatMapToLong(function),
LongVersion::new
)
;
}
@Override
public IntVersion flatMapToInt(final Function<? super T, ? extends IntStream> function)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.flatMapToInt(function),
IntVersion::new
)
;
}
@Override
public <R> StreamLinesOverInternet<R> flatMap(final Function<? super T, ? extends Stream<? extends R>> function)
{
Objects.requireNonNull(function);
return this.continueStreamSafely(stream -> stream.flatMap(function));
}
@Override
public DoubleVersion mapToDouble(final ToDoubleFunction<? super T> toDoubleFunction)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToDouble(toDoubleFunction),
DoubleVersion::new
)
;
}
@Override
public LongVersion mapToLong(final ToLongFunction<? super T> toLongFunction)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToLong(toLongFunction),
LongVersion::new
)
;
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
@Override
public IntVersion mapToInt(final ToIntFunction<? super T> toIntFunction)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToInt(toIntFunction),
IntVersion::new
)
;
}
@Override
public <R> StreamLinesOverInternet<R> map(final Function<? super T, ? extends R> function)
{
Objects.requireNonNull(function);
return this.continueStreamSafely(stream -> stream.map(function));
}
@Override
public StreamLinesOverInternet<T> filter(final Predicate<? super T> predicate)
{
Objects.requireNonNull(predicate);
return this.continueStreamSafely(stream -> stream.filter(predicate));
}
@Override
public void close()
{
this.terminateSafely(Stream::close);
System.out.println("closed " + this);
}
@Override
public StreamLinesOverInternet<T> onClose(final Runnable runnable)
{
Objects.requireNonNull(runnable);
return this.continueStreamSafely(stream -> stream.onClose(runnable));
}
@Override
public StreamLinesOverInternet<T> unordered()
{
return this.continueStreamSafely(Stream::unordered);
}
@Override
public StreamLinesOverInternet<T> parallel()
{
return this.continueStreamSafely(Stream::parallel);
}
@Override
public StreamLinesOverInternet<T> sequential()
{
return this.continueStreamSafely(Stream::sequential);
}
@Override
//THIS FEELS LIKE A HORRIBLE IDEA, and yet, it doesn't seem that bad.
public boolean isParallel()
{
return this.terminateWithValueSafely(Stream::isParallel);
}
@Override
public Spliterator<T> spliterator()
{
final List<T> list = this.toList();
return list.spliterator();
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
@Override
public Iterator<T> iterator()
{
final Spliterator<T> spliterator = this.spliterator();
return Spliterators.iterator(spliterator);
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public static class IntVersion
implements IntStream
{
private final Supplier<IntStream> encapsulatedStream;
private IntVersion(final Supplier<IntStream> encapsulatedStream)
{
Objects.requireNonNull(encapsulatedStream);
this.encapsulatedStream = encapsulatedStream;
}
private IntVersion continueStreamSafely(final UnaryOperator<IntStream> function)
{
return
convertStream
(
this.encapsulatedStream,
function,
IntVersion::new
)
;
}
private <U> U terminateWithValueSafely(final Function<IntStream, U> function)
{
try
(
final IntStream stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(function);
return function.apply(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
private void terminateSafely(final Consumer<IntStream> consumer)
{
try
(
final IntStream stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(consumer);
consumer.accept(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
@Override
public Spliterator.OfInt spliterator()
{
final int[] array = this.terminateWithValueSafely(IntStream::toArray);
return Arrays.spliterator(array);
}
@Override
public PrimitiveIterator.OfInt iterator()
{ | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
@Override
public PrimitiveIterator.OfInt iterator()
{
final Spliterator.OfInt spliterator = this.spliterator();
return Spliterators.iterator(spliterator);
}
@Override
public StreamLinesOverInternet.IntVersion parallel()
{
return this.continueStreamSafely(IntStream::parallel);
}
@Override
public StreamLinesOverInternet.IntVersion sequential()
{
return this.continueStreamSafely(IntStream::sequential);
}
@Override
public StreamLinesOverInternet<Integer> boxed()
{
return
convertStream
(
this.encapsulatedStream,
IntStream::boxed,
StreamLinesOverInternet::new
)
;
}
@Override
public OptionalInt findAny()
{
return this.terminateWithValueSafely(IntStream::findAny);
}
@Override
public OptionalInt findFirst()
{
return this.terminateWithValueSafely(IntStream::findFirst);
}
@Override
public boolean noneMatch(final IntPredicate intPredicate)
{
Objects.requireNonNull(intPredicate);
return this.terminateWithValueSafely(intStream -> intStream.noneMatch(intPredicate));
}
@Override
public boolean allMatch(final IntPredicate intPredicate)
{
Objects.requireNonNull(intPredicate);
return this.terminateWithValueSafely(intStream -> intStream.allMatch(intPredicate));
}
@Override
public boolean anyMatch(final IntPredicate intPredicate)
{
Objects.requireNonNull(intPredicate);
return this.terminateWithValueSafely(intStream -> intStream.anyMatch(intPredicate));
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
@Override
public IntSummaryStatistics summaryStatistics()
{
return this.terminateWithValueSafely(IntStream::summaryStatistics);
}
@Override
public OptionalDouble average()
{
return this.terminateWithValueSafely(IntStream::average);
}
@Override
public long count()
{
return this.terminateWithValueSafely(IntStream::count);
}
@Override
public OptionalInt max()
{
return this.terminateWithValueSafely(IntStream::max);
}
@Override
public OptionalInt min()
{
return this.terminateWithValueSafely(IntStream::min);
}
@Override
public int sum()
{
return this.terminateWithValueSafely(IntStream::sum);
}
@Override
public <R> R collect(final Supplier<R> supplier, final ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner)
{
Objects.requireNonNull(supplier);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(combiner);
return this.terminateWithValueSafely(intStream -> intStream.collect(supplier, accumulator, combiner));
}
@Override
public OptionalInt reduce(final IntBinaryOperator intBinaryOperator)
{
Objects.requireNonNull(intBinaryOperator);
return this.terminateWithValueSafely(intStream -> intStream.reduce(intBinaryOperator));
}
@Override
public int reduce(final int identity, final IntBinaryOperator intBinaryOperator)
{
Objects.requireNonNull(intBinaryOperator);
return this.terminateWithValueSafely(intStream -> intStream.reduce(identity, intBinaryOperator));
}
@Override
public int[] toArray()
{ | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
@Override
public int[] toArray()
{
return this.terminateWithValueSafely(IntStream::toArray);
}
@Override
public void forEachOrdered(final IntConsumer intConsumer)
{
Objects.requireNonNull(intConsumer);
this.terminateSafely(intStream -> intStream.forEachOrdered(intConsumer));
}
@Override
public void forEach(final IntConsumer intConsumer)
{
Objects.requireNonNull(intConsumer);
this.terminateSafely(intStream -> intStream.forEach(intConsumer));
}
@Override
public IntVersion skip(final long n)
{
return this.continueStreamSafely(intStream -> intStream.skip(n));
}
@Override
public IntVersion limit(final long n)
{
return this.continueStreamSafely(intStream -> intStream.limit(n));
}
@Override
public IntVersion peek(final IntConsumer intConsumer)
{
Objects.requireNonNull(intConsumer);
return this.continueStreamSafely(intStream -> intStream.peek(intConsumer));
}
@Override
public IntVersion sorted()
{
return this.continueStreamSafely(IntStream::sorted);
}
@Override
public IntVersion distinct()
{
return this.continueStreamSafely(IntStream::distinct);
}
@Override
public IntVersion flatMap(final IntFunction<? extends IntStream> intFunction)
{
Objects.requireNonNull(intFunction);
return this.continueStreamSafely(intStream -> intStream.flatMap(intFunction));
}
@Override
public DoubleVersion asDoubleStream()
{
final Supplier<DoubleStream> nextStreamSupplier =
() ->
{ | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
() ->
{
final IntStream currentStream = this.encapsulatedStream.get();
final DoubleStream nextStream = currentStream.asDoubleStream();
return nextStream;
}
;
return new DoubleVersion(nextStreamSupplier);
}
@Override
public LongVersion asLongStream()
{
final Supplier<LongStream> nextStreamSupplier =
() ->
{
final IntStream currentStream = this.encapsulatedStream.get();
final LongStream nextStream = currentStream.asLongStream();
return nextStream;
}
;
return new LongVersion(nextStreamSupplier);
}
@Override
public DoubleVersion mapToDouble(final IntToDoubleFunction intToDoubleFunction)
{
Objects.requireNonNull(intToDoubleFunction);
final Supplier<DoubleStream> nextStreamSupplier =
() ->
{
final IntStream currentStream = this.encapsulatedStream.get();
final DoubleStream nextStream = currentStream.mapToDouble(intToDoubleFunction);
return nextStream;
}
;
return new DoubleVersion(nextStreamSupplier);
}
@Override
public LongVersion mapToLong(final IntToLongFunction intToLongFunction)
{
Objects.requireNonNull(intToLongFunction);
final Supplier<LongStream> nextStreamSupplier =
() ->
{
final IntStream currentStream = this.encapsulatedStream.get();
final LongStream nextStream = currentStream.mapToLong(intToLongFunction); | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
final LongStream nextStream = currentStream.mapToLong(intToLongFunction);
return nextStream;
}
;
return new LongVersion(nextStreamSupplier);
}
@Override
public <U> StreamLinesOverInternet<U> mapToObj(final IntFunction<? extends U> intFunction)
{
Objects.requireNonNull(intFunction);
final Supplier<Stream<U>> nextStreamSupplier =
() ->
{
final IntStream currentStream = this.encapsulatedStream.get();
final Stream<U> nextStream = currentStream.mapToObj(intFunction);
return nextStream;
}
;
return new StreamLinesOverInternet<>(nextStreamSupplier);
}
@Override
public IntVersion map(final IntUnaryOperator intUnaryOperator)
{
Objects.requireNonNull(intUnaryOperator);
return this.continueStreamSafely(intStream -> intStream.map(intUnaryOperator));
}
@Override
public IntVersion filter(final IntPredicate intPredicate)
{
Objects.requireNonNull(intPredicate);
return this.continueStreamSafely(intStream -> intStream.filter(intPredicate));
}
@Override
public void close()
{
this.terminateSafely(IntStream::close);
System.out.println("closed " + this);
}
@Override
public IntVersion onClose(final Runnable runnable)
{
Objects.requireNonNull(runnable);
return this.continueStreamSafely(intStream -> intStream.onClose(runnable));
}
@Override
public IntVersion unordered()
{
return this.continueStreamSafely(IntStream::unordered);
}
@Override | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
return this.continueStreamSafely(IntStream::unordered);
}
@Override
public boolean isParallel()
{
try
(
final IntStream stream = this.encapsulatedStream.get()
)
{
return stream.isParallel();
}
catch (final Exception exception)
{
throw new IllegalStateException(exception);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public static class LongVersion
implements LongStream
{
private final Supplier<LongStream> encapsulatedStream;
private LongVersion(final Supplier<LongStream> encapsulatedStream)
{
Objects.requireNonNull(encapsulatedStream);
this.encapsulatedStream = encapsulatedStream;
}
private LongVersion continueStreamSafely(final UnaryOperator<LongStream> function)
{
Objects.requireNonNull(function);
final Supplier<LongStream> nextStreamSupplier =
() ->
{
final LongStream currentStream = this.encapsulatedStream.get();
final LongStream nextStream = function.apply(currentStream);
return nextStream;
}
;
return new LongVersion(nextStreamSupplier);
}
private <U> U terminateWithValueSafely(final Function<LongStream, U> function)
{
try
(
final LongStream stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(function);
return function.apply(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
private void terminateSafely(final Consumer<LongStream> consumer)
{
try
(
final LongStream stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(consumer);
consumer.accept(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
@Override | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
}
@Override
public Spliterator.OfLong spliterator()
{
final long[] array = this.terminateWithValueSafely(LongStream::toArray);
return Arrays.spliterator(array);
}
@Override
public PrimitiveIterator.OfLong iterator()
{
final Spliterator.OfLong spliterator = this.spliterator();
return Spliterators.iterator(spliterator);
}
@Override
public StreamLinesOverInternet.LongVersion parallel()
{
return this.continueStreamSafely(LongStream::parallel);
}
@Override
public StreamLinesOverInternet.LongVersion sequential()
{
return this.continueStreamSafely(LongStream::sequential);
}
@Override
public StreamLinesOverInternet<Long> boxed()
{
final Supplier<Stream<Long>> nextStreamSupplier =
() ->
{
final LongStream currentStream = this.encapsulatedStream.get();
final Stream<Long> nextStream = currentStream.boxed();
return nextStream;
}
;
return new StreamLinesOverInternet<>(nextStreamSupplier);
}
@Override
public OptionalLong findAny()
{
return this.terminateWithValueSafely(LongStream::findAny);
}
@Override
public OptionalLong findFirst()
{
return this.terminateWithValueSafely(LongStream::findFirst);
}
@Override
public boolean noneMatch(final LongPredicate longPredicate)
{
Objects.requireNonNull(longPredicate);
return this.terminateWithValueSafely(longStream -> longStream.noneMatch(longPredicate));
}
@Override | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
@Override
public boolean allMatch(final LongPredicate longPredicate)
{
Objects.requireNonNull(longPredicate);
return this.terminateWithValueSafely(longStream -> longStream.allMatch(longPredicate));
}
@Override
public boolean anyMatch(final LongPredicate longPredicate)
{
Objects.requireNonNull(longPredicate);
return this.terminateWithValueSafely(longStream -> longStream.anyMatch(longPredicate));
}
@Override
public LongSummaryStatistics summaryStatistics()
{
return this.terminateWithValueSafely(LongStream::summaryStatistics);
}
@Override
public OptionalDouble average()
{
return this.terminateWithValueSafely(LongStream::average);
}
@Override
public long count()
{
return this.terminateWithValueSafely(LongStream::count);
}
@Override
public OptionalLong max()
{
return this.terminateWithValueSafely(LongStream::max);
}
@Override
public OptionalLong min()
{
return this.terminateWithValueSafely(LongStream::min);
}
@Override
public long sum()
{
return this.terminateWithValueSafely(LongStream::sum);
}
@Override
public <R> R collect(final Supplier<R> supplier, final ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner)
{
Objects.requireNonNull(supplier);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(combiner);
return this.terminateWithValueSafely(longStream -> longStream.collect(supplier, accumulator, combiner));
}
@Override
public OptionalLong reduce(final LongBinaryOperator longBinaryOperator)
{ | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public OptionalLong reduce(final LongBinaryOperator longBinaryOperator)
{
Objects.requireNonNull(longBinaryOperator);
return this.terminateWithValueSafely(longStream -> longStream.reduce(longBinaryOperator));
}
@Override
public long reduce(final long identity, final LongBinaryOperator longBinaryOperator)
{
Objects.requireNonNull(longBinaryOperator);
return this.terminateWithValueSafely(longStream -> longStream.reduce(identity, longBinaryOperator));
}
@Override
public long[] toArray()
{
return this.terminateWithValueSafely(LongStream::toArray);
}
@Override
public void forEachOrdered(final LongConsumer longConsumer)
{
Objects.requireNonNull(longConsumer);
this.terminateSafely(longStream -> longStream.forEachOrdered(longConsumer));
}
@Override
public void forEach(final LongConsumer longConsumer)
{
Objects.requireNonNull(longConsumer);
this.terminateSafely(longStream -> longStream.forEach(longConsumer));
}
@Override
public LongVersion skip(final long n)
{
return this.continueStreamSafely(longStream -> longStream.skip(n));
}
@Override
public LongVersion limit(final long n)
{
return this.continueStreamSafely(longStream -> longStream.limit(n));
}
@Override
public LongVersion peek(final LongConsumer longConsumer)
{
Objects.requireNonNull(longConsumer);
return this.continueStreamSafely(longStream -> longStream.peek(longConsumer));
}
@Override
public LongVersion sorted()
{
return this.continueStreamSafely(LongStream::sorted);
}
@Override | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
return this.continueStreamSafely(LongStream::sorted);
}
@Override
public LongVersion distinct()
{
return this.continueStreamSafely(LongStream::distinct);
}
@Override
public LongVersion flatMap(final LongFunction<? extends LongStream> longFunction)
{
Objects.requireNonNull(longFunction);
return this.continueStreamSafely(longStream -> longStream.flatMap(longFunction));
}
@Override
public DoubleVersion asDoubleStream()
{
final Supplier<DoubleStream> nextStreamSupplier =
() ->
{
final LongStream currentStream = this.encapsulatedStream.get();
final DoubleStream nextStream = currentStream.asDoubleStream();
return nextStream;
}
;
return new DoubleVersion(nextStreamSupplier);
}
@Override
public DoubleVersion mapToDouble(final LongToDoubleFunction longToDoubleFunction)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToDouble(longToDoubleFunction),
DoubleVersion::new
)
;
}
@Override
public IntVersion mapToInt(final LongToIntFunction longToIntFunction)
{
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToInt(longToIntFunction),
IntVersion::new
)
;
}
@Override
public <U> StreamLinesOverInternet<U> mapToObj(final LongFunction<? extends U> longFunction)
{
return
convertStream
(
this.encapsulatedStream, | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToObj(longFunction),
StreamLinesOverInternet<U>::new
)
;
}
@Override
public LongVersion map(final LongUnaryOperator longUnaryOperator)
{
Objects.requireNonNull(longUnaryOperator);
return this.continueStreamSafely(longStream -> longStream.map(longUnaryOperator));
}
@Override
public LongVersion filter(final LongPredicate longPredicate)
{
Objects.requireNonNull(longPredicate);
return this.continueStreamSafely(longStream -> longStream.filter(longPredicate));
}
@Override
public void close()
{
this.terminateSafely(LongStream::close);
}
@Override
public LongVersion onClose(final Runnable runnable)
{
Objects.requireNonNull(runnable);
return this.continueStreamSafely(longStream -> longStream.onClose(runnable));
}
@Override
public LongVersion unordered()
{
return this.continueStreamSafely(LongStream::unordered);
}
@Override
public boolean isParallel()
{
return this.terminateWithValueSafely(LongStream::isParallel);
}
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public static class DoubleVersion
implements DoubleStream
{
private final Supplier<DoubleStream> encapsulatedStream;
private DoubleVersion(final Supplier<DoubleStream> encapsulatedStream)
{
Objects.requireNonNull(encapsulatedStream);
this.encapsulatedStream = encapsulatedStream;
}
private DoubleVersion continueStreamSafely(final UnaryOperator<DoubleStream> function)
{
return
convertStream
(
this.encapsulatedStream,
function,
DoubleVersion::new
)
;
}
private <U> U terminateWithValueSafely(final Function<DoubleStream, U> function)
{
try
(
final DoubleStream stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(function);
return function.apply(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
private void terminateSafely(final Consumer<DoubleStream> consumer)
{
try
(
final DoubleStream stream = this.encapsulatedStream.get();
)
{
Objects.requireNonNull(consumer);
consumer.accept(stream);
}
catch (final Exception exception)
{
throw new RuntimeException(exception);
}
}
@Override
public Spliterator.OfDouble spliterator()
{
final double[] array = this.terminateWithValueSafely(DoubleStream::toArray);
return Arrays.spliterator(array);
}
@Override
public PrimitiveIterator.OfDouble iterator() | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
@Override
public PrimitiveIterator.OfDouble iterator()
{
final Spliterator.OfDouble spliterator = this.spliterator();
return Spliterators.iterator(spliterator);
}
@Override
public StreamLinesOverInternet.DoubleVersion parallel()
{
return this.continueStreamSafely(DoubleStream::parallel);
}
@Override
public StreamLinesOverInternet.DoubleVersion sequential()
{
return this.continueStreamSafely(DoubleStream::sequential);
}
@Override
public StreamLinesOverInternet<Double> boxed()
{
return
convertStream
(
this.encapsulatedStream,
DoubleStream::boxed,
StreamLinesOverInternet<Double>::new
)
;
}
@Override
public OptionalDouble findAny()
{
return this.terminateWithValueSafely(DoubleStream::findAny);
}
@Override
public OptionalDouble findFirst()
{
return this.terminateWithValueSafely(DoubleStream::findFirst);
}
@Override
public boolean noneMatch(final DoublePredicate doublePredicate)
{
Objects.requireNonNull(doublePredicate);
return this.terminateWithValueSafely(doubleStream -> doubleStream.noneMatch(doublePredicate));
}
@Override
public boolean allMatch(final DoublePredicate doublePredicate)
{
Objects.requireNonNull(doublePredicate);
return this.terminateWithValueSafely(doubleStream -> doubleStream.allMatch(doublePredicate));
}
@Override
public boolean anyMatch(final DoublePredicate doublePredicate)
{
Objects.requireNonNull(doublePredicate); | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
{
Objects.requireNonNull(doublePredicate);
return this.terminateWithValueSafely(doubleStream -> doubleStream.anyMatch(doublePredicate));
}
@Override
public DoubleSummaryStatistics summaryStatistics()
{
return this.terminateWithValueSafely(DoubleStream::summaryStatistics);
}
@Override
public OptionalDouble average()
{
return this.terminateWithValueSafely(DoubleStream::average);
}
@Override
public long count()
{
return this.terminateWithValueSafely(DoubleStream::count);
}
@Override
public OptionalDouble max()
{
return this.terminateWithValueSafely(DoubleStream::max);
}
@Override
public OptionalDouble min()
{
return this.terminateWithValueSafely(DoubleStream::min);
}
@Override
public double sum()
{
return this.terminateWithValueSafely(DoubleStream::sum);
}
@Override
public <R> R collect(final Supplier<R> supplier, final ObjDoubleConsumer<R> accumulator, BiConsumer<R, R> combiner)
{
Objects.requireNonNull(supplier);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(combiner);
return this.terminateWithValueSafely(doubleStream -> doubleStream.collect(supplier, accumulator, combiner));
}
@Override
public OptionalDouble reduce(final DoubleBinaryOperator doubleBinaryOperator)
{
Objects.requireNonNull(doubleBinaryOperator);
return this.terminateWithValueSafely(doubleStream -> doubleStream.reduce(doubleBinaryOperator));
}
@Override
public double reduce(final double identity, final DoubleBinaryOperator doubleBinaryOperator)
{ | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
{
Objects.requireNonNull(doubleBinaryOperator);
return this.terminateWithValueSafely(doubleStream -> doubleStream.reduce(identity, doubleBinaryOperator));
}
@Override
public double[] toArray()
{
return this.terminateWithValueSafely(DoubleStream::toArray);
}
@Override
public void forEachOrdered(final DoubleConsumer doubleConsumer)
{
Objects.requireNonNull(doubleConsumer);
this.terminateSafely(doubleStream -> doubleStream.forEachOrdered(doubleConsumer));
}
@Override
public void forEach(final DoubleConsumer doubleConsumer)
{
Objects.requireNonNull(doubleConsumer);
this.terminateSafely(doubleStream -> doubleStream.forEach(doubleConsumer));
}
@Override
public DoubleVersion skip(final long n)
{
return this.continueStreamSafely(doubleStream -> doubleStream.skip(n));
}
@Override
public DoubleVersion limit(final long n)
{
return this.continueStreamSafely(doubleStream -> doubleStream.limit(n));
}
@Override
public DoubleVersion peek(final DoubleConsumer doubleConsumer)
{
Objects.requireNonNull(doubleConsumer);
return this.continueStreamSafely(doubleStream -> doubleStream.peek(doubleConsumer));
}
@Override
public DoubleVersion sorted()
{
return this.continueStreamSafely(DoubleStream::sorted);
}
@Override
public DoubleVersion distinct()
{
return this.continueStreamSafely(DoubleStream::distinct);
}
@Override
public DoubleVersion flatMap(final DoubleFunction<? extends DoubleStream> doubleFunction)
{
Objects.requireNonNull(doubleFunction); | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
{
Objects.requireNonNull(doubleFunction);
return this.continueStreamSafely(doubleStream -> doubleStream.flatMap(doubleFunction));
}
@Override
public LongVersion mapToLong(final DoubleToLongFunction doubleToLongFunction)
{
Objects.requireNonNull(doubleToLongFunction);
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToLong(doubleToLongFunction),
LongVersion::new
)
;
}
@Override
public IntVersion mapToInt(final DoubleToIntFunction doubleToIntFunction)
{
Objects.requireNonNull(doubleToIntFunction);
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToInt(doubleToIntFunction),
IntVersion::new
)
;
}
@Override
public <U> StreamLinesOverInternet<U> mapToObj(final DoubleFunction<? extends U> doubleFunction)
{
Objects.requireNonNull(doubleFunction);
return
convertStream
(
this.encapsulatedStream,
stream -> stream.mapToObj(doubleFunction),
StreamLinesOverInternet<U>::new
)
;
}
@Override
public DoubleVersion map(final DoubleUnaryOperator doubleUnaryOperator)
{
Objects.requireNonNull(doubleUnaryOperator);
return this.continueStreamSafely(doubleStream -> doubleStream.map(doubleUnaryOperator));
}
@Override
public DoubleVersion filter(final DoublePredicate doublePredicate)
{
Objects.requireNonNull(doublePredicate); | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
{
Objects.requireNonNull(doublePredicate);
return this.continueStreamSafely(doubleStream -> doubleStream.filter(doublePredicate));
}
@Override
public void close()
{
this.terminateSafely(DoubleStream::close);
System.out.println(this);
}
@Override
public DoubleVersion onClose(final Runnable runnable)
{
Objects.requireNonNull(runnable);
return this.continueStreamSafely(doubleStream -> doubleStream.onClose(runnable));
}
@Override
public DoubleVersion unordered()
{
return this.continueStreamSafely(DoubleStream::unordered);
}
@Override
public boolean isParallel()
{
return this.terminateWithValueSafely(DoubleStream::isParallel);
}
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
}
```
Answer: try-with-resources and exception handling are features, not bugs. The vastly less complicated approach is to use Java as Java was intended - write an AutoCloseable utility class. For a very typical example of a situation where the JDK itself operates this way, see DirectoryStream. This is how Java is designed to work. Attempting otherwise is going to be some mix of non-constructive, difficult, non-idiomatic, or "the bad kind of surprise".
I am opening a connection to the internet just to check if my stream is parallel. I don't know how terrible that is
Very.
TWR keeps getting forgotten.
If someone keeps forgetting to hold the steering wheel, the solution is not to remove the steering wheel and build a more complicated, less accessible steering wheel behind the dashboard. Your entry-level developers should be learning how to write idiomatic Java, rather than learning (or - as the case may be - not learning) a custom framework that attempts to be too clever. There are standard tools, some mentioned in the comments, that flag when resources are mismanaged. Learn to use these tools.
To quote a separate commenter,
I would like to consume a stream shared between threads. The stream should autodetect when it is not used any more | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
It's only safe to close the stream once we can guarantee that all threads are done (i.e. after a join). This can still use AutoCloseable. And what does it even mean to auto-detect when a stream isn't used any more? When it hits EOF? No: because then we break the case where a user wants to perform special logic on EOF, or seek away from EOF. How about when it "goes out of scope"? Other than TWR, this is not possible, since (unlike, say, C++) Java scope is not directly coupled to memory management. The clearest and least-surprising mechanism to declare that we're done with a stream is not automatic, but explicit.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.stream.Stream;
public class Main {
public static class HTTPLineStream implements AutoCloseable {
public final URI uri;
private final BufferedReader reader;
public HTTPLineStream(URI uri) throws IOException {
this.uri = uri;
reader = new BufferedReader(
new InputStreamReader(
uri.toURL().openStream()
)
);
}
public HTTPLineStream(String uri) throws URISyntaxException, IOException {
this(new URI(uri));
}
public Stream<String> lines() {
return reader.lines();
}
@Override
public void close() throws IOException {
// also closes the inner stream
reader.close();
}
} | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, stream, lazy
public static void main(String[] args) {
try (HTTPLineStream stream = new HTTPLineStream(
"https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv"
)) {
stream.lines()
.limit(10)
.forEach(System.out::println);
}
catch (IOException e) {
e.printStackTrace();
}
catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
date,cases,deaths
2020-01-21,1,0
2020-01-22,1,0
2020-01-23,1,0
2020-01-24,2,0
2020-01-25,3,0
2020-01-26,5,0
2020-01-27,5,0
2020-01-28,5,0
2020-01-29,5,0 | {
"domain": "codereview.stackexchange",
"id": 45553,
"lm_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, lazy",
"url": null
} |
java, performance, algorithm, programming-challenge, time-limit-exceeded
Title: Leetcode: Steps to Make Array Non-decreasing
Question: I was trying out leetcode's Steps to Make Array Non-decreasing
As per the challenge's description:
You are given a 0-indexed integer array nums. In one step, remove all
elements nums[i] where nums[i - 1] > nums[i] for all 0 < i <
nums.length.
Return the number of steps performed until nums becomes a
non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11] Output: 3 Explanation: The
following are the steps performed:
Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
Step 3: [5,4,7,11,11] becomes [5,7,11,11] [5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Constraints:
1 <= nums.length <= 1e5
1 <= nums[i] <= 1e9
Even though it doesn't mention any Big O constraint with regards to memory overheads, I am trying to build a solution that runs in O(n) time complexity along with O(1) memory overhead.
So far here is my solution in Java:
class Solution {
private static void swap(int[] arr, int i, int ni) {
int temp = arr[i];
arr[i] = arr[ni];
arr[ni] = temp;
}
public int totalSteps(int[] nums) {
// Taking care of constraints given in challenge
if (nums.length == 0
|| nums.length == 1
|| nums.length > Math.pow(10, 5)) {
return 0;
}
// if array of size 2, O(1) check steps
if (nums.length == 2)
return nums[0] > nums[1] ? 1 : 0;
// how many items removed in one full loop cycle
int totalRemovedInACompleteLoop = 0;
int steps = 0;
for (int i = nums.length; i >= 1; i--) {
// PS: this one is a temporary fix, refactor code for better approach
// resolve resetting i at end
// to re run a loop without going out of bound index
if (i == nums.length)
i -= 1;
// -- temporary - to refactor--//
// skip if already removed
if (nums[i] == -1)
continue; | {
"domain": "codereview.stackexchange",
"id": 45554,
"lm_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, performance, algorithm, programming-challenge, time-limit-exceeded",
"url": null
} |
java, performance, algorithm, programming-challenge, time-limit-exceeded
// skip if already removed
if (nums[i] == -1)
continue;
if (nums[i - 1] == -1) {
// swap by moving removed (-1) nb to right
swap(nums, i, i - 1);
continue;
}
if (nums[i - 1] > nums[i]) {
nums[i] = -1;// mark as removed
++totalRemovedInACompleteLoop;// increment counter
}
// Done or need to reloop?
if (i == 1 && totalRemovedInACompleteLoop > 0) {
i = nums.length;
++steps;
totalRemovedInACompleteLoop = 0;
}
}
return steps;
}
}
My solution so far passes 83/87 tests, until It reaches a test where the nums array's size is \$10^5\$. When the array is of that size I get "Time Limit Exceeded". (PS: I had similar issues while trying leetcode's First missing Positive)
Note:
This code while it works, will be refactored later on once i know which approach to follow for O(n) speed.
I am aware that so far this solution's time complexity is \$O(n^2)+\$ and not \$O(n)\$
When an item is removed it gets marked as "-1", I am modifying inputs of array in place.
I could have used some DS to help (like stack, list etc..) and write another solution ( I saw several solutions posted there do that). But I want to make it work with O(1) memory overhead.
My question is: Can the approach I am following so far be done in O(n) time if ones insists on going with O(1) memory overhead? if yes, what algorithms should I read about and follow through to modify my code, and/or what are your suggestions? (The point here is that I am trying to expand my knowledge in areas where it lacks)
Example and output of this code so far:
int[] nums = new int[]{5, 3, 4, 4, 7, 3, 6, 11, 8, 5, 11}; //expected 3
Step 1: ie when for loop cycle finishes and before relooping
--> array [5, -1, 4, 4, 7, -1, 6, 11, -1, -1, 11]
// ie [5,4,4,7,6,11,11] | {
"domain": "codereview.stackexchange",
"id": 45554,
"lm_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, performance, algorithm, programming-challenge, time-limit-exceeded",
"url": null
} |
java, performance, algorithm, programming-challenge, time-limit-exceeded
Step 2: ie when for loop cycle finishes and before relooping
--> array [5, -1, -1, 4, 7, -1, -1, 11, 11, -1, -1]
//ie [5,4,7,11,11]
Step 3: ie when for loop cycle finishes and before relooping
--> array [5, -1, -1, -1, 7, 11, -1, -1, 11, -1, -1]
// ie [5,7,11,11]
> Final array [5, 7, -1, -1, -1, 11, 11, -1, -1, -1, -1]
> Done in 3 Steps.
Answer: Update
After several trials and coming up with multiple approaches, this exercise is not solvable in O(1) memory space/ with O(n) time complexity - to the best of my knowledge and trials past couple of days.
A better and more adequate solution is to use an extra DS like monotonic stack.
Otherwise you can check a top solution on leetcode.
Original Answer
I have found a potential O(1) memory overhead solution,but haven't finished coding it. I will post it in pseudo code/ Graphical (@Moderators: if this is not where I should post it but better edit my original question and add it as an update, please advise). I am drained a bit from this assignment for the moment.
PS: will not mark it as accepted, since no code yet provided. If anyone codes it before I do, will accept your answer. | {
"domain": "codereview.stackexchange",
"id": 45554,
"lm_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, performance, algorithm, programming-challenge, time-limit-exceeded",
"url": null
} |
beginner, rust, unit-conversion
Title: Yet another Fahrenheit and Celsius converter
Question: Introduction
I am recently learning Rust by reading The Rust Programming Language (a.k.a. the book). I have finished the first three chapters so far, and this is my attempt for the first exercise listed at the end of Chapter 3, which has a simple description:
Convert temperatures between Fahrenheit and Celsius.
My program repetitively prompts the user to input for a command (one of
\${^{\circ}\text{F}} \to {^{\circ}\text{C}}\$,
\${^{\circ}\text{C}} \to {^{\circ}\text{F}}\$, and quit), and asks for temperature values to be converted as floating-point values. If the user input cannot be properly interpreted, the program sends an error message and resumes executing if possible.
I have run rustfmt and clippy on my program. rustfmt taught me something new (removing , after {} in a match expression), and clippy did not report any problems. I have also tested the program with different inputs, and so far it seems to work properly.
Before moving on, I would like to know whether I am in the right direction. Feel free to point out edge cases I neglected, failures to conform to received Rust guidelines, or other things that I did wrong, so I can correct these mistakes as soon as possible and learn productively in the future.
Code
src/main.rs
use std::io;
fn main() {
println!("This is a program that converts temperatures between Fahrenheit and Celsius.");
loop {
println!("\nEnter one of the following commands:");
println!(" - 0: convert from Fahrenheit to Celsius");
println!(" - 1: convert from Celsius to Fahrenheit");
println!(" - 2: quit");
let mut command = String::new();
match io::stdin().read_line(&mut command) {
Ok(_) => {}
Err(_) => {
println!("Failed to read command.");
continue;
}
} | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
beginner, rust, unit-conversion
let command: u32 = match command.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid command.");
continue;
}
};
match command {
0 => fahrenheit_to_celsius(),
1 => celsius_to_fahrenheit(),
2 => break,
_ => println!("Invalid command."),
}
}
}
fn fahrenheit_to_celsius() {
println!("Enter the temperature in Fahrenheit.");
let mut temperature = String::new();
match io::stdin().read_line(&mut temperature) {
Ok(_) => {}
Err(_) => {
println!("Failed to read temperature.");
return;
}
}
let temperature: f64 = match temperature.trim().parse() {
Ok(t) => t,
Err(_) => {
println!("Invalid temperature.");
return;
}
};
let converted = (temperature - 32.0) / 1.8;
println!("{} Fahrenheit = {} Celsius", temperature, converted);
}
fn celsius_to_fahrenheit() {
println!("Enter the temperature in Celsius.");
let mut temperature = String::new();
match io::stdin().read_line(&mut temperature) {
Ok(_) => {}
Err(_) => {
println!("Failed to read temperature.");
return;
}
}
let temperature: f64 = match temperature.trim().parse() {
Ok(t) => t,
Err(_) => {
println!("Invalid temperature.");
return;
}
};
let converted = temperature * 1.8 + 32.0;
println!("{} Celsius = {} Fahrenheit", temperature, converted);
}
Cargo.toml
[package]
name = "temperature"
version = "0.1.0"
authors = ["L. F."]
edition = "2018"
[dependencies]
Example session
Here's an example cargo run session:
This is a program that converts temperatures between Fahrenheit and Celsius. | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
beginner, rust, unit-conversion
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
0
Enter the temperature in Fahrenheit.
200
200 Fahrenheit = 93.33333333333333 Celsius
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
0
Enter the temperature in Fahrenheit.
123.4
123.4 Fahrenheit = 50.77777777777778 Celsius
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
0
Enter the temperature in Fahrenheit.
cat
Invalid temperature.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
1
Enter the temperature in Celsius.
1.98e5
198000 Celsius = 356432 Fahrenheit
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
1
Enter the temperature in Celsius.
unicorn
Invalid temperature.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
3
Invalid command.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
dog
Invalid command.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
2
Answer: Unnecessary match
When reading from stdin, you check if there's an error with match:
match io::stdin().read_line(&mut temperature) {
Ok(_) => {}
Err(_) => {
println!("Failed to read temperature.");
return;
}
}
But you don't care about the value of the error, so you can use a simple if:
if io::stdin().read_line(&mut temperature).is_err() {
println!("Failed to read temperature.");
return;
} | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
beginner, rust, unit-conversion
Code duplication
You have a lot of duplicated code between the celsius_to_fahrenheit and fahrenheit_to_celsius functions for reading a String input and converting it to a f64. Let's combine them into one function that takes command as an argument:
fn convert_temperature(command: u32) {
if command == 0 {
println!("Enter the temperature in Fahrenheit.");
}
else {
println!("Enter the temperature in Celsius.");
}
let mut temperature = String::new();
if io::stdin().read_line(&mut temperature).is_err() {
println!("Failed to read temperature.");
return;
}
let temperature: f64 = match temperature.trim().parse() {
Ok(t) => t,
Err(_) => {
println!("Invalid temperature.");
return;
}
};
if command == 0 {
let converted = (temperature - 32.0) / 1.8;
println!("{} Fahrenheit = {} Celsius", temperature, converted);
}
else {
let converted = temperature * 1.8 + 32.0;
println!("{} Celsius = {} Fahrenheit", temperature, converted);
}
}
Then the match in main would be:
match command {
0 | 1 => convert_temperature(command),
2 => break,
_ => println!("Invalid command."),
}
eprintln! for errors
For your error messages, use eprintln! instead of println! to print to stderr instead of stdout.
if let instead of match
This may be personal preference, but I think that an if let is easier to read than a match here:
let command: u32 = match command.trim().parse() {
Ok(num) => num,
Err(_) => {
eprintln!("Invalid command.");
continue;
}
};
would become
let command: u32 = if let Ok(num) = command.trim().parse() {
num
} else {
eprintln!("Invalid command.");
continue;
}; | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
beginner, rust, unit-conversion
Same for the parsing of the temperature.
Inline variables in formatted strings
This makes it easier to read:
println!("{} Fahrenheit = {} Celsius", temperature, converted);
can be just:
println!("{temperature} Fahrenheit = {converted} Celsius");
Putting it together so far
use std::io;
fn main() {
println!("This is a program that converts temperatures between Fahrenheit and Celsius.");
loop {
println!("\nEnter one of the following commands:");
println!(" - 0: convert from Fahrenheit to Celsius");
println!(" - 1: convert from Celsius to Fahrenheit");
println!(" - 2: quit");
let mut command = String::new();
if io::stdin().read_line(&mut command).is_err() {
eprintln!("Failed to read command.");
continue;
}
let command: u32 = if let Ok(num) = command.trim().parse() {
num
} else {
eprintln!("Invalid command.");
continue;
};
match command {
0 | 1 => convert_temperature(command),
2 => break,
_ => eprintln!("Invalid command."),
}
}
}
fn convert_temperature(command: u32) {
if command == 0 {
println!("Enter the temperature in Fahrenheit.");
} else {
println!("Enter the temperature in Celsius.");
}
let mut temperature = String::new();
if io::stdin().read_line(&mut temperature).is_err() {
eprintln!("Failed to read temperature.");
return;
}
let temperature: f64 = if let Ok(num) = temperature.trim().parse() {
num
} else {
eprintln!("Invalid temperature.");
return;
};
if command == 0 {
let converted = (temperature - 32.0) / 1.8;
println!("{temperature} Fahrenheit = {converted} Celsius");
} else {
let converted = temperature * 1.8 + 32.0;
println!("{temperature} Celsius = {converted} Fahrenheit");
}
} | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
beginner, rust, unit-conversion
Reusability
Right now, this code is coupled tightly with the input and output system. However, with some changes, it will become more modular and flexible so that other code can reuse its logic.
First, let's add an enum for the two temperatures:
enum Temperature {
Celsius(f64),
Fahrenheit(f64),
}
And a method for converting between the two variants:
impl Temperature {
fn convert(&self) -> Self {
match self {
Self::Celsius(t) => Self::Fahrenheit(t * 1.8 + 32.0),
Self::Fahrenheit(t) => Self::Celsius((t - 32.0) / 1.8),
}
}
}
Further, let's add an implementation of fmt::Display to allow printing a temperature:
use std::fmt;
impl fmt::Display for Temperature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Celsius(t) => format!("{t} Celsius"),
Self::Fahrenheit(t) => format!("{t} Fahrenheit"),
}
)
}
}
Finally, this can be used in convert_temperature by replacing the last if with:
let original = if command == 0 {
Temperature::Fahrenheit(temperature)
} else {
Temperature::Celsius(temperature)
};
let converted = original.convert();
println!("{original} = {converted}");
Final code:
use std::{fmt, io};
enum Temperature {
Celsius(f64),
Fahrenheit(f64),
}
impl Temperature {
fn convert(&self) -> Self {
match self {
Self::Celsius(t) => Self::Fahrenheit(t * 1.8 + 32.0),
Self::Fahrenheit(t) => Self::Celsius((t - 32.0) / 1.8),
}
}
}
impl fmt::Display for Temperature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Celsius(t) => format!("{t} Celsius"),
Self::Fahrenheit(t) => format!("{t} Fahrenheit"),
}
)
}
} | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
beginner, rust, unit-conversion
fn main() {
println!("This is a program that converts temperatures between Fahrenheit and Celsius.");
loop {
println!("\nEnter one of the following commands:");
println!(" - 0: convert from Fahrenheit to Celsius");
println!(" - 1: convert from Celsius to Fahrenheit");
println!(" - 2: quit");
let mut command = String::new();
if io::stdin().read_line(&mut command).is_err() {
eprintln!("Failed to read command.");
continue;
}
let command: u32 = if let Ok(num) = command.trim().parse() {
num
} else {
eprintln!("Invalid command.");
continue;
};
match command {
0 | 1 => convert_temperature(command),
2 => break,
_ => eprintln!("Invalid command."),
}
}
}
fn convert_temperature(command: u32) {
if command == 0 {
println!("Enter the temperature in Fahrenheit.");
} else {
println!("Enter the temperature in Celsius.");
}
let mut temperature = String::new();
if io::stdin().read_line(&mut temperature).is_err() {
eprintln!("Failed to read temperature.");
return;
}
let temperature: f64 = if let Ok(num) = temperature.trim().parse() {
num
} else {
eprintln!("Invalid temperature.");
return;
};
let original = if command == 0 {
Temperature::Fahrenheit(temperature)
} else {
Temperature::Celsius(temperature)
};
let converted = original.convert();
println!("{original} = {converted}");
} | {
"domain": "codereview.stackexchange",
"id": 45555,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, unit-conversion",
"url": null
} |
c#, performance
Title: Autocorrelation of a vector series
Question: Related: Autocorrelation of a vector series (2)
The given C# source code computed autocorrelation of a vector series.
The listing gives accurate results, but is horribly slow.
How can I optimize it to make it fast?
public class TimeSeriesAnalysisForVectors
{
private static double C(int t, List<Vec3> vectors)
{
int n = vectors.Count;
if (t >= n || t < 0)
throw new ArgumentException("Invalid value for t. It must be between 0 and n-1.");
double sum = 0;
for (int i = 0; i < n - t; i++)
{
sum += vectors[i].Dot(vectors[i + t]);
}
return sum / (n - t);
}
public static (List<double> taus, List<double> autocorrs)
GetAutoCorrelationPoints(List<Vec3> vectors, int maxLag)
{
var tValues = new List<double>();
var cResults = new List<double>();
double c0 = C(0, vectors); // This is the normalization factor
Console.WriteLine($"Normalization factor: {c0}");
for (int lag = 0; lag <= maxLag; lag++) // Start from 0 to include the autocorrelation at lag 0
{
try
{
double cValue = C(lag, vectors);
Console.WriteLine($"Lag={lag}, Raw Autocorr={cValue}, Normalized Autocorr={cValue / c0}");
tValues.Add(lag);
cResults.Add(cValue / c0); // Normalization is done here
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
break;
}
}
return (tValues, cResults);
}
}
Answer:
C is not the greatest name. It does not tell what the function does, and it is too short, easy to miss. It took me a while to find where it is used.
The first argument is better to be lag, not t.
c0 is better to be normFactor. Then you may safely drop the comment. | {
"domain": "codereview.stackexchange",
"id": 45556,
"lm_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",
"url": null
} |
c#, performance
Throwing ArgumentException doesn't feel right. C is a private method, and you are in full control of how it is called. This exception may never happen, and checking a validity of t is a waste of cycles.
cValue is never used. It is OK to drop it.
Regarding performance. It is not possible to optimize this code. It has a quadratic time complexity, and will be slow no matter how you modify it. You need a better algorithm. Specifically, using FFT would reduce time complexity to \$O(n\log n)\$ | {
"domain": "codereview.stackexchange",
"id": 45556,
"lm_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",
"url": null
} |
python, beginner, graphics, turtle-graphics, raytracing
Title: Basic Ray Tracer
Question: This is my first self-guided programming project, and all the math used in the program is self-taught. I wanted to get a better understanding of how computer graphics worked, but I just feel more confused. Please tell me what I could do better in my next attempt programming something like this and how to learn more. Note: if you are running this code, it's not broken but takes about 40 seconds for the image to be drawn.
import math
import turtle
window = turtle.Screen()
window.title("My Window")
window.bgcolor(0.65, 0.65, 0.65)
window.tracer(0)
window.setup(width=1200, height=500)
turtle = turtle.Turtle()
turtle.hideturtle()
turtle.speed(0)
turtle.pencolor(1, 0, 0)
turtle.pensize(0.001)
light = [60, 60, -50]
sphere = [0, 0, 101]
floorLevel = 100
radius = 100
camera = [0, 0, -100]
pixel = [20, 20, 0]
def checkIntersections_sphere(camera, pixel, sphere, radius):
global point_of_contact
point_of_contact = []
a = (
(pixel[0] - camera[0]) ** 2
+ (pixel[1] - camera[1]) ** 2
+ (pixel[2] - camera[2]) ** 2
)
b = (-1 * 2) * (
(pixel[0] - camera[0]) * (sphere[0] - camera[0])
+ (pixel[1] - camera[1]) * (sphere[1] - camera[1])
+ (sphere[2] - camera[2]) * (pixel[2] - camera[2])
)
c = (
(sphere[0] - camera[0]) ** 2
+ (sphere[1] - camera[1]) ** 2
+ (sphere[2] - camera[2]) ** 2
- radius**2
)
d = b**2 - 4 * a * c | {
"domain": "codereview.stackexchange",
"id": 45557,
"lm_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, beginner, graphics, turtle-graphics, raytracing",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.