text stringlengths 1 2.12k | source dict |
|---|---|
java, beginner, object-oriented, game, 2048
isOver()
It seems that the current implementation does not allow to win :-( Even if a user reaches 2048 the game continues until there are no legal moves and then the user will get "Game over!". I feel cheated ;-)
for loop iterates over directions array using BOARD_SIZE as the limit, which coincidently happens to be both 4. If you wanted to try to play the game on a bigger board it would crash. Use directions.length instead or even better for (var direction: directions). | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, beginner, object-oriented, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
printBoard()
For simple text formatting use String.format(...) or System.out.printf(...): no need to count spaces manually ;-)
setDirection(userMove) and paramless isLegal() & move()
This is really ugly and misleading. I started reading main code first and it really made me scratch my head for few minutes wondering how isLegal() and move() work without providing any actual move data :? Only after a while I noticed that it so happens that setDirection(userMove) is always called upfront sets a "temporary state" for them... setDirection(userMove) should not exist (or at least not be accessible) and both isLegal() and move() should have a userMove param.
As a first fix, setDirection(userMove) may be made private and called at the beginning of isLegal(userMove) and move(userMove). It's still ugly though, as it uses a "temporary" instance state instead of local vars. To fix this, you can introduce a simple static inner class called for example DirectionConfig with these 6 fields (rowStart, columnStart, rowStep, columnStep, nextRow, nextColumn) and change setDirection(userMove) to return a new instance of this class, that move(userMove) and isLegal(userMove) would use instead of Game's instance fields (in such case you can also rename setDirection(userMove) to getDirectionConfig(userMove)).
rowStart, columnStart, rowStep, columnStep, nextRow, nextColumn usage in move() and isLegal()
These are SIX input parameters for a pretty complex board matrix processing using TWO additional vars (changed and Cell.hasMarged), but OTOH there's ZERO javadoc, comment or any other explanation... I would prefer to carry concrete bricks at some construction yard for half a day, than to be forced to understand this code with this level of documentation ;-)
Cell class | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, beginner, object-oriented, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
it is just a tiny helper that will never be used outside of Game, so it should rather be an inner class (static).
it serves both as a holder of the board state and as a holder of a temporary flag hasMerged used in Game.move(). Combining these 2 purposes is really ugly and confusing. At the very least, the meaning of this flag should be documented.
Game2048 class
Currently in only has main method that could simply be moved to Game | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, beginner, object-oriented, game, 2048",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
Title: Evaluate a prefix expression
Question: The algorithm involves using two stacks.
One stack (call it token_stack) holds the operators (like +, - etc) and operands (like 3,4 etc) and the other stack (call it count_stack) holds the number of operands left to be seen (say 2 for binary operators).
Anytime an operator is seen, it is pushed onto the token_stack and the number of operands left to be seen for it is pushed onto the count_stack.
Anytime an operand (like 3,5 etc) is seen, the top element of the count_stack is decremented.
If the number of operands left to be seen becomes zero, the top element is popped off from the count_stack. Then from the token_stack, the number of operands required and the operator is popped off. The operation is then performed to get a new value (or operand).
Now the new operand is pushed back onto the token_stack. This new operand push causes you to take another look at the top of the count_stack and the same process is repeated (decrement the operands seen, compare with zero etc).
If the operand count does not become zero, you continue with the next token in the input.
For example, say you had to evaluate "- 10 + 7 * 2 3", the stacks will look like (left is the top of the stack):
count_stack token_stack Input
2 - 10 + 7 * 2 3
1 10 - + 7 * 2 3
2 1 + 10 - 7 * 2 3
1 1 7 + 10 - * 2 3
2 1 1 * 7 + 10 - 2 3
1 1 1 2 * 7 + 10 - 3
0 1 1 3 2 * 7 + 10 -
Since it has become zero, you pop off two operands, the operator * and evaluate
and push back 6. You pop 0 from the count_stack.
1 1 6 7 + 10 -
Pushing back you decrement the current count_stack top.
0 1 6 7 + 10 -
Since it has become zero, you pop off two operands, the operator + and evaluate
and push back 13.
1 13 10 -
Pushing back you decrement the current count_stack top. | {
"domain": "codereview.stackexchange",
"id": 45519,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
1 13 10 -
Pushing back you decrement the current count_stack top.
0 13 10 -
Since it has become zero, you pop off two operands, the operator - and evaluate
and push back -3.
Since count_stack is now empty and token_stack contain the final result, return it.
Code:
#!/usr/bin/env python3
import operator
from typing import Iterable, Union
OPCODES = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"//": operator.floordiv,
"%": operator.mod,
"^": operator.pow,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
"==": operator.eq,
"!=": operator.ne,
}
def _eval_op(lhs: float, rhs: float, opcode: str) -> float:
return OPCODES[opcode](lhs, rhs)
def _eval_expr(tokens: Iterable[Union[float, str]]) -> float:
token_stack = []
count_stack = []
for token in tokens:
if isinstance(token, (int, float)):
# If the first token is an operand and there are more tokens
# following it.
if not token_stack and len(list(tokens)) > 1:
raise ValueError("Invalid expression.")
token_stack.append(token)
if count_stack:
count_stack[-1] -= 1
else:
if token in OPCODES:
count_stack.append(2) # Two operands left to be seen for the binary op.
else:
raise ValueError("Invalid operator seen.")
token_stack.append(token) | {
"domain": "codereview.stackexchange",
"id": 45519,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
while count_stack and count_stack[-1] == 0:
count_stack.pop()
try:
rhs = token_stack.pop()
lhs = token_stack.pop()
op = token_stack.pop()
token_stack.append(_eval_op(lhs, rhs, op))
except (ValueError, IndexError):
raise ValueError("Invalid expression.")
except ZeroDivisionError:
raise ValueError("Can not divide by zero.")
if count_stack:
count_stack[-1] -= 1
if len(token_stack) != 1 or count_stack:
raise ValueError("Invalid expression.")
if token_stack:
return token_stack.pop()
return 0
def _tokenize_expr(expr: str) -> Iterable[Union[str, float]]:
for token in expr.split():
if token in OPCODES:
yield token
else:
try:
yield int(token)
except ValueError:
try:
yield float(token)
except ValueError:
raise ValueError("Invalid symbol found.")
def eval_prefix_expr(expr: str):
"""
Evaluate a prefix expression.
Supported operators:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Floor Division (//)
- Modulo (%)
- Equality - equal to (==)
- Difference - not equal to (!=)
- Ordering:
1) less than (<)
2) less than or equal to (<=)
3) greater than (>)
4) greater than or equal to (>=)
"""
tokens = _tokenize_expr(expr)
return _eval_expr(tokens) | {
"domain": "codereview.stackexchange",
"id": 45519,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
def main() -> None:
test_data = [
("34", 34),
("+", None),
(" + 1 2 3", None),
("+ 3 4", 7),
("+ -3 4", 1),
("+ ^ 5 4 + 3 4", 632),
("+ 10a 29", None),
("/ * 10 5 + 6 2", 6.25),
("- 10 + 7 * 2 3", -3),
("icaoscasjcs", None),
("1038 - // * 10 5 + 7 3 2", None),
("", 0),
("$ 9 2", None),
("+ 3e-08 2.1", 2.10000003),
("+ < 1 9 9", 10),
("== 1 1", 1),
]
for expr, res in test_data:
expr_repr = repr(expr)
print(f"expr: {expr_repr}", end="")
try:
rv = eval_prefix_expr(expr)
assert rv == res, f"Expected: {res}, Received: {rv}"
except Exception as e:
rv = e
print(f", result: {repr(rv)}")
if __name__ == "__main__":
main()
prints:
expr: '34', result: 34
expr: '+', result: ValueError('Invalid expression.')
expr: ' + 1 2 3', result: ValueError('Invalid expression.')
expr: '+ 3 4', result: 7
expr: '+ -3 4', result: 1
expr: '+ ^ 5 4 + 3 4', result: 632
expr: '+ 10a 29', result: ValueError('Invalid symbol found.')
expr: '/ * 10 5 + 6 2', result: 6.25
expr: '- 10 + 7 * 2 3', result: -3
expr: 'icaoscasjcs', result: ValueError('Invalid symbol found.')
expr: '1038 - // * 10 5 + 7 3 2', result: ValueError('Invalid expression.')
expr: '', result: ValueError('Invalid expression.')
expr: '$ 9 2', result: ValueError('Invalid symbol found.')
expr: '+ 3e-08 2.1', result: 2.10000003
expr: '+ < 1 9 9', result: 10
expr: '== 1 1', result: True
Why did I not reverse the list of tokens and swap the operands for each operator and evaluate it like a postfix expression, which would have been way simpler? I already did that here.
Review Request:
Are there simpler ways to solve the problem?
General coding comments, style, idiomatic code, et cetera.
Answer: Helpful errors
You raise a couple of errors like
raise ValueError("Invalid expression.") | {
"domain": "codereview.stackexchange",
"id": 45519,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
Answer: Helpful errors
You raise a couple of errors like
raise ValueError("Invalid expression.")
If I were to use your code and it gives me this error, I might be helpful if you gave me more information on what exactly is wrong here. For example raise ValueError("Invalid symbol found."): which symbol exactly?
Reduce complexity
You could reduce the complexity of your _eval_expr method by introducing a _eval_token method and using this as loop body for the for token in tokens loop.
try_parse utility function
try:
yield int(token)
except ValueError:
try:
yield float(token)
except ValueError:
raise ValueError("Invalid symbol found.")
What about introducing a utility function try_parse (warning: untested):
T = TypeVar("T")
U = TypeVar("U")
def try_parse(value: T, *parse_functions: Callable[[T], U]) -> U:
for parse_function in parse_functions:
try:
return parse_function(value)
except ValueError:
pass
raise ValueError(f"Cannot parse {value} with any of {parse_functions}")
This takes a level of indentation (complexity) out of your _tokenize_expr method. | {
"domain": "codereview.stackexchange",
"id": 45519,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
Title: Logging in a different thread using circular buffer C++
Question: What it does
The code creates a logger class which instantiates a circular buffer at construction and uses producer-consumer style approach using condition_variable to log and print the messages to stdout.
Code
logger.h
#pragma once
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
#include <sstream>
#include <stdio.h>
#include <string>
#include <sys/time.h>
#include <thread>
#include <utility>
#include <vector>
namespace TIME
{
void get_time(char*);
} // namespace TIME
class my_logger
{
static constexpr size_t TIME_BUF_SIZE = 19;
static constexpr size_t MESSAGE_BUFFER_SIZE = 300;
static constexpr size_t BUFFER_SIZE = 500;
static constexpr size_t MESSAGE_PRINT_THRESHOLD = 450;
static_assert(MESSAGE_PRINT_THRESHOLD < BUFFER_SIZE,
"Message print threshold must be smaller than msg buffer size");
std::vector<std::array<char, MESSAGE_BUFFER_SIZE>> m_to_print;
size_t m_head;
size_t m_tail;
std::mutex mu_buffer;
std::condition_variable m_consumer_cond_var;
std::condition_variable m_producer_cond_var;
std::atomic<bool> m_continue_logging;
std::thread m_printing_thread;
public:
my_logger();
~my_logger();
void logging_thread();
size_t msg_count() const
{
if(m_tail >= m_head)
return m_tail - m_head;
return m_tail + BUFFER_SIZE - m_head;
} | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
template <typename... Args>
void log(const char* format, const char msg_type[], Args... args)
{
std::unique_lock lg(mu_buffer);
// m_producer_cond_var.wait(lg, [this] { return msg_count() <= MESSAGE_PRINT_THRESHOLD; });
auto buf_ptr = m_to_print[m_tail].data();
const size_t N = std::strlen(msg_type);
TIME::get_time(buf_ptr);
std::snprintf(buf_ptr + TIME_BUF_SIZE - 1, N + 1, "%s", msg_type);
std::snprintf(buf_ptr + TIME_BUF_SIZE + N - 1,
MESSAGE_BUFFER_SIZE - N - TIME_BUF_SIZE + 1,
format,
std::forward<Args>(args)...);
m_tail = (m_tail + 1) % BUFFER_SIZE;
if(msg_count() > MESSAGE_PRINT_THRESHOLD)
{
lg.unlock();
m_consumer_cond_var.notify_one(); // notify the single consumer
}
}
template <typename... Args>
void info(const char* format, Args... args)
{
log(format, " [INFO] ", std::forward<Args>(args)...);
}
template <typename... Args>
void warn(const char* format, Args... args)
{
log(format, " [WARN] ", std::forward<Args>(args)...);
}
template <typename... Args>
void error(const char* format, Args... args)
{
log(format, " [ERROR] ", std::forward<Args>(args)...);
}
};
logger.cpp
#include "logger.h"
#include <algorithm>
#include <mutex>
namespace TIME
{
void get_time(char* buf)
{
auto currentTime = std::chrono::high_resolution_clock::now();
auto nanoSeconds = std::chrono::time_point_cast<std::chrono::nanoseconds>(currentTime);
auto nanoSecondsCount = nanoSeconds.time_since_epoch().count();
// Convert nanoseconds to seconds and fractional seconds
auto fracSeconds = nanoSecondsCount % 1'000'000'000;
// Convert seconds to std::time_t
std::time_t time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
// Convert time to struct tm in local time zone
std::tm* tm = std::localtime(&time);
std::strftime(buf, 9, "%H:%M:%S.", std::localtime(&time));
std::snprintf(buf + 9, 10, "%09lld", fracSeconds);
}
} // namespace TIME
my_logger::my_logger()
: m_head(0)
, m_tail(0)
, m_continue_logging(true)
{
m_to_print.assign(BUFFER_SIZE, {});
m_printing_thread = std::thread(&my_logger::logging_thread, this);
}
void my_logger::logging_thread()
{
while(m_continue_logging)
{
std::unique_lock lg(mu_buffer);
m_consumer_cond_var.wait(lg, [this] { return m_head != m_tail; });
while(m_head != m_tail)
{
std::printf("%s\n", m_to_print[m_head].data());
m_head = (m_head + 1) % BUFFER_SIZE;
}
lg.unlock();
m_producer_cond_var.notify_all(); //notify all producers
}
}
my_logger::~my_logger()
{
m_continue_logging = false;
m_consumer_cond_var.notify_one();
if(m_printing_thread.joinable())
m_printing_thread.join();
}
Benchmarking code
#include "logger.h"
#include <chrono>
#include <fstream>
#include <string>
int main(int argc, char* argv[])
{
if(argc != 2)
{
std::cerr << "Usage: logger <file>";
return 1;
}
constexpr unsigned RUNS = 33333;
const std::string benchmark_file_path = argv[1];
std::fstream file(benchmark_file_path, std::ios::out | std::ios::app);
if(!file.is_open())
{
std::cerr << "Couldn't open " << benchmark_file_path << "\n";
return 1;
} | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
auto start = std::chrono::high_resolution_clock::now();
{
my_logger logger;
for(size_t i = 0; i < RUNS; i++)
{
logger.info("this is a %s string with id: %u and double: %f",
"sundar",
i,
static_cast<double>(i + 0.5));
logger.warn("this is a %s string with id: %u and double: %f",
"WARN",
2 * i,
static_cast<double>(2 * i));
logger.error("this is a %s string with id: %u and double: %f",
"ERROR",
4 * i,
static_cast<double>(4 * i));
}
}
auto finish = std::chrono::high_resolution_clock::now();
auto time1 = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();
file << "RUNS: " << 3 * RUNS << " TIME_MULTITHREADED: " << time1 << " ms\n";
start = std::chrono::high_resolution_clock::now();
{
char time_buf[19];
for(size_t i = 0; i < RUNS; i++)
{
TIME::get_time(time_buf);
fprintf(stdout,
"%s"
" [INFO] "
"this is a %s string with id: %zu and double: %f\n",
time_buf,
"atisundar",
i,
static_cast<double>(i + 0.5));
TIME::get_time(time_buf);
fprintf(stdout,
"%s"
" [WARN] "
"this is a %s string with id: %zu and double: %f\n",
time_buf,
"atisundar",
i,
static_cast<double>(2 * i)); | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
TIME::get_time(time_buf);
fprintf(stdout,
"%s"
" [ERROR] "
"this is a %s string with id: %zu and double: %f\n",
time_buf,
"atisundar",
i,
static_cast<double>(4 * i));
}
}
finish = std::chrono::high_resolution_clock::now();
auto time2 = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();
file << "RUNS: " << 3 * RUNS << " TIME_PLAIN_LOGGER: " << time2 << " ms\n";
return 0;
}
Current performance
RUNS: 99999 TIME_MULTITHREADED: 282 ms
RUNS: 99999 TIME_PLAIN_LOGGER: 970 ms
RUNS: 99999 TIME_MULTITHREADED: 203 ms
RUNS: 99999 TIME_PLAIN_LOGGER: 972 ms
RUNS: 99999 TIME_MULTITHREADED: 217 ms
RUNS: 99999 TIME_PLAIN_LOGGER: 970 ms
Known issues
The log function in logger.h isn't thread safe because when multiple threads are trying to log and one of them causes total messages to exceed MESSAGE_PRINT_THRESHOLD, then after the unlock step in log and before notifying the m_consumer_cond_var, one of the other logging threads might take ownership of the mutex and keep writing into the buffer and potentially lead to overwriting the circular buffer. The solution I can see for this is to uncomment the m_producer_cond_var.wait line in log function, but that is causing the code to become slower than plain logger function by almost 1.5x . Can you please suggest what I may be doing wrong here? | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
Answer: Create a separate class for the message queue
Your class my_logger has too many responsibilities and is therefore quite complex. The first thing I would do is to create a separate class for a thread-safe message queue. Your logger class can then use that queue.
msg_count() should not be public
msg_count() should never be called from outside the class. It doesn't take a lock, so it can return incorrect values. Even if it would take a lock, by the time an outside caller would get the result, it might no longer be valid.
log() should do as little as possible
It's clear from your code that you want to optimize the throughput of the log() function. So do as much as possible without holding the lock: you can format the time and build the whole log message first, then take the lock to just push that log message onto the queue.
Even better, don't do that at all inside log(), but defer as much as possible to the logging_thread(): you still have to get the current time in log(), but instead of immediately formatting it, just store the result from now() directly in the queue.
Of course, all this requires some changes to your code, in particular how you store data in the queue.
logging_thread() should not hold the lock for a long time
Consider that you only notify the logging thread when there are at least MESSAGE_PRINT_THRESHOLD messages in the queue. It will then lock the mutex, and print all those messages. During that time, other threads that want to add a log message to the queue are blocked.
Note that you don't need to hold the lock while you are printing, at least if you make sure that the loggers wait if the queue is full.
Log messages can be dropped or printed lated
Since you currently don't block threads from adding log messages if the queue is already full, it can be that messages are being dropped. Is that OK? If not, then do add the wait() call back, and find other ways to improve performance. | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
However, another issue is that you wait for a threshold to start printing log messages. What if you have a situation where there is just one thread, and it only has one very important log message to print? Unfortunately, the printing thread will not be woken up, and you have to wait for the destructor to be called before it will finally wake up.
Also, it can happen that m_continue_logging is set to false when there are still messages in the buffer, and the printing thread could then exit before it as printed all messages. More about that below.
Avoid using C functions
You are using C functions like strftime(), snprintf(), and so on, when there are much better C++ equivalents for them. In particular, you can use std::format_to_n() to format strings to a buffer. It can also directly format time.
I also see you mixing fprintf(stderr, …) and std::cerr << …. Don't mix C's stdio and C++'s iostreams, it's not guaranteed how those will interact.
Avoid std::chrono::high_resolution_clock()
There is no guarantee what kind of time std::chrono::high_resolution_clock() actually returns. It might give you something that follows wall clock time, or it might follow some other timer that doesn't track the actual time. Either use std::chrono::system_clock() if you need wall clock time (so you can compare timestamps with events outside the local computer), or if you really need high resolution timestamps so you can more accurately see in which order things happen on the local computer, use std::chrono::steady_clock().
Don't mix atomics and mutexes
Because m_continue_logging is not guarded by the same mutex as m_head and m_tail, it can happen that something sets m_continue_logging to false between the check in the while-condition and the subsequent m_consumer_cond_var.wait(). Note that any notifications sent before wait() is called are ignored. So this can cause the printing thread to hang indefinitely. | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
c++, multithreading, thread-safety, logging, c++20
Make m_continue_logging a regular bool, and check it in the predicate you pass to wait(). And in the destructor, you still need to take a lock when setting it to false.
No need to check for m_printing_thread.joinable()
Since you always start the thread in the constructor, m_printing_thread will always be joinable when you call the destructor. But even better:
Use std::jthread
Instead of manually joining a std::thread, use std::jthread; it takes care of this automatically.
You only need one condition variable
It is extremely unlikely that the printing thread is waiting for the queue to become non-empty, and any other threads waiting for the queue to become non-full at the same time. So there is no need to have two condition variables. | {
"domain": "codereview.stackexchange",
"id": 45520,
"lm_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++, multithreading, thread-safety, logging, c++20",
"url": null
} |
python, stack, balanced-delimiters
Title: Detecting balanced parentheses
Question: Objective:
Given a string s containing '(', ')', '{', '}', '[', ']' (and other
characters), determine if the input string is valid.
An input string is valid if:
Open brackets are closed by the same type of brackets.
Open brackets are closed in the correct order.
Code:
#!/usr/bin/env python3
from pathlib import Path
import typer
def validate_brackets(s: str, brackets={"[": "]", "{": "}", "(": ")"}) -> bool:
stack = []
opening = brackets.keys()
closing = brackets.values()
for c in s:
if c in opening:
stack.append(c)
if c in closing:
if not stack or c != brackets[stack[-1]]:
return False
stack.pop()
return not stack
def main(file: Path) -> None:
with open(file) as f:
print(validate_brackets(f.read()))
if __name__ == "__main__":
typer.run(main)
Review Request:
General coding comments, style, bad practices, et cetera. | {
"domain": "codereview.stackexchange",
"id": 45521,
"lm_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, stack, balanced-delimiters",
"url": null
} |
python, stack, balanced-delimiters
Review Request:
General coding comments, style, bad practices, et cetera.
Answer: Permit me to add the following to the review posted by toolic:
Use Docstrings
I would add a docstring to function validate_brackets describing its functionality.
Create a set from closing
Update
I have done a little research into the implementation of the dict_keys class an instance of which is created with opening = brackets.keys() and checking c in opening should be more or less equivalent to checking c in brackets, which is to say efficient. So there appears to be no need to create a set from the keys. However, if we want to efficiently check to see whether brackets.values() contains duplicates, then it seems to me we should create a set from these values and verify that its length is the same as the number of keys. This should also speed up the check c in closing. We can check to see if the set of keys and the set of values are disjoint by using opening.isdisjoint(closing) (see the next section concerning validation).
Sample Validation of the brackets Argument
Things you might test for:
The brackets argument is a non-empty dict instance.
brackets.values() contains no duplicate characters. Although this condition is not strictly necessary, it is the norm and we will enforce it.
The opening and closing characters should be disjoint. | {
"domain": "codereview.stackexchange",
"id": 45521,
"lm_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, stack, balanced-delimiters",
"url": null
} |
python, stack, balanced-delimiters
The above validations are more easily performed when the closing characters are a set. This will also speed up the check c in closing. We will place the validation logic in a separate validate_brackets_dict function for greater readability. Since this function might be called repeatedly for the same brackets dictionary instance, we can cache previously-validated dictionaries in a dictionary whose key is a frozenset of the dictionary's items (since dictionaries are not hashable) and whose value is a tuple consisting of the opening and closing characters to be used.
I would also make the default value for the brackets argument to be None for which a default dictionary that requires no validation will be provided.
Putting It All Together
With the above suggested changes, the final source could be:
#!/usr/bin/env python3
from pathlib import Path
import typer
from typing import Union, Dict # For older Python versions
default_brackets = {"[": "]", "{": "}", "(": ")"}
default_opening = default_brackets.keys()
default_closing = set(default_brackets.values())
validated_brackets_dict = {}
def validate_brackets_dict(brackets: Dict) -> tuple:
"""Validate the brackets dictionary and if valid
return a tuple of the opening and closing characters to be
used. Otherwise, an exception is raised."""
if not (isinstance(brackets, dict) and brackets):
raise ValueError('brackets must be a non-empty dict instance')
cache_key = frozenset(brackets.items()) # We cannot cache a dictionary
opening_closing = validated_brackets_dict.get(cache_key, None) | {
"domain": "codereview.stackexchange",
"id": 45521,
"lm_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, stack, balanced-delimiters",
"url": null
} |
python, stack, balanced-delimiters
if opening_closing is None:
# Validating a brackets dictionary that we haven't seen before
opening, closing = brackets.keys(), set(brackets.values())
# Although ensuring non-duplicate closing brackets is not strictly necessary,
# it is certainly the norm. So we can consider the following
# check optional but desirable:
if len(closing) != len(brackets):
raise ValueError('Duplicate closing characters')
# Check for closing characters disjoint from opening
# characters:
if not opening.isdisjoint(closing):
raise ValueError('Opening and closing characters are not disjoint')
# Cache for possible next time:
opening_closing = (opening, closing)
validated_brackets_dict[cache_key] = opening_closing
return opening_closing
def validate_brackets(text: str, brackets: Union[Dict, None]) -> bool:
"""Determine if the input text argument contains balanced
parentheses. The optional brackets arguments is a dictionary
of "parentheses" key/value pairs to be used.
If brackets is None then a default dictionary is used."""
if brackets is None:
brackets = default_brackets
opening, closing = default_opening, default_closing
else:
opening, closing = validate_brackets_dict(brackets)
stack = []
for c in text:
if c in opening:
stack.append(c)
elif c in closing:
if not stack or c != brackets[stack[-1]]:
return False
stack.pop()
return not stack
def main(file: Path) -> None:
with open(file) as f:
text = f.read() | {
"domain": "codereview.stackexchange",
"id": 45521,
"lm_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, stack, balanced-delimiters",
"url": null
} |
python, stack, balanced-delimiters
def main(file: Path) -> None:
with open(file) as f:
text = f.read()
print('text:', repr(text))
print()
# Some test case for validation:
for brackets in (
[],
{},
{'[': ']','(': ']'},
{'[': ']','(': '['},
{'[': 'x'},
None
):
print('brackets:', repr(brackets), end='')
try:
result = validate_brackets(text, brackets)
except Exception as e:
result = e
print(', result:', repr(result))
if __name__ == "__main__":
typer.run(main)
Prints:
text: 'abc[xx]'
brackets: [], result: ValueError('brackets must be a non-empty dict instance')
brackets: {}, result: ValueError('brackets must be a non-empty dict instance')
brackets: {'[': ']', '(': ']'}, result: ValueError('Duplicate closing characters')
brackets: {'[': ']', '(': '['}, result: ValueError('Opening and closing characters are not disjoint')
brackets: {'[': 'x'}, result: False
brackets: None, result: True | {
"domain": "codereview.stackexchange",
"id": 45521,
"lm_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, stack, balanced-delimiters",
"url": null
} |
c, memory-management
Title: Use of double pointers and memory allocation/deallocation
Question: I've made an associative array data structure (more details in the code comments below). What I'm interested in getting a critique on is the usage of double pointers.
Are they necessary here?
Am I allocating and freeing the memory correctly?
assoc_array.h
#ifndef __ASSOC_ARRAY_H__
#define __ASSOC_ARRAY_H__
/*
* A data structure to map characters
* to integer values.
*
* The value always starts at 0, and
* can be incremented from there.
*
* There's a space/speed trade-off based on
* the `size` provided. A character, `c`, will be
* inserted according to `c % size`. When more
* than one character maps to the same "bucket",
* a linear search is used to differentiate between
* those characters.
*
*/
typedef struct AssocArray AssocArray;
/*
* Create an array of N (size) buckets.
*/
AssocArray *aaAlloc(size_t size);
void aaFree(AssocArray *assoc_array);
/*
* Increment or set to 0 for the given character.
* Return -1 if an error occurs.
*/
int aaIncValue(AssocArray *assoc_array, char key);
#endif
assoc_array.c
#include <stdbool.h>
#include <stdlib.h>
#include "assoc_array.h"
typedef struct AssocArrayItem {
char key;
int value;
} AssocArrayItem;
typedef struct AssocArrayBucket {
size_t size;
AssocArrayItem **items;
} AssocArrayBucket;
typedef struct AssocArray {
size_t size;
AssocArrayBucket **buckets;
} AssocArray;
AssocArray *aaAlloc(size_t size) {
AssocArray *aa = malloc(sizeof(AssocArray));
aa->size = size;
aa->buckets = calloc(aa->size, sizeof(AssocArrayBucket *));
for (int i = 0; i < aa->size; i++) {
aa->buckets[i] = malloc(sizeof(AssocArrayBucket));
aa->buckets[i]->size = 0;
aa->buckets[i]->items = NULL;
}
return aa;
}
void aaFree(AssocArray *assoc_array) {
for (int i = 0; i < assoc_array->size; i++) {
size_t bucket_size = assoc_array->buckets[i]->size; | {
"domain": "codereview.stackexchange",
"id": 45522,
"lm_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, memory-management",
"url": null
} |
c, memory-management
for (int j = 0; j < bucket_size; j++) {
if (assoc_array->buckets[i] != NULL &&
assoc_array->buckets[i]->items[j] != NULL) {
free(assoc_array->buckets[i]->items[j]);
}
}
if (assoc_array->buckets[i] != NULL) {
if (assoc_array->buckets[i]->items != NULL) {
free(assoc_array->buckets[i]->items);
}
free(assoc_array->buckets[i]);
}
}
if (assoc_array->buckets != NULL) {
free(assoc_array->buckets);
}
if (assoc_array != NULL) {
free(assoc_array);
}
}
int aaIncValue(AssocArray *assoc_array, char key) {
unsigned int idx = key % assoc_array->size;
AssocArrayBucket *bucket = assoc_array->buckets[idx];
if (bucket == NULL) {
return -1;
}
int incremented_value;
if (bucket->size == 0) {
bucket->size = 1;
bucket->items = calloc(bucket->size, sizeof(AssocArrayItem *));
bucket->items[0] = malloc(sizeof(AssocArrayItem));
bucket->items[0]->key = key;
bucket->items[0]->value = 1;
incremented_value = bucket->items[0]->value;
} else {
bool exists = false;
for (int i = 0; i < bucket->size; i++) {
if (bucket->items[i]->key == key) {
exists = true;
bucket->items[i]->value++;
incremented_value = bucket->items[i]->value;
break;
}
}
if (exists == false) {
bucket->items = realloc(bucket->items, bucket->size + 1);
bucket->items[bucket->size] = malloc(sizeof(AssocArrayItem));
bucket->items[bucket->size]->key = key;
bucket->items[bucket->size]->value = 1;
incremented_value = bucket->items[bucket->size]->value;
bucket->size++;
}
}
return incremented_value;
}
assoc_array_test.c
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include "assoc_array.h"
void printPass() {
if (isatty(STDOUT_FILENO)) {
printf("\e[32mPASS\e[0m\n");
} else {
printf("PASS\n");
}
} | {
"domain": "codereview.stackexchange",
"id": 45522,
"lm_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, memory-management",
"url": null
} |
c, memory-management
void test1() {
printf("[TEST] Characters that end up in the same bucket inc'd correctly\t");
AssocArray *aa = aaAlloc(26);
// 'm' % 26 == 5
// 'S' % 26 == 5
assert(aaIncValue(aa, 'm') == 1);
assert(aaIncValue(aa, 'm') == 2);
assert(aaIncValue(aa, 'S') == 1);
assert(aaIncValue(aa, 'm') == 3);
assert(aaIncValue(aa, 'S') == 2);
aaFree(aa);
printPass();
}
int main() {
printf("\n");
test1();
return 0;
}
Compiled with:
clang -g -Wall assoc_array.c assoc_array_test.c -o assoc_array_test
Answer:
Allocating.
The functions of *alloc family may fail. Always test their return values.
bucket->items = realloc(bucket->items, bucket->size + 1); is plain wrong. It allocates only bucket->size + 1 bytes. You need (bucket->size + 1) * sizeof(AssocArrayItem *) of them.
Freeing.
A test for assoc_array != NULL happens too late. A test for assoc_array->buckets != NULL is also too late. You shall test before use, not after.
Using double pointers is not justified. aaAlloc allocates that many pointers to buckets, and also that many buckets. It is a pure waste of space. Similarly, there is no reason to separately allocate pointers to items, and items themselves.
aaIncValue looks clumsy. There is no need to single out the case of bucket->size == 0. What is important is whether the key is found or not, and bucket->size == 0 guarantees that the key is not found. So, consider
AssocArrayItem * item = aaFindItemInBucket(bucket, key);
if (item == NULL) {
bucket = extend_bucket(bucket);
item = bucket[bucket->size - 1];
item->key = key;
}
item->value += 1;
Also, it looks like a misnomer (should be aaPut or aaInsert).
As a side note, size is not a best name.Consider n_items and n_buckets | {
"domain": "codereview.stackexchange",
"id": 45522,
"lm_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, memory-management",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
Title: recursive_find and recursive_find_if_not Template Functions Implementation in C++
Question: This is a follow-up question for A recursive_find_if Template Function with Unwrap Level Implementation in C++ and recursive_invocable and recursive_project_invocable Concept Implementation in C++. I am trying to implement recursive_find and recursive_find_if_not template functions in this post.
The experimental implementation
recursive_find Template Function
template<std::size_t unwrap_level, class R, class T, class Proj = std::identity>
requires(recursive_invocable<unwrap_level, Proj, R>)
constexpr auto recursive_find(R&& range, T&& target, Proj&& proj = {})
{
if constexpr (unwrap_level)
{
return std::ranges::find_if(range, [&](auto& element) {
return recursive_find<unwrap_level - 1>(element, target, proj);
}) != std::ranges::end(range);
}
else
{
return range == std::invoke(proj, target);
}
}
recursive_find Template Function with Execution Policy
template<std::size_t unwrap_level, class ExecutionPolicy, class R, class T, class Proj = std::identity>
requires(recursive_invocable<unwrap_level, Proj, R>&&
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>)
constexpr auto recursive_find(ExecutionPolicy execution_policy, R&& range, T&& target, Proj&& proj = {})
{
if constexpr (unwrap_level)
{
return std::find_if(execution_policy,
std::ranges::begin(range),
std::ranges::end(range),
[&](auto& element) {
return recursive_find<unwrap_level - 1>(execution_policy, element, target, proj);
}) != std::ranges::end(range);
}
else
{
return range == std::invoke(proj, target);
}
} | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
recursive_find_if_not Template Function
/* 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));
}
}
Full Testing Code
The full testing code:
// recursive_find and recursive_find_if_not Template Functions Implementation in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
//#include <experimental/ranges/algorithm>
#include <experimental/array>
#include <functional>
#include <iostream>
#include <iterator>
#include <ranges>
#include <string>
#include <utility>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
template<typename T>
concept is_summable = requires(T x) { x + x; };
// recursive_unwrap_type_t struct implementation
template<std::size_t, typename, typename...>
struct recursive_unwrap_type { };
template<class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...>
{
using type = std::ranges::range_value_t<Container1<Ts1...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...>
{
using type = typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>
>::type;
};
template<std::size_t unwrap_level, typename T1, typename... Ts>
using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
// recursive_array_invoke_result implementation
template<std::size_t, typename, typename, typename...>
struct recursive_array_invoke_result { };
template< typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_invoke_result<1, F, Container<T, N>>
{
using type = Container<
std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>,
N>;
}; | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>>
{
using type = Container<
typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>
>::type, N>;
};
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type;
// recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035
template<std::size_t, typename>
struct recursive_array_unwrap_type { };
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_unwrap_type<1, Container<T, N>>
{
using type = std::ranges::range_value_t<Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
template<std::size_t unwrap_level, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_unwrap_type<unwrap_level, Container<T, N>>
{
using type = typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>
>::type;
};
template<std::size_t unwrap_level, class Container>
using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type;
// https://codereview.stackexchange.com/a/253039/231235
template<std::size_t dim, class T, template<class...> class Container = std::vector>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, T, Container>(input, times));
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
for (size_t i = 0; i < times; i++)
{
output[i] = n_dim_array_generator<dim - 1, times>(input);
}
return output;
}
}
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
} | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
// recursive_depth function implementation with target type
template<typename T_Base, typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<typename T_Base, std::ranges::input_range Range>
requires (!std::same_as<Range, T_Base>)
constexpr std::size_t recursive_depth()
{
return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1};
}
// is_recursive_invocable template function implementation
template<std::size_t unwrap_level, class F, class... T>
requires(unwrap_level <= recursive_depth<T...>())
static constexpr bool is_recursive_invocable()
{
if constexpr (unwrap_level == 0) {
return std::invocable<F, T...>;
} else {
return is_recursive_invocable<
unwrap_level - 1,
F,
std::ranges::range_value_t<T>...>();
}
}
// recursive_invocable concept
template<std::size_t unwrap_level, class F, class... T>
concept recursive_invocable =
is_recursive_invocable<unwrap_level, F, T...>();
// is_recursive_project_invocable template function implementation
template<std::size_t unwrap_level, class Proj, class F, class... T>
requires(unwrap_level <= recursive_depth<T...>() &&
recursive_invocable<unwrap_level, Proj, T...>)
static constexpr bool is_recursive_project_invocable()
{
if constexpr (unwrap_level == 0) {
return std::invocable<F, std::invoke_result_t<Proj, T...>>;
} else {
return is_recursive_project_invocable<
unwrap_level - 1,
Proj,
F,
std::ranges::range_value_t<T>...>();
}
}
// recursive_project_invocable concept
template<class F, std::size_t unwrap_level, class Proj, class... T>
concept recursive_projected_invocable =
is_recursive_project_invocable<unwrap_level, Proj, F, T...>(); | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
/* recursive_all_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_all_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) {
if constexpr (unwrap_level > 0)
{
return std::ranges::all_of(value, [&](auto&& element) {
return recursive_all_of<unwrap_level - 1>(element, p, proj);
});
}
else
{
return std::invoke(p, std::invoke(proj, value));
}
}
/* recursive_find template function implementation with unwrap level
*/
template<std::size_t unwrap_level, class R, class T, class Proj = std::identity>
requires(recursive_invocable<unwrap_level, Proj, R>)
constexpr auto recursive_find(R&& range, T&& target, Proj&& proj = {})
{
if constexpr (unwrap_level)
{
return std::ranges::find_if(range, [&](auto& element) {
return recursive_find<unwrap_level - 1>(element, target, proj);
}) != std::ranges::end(range);
}
else
{
return range == std::invoke(proj, target);
}
}
template<std::size_t unwrap_level, class ExecutionPolicy, class R, class T, class Proj = std::identity>
requires(recursive_invocable<unwrap_level, Proj, R>&&
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>)
constexpr auto recursive_find(ExecutionPolicy execution_policy, R&& range, T&& target, Proj&& proj = {})
{
if constexpr (unwrap_level)
{
return std::find_if(execution_policy,
std::ranges::begin(range),
std::ranges::end(range),
[&](auto& element) {
return recursive_find<unwrap_level - 1>(execution_policy, element, target, proj);
}) != std::ranges::end(range);
}
else
{
return range == std::invoke(proj, target);
}
} | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
/* 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": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
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(input.cbegin(), input.cend(), 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;
}
void recursive_find_tests()
{
auto test_vectors_1 = n_dim_container_generator<4, int, std::vector>(1, 3);
test_vectors_1[0][0][0][0] = 2;
assert(recursive_find<4>(test_vectors_1, 2));
assert(recursive_find<4>(std::execution::par, test_vectors_1, 2));
auto test_vectors_2 = n_dim_container_generator<4, int, std::vector>(3, 3);
assert(recursive_find<4>(test_vectors_2, 2) == false);
assert(recursive_find<4>(test_vectors_2, 3));
assert(recursive_find<4>(test_vectors_2, 4) == false);
// Tests with std::string
auto test_vector_string = n_dim_container_generator<4, std::string, std::vector>("1", 3);
assert(recursive_find<4>(test_vector_string, "1"));
assert(recursive_find<4>(test_vector_string, "2") == false); | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
// Tests with std::string, projection
assert(recursive_find<4>(
test_vector_string,
"1",
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }) == false);
// Tests with std::array of std::string
std::array<std::string, 3> word_array1 = {"foo", "foo", "foo"};
assert(recursive_find<1>(word_array1, "foo"));
assert(recursive_find<1>(word_array1, "bar") == false);
// Tests with std::deque of std::string
std::deque<std::string> word_deque1 = {"foo", "foo", "foo", "bar"};
assert(recursive_find<1>(word_deque1, "foo"));
assert(recursive_find<1>(word_deque1, "bar"));
assert(recursive_find<1>(word_deque1, "abcd") == false);
assert(recursive_find<2>(word_deque1, 'a'));
assert(recursive_find<2>(word_deque1, 'b'));
assert(recursive_find<2>(word_deque1, 'c') == false);
std::vector<std::wstring> wstring_vector1{};
for(int i = 0; i < 4; ++i)
{
wstring_vector1.push_back(std::to_wstring(1));
}
assert(recursive_find<1>(wstring_vector1, std::to_wstring(1)));
assert(recursive_find<1>(wstring_vector1, std::to_wstring(2)) == false);
std::vector<std::u8string> u8string_vector1{};
for(int i = 0; i < 4; ++i)
{
u8string_vector1.push_back(u8"\u20AC2.00");
}
assert(recursive_find<1>(u8string_vector1, u8"\u20AC2.00"));
assert(recursive_find<1>(u8string_vector1, u8"\u20AC1.00") == false);
std::pmr::string pmr_string1 = "123";
std::vector<std::pmr::string> pmr_string_vector1 = {pmr_string1, pmr_string1, pmr_string1};
assert(recursive_find<1>(pmr_string_vector1, "123"));
assert(recursive_find<1>(pmr_string_vector1, "456") == false);
std::cout << "All tests passed!\n";
return;
} | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
return;
}
void recursive_find_if_not_tests()
{
auto test_vectors_1 = n_dim_container_generator<4, int, std::vector>(1, 3);
test_vectors_1[0][0][0][0] = 2;
assert(recursive_find_if_not<4>(test_vectors_1, [](auto&& i) { return i == 1; }));
auto test_vectors_2 = n_dim_container_generator<4, int, std::vector>(3, 3);
assert(recursive_find_if_not<4>(test_vectors_2, [](auto&& i) { return i == 3; }) == false);
// Tests with std::string
auto test_vector_string = n_dim_container_generator<4, std::string, std::vector>("1", 3);
assert(recursive_find_if_not<4>(test_vector_string, [](auto&& i) { return i == "1"; }) == false);
assert(recursive_find_if_not<4>(test_vector_string, [](auto&& i) { return i == "2"; }));
assert(recursive_find_if_not<4>(test_vector_string, [](auto&& i) { return i == "3"; }));
// Tests with std::string, projection
assert(recursive_find_if_not<4>(
test_vector_string,
[](auto&& i) { return i == "1"; },
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }));
assert(recursive_find_if_not<4>(
test_vector_string,
[](auto&& i) { return i == "2"; },
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }) == false);
// Tests with std::array of std::string
std::array<std::string, 3> word_array1 = {"foo", "foo", "foo"};
assert(recursive_find_if_not<1>(word_array1, [](auto&& i) { return i == "foo"; }) == false);
assert(recursive_find_if_not<1>(word_array1, [](auto&& i) { return i == "bar"; }));
std::cout << "All tests passed!\n";
return;
} | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
std::cout << "All tests passed!\n";
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_find_tests();
recursive_find_if_not_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!
All tests passed!
Computation finished at Sat Feb 24 02:56:36 2024
elapsed time: 0.00221348
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_find_if Template Function with Unwrap Level 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 recursive_find and recursive_find_if_not template functions in this post.
Why a new review is being asked for?
Please review the implementation of recursive_find and recursive_find_if_not template functions.
Answer: Looks good, except for one issue that I see I also missed in my previous reviews of your recursive find algorithms:
The projection is applied incorrectly
The projection should always be applied to the elements of the range, not to the target value. So you should write this instead:
return target == std::invoke(proj, range);
This also means that your tests that are using projection are wrong. | {
"domain": "codereview.stackexchange",
"id": 45523,
"lm_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++, recursion, template, constrained-templates, c++23",
"url": null
} |
c#, async-await, winforms
Title: Proving that a Window Message is being sent by async/await | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
Question: I asked a question on Stack Overflow and there's a discussion between @Serg, who posted an answer and @Jimi, whose comments suggest that the answer might be wrong.
So I implemented the following code for demonstration purposes. It is a WinForms application written in C#. I'm running old fashioned .NET Framework 4.7.2, because that's what I know best.
From the Stack Overflow answer's link to Microsoft's implementation of async/await, we expect that .NET registers a Windows Message and uses that to delegate control to the UI thread.
In order to see that message, I implemented a message loop myself. I wanted to do it fully correctly, including TranslateAccelerator(), but I failed on that one. Since my application doesn't use accelerators and the demo works without it, I felt that the program is "correct enough" and maybe that additional method would prevent me from seeing some messages, so perhaps it's even better.
The app is supposed to run in debug mode, since it uses Debug.Write() to show what's going on. This is to avoid even more Window Messages.
My question is: does this program indeed show that the linked SO answer is correct and that .NET is posting messages to the UI thread? Or do I observe something else here?
Possible output in the debug window, 1 is the thread ID, C339 is the Window Message along with parameters. I'm doing 10 async calls and there are 10 messages received:
Running on 1
Running on 1
Running on 1
Running on 1
Running on 1
Running on 1
Running on 1
Running on 1
Running on 1
Running on 1
C339 0x00000000 0x00000000 0x007A06FE, 3391921
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392015
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392125
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392234
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392328
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392421
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392531
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392625
Done on 1 | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392625
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392734
Done on 1
C339 0x00000000 0x00000000 0x007A06FE, 3392828
Done on 1 | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
Class for the native P/Invoke stuff:
using System;
using System.Runtime.InteropServices;
using System.Windows.Interop;
namespace SO78028901MRE
{
internal static class Native
{
internal const int MaxIntAtom = 0xC000;
internal static readonly IntPtr AnyHWnd = IntPtr.Zero;
internal const uint NoFilter = 0;
[DllImport("user32.dll")]
internal static extern bool GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin = NoFilter, uint wMsgFilterMax = NoFilter);
[DllImport("user32.dll")]
internal static extern bool TranslateMessage([In] ref MSG lpMsg);
[DllImport("user32.dll")]
internal static extern IntPtr DispatchMessage([In] ref MSG lpMsg);
[DllImport("user32.dll")]
internal static extern bool TranslateAccelerator(IntPtr hWnd, IntPtr hAccTable, ref MSG lpMsg);
}
}
Form for testing purposes:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Interop;
// Stack Overflow question 78028901
// Does async await use Windows Messages to return control to the UI thread?
// Minimum Reproducible Example to see Windows Messages arrive
namespace SO78028901MRE
{
/// <summary>
/// Form which will receive the expected async/await Windows Messages
/// </summary>
public partial class WMReceiveTestForm : Form
{
public WMReceiveTestForm()
{
InitializeComponent();
}
private void btnPerformTest_Click(object sender, EventArgs e)
{
StartAsyncCalls(10);
EndlessMessageLoop();
}
private void StartAsyncCalls(int count)
{
for (int i = 0; i < count; i++)
{
AsyncMethod();
Thread.Sleep(100);
}
} | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
//
/// <summary>
/// Prevent Windows Messages from being processed by some .NET code.
/// We want to see all messages ourselves.
/// </summary>
private static void EndlessMessageLoop()
{
while (Native.GetMessage(out var msg, Native.AnyHWnd))
{
// TODO: if (!Native.TranslateAccelerator(???, ???, ref msg))
{
if (IsRegisteredMessage(msg))
{
Debug.WriteLine("{0:X4} 0x{1:X8} 0x{2:X8} 0x{3:X8}, {4}",
msg.message, msg.lParam.ToInt32(), msg.wParam.ToInt32(), msg.hwnd.ToInt32(), msg.time);
}
Native.TranslateMessage(ref msg);
Native.DispatchMessage(ref msg);
}
}
}
/// <summary>
/// .NET should register a Windows Message via RegisterWindowMessage().
/// Such a message should have a message number above 0xC000.
/// This method determines if such a message was found.
/// </summary>
private static bool IsRegisteredMessage(MSG msg)
{
return msg.message > Native.MaxIntAtom;
}
/// <summary>
/// Simple method that can be called asynchronously and just waits.
/// Prints the thread ID before and after waiting.
/// </summary>
private async void AsyncMethod()
{
Debug.WriteLine("Running on " + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000).ConfigureAwait(true);
Debug.WriteLine("Done on " + Thread.CurrentThread.ManagedThreadId);
}
}
}
What else can we do with this code? (Not for review purposes, just FYI) | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
What else can we do with this code? (Not for review purposes, just FYI)
ConfigureAwait(false) will print Done on X, where X is a thread number, certainly one of the thread pool. In this case we don't see a message, because the task can easily be picked up by a threadpool thread without any message. IMHO, this confirms that the message is only sent if control needs to go to the UI thread.
Adding if (!IsRegisteredMessage(msg)) in front of Native.DispatchMessage(ref msg); will successfully prevent the remaining code of the async method from running. IMHO this confirms that the message is related to the async execution.
Using Task.Run(AsyncMethod); instead of AsyncMethod(); will begin execution on a threadpool thread rather than the UI thread. This makes .ConfigureAwait(true) useless (at least if someone thinks that this makes it go back to the UI thread). Since it does not go back to the UI thread, there will also not be messages. But we should see the same thread IDs in the same order.
Combining Task.Run(AsyncMethod); and .ConfigureAwait(false) may show different thread IDs when starting compared to ending. As expected.
Answer: Yes, your code is sufficient to show that async/await sends or posts Window Messages in order to get back to the UI thread.
Yet, you can still do better. As @Jimi pointed out in the comments, your code doesn't follow the async/await best practices [
1,
2,
3,
4
]. But that was certainly not the primary goal.
In particular, you would make the button click method async, and use Task.Delay() instead of Thread.Sleep():
private async void btnPerformTest_Click(object sender, EventArgs e)
{
await StartAsyncCalls(10);
EndlessMessageLoop();
}
private async Task StartAsyncCalls(int count)
{
for (int i = 0; i < count; i++)
{
AsyncMethod();
await Task.Delay(100);
}
} | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
Only button click handlers may be async void for backwards compatibility reasons. AsyncMethod() should not be void:
private async Task AsyncMethod()
{
Debug.WriteLine("Running on " + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000).ConfigureAwait(true);
Debug.WriteLine("Done on " + Thread.CurrentThread.ManagedThreadId);
}
In the .NET source code, you find that .NET uses RegisterWindowMessage(), and you can check exactly for that message only, instead of checking all messages in range 0xC000 through 0xFFFF:
Declare a P/Invoke and use the same message:
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint RegisterWindowMessage(string lpString);
[...]
_registeredMessage = Native.RegisterWindowMessage("WindowsForms12_ThreadCallbackMessage");
[...]
private bool IsRegisteredMessage(MSG msg)
{
return msg.message == _registeredMessage;
}
Now that you have proved that .NET indeed uses Window Messages, you still shouldn't blindly believe everything that @Serg said in the answer on Stack Overflow. Instead, get a debugger, put a conditional breakpoint in PostMessage() and see what callstack you get.
You'll find that @Serg is correct about PostMessage() being used, but he was wrong by saying that .Invoke() is used. @Jimi is correct that .Invoke() will not use PostMessage(), but was wrong in the assumption that .BeginInvoke() is not used.
Correct is: WindowsFormsSynchronizationContext will use .BeginInvoke() and that will result in a PostMessage() call. Hopefully, everyone has learned something from the question.
Conditional breakpoint for WinDbg (0xC339 is the message number; check it first). When the app is 64 bit, the second argument (msg) will be in the EDX register:
bp user32!PostMessageW ".if (edx == 0xC339) {} .else {g}" | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
c#, async-await, winforms
Call stack (return address and child stack removed for brevity):
0:011> k
# Call Site
00 USER32!PostMessageW
01 System_Windows_Forms_ni+0x3496e2
02 System_Windows_Forms_ni!System.Windows.Forms.Control.MarshaledInvoke+0x36f
03 System_Windows_Forms_ni!System.Windows.Forms.Control.BeginInvoke+0x62
04 System_Windows_Forms_ni!System.Windows.Forms.WindowsFormsSynchronizationContext.Post+0x51
05 mscorlib_ni!System.Threading.Tasks.AwaitTaskContinuation.RunCallback+0x6a [...\TaskContinuation.cs @ 759]
06 mscorlib_ni!System.Threading.Tasks.Task.FinishContinuations+0xfe [...\Task.cs @ 3642]
07 mscorlib_ni!System.Threading.Tasks.Task<System.Threading.Tasks.VoidTaskResult>.TrySetResult+0x65 [...\Future.cs @ 490]
08 mscorlib_ni!System.Threading.Tasks.Task.DelayPromise.Complete+0xad [...\Task.cs @ 5942]
09 mscorlib_ni!System.Threading.ExecutionContext.RunInternal+0x108 [...\executioncontext.cs @ 980]
0a mscorlib_ni!System.Threading.ExecutionContext.Run+0x15 [...g\executioncontext.cs @ 928]
0b mscorlib_ni!System.Threading.TimerQueueTimer.CallCallback+0x138 [...\timer.cs @ 713]
0c mscorlib_ni!System.Threading.TimerQueueTimer.Fire+0x91 [...\timer.cs @ 670]
0d mscorlib_ni!System.Threading.TimerQueue.FireNextTimers+0x78 [...\timer.cs @ 425]
0e clr!CallDescrWorkerInternal+0x83
WindowsFormsSynchronizationContext.Post() calls
Control.BeginInvoke(), which calls
Control.MarshaledInvoke() which registers the message and calls PostMessage() | {
"domain": "codereview.stackexchange",
"id": 45524,
"lm_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#, async-await, winforms",
"url": null
} |
javascript
Title: Optimizing for() loops on Roman Numeral Converter JS
Question: I'm looking for some feedback on this converter I made. It works just fine for the instructions I had, but I'm wondering what else could be done to improve it or if there's a better aproach to doing this. I wasn't expecting to nail this since I'm just starting to learn JS.
I'm aware I could've implemented things like Math.floor(), Math.min() to make the validations, I'm mostly wondering on the conversion itself, what else could be optimized, I'm sure there was an easier way. I also thought of using forEach() instead of multiple for() and arrays but I'm not sure how
Here's the whole thing in codepen: Roman Numeral Converter
Here's the JS code itself:
const numberInput = document.getElementById("number");
const convertButton = document.getElementById("convert-btn");
const output = document.getElementById("output");
function convertRom () {
const numbersList = numberInput.value.split((/(\d)/)).filter(Boolean)
for (let i = numbersList.length; numbersList.length < 4; i--) {
numbersList.unshift('0');
i -= 1
}
console.log("numbersList " + numbersList);
const romanDigit1 = [];
const romanDigit2 = [];
const romanDigit3 = [];
const romanDigit4 = [];
for (let digit1 = numbersList[0]; digit1 > 0; digit1 -1){
romanDigit1.push("M");
digit1 -= 1
}
for (let digit2 = Number(numbersList[1]); digit2 > 0; digit2 === digit2){
if (digit2 === 9) {
romanDigit2.push("CM")
digit2 -= 9;
} else if (digit2 === 5){
romanDigit2.unshift("D")
digit2 -= 5;
} else if (digit2 === 4){
romanDigit2.push("CD")
digit2 -= 4;
} else {
romanDigit2.push("C");
digit2 -= 1
}
}
for (let digit3 = Number(numbersList[2]); digit3 > 0; digit3 === digit3){ | {
"domain": "codereview.stackexchange",
"id": 45525,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
for (let digit3 = Number(numbersList[2]); digit3 > 0; digit3 === digit3){
if (digit3 === 9) {
romanDigit3.push("XC")
digit3 -= 9;
} else if (digit3 === 5){
romanDigit3.unshift("L")
digit3 -= 5;
} else if (digit3 === 4){
romanDigit3.push("XL")
digit3 -= 4;
} else {
romanDigit3.push("X");
digit3 -= 1
}
}
for (let digit4 = Number(numbersList[3]); digit4 > 0; digit4 === digit4){
if (digit4 === 9) {
romanDigit4.push("IX")
digit4 -= 9;
} else if (digit4 === 5){
romanDigit4.unshift("V")
digit4 -= 5;
} else if (digit4 === 4){
romanDigit4.push("IV")
digit4 -= 4;
} else {
romanDigit4.push("I");
digit4 -= 1
}
}
const romanResult = romanDigit1.join("") + romanDigit2.join("") + romanDigit3.join("") + romanDigit4.join("");
output.innerHTML = romanResult;
}
function validate() {
switch (true){
case numberInput.value === "":
output.innerHTML = "Please enter a valid number";
numberInput.value = "";
break
case numberInput.value <= 0:
output.innerHTML = "Please enter a number greater than or equal to 1";
numberInput.value = "";
break
case numberInput.value >= 4000:
output.innerHTML = "Please enter a number less than or equal to 3999";
numberInput.value = "";
break
default:
convertRom();
}
}
convertButton.addEventListener("click", validate)
Answer: A function should have parameters. They should not use global variables as input instead of using parameters.
numbersList.length < 4 why is this line here, and more importantly, what is "4" to mean here? This is often referred to as "magic value" and we hope not to have to guess meaning other than at the start of an executable.
The numberList generation should be in a specific function that indicates what it actually does. | {
"domain": "codereview.stackexchange",
"id": 45525,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
The numberList generation should be in a specific function that indicates what it actually does.
const romanDigit1..4 = [];
Every time that you start to count in your code you're doing something wrong; the computer should do the counting.
By definition a digit can never consist of multiple characters. The Roman system doesn't use "digits" so defining them as an array seems incorrect. What about romanNumerals?
for (let digit1 = numbersList[0]; digit1 > 0; digit1 -1){
Code is incorrect: it doesn't work for values over 3999, those should be caught before entering the loop, for instance by adding a guard clause such as:
if (value >= 4000) {
throw new Error("Function is capped at 3999, which is the maximum classic Roman numerals can encode");
}
Of course the input should try and make sure that the user doesn't enter that value so that the error never gets thrown. Public methods however should always check that the input confirms to the preconditions for successfully executing the method, rather than to return incorrect values.
There is another digit -= 1 later on, which was probably required as digit - 1 doesn't assign a different value to digit1.
for (let digit2 = Number(numbersList[1]); digit2 > 0; digit2 === digit2)
The 3rd term is not required in a for loop. It may be a good idea to always have an expression in there, but there is no need for a filler if it is not needed.
The strict equals operator === is not wrong, but as digitN is always of the correct type it is probably easier to just use ==.
NOTE: apparently it is good practice to use === anyway for JavaScript, see the comment below.
A slightly smarter algorithm would give a set of roman numerals to a function and then performs the exact same for loop for those. There are even smarter algorithms possible where you just start with a string consisting of all roman numerals. That way it is also easier to extend your implementation to allow higher numbers by simply adjusting the string. | {
"domain": "codereview.stackexchange",
"id": 45525,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
default:
convertRom();
OK, so you ask for a number and if anything other than an empty string is entered it will be converted? That's just weird and should at least be indicated to the user.
In general the code is readable & relatively well spaced out. Sometimes it is slightly inconsistent, such as the white line before the for loops that happens most of the time but not always.
The identifiers are named OK in general, but here we get into the strange situations where the numbers are actual decimal digits. So, uh, I'd propose decimalsDigits. | {
"domain": "codereview.stackexchange",
"id": 45525,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
python, java, parsing
Title: Parsing Java's class file
Question: The structure of a class file consists of a single structure (presented here using pseudostructures written in a C-like structure notation):
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
u2 constant_pool_count;
cp_info constant_pool[constant_pool_count-1];
u2 access_flags;
u2 this_class;
u2 super_class;
u2 interfaces_count;
u2 interfaces[interfaces_count];
u2 fields_count;
field_info fields[fields_count];
u2 methods_count;
method_info methods[methods_count];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
The script parses the class file into a dictionary, except for the attributes, but does not verify that the file is valid/correct. (I did not deem that a good use of my time)
For a class file generated for this simple program:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
} | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
the script produces:
{'access_flags': ['ACC_FINAL',
'ACC_INTERFACE',
'ACC_ABSTRACT',
'ACC_SYNTHETIC',
'ACC_ANNOTATION',
'ACC_ENUM'],
'attributes': [{'attribute_length': 2,
'attribute_name_index': 13,
'info': b'\x00\x0e'}],
'attributes_count': 1,
'constant_pool': [{'class_index': 6, 'name_and_type_index': 15, 'tag': 10},
{'class_index': 16, 'name_and_type_index': 17, 'tag': 9},
{'name_index': 18, 'tag': 8},
{'class_index': 19, 'name_and_type_index': 20, 'tag': 10},
{'name_index': 21, 'tag': 7},
{'name_index': 22, 'tag': 7},
{'bytes': b'<init>', 'length': 6, 'tag': 1},
{'bytes': b'()V', 'length': 3, 'tag': 1},
{'bytes': b'Code', 'length': 4, 'tag': 1},
{'bytes': b'LineNumberTable', 'length': 15, 'tag': 1},
{'bytes': b'main', 'length': 4, 'tag': 1},
{'bytes': b'([Ljava/lang/String;)V', 'length': 22, 'tag': 1},
{'bytes': b'SourceFile', 'length': 10, 'tag': 1},
{'bytes': b'Main.java', 'length': 9, 'tag': 1},
{'descriptor_index': 8, 'name_index': 7, 'tag': 12},
{'name_index': 23, 'tag': 7},
{'descriptor_index': 25, 'name_index': 24, 'tag': 12},
{'bytes': b'Hello, World!', 'length': 13, 'tag': 1},
{'name_index': 26, 'tag': 7},
{'descriptor_index': 28, 'name_index': 27, 'tag': 12},
{'bytes': b'Main', 'length': 4, 'tag': 1},
{'bytes': b'java/lang/Object', 'length': 16, 'tag': 1},
{'bytes': b'java/lang/System', 'length': 16, 'tag': 1},
{'bytes': b'out', 'length': 3, 'tag': 1}, | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
{'bytes': b'out', 'length': 3, 'tag': 1},
{'bytes': b'Ljava/io/PrintStream;', 'length': 21, 'tag': 1},
{'bytes': b'java/io/PrintStream', 'length': 19, 'tag': 1},
{'bytes': b'println', 'length': 7, 'tag': 1},
{'bytes': b'(Ljava/lang/String;)V', 'length': 21, 'tag': 1}],
'constant_pool_count': 29,
'fields': [],
'fields_count': 0,
'interfaces': [],
'interfaces_count': 0,
'magic': '0XCAFEBABE',
'major': 55,
'methods': [{'access_flags': ['ACC_PRIVATE',
'ACC_PROTECTED',
'ACC_STATIC',
'ACC_FINAL',
'ACC_SYNCHRONIZED',
'ACC_BRIDGE',
'ACC_VARARGS',
'ACC_NATIVE',
'ACC_ABSTRACT',
'ACC_STRICT',
'ACC_SYNTHETIC'],
'attributes': [{'attribute_length': 29,
'attribute_name_index': 9,
'info': b'\x00\x01\x00\x01\x00\x00\x00\x05'
b'*\xb7\x00\x01\xb1\x00\x00\x00'
b'\x01\x00\n\x00\x00\x00\x06\x00'
b'\x01\x00\x00\x00\x01'}],
'attributes_count': 1,
'descriptor_index': 8,
'name_index': 7},
{'access_flags': ['ACC_PRIVATE',
'ACC_PROTECTED',
'ACC_FINAL',
'ACC_SYNCHRONIZED',
'ACC_BRIDGE',
'ACC_VARARGS',
'ACC_NATIVE',
'ACC_ABSTRACT',
'ACC_STRICT',
'ACC_SYNTHETIC'], | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
'ACC_STRICT',
'ACC_SYNTHETIC'],
'attributes': [{'attribute_length': 37,
'attribute_name_index': 9,
'info': b'\x00\x02\x00\x01\x00\x00\x00\t'
b'\xb2\x00\x02\x12\x03\xb6\x00\x04'
b'\xb1\x00\x00\x00\x01\x00\n\x00'
b'\x00\x00\n\x00\x02\x00\x00\x00'
b'\x03\x00\x08\x00\x04'}],
'attributes_count': 1,
'descriptor_index': 12,
'name_index': 11}],
'methods_count': 2,
'minor': 0,
'super_class': 6,
'this_class': 5} | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
Code:
#!/usr/bin/env python3
from enum import Enum
from io import BytesIO
from pathlib import Path
from pprint import pprint
import typer
# fmt: off
# This got rather duplicative.
class Constants(Enum):
CONSTANT_Class = 7
CONSTANT_Fieldref = 9
CONSTANT_Methodref = 10
CONSTANT_InterfaceMethodref = 11
CONSTANT_String = 8
CONSTANT_Integer = 3
CONSTANT_Float = 4
CONSTANT_Long = 5
CONSTANT_Double = 6
CONSTANT_NameAndType = 12
CONSTANT_Utf8 = 1
CONSTANT_MethodHandle = 15
CONSTANT_MethodType = 16
CONSTANT_InvokeDynamic = 18
ACCESS_FLAGS = {
"class": [
("ACC_PUBLIC" ,0x0001),
("ACC_FINAL" ,0x0010),
("ACC_SUPER" ,0x0020),
("ACC_INTERFACE" ,0x0200),
("ACC_ABSTRACT" ,0x0400),
("ACC_SYNTHETIC" ,0x1000),
("ACC_ANNOTATION" ,0x2000),
("ACC_ENUM" ,0x4000),
],
"field": [
("ACC_PUBLIC" ,0x0001),
("ACC_PRIVATE" ,0x0002),
("ACC_PROTECTED" ,0x0004),
("ACC_STATIC" ,0x0008),
("ACC_FINAL" ,0x0010),
("ACC_VOLATILE" ,0x0040),
("ACC_TRANSIENT" ,0x0080),
("ACC_SYNTHETIC" ,0x1000),
("ACC_ENUM" ,0x4000),
],
"method": [
("ACC_PUBLIC" ,0x0001),
("ACC_PRIVATE" ,0x0002),
("ACC_PROTECTED" ,0x0004),
("ACC_STATIC" ,0x0008),
("ACC_FINAL" ,0x0010),
("ACC_SYNCHRONIZED" ,0x0020),
("ACC_BRIDGE" ,0x0040),
("ACC_VARARGS" ,0x0080),
("ACC_NATIVE" ,0x0100),
("ACC_ABSTRACT" ,0x0400),
("ACC_STRICT" ,0x0800),
("ACC_SYNTHETIC" ,0x1000),
],
}
# fmt: on | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
def parse_ux(file: BytesIO, length: int) -> int:
return int.from_bytes(file.read(length), "big")
def parse_u1(file: BytesIO) -> int:
return parse_ux(file, 1)
def parse_u2(file: BytesIO) -> int:
return parse_ux(file, 2)
def parse_u4(file: BytesIO) -> int:
return parse_ux(file, 4)
def parse_constant_pool(f: BytesIO, pool_size: int) -> int:
constant_pool = []
# We could map each constant tag to its corresponding processing logic.
# Would that be better? This looks horrendous.
for _ in range(pool_size):
cp_info = {}
tag = parse_u1(f)
constant = Constants(tag) | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
if constant in (
Constants.CONSTANT_Methodref,
Constants.CONSTANT_InterfaceMethodref,
Constants.CONSTANT_Fieldref,
):
cp_info["tag"] = constant.value
cp_info["class_index"] = parse_u2(f)
cp_info["name_and_type_index"] = parse_u2(f)
elif constant in (Constants.CONSTANT_Class, Constants.CONSTANT_String):
cp_info["tag"] = constant.value
cp_info["name_index"] = parse_u2(f)
elif constant == Constants.CONSTANT_Utf8:
cp_info["tag"] = constant.value
cp_info["length"] = parse_u2(f)
cp_info["bytes"] = f.read(cp_info["length"])
elif constant == Constants.CONSTANT_NameAndType:
cp_info["tag"] = constant.value
cp_info["name_index"] = parse_u2(f)
cp_info["descriptor_index"] = parse_u2(f)
elif constant in (Constants.CONSTANT_Integer, Constants.CONSTANT_Float):
cp_info["tag"] = constant.value
cp_info["bytes"] = f.read(4)
elif constant in (Constants.CONSTANT_Long, Constants.CONSTANT_Double):
cp_info["tag"] = constant.value
cp_info["high_bytes"] = f.read(4)
cp_info["low_bytes"] = f.read(4)
elif constant == Constants.CONSTANT_MethodHandle:
cp_info["tag"] = constant.value
cp_info["reference_kind"] = parse_u1(f)
cp_info["reference_index"] = parse_u2(f)
elif constant == Constants.CONSTANT_MethodType:
cp_info["tag"] = constant.value
cp_info["descriptor_index"] = parse_u2(f)
elif constant == Constants.CONSTANT_InvokeDynamic:
cp_info["tag"] = constant.value
cp_info["bootstrap_method_attr_index"] = parse_u2(f)
cp_info["name_and_type_index"] = parse_u2(f)
else:
assert False, f"Unexpected tag encountered {tag = }"
constant_pool.append(cp_info)
return constant_pool | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
def parse_access_flags(val: int, flags: [(str, int)]) -> list[str]:
return [name for (name, mask) in flags if not (val & mask)]
def parse_attributes(f: BytesIO, attributes_count: int) -> list:
attributes = []
for _ in range(attributes_count):
attribute_info = {}
attribute_info["attribute_name_index"] = parse_u2(f)
attribute_info["attribute_length"] = parse_u4(f)
attribute_info["info"] = f.read(attribute_info["attribute_length"])
attributes.append(attribute_info)
return attributes
def parse_methods(f: BytesIO, methods_count: int) -> list:
methods = []
for _ in range(methods_count):
method_info = {}
method_info["access_flags"] = parse_access_flags(
parse_u2(f), ACCESS_FLAGS["method"]
)
method_info["name_index"] = parse_u2(f)
method_info["descriptor_index"] = parse_u2(f)
method_info["attributes_count"] = parse_u2(f)
method_info["attributes"] = parse_attributes(f, method_info["attributes_count"])
methods.append(method_info)
return methods
def parse_fields(f: BytesIO, fields_count: int) -> dict:
fields = []
for _ in range(fields_count):
field_info = {}
field_info["access_flags"] = parse_access_flags(
parse_u2(f), ACCESS_FLAGS["field"]
)
field_info["name_index"] = parse_u2(f)
field_info["descriptor_index"] = parse_u2(f)
field_info["attributes_count"] = parse_u2(f)
field_info["attributes"] = parse_attributes(f, field_info["attributes_count"])
fields.append(field_info)
return fields
def parse_interfaces(f: BytesIO, interfaces_count: int) -> dict:
interfaces = []
for _ in range(interfaces_count):
parse_u1(f) # Discard tag
class_info = {"tag": "CONSTANT_Class", "name_index": parse_u2()}
interfaces.append(class_info)
return interfaces | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
return interfaces
def parse_class_file(f: BytesIO) -> dict:
class_file = {}
class_file["magic"] = str(hex(parse_u4(f))).upper()
class_file["minor"] = parse_u2(f)
class_file["major"] = parse_u2(f)
class_file["constant_pool_count"] = parse_u2(f)
class_file["constant_pool"] = parse_constant_pool(
f, class_file["constant_pool_count"] - 1
)
class_file["access_flags"] = parse_access_flags(parse_u2(f), ACCESS_FLAGS["class"])
class_file["this_class"] = parse_u2(f)
class_file["super_class"] = parse_u2(f)
class_file["interfaces_count"] = parse_u2(f)
class_file["interfaces"] = parse_interfaces(f, class_file["interfaces_count"])
class_file["fields_count"] = parse_u2(f)
class_file["fields"] = parse_fields(f, class_file["fields_count"])
class_file["methods_count"] = parse_u2(f)
class_file["methods"] = parse_methods(f, class_file["methods_count"])
class_file["attributes_count"] = parse_u2(f)
class_file["attributes"] = parse_attributes(f, class_file["attributes_count"])
return class_file
def main(file_path: Path) -> None:
with open(file_path, mode="rb") as f:
class_file = parse_class_file(BytesIO(f.read()))
pprint(class_file)
if __name__ == "__main__":
typer.run(main)
Review Request:
Bugs, general coding comments, style, idiomatic code, et cetera.
PS: This was done as a recreational activity. | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
Answer: Your reference is extremely out-of-date; refer to version 21. Luckily the JVM hasn't changed much.
Typer seems like overkill for a program that unconditionally accepts one command-line argument. I scarcely consider that justification for bringing in a third-party library.
Your Constants shouldn't be an Enum; it should be an IntEnum. Your ACCESS_FLAGS should not be a dict of lists; it should be split out into separate IntFlags.
When you print the constant tag, don't print the number; print the symbol. repr (!r) will do this.
I consider int.from_bytes and the variable-length method used in parse_ux to be less explicit than the other two options I'll be demonstrating, which are struct unpacking and ctypes unpacking. Your parse_fields and similar methods should be entirely replaced with big-endian structure definitions.
Don't use dictionaries for internal program data; they aren't well-typed.
Your script will not be very useful until you resolve the constant indices to their respective structures. For instance, your output 'attribute_name_index': 9 would be replaced with a reference to the corresponding constant string.
Replace open(file_path, mode="rb") with file_path.open().
It's actually a pretty reasonable idea to in-memory buffer the file content before deserialising it, and may have performance advantages; but for simplicity I do not include this in my demonstration.
Suggested
The following is a little long-winded, but demonstrates some of the concepts I've talked about above. It has nearly mypy-compliant types, save for the functional enums that mypy does not support.
#!/usr/bin/env python3
import ctypes
import struct
import sys
from dataclasses import dataclass
from enum import IntEnum, IntFlag
from functools import partial
from io import BufferedIOBase
from itertools import chain
from pathlib import Path
from typing import Callable, ClassVar, Iterator, NamedTuple, Type, TypeVar | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
# Spec from
# https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-4.html
# Since we don't require strict validation, this captures all flags that don't
# have multiple definitions.
ACCESS_SHARED = {
'PUBLIC' : 0x0001,
'PRIVATE' : 0x0002,
'PROTECTED' : 0x0004,
'STATIC' : 0x0008,
'FINAL' : 0x0010,
'NATIVE' : 0x0100,
'INTERFACE' : 0x0200,
'ABSTRACT' : 0x0400,
'STRICT' : 0x0800,
'SYNTHETIC' : 0x1000,
'ANNOTATION': 0x2000,
'ENUM' : 0x4000,
}
# This functional enum form is not mypy-compatible.
CommonAccess = IntFlag('CommonAccess', ACCESS_SHARED)
ClassAccess = IntFlag('ClassAccess', {
**ACCESS_SHARED,
'SUPER': 0x0020,
'MODULE': 0x8000,
})
MethodAccess = IntFlag('MethodAccess', {
**ACCESS_SHARED,
'SYNCHRONIZED' : 0x0020,
'BRIDGE' : 0x0040,
'VARARGS' : 0x0080,
})
ParameterAccess = IntFlag('ParameterAccess', {
**ACCESS_SHARED,
'MANDATED' : 0x8000,
})
ModuleAccess = IntFlag('ModuleAccess', {
**ACCESS_SHARED,
'OPEN' : 0x0020,
'MANDATED' : 0x8000,
})
ModuleRequiresAccess = IntFlag('ModuleRequiresAccess', {
**ACCESS_SHARED,
'TRANSITIVE' : 0x0020,
'STATIC_PHASE' : 0x0040,
'MANDATED' : 0x8000,
})
FieldAccess = IntFlag('FieldAccess', {
**ACCESS_SHARED,
'VOLATILE' : 0x0040,
'TRANSIENT' : 0x0080,
})
class ConstantTag(IntEnum):
UTF8 = 1
INTEGER = 3
FLOAT = 4
LONG = 5
DOUBLE = 6
CLASS = 7
STRING = 8
FIELD_REF = 9
METHOD_REF = 10
INTERFACE_METHOD_REF = 11
NAME_AND_TYPE = 12
METHOD_HANDLE = 15
METHOD_TYPE = 16
DYNAMIC = 17
INVOKE_DYNAMIC = 18
MODULE = 19
PACKAGE = 20 | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
class ReferenceKind(IntEnum):
getField = 1
getStatic = 2
putField = 3
putStatic = 4
invokeVirtual = 5
invokeStatic = 6
invokeSpecial = 7
newInvokeSpecial = 8
invokeInterface = 9
class Version(ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('magic', ctypes.c_uint32),
('minor_version', ctypes.c_uint16),
('major_version', ctypes.c_uint16),
)
__slots__ = [k for k, t in _fields_]
class Constant:
CHILDREN: ClassVar[tuple[str, ...]]
class ClassConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('name_index', ctypes.c_uint16),
)
CHILDREN = 'name_index',
__slots__ = ('name_index', 'name_constant')
def __str__(self) -> str:
return str(self.name_constant)
ModuleConstant = ClassConstant
PackageConstant = ClassConstant
class DoubleConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
# Don't represent as high bytes and low bytes in the spec;
# directly unpack to value
('value', ctypes.c_double),
)
CHILDREN = ()
__slots__ = 'value',
def __str__(self) -> str:
return str(self.value)
class DynamicConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('bootstrap_method_attr_index', ctypes.c_uint16),
('name_and_type_index', ctypes.c_uint16),
)
CHILDREN = ('bootstrap_method_attr_index', 'name_and_type_index')
__slots__ = (
'bootstrap_method_attr_index', 'bootstrap_method_attr_constant',
'name_and_type_index', 'name_and_type_constant',
)
def __str__(self) -> str:
return f'{self.name_and_type_constant} -> {self.bootstrap_method_attr_constant}'
class FloatConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('value', ctypes.c_float),
)
CHILDREN = ()
__slots__ = 'value', | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
def __str__(self) -> str:
return str(self.value)
class IntegerConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('value', ctypes.c_int32),
)
CHILDREN = ()
__slots__ = 'value',
def __str__(self) -> str:
return str(self.value)
class LongConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('value', ctypes.c_int64),
)
CHILDREN = ()
__slots__ = 'value',
def __str__(self) -> str:
return str(self.value)
InvokeDynamicConstant = DynamicConstant
class MethodHandleConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('reference_kind', ctypes.c_uint8),
('reference_index', ctypes.c_uint16),
)
CHILDREN = 'reference_index',
__slots__ = (
'reference_kind',
'reference_index', 'reference_constant',
)
@property
def kind(self) -> ReferenceKind:
return ReferenceKind(self.reference_kind)
def __str__(self) -> str:
return f'{self.kind.name} {self.reference_constant}'
class MethodRefConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('class_index', ctypes.c_uint16),
('name_and_type_index', ctypes.c_uint16),
)
CHILDREN = ('class_index', 'name_and_type_index')
__slots__ = (
'class_index', 'class_constant',
'name_and_type_index', 'name_and_type_constant',
)
def __str__(self) -> str:
return str(self.name_and_type_constant)
class MethodTypeConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('descriptor_index', ctypes.c_uint16),
)
CHILDREN = 'descriptor_index',
__slots__ = ('descriptor_index', 'descriptor_constant')
def __str__(self) -> str:
return str(self.descriptor_constant)
FieldRefConstant = MethodRefConstant
InterfaceMethodConstant = MethodRefConstant | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
FieldRefConstant = MethodRefConstant
InterfaceMethodConstant = MethodRefConstant
class NameAndTypeConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('name_index', ctypes.c_uint16),
('descriptor_index', ctypes.c_uint16),
)
CHILDREN = ('name_index', 'descriptor_index')
__slots__ = (
'name_index', 'name_constant',
'descriptor_index', 'descriptor_constant',
)
def __str__(self) -> str:
return f'{self.name_constant} "{self.descriptor_constant}"'
class StringConstant(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('string_index', ctypes.c_uint16),
)
CHILDREN = 'string_index',
__slots__ = ('string_index', 'string_constant')
def __str__(self) -> str:
return str(self.string_constant)
class AttributeInfo(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('attribute_name_index', ctypes.c_uint16),
('attribute_length', ctypes.c_uint32),
)
data: bytes
CHILDREN = 'attribute_name_index',
__slots__ = (
'attribute_name_index', 'attribute_name_constant',
'attribute_length', 'data',
)
def __str__(self) -> str:
return f'{self.attribute_name_constant}'
class FieldInfo(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('access_flags', ctypes.c_uint16),
('name_index', ctypes.c_uint16),
('descriptor_index', ctypes.c_uint16),
('attributes_count', ctypes.c_uint16),
)
CHILDREN = ('name_index', 'descriptor_index')
attributes: tuple[AttributeInfo, ...]
__slots__ = (
'name_index', 'name_constant',
'descriptor_index', 'descriptor_constant',
'access_flags', 'attributes_count',
'attributes',
)
@property
def access(self) -> FieldAccess:
return FieldAccess(self.access_flags) | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
@property
def access(self) -> FieldAccess:
return FieldAccess(self.access_flags)
def __str__(self) -> str:
s = f'{self.access!r} {self.name_constant} "{self.descriptor_constant}"'
attrs = ', '.join(str(a) for a in self.attributes)
if attrs:
s += ' @ ' + attrs
return s
class MethodInfo(Constant, ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = (
('access_flags', ctypes.c_uint16),
('name_index', ctypes.c_uint16),
('descriptor_index', ctypes.c_uint16),
('attributes_count', ctypes.c_uint16),
)
CHILDREN = ('name_index', 'descriptor_index')
attributes: tuple[AttributeInfo, ...]
__slots__ = (
'name_index', 'name_constant',
'descriptor_index', 'descriptor_constant',
'access_flags', 'attributes_count',
'attributes',
)
@property
def access(self) -> MethodAccess:
return MethodAccess(self.access_flags)
def __str__(self) -> str:
s = f'{self.access!r} {self.name_constant} "{self.descriptor_constant}"'
attrs = ', '.join(str(a) for a in self.attributes)
if attrs:
s += ' @ ' + attrs
return s
@dataclass(frozen=True, slots=True)
class UTF8Constant(Constant):
length: int
bytes_: bytes
CHILDREN = ()
@classmethod
def read(cls, f: BufferedIOBase) -> 'UTF8Constant':
length = read_short(f)
bytes_ = f.read(length)
return cls(length=length, bytes_=bytes_)
def __str__(self) -> str:
return self.bytes_.decode(encoding='utf8')
StructT = TypeVar('StructT', bound=ctypes.BigEndianStructure)
def read_struct(f: BufferedIOBase, type_: Type[StructT]) -> StructT:
value = type_()
f.readinto(value)
return value
def read_short(f: BufferedIOBase) -> int:
fmt = '>H'
buffer = f.read(struct.calcsize(fmt))
value, = struct.unpack(fmt, buffer)
return value | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
def read_indices(f: BufferedIOBase, n: int) -> tuple[int, ...]:
fmt = f'>{n}H'
buffer = f.read(struct.calcsize(fmt))
return struct.unpack(fmt, buffer)
def bind_read(type_: Type[StructT]) -> Callable[[BufferedIOBase], StructT]:
return partial(read_struct, type_=type_)
CONSTANT_READERS = {
ConstantTag.CLASS: bind_read(ClassConstant),
ConstantTag.DOUBLE: bind_read(DoubleConstant),
ConstantTag.DYNAMIC: bind_read(DynamicConstant),
ConstantTag.FIELD_REF: bind_read(FieldRefConstant),
ConstantTag.FLOAT: bind_read(FloatConstant),
ConstantTag.INTEGER: bind_read(IntegerConstant),
ConstantTag.INTERFACE_METHOD_REF: bind_read(InterfaceMethodConstant),
ConstantTag.INVOKE_DYNAMIC: bind_read(InvokeDynamicConstant),
ConstantTag.LONG: bind_read(LongConstant),
ConstantTag.METHOD_REF: bind_read(MethodRefConstant),
ConstantTag.METHOD_HANDLE: bind_read(MethodHandleConstant),
ConstantTag.METHOD_TYPE: bind_read(MethodTypeConstant),
ConstantTag.MODULE: bind_read(ModuleConstant),
ConstantTag.NAME_AND_TYPE: bind_read(NameAndTypeConstant),
ConstantTag.PACKAGE: bind_read(PackageConstant),
ConstantTag.STRING: bind_read(StringConstant),
ConstantTag.UTF8: UTF8Constant.read,
}
def generate_constants(f: BufferedIOBase, n: int) -> Iterator[Constant]:
for _ in range(n):
tag_value, = f.read(1)
tag = ConstantTag(tag_value)
yield CONSTANT_READERS[tag](f)
def generate_attrs(f: BufferedIOBase, n: int) -> Iterator[AttributeInfo]:
for _ in range(n):
attr = read_struct(f, AttributeInfo)
attr.data = f.read(attr.attribute_length)
yield attr | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
class Class(NamedTuple):
major_version: int
minor_version: int
access_flags: ClassAccess
constants: tuple[Constant, ...]
this_class: Constant
super_class: Constant
interfaces: tuple[Constant, ...]
fields: tuple[FieldInfo, ...]
methods: tuple[MethodInfo, ...]
attributes: tuple[AttributeInfo, ...]
@classmethod
def deserialise(cls, f: BufferedIOBase) -> 'Class':
version = read_struct(f=f, type_=Version)
constant_pool_count = read_short(f)
constant_pool = tuple(generate_constants(f, n=constant_pool_count - 1))
access_flags = ClassAccess(read_short(f))
this_class = read_short(f)
super_class = read_short(f)
interfaces_count = read_short(f)
interfaces = read_indices(f=f, n=interfaces_count)
fields_count = read_short(f)
fields = [
(
field := read_struct(f, FieldInfo),
tuple(generate_attrs(f, field.attributes_count)),
)
for _ in range(fields_count)
]
methods_count = read_short(f)
methods = [
(
method := read_struct(f, MethodInfo),
tuple(generate_attrs(f, method.attributes_count)),
)
for _ in range(methods_count)
]
attributes_count = read_short(f)
attributes = tuple(generate_attrs(f, attributes_count))
trailing = len(f.read())
if trailing != 0:
raise ValueError(f'{trailing} trailing bytes after deserialise')
return cls._traverse(
version=version, constants=constant_pool, access_flags=access_flags,
this_idx=this_class, interfaces=interfaces,
super_idx=super_class, attributes=attributes,
fields=fields, methods=methods,
) | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
@classmethod
def _traverse(
cls,
version: Version,
constants: tuple[Constant, ...],
access_flags: ClassAccess,
this_idx: int,
super_idx: int,
interfaces: tuple[int, ...],
fields: list[
tuple[
FieldInfo,
tuple[AttributeInfo, ...],
]
],
methods: list[
tuple[
MethodInfo,
tuple[AttributeInfo, ...],
]
],
attributes: tuple[AttributeInfo, ...],
) -> 'Class':
field_constants = [field[0] for field in fields]
method_constants = [method[0] for method in methods]
all_nodes: tuple[Constant, ...] = (
*constants,
*field_constants,
*method_constants,
*chain.from_iterable(field[1] for field in fields),
*chain.from_iterable(method[1] for method in methods),
*attributes,
)
for constant in all_nodes:
for child_name in constant.CHILDREN:
varname = child_name.removesuffix('_index') + '_constant'
child = constants[getattr(constant, child_name)]
setattr(constant, varname, child)
for field, attrs in fields:
field.attributes = attrs
for method, attrs in methods:
method.attributes = attrs
return cls(
major_version=version.major_version,
minor_version=version.minor_version,
access_flags=access_flags,
constants=constants,
this_class=constants[this_idx],
super_class=constants[super_idx],
interfaces=tuple(
constants[idx] for idx in interfaces
),
fields=tuple(field_constants),
methods=tuple(method_constants),
attributes=attributes,
) | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
def dump(self, verbose: bool = False) -> Iterator[str]:
yield f'Version {self.major_version}.{self.minor_version}'
yield f'Class: {self.this_class}'
yield f'Super: {self.super_class}'
yield f'Access flags: {self.access_flags!r}'
yield 'Attributes:'
for attr in self.attributes:
yield f' {attr}'
yield 'Fields:'
for field in self.fields:
yield f' {field}'
yield 'Methods:'
for method in self.methods:
yield f' {method}'
yield 'Interfaces:'
for iface in self.interfaces:
yield f' {iface}'
if verbose:
yield 'Constant pool:'
for constant in self.constants:
yield f' {constant}'
def main() -> None:
_, file_path = sys.argv
with Path(file_path).open(mode='rb') as f:
class_ = Class.deserialise(f)
print('\n'.join(class_.dump(verbose=True)))
if __name__ == '__main__':
main()
Output (simple example)
Version 65.0
Class: I "comparator"
Super: ()V "TopByOrder"
Access flags: <ClassAccess.SUPER|PUBLIC: 33>
Attributes:
Ljava/util/Comparator<TE;>;
TopByOrder.java
InnerClasses
CountingComparator
Fields:
<FieldAccess.FINAL|PUBLIC: 17> I "comparator"
<FieldAccess.FINAL|PUBLIC: 17> Ljava/util/Comparator; "(ILjava/util/Comparator;)V"Ljava/util/Comparator<TE;>;
Methods:
<MethodAccess.PUBLIC: 1> ()V "java/util/Collection" @ LineNumberTable, Ljava/util/Comparator<TE;>;
<MethodAccess.PUBLIC: 1> (Ljava/util/Collection;)Ljava/util/PriorityQueue; "java/util/Collection" @ LineNumberTable, Ljava/util/Comparator<TE;>;
<MethodAccess.STATIC|PUBLIC: 9> ([Ljava/lang/String;)V "Ljava/lang/String;" @ LineNumberTable | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
python, java, parsing
Output (more complex example)
This one has Dynamics.
Version 65.0
Class: (Ljava/util/List;)Ljava/util/List; "(Ljava/util/List;)V"
Super: ()V "java/lang/Object"
Access flags: <ClassAccess.SUPER|FINAL|PUBLIC: 49>
Attributes:
MultipleGroupPermuterDemo.java
<ReferenceKind.invokeVirtual: 5> (Ljava/lang/Integer;)I "<ReferenceKind.invokeStatic: 6> (Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;"
Lookup
Fields:
Methods:
<MethodAccess.PUBLIC: 1> ()V "java/lang/Object" @ LineNumberTable
<MethodAccess.STATIC|PUBLIC: 9> ([Ljava/lang/String;)V "groupPermutation" @ LineNumberTable
<MethodAccess.STATIC|PRIVATE: 10> (Ljava/util/Map;)I "makeConcatWithConstants -> <init>" @ LineNumberTable, <T:Ljava/lang/Object;>(Ljava/util/Map<Ljava/util/List<Ljava/util/List<TT;>;>;Ljava/lang/Integer;>;)I
<MethodAccess.STATIC|PRIVATE: 10> (Ljava/util/List;)Ljava/lang/String; "java/io/PrintStream" @ LineNumberTable, <T:Ljava/lang/Object;>(Ljava/util/Map<Ljava/util/List<Ljava/util/List<TT;>;>;Ljava/lang/Integer;>;)I
<MethodAccess.STATIC|PRIVATE: 10> format "java/io/PrintStream" @ LineNumberTable, <T:Ljava/lang/Object;>(Ljava/util/Map<Ljava/util/List<Ljava/util/List<TT;>;>;Ljava/lang/Integer;>;)I
<MethodAccess.STATIC|PRIVATE: 10> (Ljava/util/List;)Ljava/util/List; "(Ljava/util/List;)V" @ LineNumberTable, <T:Ljava/lang/Object;>(Ljava/util/Map<Ljava/util/List<Ljava/util/List<TT;>;>;Ljava/lang/Integer;>;)I
<MethodAccess.STATIC|PRIVATE: 10> java/lang/System "computeGroupPermutations" @ LineNumberTable, <T:Ljava/lang/Object;>(Ljava/util/Map<Ljava/util/List<Ljava/util/List<TT;>;>;Ljava/lang/Integer;>;)I | {
"domain": "codereview.stackexchange",
"id": 45526,
"lm_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, java, parsing",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
Title: First order hidden Markov model with Viterbi algorithm in Java
Question: Introduction
A first order HMM (hidden Markov model) is a tuple \$(H, \Sigma, T, E, \mathbb{P})\$, where \$H = \{1, \ldots, \vert H \vert\}\$ is the set of hidden states, \$\Sigma\$ is the set of symbols, \$T \subseteq H \times H\$ is the set of transitions, \$E \subseteq H \times \Sigma\$ is the set of emissions, and \$\mathbb{P}\$ is the probability function for elements of \$T\$ and \$E\$, satisfying the following conditions:
There is a single start state \$h_{\texttt{start}} \in H\$ with no incoming transitions \$(h, h_{\texttt{start}}) \in T\$, and no emissions.
There is a single end state \$h_{\texttt{end}} \in H\$ with no out-going transitions \$(h_{\texttt{end}}, h) \in H\$, and no emissions.
Let \$\mathbb{P}(h \, \vert \, h^\prime)\$ denote the probability for the transition \$(h^\prime, h) \in T\$, and let \$\mathbb{P}(c \, \vert \, h)\$ denote the probability of an emission \$(h, c) \in E\$, for \$h^\prime, h \in H\$ and \$c \in \Sigma\$. It must hold that
$$
\sum_{h \in H} \mathbb{P}(h \, \vert \, h^\prime) = 1, \text{ for all } h^\prime \in H \setminus \{ h_{\texttt{end}} \},
$$
and
$$\sum_{c \in \Sigma} \mathbb{P}(c \, \vert \, h) = 1, \text{ for all } h \in H \setminus \{ h_{\texttt{start}}, h_{\texttt{end}} \}.$$ | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
A path through an HMM is a sequence \$P\$ of hidden states \$P=p_0p_1 \cdots p_n p_{n+1}\$, where \$(p_i, p_{i + 1}) \in T\$, for each \$i \in \{ 0, \ldots, n \}. \$ The joint probability of \$P\$ and a sequence \$S = s_1 s_2 \cdots s_n\$, with each \$s_i \in \Sigma,\$ is
$$
\mathbb{P}(P, S) = \prod_{i = 0}^n \mathbb{P}(p_{i + 1} \, \vert \, p_i) \prod_{i = 1}^n \mathbb{P}(s_i \, \vert \, p_i).
$$
Also, we define \$\mathcal{P}(n)\$ as the set of all paths \$p_0 p_1 \cdots p_{n + 1}\$ through the HMM, of length \$n + 2\$, such that \$p_0 = h_{\texttt{start}}\$ and \$p_{n + 1} = h_{\texttt{end}}.\$
We need to solve two problems here. First, we need to construct the most probable path \$P^{\star}\$ that accords the input sequence \$S\$:
$$
P^\star = \arg \max_{P \in \mathcal{P}(n)} \mathbb{P}(P,
S).
$$
Second, we want to generate all the sequence \$S\$ according state paths and return the sum of all state path probabilities:
$$
\mathbb{P}(S) = \sum_{P \in \mathcal{P}(n)} \mathbb{P}(P, S).
$$
Code
(The entire repository is in HiddenMarkovModel.java.)
com.github.coderodde.hmm.HiddenMarkovModel.java:
package com.github.coderodde.hmm;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
/**
* This class implements an HMM (hidden Markov model).
*/
public final class HiddenMarkovModel {
/**
* Used to denote the Viterbi matrix cells that are not yet computed.
*/
private static final double UNSET_PROBABILITY = -1.0;
/**
* The start state of the process.
*/
private final HiddenMarkovModelState startState;
/**
* The end state of the process.
*/
private final HiddenMarkovModelState endState;
private final Random random;
public HiddenMarkovModel(HiddenMarkovModelState startState,
HiddenMarkovModelState endState,
Random random) {
this.startState = startState;
this.endState = endState;
this.random = random;
}
public static double sumPathProbabilities(
List<HiddenMarkovModelStatePath> paths) {
double psum = 0.0;
for (HiddenMarkovModelStatePath path : paths) {
psum += path.getProbability();
}
return psum;
}
/**
* Performs a brute-force computation of the list of all possible paths in
* this HMM.
*
* @param sequence the target text.
* @return the list of sequences, sorted from most probable to the most
* improbable.
*/
public List<HiddenMarkovModelStatePath>
computeAllStatePaths(String sequence) {
int expectedStatePathSize = sequence.length() + 2;
List<List<HiddenMarkovModelState>> statePaths = new ArrayList<>();
List<HiddenMarkovModelState> currentPath = new ArrayList<>();
// BEGIN: Do the search:
currentPath.add(startState);
depthFirstSearchImpl(statePaths,
currentPath,
expectedStatePathSize,
startState);
// END: Searching done. | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
startState);
// END: Searching done.
// Construct the sequences:
List<HiddenMarkovModelStatePath> sequenceList =
new ArrayList<>(statePaths.size());
for (List<HiddenMarkovModelState> statePath : statePaths) {
sequenceList.add(
new HiddenMarkovModelStatePath(
statePath,
sequence,
this));
}
// Put into descending order by probabilities:
Collections.sort(sequenceList);
Collections.reverse(sequenceList);
return sequenceList;
}
/**
* Returns the most probable state path for the input sequence using the
* <a href="https://en.wikipedia.org/wiki/Viterbi_algorithm">
* Viterbi algorithm.</a>
*
* @param sequence the target sequence.
* @return the state path.
*/
public HiddenMarkovModelStatePath runViterbiAlgorithm(String sequence) {
// Get all the states reachable from the start state:
Set<HiddenMarkovModelState> graph = computeAllStates();
if (!graph.contains(endState)) {
// End state unreachable. Abort.
throw new IllegalStateException("End state is unreachable.");
}
// Maps the column index to the corresponding state:
Map<Integer, HiddenMarkovModelState> stateMap =
new HashMap<>(graph.size());
// Maps the state to the corresponding column index:
Map<HiddenMarkovModelState, Integer> inverseStateMap =
new HashMap<>(graph.size());
// Initialize maps for start and end states:
stateMap.put(0, startState);
stateMap.put(graph.size() - 1, endState);
inverseStateMap.put(startState, 0);
inverseStateMap.put(endState, graph.size() - 1); | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
inverseStateMap.put(startState, 0);
inverseStateMap.put(endState, graph.size() - 1);
int stateId = 1;
// Assign indices to hidden states:
for (HiddenMarkovModelState state : graph) {
if (!state.equals(startState) && !state.equals(endState)) {
stateMap.put(stateId, state);
inverseStateMap.put(state, stateId);
stateId++;
}
}
// Computes the entire Viterbi matrix:
double[][] viterbiMatrix =
computeViterbiMatrix(
sequence,
stateMap,
inverseStateMap);
// Uses the dynamic programming result reconstruction:
return tracebackStateSequenceViterbi(viterbiMatrix,
sequence,
stateMap,
inverseStateMap);
}
/**
* Returns the sum of probabilities over all the feasible paths that accord
* to the {@code sequence}.
*
* @param sequence the sequence text.
*
* @return the sum of probabilities.
*/
public double runForwardAlgorithm(String sequence) {
// Get all the states reachable from the start state:
Set<HiddenMarkovModelState> graph = computeAllStates();
if (!graph.contains(endState)) {
// End state unreachable. Abort.
throw new IllegalStateException("End state is unreachable.");
}
// Maps the column index to the corresponding state:
Map<Integer, HiddenMarkovModelState> stateMap =
new HashMap<>(graph.size());
// Maps the state to the corresponding column index:
Map<HiddenMarkovModelState, Integer> inverseStateMap =
new HashMap<>(graph.size()); | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
new HashMap<>(graph.size());
// Initialize maps for start and end states:
stateMap.put(0, startState);
stateMap.put(graph.size() - 1, endState);
inverseStateMap.put(startState, 0);
inverseStateMap.put(endState, graph.size() - 1);
int stateId = 1;
// Assign indices to hidden states:
for (HiddenMarkovModelState state : graph) {
if (!state.equals(startState) && !state.equals(endState)) {
stateMap.put(stateId, state);
inverseStateMap.put(state, stateId);
stateId++;
}
}
// Computes the entire forward matrix:
double[][] forwardMatrix =
computeForwardMatrix(
sequence,
stateMap,
inverseStateMap);
// Uses the dynamic programming result reconstruction:
return tracebackStateSequenceForward(forwardMatrix,
inverseStateMap);
}
/**
* Composes a sequence according to this HMM.
*
* @return a sequence.
*/
public String compose() {
StringBuilder sb = new StringBuilder();
HiddenMarkovModelState currentState = startState;
while (true) {
currentState = doStateTransition(currentState);
if (currentState.equals(endState)) {
// Once here, we are done:
return sb.toString();
}
sb.append(doEmit(currentState));
}
}
/**
* Computes the entire Viterbi matrix.
*
* @param sequence the input text.
* @param stateMap the state map. From column index to the state.
* @param inverseStateMap the inverse state map. From state to column index.
* | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
* @param inverseStateMap the inverse state map. From state to column index.
*
* @return the entire Viterbi matrix.
*/
private double[][] computeViterbiMatrix(
String sequence,
Map<Integer, HiddenMarkovModelState> stateMap,
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
double[][] matrix = new double[sequence.length() + 1]
[stateMap.size()];
// Set all required cells to unset sentinel:
for (int rowIndex = 1; rowIndex < matrix.length; rowIndex++) {
Arrays.fill(matrix[rowIndex], UNSET_PROBABILITY);
}
// BEGIN: Base case initialization.
matrix[0][0] = 1.0;
for (int columnIndex = 1;
columnIndex < matrix[0].length;
columnIndex++) {
matrix[0][columnIndex] = 0.0;
}
// END: Done with the base case initialization.
// Recursively build the matrix:
for (int h = 1; h < matrix[0].length - 1; h++) {
matrix[sequence.length()][h] =
computeViterbiMatrixImpl(
sequence.length(),
h,
matrix,
sequence,
stateMap,
inverseStateMap);
}
return matrix;
}
/**
* Computes the entire forward matrix.
*
* @param sequence the input text.
* @param stateMap the state map. From column index to the state.
* @param inverseStateMap the inverse state map. From state to column index.
*
* @return the entire Viterbi matrix.
*/
private double[][] computeForwardMatrix(
String sequence,
Map<Integer, HiddenMarkovModelState> stateMap,
Map<HiddenMarkovModelState, Integer> inverseStateMap) { | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
double[][] forwardMatrix = new double[sequence.length() + 1]
[stateMap.size()];
// Set all required cells to unset sentinel:
for (int rowIndex = 1; rowIndex < forwardMatrix.length; rowIndex++) {
Arrays.fill(forwardMatrix[rowIndex], UNSET_PROBABILITY);
}
// BEGIN: Base case initialization.
forwardMatrix[0][0] = 1.0;
for (int columnIndex = 1;
columnIndex < forwardMatrix[0].length;
columnIndex++) {
forwardMatrix[0][columnIndex] = 0.0;
}
// END: Done with the base case initialization.
// Recursively build the matrix:
for (int h = 1; h < forwardMatrix[0].length - 1; h++) {
forwardMatrix[sequence.length()][h] =
computeForwardMatrixImpl(
sequence.length(),
h,
forwardMatrix,
sequence,
stateMap,
inverseStateMap);
}
return forwardMatrix;
}
/**
* Computes the actual Viterbi matrix.
*
* @param i the {@code i} variable; the length of the sequence
* prefix.
* @param h the state index.
* @param viterbiMatrix the actual Viterbi matrix under construction.
* @param sequence the symbol sequence.
* @param stateMap the map mapping state IDs to states.
* @return
*/
private double computeViterbiMatrixImpl(
int i,
int h,
double[][] viterbiMatrix,
String sequence,
Map<Integer, HiddenMarkovModelState> stateMap,
Map<HiddenMarkovModelState, Integer> inverseStateMap) { | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
if (viterbiMatrix[i][h] != UNSET_PROBABILITY) {
return viterbiMatrix[i][h];
}
final int NUMBER_OF_STATES = stateMap.size();
if (h >= NUMBER_OF_STATES - 1) {
return UNSET_PROBABILITY;
}
if (h == 0) {
return i == 0 ? 1.0 : -1.0;
}
char symbol = sequence.charAt(i - 1);
HiddenMarkovModelState state = stateMap.get(h);
double psih = state.getEmissions().get(symbol);
Set<HiddenMarkovModelState> parentStates = state.getIncomingStates();
double maximumProbability = Double.NEGATIVE_INFINITY;
for (HiddenMarkovModelState parent : parentStates) {
double v =
computeViterbiMatrixImpl(
i - 1,
inverseStateMap.get(parent),
viterbiMatrix,
sequence,
stateMap,
inverseStateMap);
v *= parent.getFollowingStates().get(state);
maximumProbability = Math.max(maximumProbability, v);
}
viterbiMatrix[i][h] = maximumProbability * psih;
return viterbiMatrix[i][h];
}
/**
* Computes the actual forward matrix.
*
* @param i the {@code i} variable; the length of the sequence
* prefix.
* @param h the state index.
* @param forwardMatrix the actual Viterbi matrix under construction.
* @param sequence the symbol sequence.
* @param stateMap the map mapping state IDs to states.
*
* @return the forward matrix.
*/
private double computeForwardMatrixImpl(
int i,
int h, | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
*/
private double computeForwardMatrixImpl(
int i,
int h,
double[][] forwardMatrix,
String sequence,
Map<Integer, HiddenMarkovModelState> stateMap,
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
if (forwardMatrix[i][h] != UNSET_PROBABILITY) {
return forwardMatrix[i][h];
}
final int NUMBER_OF_STATES = stateMap.size();
if (h >= NUMBER_OF_STATES - 1) {
return UNSET_PROBABILITY;
}
if (h == 0) {
return i == 0 ? 1.0 : 0.0;
}
char symbol = sequence.charAt(i - 1);
HiddenMarkovModelState state = stateMap.get(h);
double psih = state.getEmissions().get(symbol);
Set<HiddenMarkovModelState> parentStates = state.getIncomingStates();
double totalProbability = 0.0;
for (HiddenMarkovModelState parent : parentStates) {
double f =
computeForwardMatrixImpl(
i - 1,
inverseStateMap.get(parent),
forwardMatrix,
sequence,
stateMap,
inverseStateMap);
f *= parent.getFollowingStates().get(state);
totalProbability += f ;
}
forwardMatrix[i][h] = totalProbability * psih;
return forwardMatrix[i][h];
}
private HiddenMarkovModelStatePath
tracebackStateSequenceViterbi(
double[][] viterbiMatrix,
String sequence,
Map<Integer, HiddenMarkovModelState> stateMap,
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
int bottomMaximumIndex = computeBottomMaximumIndex(viterbiMatrix); | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
int bottomMaximumIndex = computeBottomMaximumIndex(viterbiMatrix);
HiddenMarkovModelState bottomState = stateMap.get(bottomMaximumIndex);
List<HiddenMarkovModelState> stateList =
new ArrayList<>(viterbiMatrix[0].length);
stateList.add(endState);
final int HIGHEST_I = viterbiMatrix.length - 1;
tracebackStateSequenceImpl(viterbiMatrix,
HIGHEST_I,
bottomState,
stateList,
inverseStateMap);
stateList.add(startState);
Collections.reverse(stateList);
return new HiddenMarkovModelStatePath(stateList, sequence, this);
}
private double
tracebackStateSequenceForward(
double[][] forwardMatrix,
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
final int ROW_INDEX = forwardMatrix.length - 1;
double probability = 0.0;
Set<HiddenMarkovModelState> parents = endState.getIncomingStates();
for (HiddenMarkovModelState parent : parents) {
if (parent.equals(startState) || parent.equals(endState)) {
// Omit the start state:
continue;
}
int parentIndex = inverseStateMap.get(parent);
double p = forwardMatrix[ROW_INDEX][parentIndex];
p *= parent.getFollowingStates().get(endState);
probability += p;
}
return probability;
}
private void tracebackStateSequenceImpl(
double[][] viterbiMatrix,
int i,
HiddenMarkovModelState state,
List<HiddenMarkovModelState> stateList,
Map<HiddenMarkovModelState, Integer> inverseStateMap) { | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
if (state.equals(startState)) {
return;
}
stateList.add(state);
HiddenMarkovModelState nextState =
computeNextState(viterbiMatrix,
i,
state,
inverseStateMap);
tracebackStateSequenceImpl(viterbiMatrix,
i - 1,
nextState,
stateList,
inverseStateMap);
}
private HiddenMarkovModelState
computeNextState(
double[][] viterbiMatrix,
int i,
HiddenMarkovModelState state,
Map<HiddenMarkovModelState, Integer> inverseStateMap) {
Set<HiddenMarkovModelState> parents = state.getIncomingStates();
HiddenMarkovModelState nextState = null;
double maximumProbability = Double.NEGATIVE_INFINITY;
for (HiddenMarkovModelState parent : parents) {
int parentIndex = inverseStateMap.get(parent);
double probability = parent.getFollowingStates().get(state);
probability *= viterbiMatrix[i - 1][parentIndex];
if (maximumProbability < probability) {
maximumProbability = probability;
nextState = parent;
}
}
return nextState;
}
private int computeBottomMaximumIndex(double[][] viterbiMatrix) {
int maximumIndex = -1;
double maximumProbability = Double.NEGATIVE_INFINITY;
final int ROW_INDEX = viterbiMatrix.length - 1;
for (int i = 1; i < viterbiMatrix[0].length; i++) {
double currentProbability = viterbiMatrix[ROW_INDEX][i]; | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
double currentProbability = viterbiMatrix[ROW_INDEX][i];
if (maximumProbability < currentProbability) {
maximumProbability = currentProbability;
maximumIndex = i;
}
}
return maximumIndex;
}
private HiddenMarkovModelState
doStateTransition(HiddenMarkovModelState currentState) {
double coin = random.nextDouble();
for (Map.Entry<HiddenMarkovModelState, Double> e
: currentState.getFollowingStates().entrySet()) {
if (coin >= e.getValue()) {
coin -= e.getValue();
} else {
return e.getKey();
}
}
throw new IllegalStateException("Should not get here.");
}
private char doEmit(HiddenMarkovModelState currentState) {
double coin = random.nextDouble();
for (Map.Entry<Character, Double> e
: currentState.getEmissions().entrySet()) {
if (coin >= e.getValue()) {
coin -= e.getValue();
} else {
return e.getKey();
}
}
throw new IllegalStateException("Should not get here.");
}
private Set<HiddenMarkovModelState> computeAllStates() {
Deque<HiddenMarkovModelState> queue = new ArrayDeque<>();
Set<HiddenMarkovModelState> visited = new HashSet<>();
queue.addLast(startState);
visited.add(startState);
while (!queue.isEmpty()) {
HiddenMarkovModelState currentState = queue.removeFirst();
for (HiddenMarkovModelState followerState
: currentState.getFollowingStates().keySet()) {
if (!visited.contains(followerState)) {
visited.add(followerState); | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
visited.add(followerState);
queue.addLast(followerState);
}
}
}
return visited;
}
private void depthFirstSearchImpl(
List<List<HiddenMarkovModelState>> statePaths,
List<HiddenMarkovModelState> currentPath,
int expectedStatePathSize,
HiddenMarkovModelState currentState) {
if (currentPath.size() == expectedStatePathSize) {
// End recursion. If the current state equals the end state, we have
// a path:
if (currentState.equals(endState)) {
statePaths.add(new ArrayList<>(currentPath));
}
return;
}
// For each child, do...
for (HiddenMarkovModelState followerState
: currentState.getFollowingStates().keySet()) {
// Do state:
currentPath.add(followerState);
// Recur deeper:
depthFirstSearchImpl(statePaths,
currentPath,
expectedStatePathSize,
followerState);
// Undo state:
currentPath.remove(currentPath.size() - 1);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
com.github.coderodde.hmm.HiddenMarkovModelState.java:
package com.github.coderodde.hmm;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
/**
* This class defines the hidden states of a hidden Markov model.
*/
public final class HiddenMarkovModelState {
/**
* The ID of this state. Used to differentiating between the states.
*/
private final int id;
/**
* The state type of this state.
*/
private final HiddenMarkovModelStateType type;
/**
* Maps each transition target to the transition probability.
*/
private final Map<HiddenMarkovModelState, Double> transitionMap =
new HashMap<>();
/**
* Holds all incoming states.
*/
private final Set<HiddenMarkovModelState> incomingTransitions =
new HashSet<>();
/**
* Maps each emission character to its probability.
*/
private final Map<Character, Double> emissionMap = new HashMap<>();
public HiddenMarkovModelState(int id, HiddenMarkovModelStateType type) {
this.id = id;
this.type = type;
}
public int getId() {
return id;
}
public Map<HiddenMarkovModelState, Double> getFollowingStates() {
return Collections.unmodifiableMap(transitionMap);
}
public Map<Character, Double> getEmissions() {
return Collections.unmodifiableMap(emissionMap);
}
public Set<HiddenMarkovModelState> getIncomingStates() {
return Collections.unmodifiableSet(incomingTransitions);
}
public void normalize() {
normalizeEmissionMap();
normalizeTransitionMap();
}
public void addStateTransition(HiddenMarkovModelState followerState,
Double probability) {
if (type.equals(HiddenMarkovModelStateType.END)) {
throw new IllegalArgumentException(
"End HMM states may not have outgoing state transitions.");
}
transitionMap.put(followerState, probability);
followerState.incomingTransitions.add(this);
} | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
followerState.incomingTransitions.add(this);
}
public void addEmissionTransition(Character character, Double probability) {
switch (type) {
case START:
case END:
throw new IllegalArgumentException(
"Start and end HMM states may not have emissions.");
}
emissionMap.put(character, probability);
}
@Override
public boolean equals(Object o) {
return id == ((HiddenMarkovModelState) o).id;
}
@Override
public int hashCode() {
return id;
}
@Override
public String toString() {
return String.format("[HMM state, ID = %d, type = %s]", id, type);
}
private void normalizeTransitionMap() {
double sumOfProbabilities = computeTransitionProbabilitySum();
for (Map.Entry<HiddenMarkovModelState, Double> e
: transitionMap.entrySet()) {
e.setValue(e.getValue() / sumOfProbabilities);
}
}
private void normalizeEmissionMap() {
double sumOfProbabilities = computeEmissionProbabilitySum();
for (Map.Entry<Character, Double> e : emissionMap.entrySet()) {
e.setValue(e.getValue() / sumOfProbabilities);
}
}
private double computeTransitionProbabilitySum() {
double sumOfProbabilities = 0.0;
for (Double probability : transitionMap.values()) {
sumOfProbabilities += probability;
}
return sumOfProbabilities;
}
private double computeEmissionProbabilitySum() {
double sumOfProbabilities = 0.0;
for (Double probability : emissionMap.values()) {
sumOfProbabilities += probability;
}
return sumOfProbabilities;
}
} | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
com.github.coderodde.hmm.HiddenMarkovModelStatePath.java:
package com.github.coderodde.hmm;
import static java.lang.Math.E;
import static java.lang.Math.log;
import static java.lang.Math.pow;
import java.util.List; | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
/**
* This class stores the state path over the hidden states of an HMM.
*/
public final class HiddenMarkovModelStatePath
implements Comparable<HiddenMarkovModelStatePath> {
private final List<HiddenMarkovModelState> stateSequence;
private final double probability;
HiddenMarkovModelStatePath(List<HiddenMarkovModelState> stateSequence,
String observedSymbols,
HiddenMarkovModel hiddenMarkovModel) {
this.stateSequence = stateSequence;
this.probability = computeJointProbability(observedSymbols);
}
public int size() {
return stateSequence.size();
}
public HiddenMarkovModelState getState(int stateIndex) {
return stateSequence.get(stateIndex);
}
public double getProbability() {
return probability;
}
@Override
public int compareTo(HiddenMarkovModelStatePath o) {
return Double.compare(probability, o.probability);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (HiddenMarkovModelState state : stateSequence) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(state.getId());
}
sb.append("| p = ");
sb.append(probability);
sb.append("]");
return sb.toString();
}
/**
* Computes the joint probability of this path.
*
* @param observedSymbols the observation text.
*
* @return the joint probability of this path and the input text.
*/
private double computeJointProbability(String observedSymbols) {
double logProbability = computeEmissionProbabilities(observedSymbols) + | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
double logProbability = computeEmissionProbabilities(observedSymbols) +
computeTransitionProbabilities();
// Convert to probability:
return pow(E, logProbability);
}
/**
* Computes the product of emission probabilities over the input text.
*
* @param observedSymbols the input text.
*
* @return the total emission probability.
*/
private double computeEmissionProbabilities(String observedSymbols) {
double probability = 0.0;
for (int i = 0; i != observedSymbols.length(); i++) {
char observedSymbol = observedSymbols.charAt(i);
HiddenMarkovModelState state = stateSequence.get(i + 1);
probability += log(state.getEmissions().get(observedSymbol));
}
return probability;
}
/**
* Computes the product of transition probabilities over this path.
*
* @return the product of transitions.
*/
private double computeTransitionProbabilities() {
double probability = 0.0;
for (int i = 0; i < stateSequence.size() - 1; i++) {
HiddenMarkovModelState sourceState = stateSequence.get(i);
HiddenMarkovModelState targetState = stateSequence.get(i + 1);
probability += log(sourceState.getFollowingStates()
.get(targetState));
}
return probability;
}
} | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
com.github.coderodde.hmm.demo.HMMDemo.java:
package com.github.coderodde.hmm.demo;
import com.github.coderodde.hmm.HiddenMarkovModel;
import com.github.coderodde.hmm.HiddenMarkovModelState;
import com.github.coderodde.hmm.HiddenMarkovModelStatePath;
import com.github.coderodde.hmm.HiddenMarkovModelStateType;
import java.util.List;
import java.util.Random; | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
/**
* This class implements the demonstration of the hidden Markov model.
*/
public final class HMMDemo {
public static void main(String[] args) {
Random random = new Random(13L);
HiddenMarkovModelState startState =
new HiddenMarkovModelState(0, HiddenMarkovModelStateType.START);
HiddenMarkovModelState endState =
new HiddenMarkovModelState(3, HiddenMarkovModelStateType.END);
HiddenMarkovModelState codingState =
new HiddenMarkovModelState(
1,
HiddenMarkovModelStateType.HIDDEN);
HiddenMarkovModelState noncodingState =
new HiddenMarkovModelState(
2,
HiddenMarkovModelStateType.HIDDEN);
HiddenMarkovModel hmm = new HiddenMarkovModel(startState,
endState,
random);
// BEGIN: State transitions.
startState.addStateTransition(noncodingState, 0.49);
startState.addStateTransition(codingState, 0.49);
startState.addStateTransition(endState, 0.02);
codingState.addStateTransition(codingState, 0.4);
codingState.addStateTransition(endState, 0.3);
codingState.addStateTransition(noncodingState, 0.3);
noncodingState.addStateTransition(noncodingState, 0.3);
noncodingState.addStateTransition(codingState, 0.35);
noncodingState.addStateTransition(endState, 0.35);
// END: State transitions.
// BEGIN: Emissions.
codingState.addEmissionTransition('A', 0.18);
codingState.addEmissionTransition('C', 0.32);
codingState.addEmissionTransition('G', 0.32);
codingState.addEmissionTransition('T', 0.18); | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
codingState.addEmissionTransition('T', 0.18);
noncodingState.addEmissionTransition('A', 0.25);
noncodingState.addEmissionTransition('C', 0.25);
noncodingState.addEmissionTransition('G', 0.25);
noncodingState.addEmissionTransition('T', 0.25);
// END: Emissions.
startState.normalize();
codingState.normalize();
noncodingState.normalize();
endState.normalize();
System.out.println("--- Composing random walks ---");
for (int i = 0; i < 10; i++) {
int lineNumber = i + 1;
System.out.printf("%2d: %s\n", lineNumber, hmm.compose());
}
String sequence = "AGCG";
List<HiddenMarkovModelStatePath> statePathSequences =
hmm.computeAllStatePaths(sequence);
System.out.printf("Brute-force path inference for sequence \"%s\", " +
"total probability = %f.\n",
sequence,
HiddenMarkovModel.sumPathProbabilities(
statePathSequences));
double hmmProbabilitySum = hmm.runForwardAlgorithm(sequence);
System.out.printf("HMM total probability: %f.\n", hmmProbabilitySum);
System.out.println("Brute-force state paths:");
int lineNumber = 1;
for (HiddenMarkovModelStatePath stateSequence : statePathSequences) {
System.out.printf("%4d: %s\n", lineNumber++, stateSequence);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
com.github.coderodde.hmm.demo.HiddenMarkovModelStateType.java:
package com.github.coderodde.hmm;
public enum HiddenMarkovModelStateType {
START,
HIDDEN,
END;
@Override
public String toString() {
switch (this) {
case START:
return "S";
case HIDDEN:
return "H";
case END:
return "E";
default:
throw new EnumConstantNotPresentException(
HiddenMarkovModelStateType.class,
"Unknown enum constant: " + this);
}
}
}
Critique request
Please, tell me anything that comes to mind.
Answer: In your repository, you need to de-indent all of HiddenMarkovModel.java.
sumPathProbabilities can be written in stream form as
double psum = paths.stream()
.mapToDouble(HiddenMarkovModelStatePath::getProbability)
.sum();
and that function should not accept a List; it should accept the more-general Collection.
Similarly, the computeProbabilitySum() methods can look like
transitionMap.values().stream().reduce(Double::sum).get() | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
java, algorithm, statistics, bioinformatics, markov-chain
The HiddenMarkovModelStatePath does not use its last constructor parameter so you should delete that.
Speaking generally, you would benefit from moving to an immutable functional style, but this will not be an easy transition for the code overall. For example, you'll want to avoid functions of the form loadStateMaps which mutates its second and third parameters; but this applies in a lot of other situations.
For final members of primitive type like id and type that also have get() accessors, the only reason you'd want to keep the accessor is if it's used in a functional member reference. If there's no functional member reference, delete the accessor. Make the member public.
In HiddenMarkovModelStatePath::toString(), the first/append(", ") logic can be cleaned up by using one of the standard join collectors.
Rewrite your StateType toString() switch as
@Override
public String toString() {
return switch (this) {
case START -> "S";
case HIDDEN -> "H";
case END -> "E";
};
}
Note that the default case is not necessary, because there's no way for an already-constructed instance to have a value other than what you've shown.
In your printf calls, replace \n with %n for portability. | {
"domain": "codereview.stackexchange",
"id": 45527,
"lm_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, algorithm, statistics, bioinformatics, markov-chain",
"url": null
} |
performance, c, strings, io
Title: Read a line from a stream
Question: Since the standard fgets() does not suffice for my use cases, as it doesn't automatically enlarge the target buffer if needed, and getline()/fgetln() are not part of the C standard, I rolled out my own.
Code:
The code below is listed as one file for code review.
#define TEST_MAIN // Or pass this with make/gcc.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
/*
* Reads the next line from the stream pointed to by `stream`.
*
* The line is terminated by a NUL character.
* On success, the memory pointed to by `len` shall contain the length of the line
* (including the terminating NUL character).
* The returned line does not contain a newline.
*
* Upon successful completion a pointer is returned, otherwise NULL is returned.
* `fgetline()` does not distinguish between end-of-file and error; the routines
* `feof()` and `ferror()` must be used to determine which occurred.
*/
char *fgetline(FILE *stream, size_t *len)
{
clearerr(stream);
char *line = NULL;
size_t capacity = 0;
size_t size = 0;
while (true) {
if (size >= capacity) {
char *const tmp = realloc(line, capacity += BUFSIZ);
if (!tmp) {
free(line);
return NULL;
}
line = tmp;
}
if (!fgets(line + size, BUFSIZ, stream)) {
if (ferror(stream)) {
free(line);
return NULL;
}
break;
}
if (strpbrk(line, "\n\r")) {
break;
}
size += BUFSIZ;
}
if (feof(stream) && size == 0) {
free(line);
return NULL;
}
/* TODO: Shrink the memory chunk here. */
*len = strcspn(line, "\n\r");
line[*len] = '\0';
*len += 1;
return line;
}
#ifdef TEST_MAIN
#include <assert.h> | {
"domain": "codereview.stackexchange",
"id": 45528,
"lm_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, c, strings, io",
"url": null
} |
performance, c, strings, io
#ifdef TEST_MAIN
#include <assert.h>
int main(int argc, char **argv)
{
assert(argv[1]);
FILE *fp = fopen(argv[1], "rb");
assert(fp);
size_t size = 0;
assert(!strcmp(fgetline(fp, &size), "12"));
assert(size == 3);
assert(!strcmp(fgetline(fp, &size), "AB"));
assert(size == 3);
assert(!strcmp(fgetline(fp, &size), "123"));
assert(size == 4);
assert(!strcmp(fgetline(fp, &size), "ABC"));
assert(size == 4);
assert(!strcmp(fgetline(fp, &size), "1234"));
assert(size == 5);
assert(!strcmp(fgetline(fp, &size), "ABCD"));
assert(size == 5);
rewind(fp);
char *res = NULL;
while ((res = fgetline(fp, &size)) != NULL) {
printf("Line read: \"%s\", line length: %zu, string length: %zu\n", res, size, strlen(res));
}
assert(!fgetline(fp, &size));
assert(feof(fp));
return EXIT_SUCCESS;
}
#endif /* TEST_MAIN */
prints:
Line read: "12", line length: 3, string length: 2
Line read: "AB", line length: 3, string length: 2
Line read: "123", line length: 4, string length: 3
Line read: "ABC", line length: 4, string length: 3
Line read: "1234", line length: 5, string length: 4
Line read: "ABCD", line length: 5, string length: 4
Line read: "", line length: 1, string length: 0
where the sample text file contained:
12
AB
123
ABC
1234
ABCD
^@^@^@^@
The last line contains 4 NUL characters, courtesy of fputc(0, fp).
Review Request:
Are there any bugs in the code?
Are there any edge cases I have missed?
Does the function provide what's expected of a good line-reading function?
If there are embedded NUL characters in the line, the function returns the string up to the first NUL character. Was that a bad decision to take?
Answer: A real good get line function is tricky and sadly missing in standard C.
Are there any bugs in the code?
See below.
Are there any edge cases I have missed?
See below.
Does the function provide what's expected of a good line-reading function? | {
"domain": "codereview.stackexchange",
"id": 45528,
"lm_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, c, strings, io",
"url": null
} |
performance, c, strings, io
See below.
Does the function provide what's expected of a good line-reading function?
Overall a fairly good effort. Yet buffer allocating O(n*n) and use of clearerr() are amiss.
If there are embedded NUL characters in the line, the function returns the string up to the first NUL character. Was that a bad decision to take?
A get line function that returns length should be able to cope with reading null characters. If not, why have a len parameter as calling code can simply perform strlen() to determine the length?
Questionable clearerr(stream)?
fgets(), fscanf() and others do not clear the error flag and end-of-file flags. The choice to do that is usually left to the calling code, not the get line code. I'd expect fgetline() to correctly operate with the error and end-of-file flags in either state upon function entry and to not employ a clearerr().
Concerning if (ferror(stream)) {, consider using if (!feof(stream)) { to not get fooled by an end-of-file with the error flag set prior to this call.
Is it possible to distinguish the error returned by fgets
*len on failure
Code has "On success, the memory pointed to by len shall contain the length of the line ...", but is silent on what happens when the is a failure. Perhaps add that *len is unchanged on failure.
Consider *len should be set in all cases with 0 on failure.
Code assumes a null character is not read
strpbrk(line, "\n\r") and strcspn(line, "\n\r") will not detect data read beyond the first '\0' in the buffer. There will be multiple '\0' in line when a null character is read, the ones read and the one appended.
Properly handling the reading of a null character is tricky.
Bug?: Code assumes a '\r' ends the line
strpbrk(line, "\n\r") and strcspn(line, "\n\r") performed as if the line stopped at '\r'. Consider a line of user input such as "abc\rdef\r\n". | {
"domain": "codereview.stackexchange",
"id": 45528,
"lm_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, c, strings, io",
"url": null
} |
performance, c, strings, io
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. ... C23dr § 7.23.2 2
What makes for a raw terminating new-line character varies between systems - it is implementation dependent. Trying to make a universal detector of line terminator is tricky should code encounter text files from local and "foreign" sources.
File open in binary mode?
If this fgetline() requires the stream is opened in text or binary, that requirement needs to be documented. Better if the function works well in either case.
Redundant work
*len = strcspn(line, "\n\r") rescans the initial portion of line that is known not to contain "\n\r". Something like *len = strcspn(line + (size - BUFSIZ), "\n\r") + (size - BUFSIZ); can avoid that.
Surprising "length"
*len += 1; does follow "all contain the length of the line * (including the terminating NUL character)." yet maybe something other than length is warranted - like size or count or .... With strings, "length" is tied closely to the return value of strlen() and that differs by 1 here.
FWIW, I see advantages of code returning this + 1 count, especially when code changed to set the *len to 0 on error.
Minor: NUL vs. null character`
Consider using null character.
C defines null character and only uses NUL in a footnote referring to ASCII.
ASCII defines NUL.
When NULL is returned
I see 3 cases:
End-of-file and nothing read.
Input error
Memory allocation failure. | {
"domain": "codereview.stackexchange",
"id": 45528,
"lm_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, c, strings, io",
"url": null
} |
performance, c, strings, io
End-of-file and nothing read.
Input error
Memory allocation failure.
The last case is not documented in the fgetline() preface.
Minor: Big buffers
BUFSIZ is at least 256 so each line read can have a cumulative significant extra size. Consider a final realloc() to right-size the buffer - or warn about these inefficient allocations.
I suppose that is all implied with the TODO: Shrink the memory chunk here.
Minor: buffer growth
line grows linearly and so can make for O(len*len) for long lines. More complexity, but other approaches have advantages.
One way that is O(len) is to form a linked list of BUFSIZ buffers and then collect them as one in the end.
Testing
Code only tested in binary mode with FILE *fp = fopen(argv[1], "rb");, yet fgetline() more likely used in text mode.
.h file
Consider a preceding
#include < ... >
// documentation
char *fgetline(FILE *stream, size_t *len);
and then
#include < ... >
char *fgetline(FILE *stream, size_t *len) {
To convey how one would present this function in a typical header file. | {
"domain": "codereview.stackexchange",
"id": 45528,
"lm_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, c, strings, io",
"url": null
} |
python, google-bigquery, google-cloud-platform
Title: Trigger Cloud Function with Eventarc and then extract BigQuery table as csv files
Question: Problem:
Whenever new data are inserted, extract BigQuery tables as csv files and
store them in Cloud Storage.
My plan:
Set up an Eventarc trigger based on Event method
google.cloud.bigquery.v2.JobService.InsertJob for Cloud Function to identify when new data are inserted into BigQuery.
from google.cloud import bigquery
import functions_framework
client = bigquery.Client()
bucket_name = "bucket"
project = "astute-coda-410816"
dataset_id = "dataset"
def move_data(table):
#extract BigQuery table
destination_uri = f"gs://{bucket_name}/{table}/{table}-*.csv"
dataset_ref = bigquery.DatasetReference(project,dataset_id)
table_ref = dataset_ref.table(f"{table}")
job_config = bigquery.job.ExtractJobConfig(print_header=False)
client.extract_table(table_ref, destination_uri, location="US",job_config=job_config)
print(f"Exported {project}:{dataset_id}.{table} to {destination_uri}")
@functions_framework.cloud_event
def transfer(cloudevent):
payload = cloudevent.data.get("protoPayload")
status = payload.get("status")
if not status: #if status is empty, the insert job is successful and tables should be extracted to Cloud Storage
move_data("table_1")
move_data("table_2")
move_data("table_3")
My questions are:
Anything else I should do to improve my code?
Is there a way to run in parallel the data transfer for all 3 tables?
Answer: Looks good.
optional type annotation
This would be a better signature:
def move_data(table: str) -> None:
It turns out we're really passing in a table name,
rather than some fancy table object.
I didn't learn that detail until I got down to the calling code.
This line mislead me:
... = dataset_ref.table(f"{table}") | {
"domain": "codereview.stackexchange",
"id": 45529,
"lm_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, google-bigquery, google-cloud-platform",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.