text stringlengths 1 2.12k | source dict |
|---|---|
php, pdo
$myQuery->insert_query($insert_query);
print_r($myQuery->commit());
Thank you for your help!
Answer: I don't like the approach from the other answer as it violates the single responsibility principle. A function called insert_query shouldn't do things unrelated to, well, insert. And at the same time it is severely limiting your SQL. Let alone a straight up SQL injection.
But I understand the desire to encapsulate the regular transaction routine, i.e.
try {
$pdo->beginTransaction();
foreach ($data as $row)
{
$pdo->prepare($row['sql'])->execute($row['params']);
}
$pdo->commit();
}catch (\Throwable $e){
$pdo->rollback();
throw $e;
}
to make this code less boilerplate-looking. I would suggest the approach used in Laravel's Eloquent: a function that accepts anonymous function as a parameter. It gives you the separation concerns and enormous flexibility: not only insert queries are allowed but any kind of query or even PHP code inbetween.
So it could be like
class MyQuery
{
public $dbConn;
public function __construct($dbConn) {
$this->dbConn = $dbConn;
}
public function query($query, $params) {
$stmt = $this->dbConn->prepare($query);
$stmt->execute($params);
return $stmt;
}
public function transaction(Callable $f)
{
try {
$this->dbConn->beginTransaction();
$return = $f($this);
$this->dbConn->commit();
return $return;
} catch (\Throwable $e) {
$this->dbConn->rollBack();
throw $e;
}
}
}
So it can be used like this
$myQuery->transaction( function () use (/* variables you need*/) {
// write any code you want to wrap into transaction
}); | {
"domain": "codereview.stackexchange",
"id": 43587,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, pdo",
"url": null
} |
php, pdo
and then using this generic transaction() method we can create a helper function for the specific multiple queries case
public function multiQueryTransaction($queries)
{
$this->transaction( function () use ($queries) {
foreach ($queries as $row)
{
$this->query($row['query'], $row['params']);
}
});
}
So the final code would be like
$insert_query[] = [
"query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => [":name" => "Name Test", ":text" => "Text Test"],
];
$insert_query[] = [
"query" => "INSERT INTO mytable (name, text) VALUES (:name, :text);",
"params" => [":name" => "Another Name", ":text" => "Another Text"],
];
$pdo = new PDO ...;
$myQuery = new MyQuery($pdo);
$myQuery->multiQueryTransaction($insert_query);
Also, regarding the MyQuery() class in general, I would recommend to read this coding standard
and this article of mine, Your first database wrapper's childhood diseases that can explain some flaws and obsoleted parts in the existing code that I fixed in my version. | {
"domain": "codereview.stackexchange",
"id": 43587,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, pdo",
"url": null
} |
c#, .net, asp.net-core, producer-consumer
Title: ASP.NET Core background logger queue with dynamic workers
Question: In a docker compose environment there are several apps that communicate with each other. One of these apps is a logger (a centralized logger). Every part of the system that needs to log something, will call the logger's APIs (which is written with gRPC).
The logger adds these log requests to a queue (a BlockingCollection) which will be consumed by workers. These workers will read from queue and store them in DB. In order to reduce DB calls, they will use a local buffer. That buffer will be flushed every (n) seconds or after getting (m) records.
These workers need to dynamically be created or disposed based on how many items are in the queue. For example for each (n) items there should be a worker.
This is the big picture:
And now the implementation,
The log entity:
public class ActivityLog
{
public string Id { get; set; }
public IPAddress IpAddress { get; set; }
public string? Parameters { get; set; }
// ...
}
gRPC proto contract:
syntax = "proto3";
import "google/protobuf/empty.proto";
import "google/protobuf/wrappers.proto";
package logger;
service Logger {
rpc LogActivity (ActivityLogPayload) returns (google.protobuf.Empty);
}
message ActivityLogPayload {
string ip_address = 1;
google.protobuf.StringValue parameters = 2;
// ...
}
gRPC service:
public class LoggerRpc : Logger.LoggerBase
{
private readonly LogQueue queue;
public LoggerRpc(LogQueue queue)
{
this.queue = queue;
}
public override Task<Empty> LogActivity(ActivityLogPayload request, ServerCallContext context)
{
var logEntity = request.ToEntity();
queue.ActivityLogsCollection.Add(logEntity);
return Task.FromResult(new Empty());
}
}
The log queue:
public class LogQueue
{
public BlockingCollection<ActivityLog> ActivityLogsCollection { get; }
public LogQueue()
{
ActivityLogsCollection = new(10_000);
}
} | {
"domain": "codereview.stackexchange",
"id": 43588,
"lm_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#, .net, asp.net-core, producer-consumer",
"url": null
} |
c#, .net, asp.net-core, producer-consumer
public LogQueue()
{
ActivityLogsCollection = new(10_000);
}
}
The worker:
public class LogWorker : IDisposable
{
private const int BufferThreshold = 100;
private readonly TimeSpan BufferTimeLimit = TimeSpan.FromSeconds(5);
private DateTimeOffset lastDbUpdate = DateTimeOffset.UtcNow;
private readonly BlockingCollection<ActivityLog> queue;
private readonly IServiceScopeFactory ssf;
private CancellationTokenSource cts = new();
private Task workerTask;
public LogWorker(
BlockingCollection<ActivityLog> queue,
IServiceScopeFactory ssf)
{
this.queue = queue;
this.ssf = ssf;
workerTask = new Task(Work, TaskCreationOptions.LongRunning);
workerTask.Start(TaskScheduler.Default);
}
private void Work()
{
using var scope = ssf.CreateScope();
using var dbContext = scope.ServiceProvider.GetRequiredService<LogDbContext>();
var localBuffer = new List<ActivityLog>();
ActivityLog? nextItem;
try
{
while (queue.TryTake(out nextItem, -1, cts.Token))
{
localBuffer.Add(nextItem);
// make a DB call when we have 100 logs
// or 5 seconds has passes from last DB call
while (localBuffer.Count < BufferThreshold
&& DateTime.UtcNow - lastDbUpdate < BufferTimeLimit)
{
// wait for the remaining time of our 5 second window
var waitTime = (int)(BufferTimeLimit - (DateTime.UtcNow - lastDbUpdate)).TotalMilliseconds;
if (queue.TryTake(out nextItem, waitTime, cts.Token))
localBuffer.Add(nextItem);
}
dbContext.AddRange(localBuffer);
dbContext.SaveChanges(); | {
"domain": "codereview.stackexchange",
"id": 43588,
"lm_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#, .net, asp.net-core, producer-consumer",
"url": null
} |
c#, .net, asp.net-core, producer-consumer
dbContext.AddRange(localBuffer);
dbContext.SaveChanges();
localBuffer.Clear();
lastDbUpdate = DateTime.UtcNow;
}
}
catch (ObjectDisposedException)
{
// queue completed
}
catch(OperationCanceledException)
{
// worker is shutting down
}
finally
{
// clear the buffer
if (localBuffer.Any())
{
dbContext.AddRange(localBuffer);
dbContext.SaveChanges();
}
}
}
public void Dispose()
{
cts.Cancel();
workerTask.Wait();
}
}
Worker manager:
public class LogWorkerManager : IHostedService
{
private const int MinimumWorkersCount = 2;
private const int LogsThreshold = 200;
private readonly TimeSpan TimerInterval = TimeSpan.FromSeconds(2);
private readonly List<LogWorker> workers = new();
private readonly LogQueue queue;
private readonly IServiceScopeFactory ssf;
Timer? timer;
public LogWorkerManager(
LogQueue queue,
IServiceScopeFactory ssf)
{
this.queue = queue;
this.ssf = ssf;
}
private void MonitorQueue(object? state)
{
var workersNeeded = (queue.ActivityLogsCollection.Count / LogsThreshold) + 1;
workersNeeded = Math.Max(workersNeeded, MinimumWorkersCount);
if (workers.Count > workersNeeded)
{
// gradually reduce workers
var worker = workers.Last();
worker.Dispose();
workers.Remove(worker);
}
else if (workers.Count < workersNeeded)
{
for (int i = 0; i < workersNeeded - workers.Count; i++)
{
var worker = new LogWorker(queue.ActivityLogsCollection, ssf);
workers.Add(worker);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43588,
"lm_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#, .net, asp.net-core, producer-consumer",
"url": null
} |
c#, .net, asp.net-core, producer-consumer
public Task StartAsync(CancellationToken cancellationToken)
{
timer = new(MonitorQueue, null, 0, (int)TimerInterval.TotalMilliseconds);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
timer?.Change(Timeout.Infinite, Timeout.Infinite);
timer?.Dispose();
Parallel.ForEach(workers, worker => worker.Dispose());
return Task.CompletedTask;
}
}
DI:
builder.Services.AddSingleton<LogQueue>();
builder.Services.AddHostedService<LogWorkerManager>();
Answer: This looks like an XY-problem.
The only work done in the worker is the DB Insert. If the worker can't keep up it's because the DB can't keep up. By creating additional workers the work is just moved to a new queue without a limit.
DbContext is not designed to be long living.
The items added to the context will continue to be tracked until cleared or disposed.
This could be the source of poor performance. | {
"domain": "codereview.stackexchange",
"id": 43588,
"lm_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#, .net, asp.net-core, producer-consumer",
"url": null
} |
javascript, comparative-review
Title: Show numbers per step count
Question: I have a problem where I need to display the below output
1
23
456
78910
My first solution is
let numberStepper = (stepLimit) => {
let stepCounter = 0;
let step = '';
for(let row = 1; row <= stepLimit; row++) {
step = '';
for(let col = 1; col <= row; col++) {
stepCounter++;
step += `${stepCounter}`
}
if(stepCounter > stepLimit) {
break;
}
console.log(step);
}
}
numberStepper(10) // Gives desired output
Another solution that limits the number of steps output is below.
let numberStepper = (stepsLimit) => {
let stepCounter = 0;
let step = '';
for(let row = 1; row <= stepsLimit; row++) {
step = '';
for(let col = 1; col <= row; col++) {
stepCounter++;
step += `${stepCounter}`
}
console.log(step);
}
}
numberStepper(4) // Gives desired output
How can I refactor this function to have a clean implementation?
Any ideas on the first implementation? where the argument determines the numbers displayed in the steps instead of using the number of steps as the determinant of the numbers displayed?
Answer: functions should return a value
It's unprofessional to use console.log for the output of a function. It's better to think of functions as a blackbox where you give it an input and it spits back an output.
If you were to write unit tests for your function, you would have to go out of your way to either mock console.log to see if it's used properly or to read directly from stdout. Those aren't the easiest options.
give meaningful variable and function names
It's not intuitively easy to understand what the variable names are intended to represent.
For example, step should probably be renamed to row or numbersOnRow or even rowString. | {
"domain": "codereview.stackexchange",
"id": 43589,
"lm_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, comparative-review",
"url": null
} |
javascript, comparative-review
Here is an alternative way that reduces the complexity. It follows the pattern that the length of each row increases by one consecutively. So in the end, no real need to have a double for loop. You can simply populate a list with all the values, and then loop through it once to build your output.
const numberStepper = (stepLimit) => {
// build list with prefilled values
const list = (new Array(stepLimit))
.fill(undefined)
.map((_,i) => i + 1);
const result = [];
for(let i = 0, j = 1; i < list.length; i+=j, j++) {
result.push(list.slice(i, i+j));
}
// format
return result.map(row => row.join('')).join('\n');
}
const result = numberStepper(10);
console.log(result); | {
"domain": "codereview.stackexchange",
"id": 43589,
"lm_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, comparative-review",
"url": null
} |
sql, sql-server, t-sql
Title: Find dogs who stopped being good boys without ever being good boys - Was HAVING the wrong approach?
Question: The problem I have solved is as follows:
Consider a table of dogs, DOGGIES, that records on each row the ID of a doggy, one skill that they have, when they started having it, when they stopped having it (assume a useful placeholder if they never stop), and an extra bool column called IS_NO_LONGER_GOOD_BOY. This bool column is magically a property of the skill and not of the dog or the history. Find every doggy who has a skill with a 0 value for IS_NO_LONGER_GOOD_BOY without, at some point in time, having that same skill with a 1 value for IS_NO_LONGER_GOOD_BOY. For each doggy found, return the IS_NO_LONGER_GOOD_BOY = 0 row(s) that caused them to appear.
Doggies can have multiple skills at any given time, but doggies with no skills aren't in the data. There is no need to worry about NULLs, malformed data, or other such traps. | {
"domain": "codereview.stackexchange",
"id": 43590,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
This was my solution. It works, but the code comments explain my dislike of it.
SELECT [ID], [SKILL_NAME], [START_DATE], [STOP_DATE], [IS_NO_LONGER_GOOD_BOY]
FROM [DOGGIES] AS [DOGS_OUT] --Not sure if the alias is needed, but it adds clarity?
WHERE EXISTS
(
SELECT 1
FROM
--Really don't like this bit.
--This SELECT 1 part only exists so I can write a WHERE after the indented query's HAVING.
--You'd really think there'd be a way to put this inside the indented query.
--But the innermost query needs the HAVING part, so I think it's inescapable?
(
SELECT [ID], [SKILL_NAME]
FROM [DOGGIES]
GROUP BY [ID], [SKILL_NAME]
HAVING
COUNT(CASE WHEN [IS_NO_LONGER_GOOD_BOY] = 0 THEN 1 END) > 0 --SQL has no COUNTIF
AND
COUNT(CASE WHEN [IS_NO_LONGER_GOOD_BOY] = 1 THEN 1 END) = 0
) AS [DOG_SKILL_PAIRS]
WHERE
[DOG_SKILL_PAIRS].[ID] = [DOGS_OUT].[ID]
AND
[DOG_SKILL_PAIRS].[SKILL_NAME] = [DOGS_OUT].[SKILL_NAME]
)
My question is simply if what I've done can be improved upon. Some suspicions of mine are as following:
I get the feeling that all of this code should only need at most one level of nesting, rather than having a correlated subquery inside the outermost query.
Working from the innermost layer outwards, I don't like how I've gone from a HAVING clause without a WHERE clause to a WHERE clause that filters the result of the HAVING clause. You typically go from WHERE to HAVING, not the other way around.
Can window functions save the day? COUNT(CASE WHEN [IS_NO_LONGER_GOOD_BOY] = 0 THEN 1 END) OVER (PARTITION BY [ID], [SKILL_NAME]) AS [FALSE_COUNT] sounds like it ought to be a good idea, but I couldn't make it fit.
I'm on a 2016 version of SQL Server.
Answer: First some commentary on the question. @200_success is right to point out that IS_NO_LONGER_GOOD_BOY does not make sense as a property on the skill, but that's hardly the only problem: | {
"domain": "codereview.stackexchange",
"id": 43590,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
Don't store booleans in negative form! Store is_good_boy instead. Otherwise, double negatives produce headaches when trying to understand logic.
Re. assume a useful placeholder if they never stop: a "useful placeholder" is null. So a well-designed schema would ignore "There is no need to worry about NULLs"; this is not a "trap" but a "feature" and a "necessary mechanism for good schema design".
doggies should be a separate table from doggy_skills should be a separate table from skills. doggy_skills being a join table, it will have foreign key references to both of the other tables.
So, making a judgement call, I will assume recommendation of "what should be done" and not only "what should be done to the letter of the question". I'm sure you can fill out the latter based on the other points I suggest, if you so need.
You do not need a group by nor a count nor a having, but you do need a correlated subquery. You only need one level of nesting.
In terms of style, delete all of your [] escaping brackets; and (more as a matter of personal taste) there is no reason to SHOUT.
Suggested
create table doggies(
id int primary key
);
create table skills(
id int primary key,
name varchar(100) not null
);
create table doggie_skills(
doggie int not null references doggies(id),
skill int not null references skills(id),
start datetime not null default current_timestamp,
stop datetime,
is_good_boy bit not null default 1,
primary key(doggie, skill, start),
check(start < stop)
);
insert into doggies(id) values
(1), (2), (3), (4), (5), (6);
insert into skills(id, name) values
(10, 'roll over'),
(11, 'brain surgery'); | {
"domain": "codereview.stackexchange",
"id": 43590,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
insert into skills(id, name) values
(10, 'roll over'),
(11, 'brain surgery');
insert into doggie_skills(doggie, skill, start, stop, is_good_boy) values
--- included ---
-- Only one skill, current, good boy
(1, 10, '2010-01-01T00:00:00', null, 1),
-- One current skill with a history, always a good boy
(2, 10, '2010-01-01T00:00:00', '2015-01-01T00:00:00', 1),
(2, 10, '2016-01-01T00:00:00', null, 1),
--- excluded ---
-- no skills (3)
-- no current skills
(4, 11, '2010-01-01T00:00:00', '2015-01-01T00:00:00', 1),
-- one current skill but not a good boy
(5, 11, '2010-01-01T00:00:00', null, 0),
-- one current skill, good boy now, bad boy before
(6, 10, '2010-01-01T00:00:00', '2015-01-01T00:00:00', 0),
(6, 10, '2016-01-01T00:00:00', null, 1);
-- Find every doggie who has a skill with a 1 value for is_good_boy
-- ^^^ implying stop is null
-- without, at some point in time, having that same skill with a 0 value for is_good_boy
select *
from doggie_skills as current_skill
where current_skill.is_good_boy = 1
and current_skill.stop is null -- current
and not exists(
select 1
from doggie_skills as old_skill
where old_skill.skill = current_skill.skill
and old_skill.doggie = current_skill.doggie
and old_skill.is_good_boy = 0
);
Also see fiddle. | {
"domain": "codereview.stackexchange",
"id": 43590,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, sql-server, t-sql",
"url": null
} |
bash, curl
Title: Bash script to automatically test Artifactory access
Question: Our team often has indeterminate access issues to our Aritfactory binaries. These issues can go missed because we may have our binaries locally cached and our projects builds may still succeed until there is new dependencies that might throw an error.
I wrote a simple script to try to access Artifactory and alert us if there are issues. My bash isn't great so wondering if there's a more elegant way to test this.
#!/usr/bin/env bash -e
result=$(curl -sSf --header "X-JFrog-Art-Api: $ARTIFACTORY_API_KEY" -XPOST "https://bin.tcc.li/artifactory/api/security/token" -d "username=$ARTIFACTORY_SVC_ACCT" -d "scope=member-of-groups:*" > /dev/null && echo "success")
if [ $result = 'success' ]; then
echo -e $result
echo -e "Your general Artifactory access is successful\n"
else
echo -e $result
echo -e "Connection to Artifactory failed\n"
fi
Answer: Looks OK. I only have four suggestions:
Use printf rather than echo. See Why is printf better than echo?
Put the URL at the end of the command, not in the middle. And put it in a variable, e.g. $URL.
Use \ and newlines and indentation to make your code more readable. Long lines, especially those wider than your terminal/editing-window are a PITA. e.g.
URL='https://bin.tcc.li/artifactory/api/security/token'
result=$(curl -sSf -XPOST \
--header "X-JFrog-Art-Api: $ARTIFACTORY_API_KEY" \
-d "username=$ARTIFACTORY_SVC_ACCT" \
-d "scope=member-of-groups:*" \
"$URL" > /dev/null && echo "success")
If necessary use variables to shorten the lines. A few variable assignments aren't going to make any noticeable impact on performance (unless done thousands of times in a loop - so avoid doing that), but can make your code a lot easier to read.
e.g. the X-JFrog-Art-Api: $ARTIFACTORY_API_KEY header and the -XPOST URL can both be put into variables, as can the username= and scope= -d data options. | {
"domain": "codereview.stackexchange",
"id": 43591,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, curl",
"url": null
} |
bash, curl
You don't need command substitution to get a $result variable. You're already testing the exit code from curl with && echo success - you can do that directly in the if statement.
#!/bin/bash
URL='https://bin.tcc.li/artifactory/api/security/token'
API_KEY="X-JFrog-Art-Api: $ARTIFACTORY_API_KEY"
username_data="username=$ARTIFACTORY_SVC_ACCT"
scope_data='scope=member-of-groups:*'
if curl -sSf -XPOST \
--header "$API_KEY" \
-d "$username_data" \
-d "$scope_data" \
"$URL" > /dev/null 2>&1; then
result='success'
printf "%s" "$result"
printf "%s\n" "Your general Artifactory access is successful"
else
printf "%s\n" "Connection to Artifactory failed"
fi
and you only need the result=success if you're going to use that variable later in the script. I can't see any benefit in printing it either.
Or you could capture the actual output from curl into $result (rather than just "success" or nothing) if you have a use for it, and still use curl's exit code for the if statement. | {
"domain": "codereview.stackexchange",
"id": 43591,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, curl",
"url": null
} |
c++, console, winapi
Title: A C++ WinAPI program for changing the process priority classes via PIDs - take 2
Question: After improving the previous post, I came up with the following program:
#include <Windows.h>
#include <iostream>
#include <sstream>
#include <string>
using std::wcout;
using std::wcerr;
using std::wstring;
using std::wstringstream;
static const DWORD BAD_PRIORITY_CLASS_SELECTION = 0xffff0000;
static void MyPrintHelp();
static bool MyAttemptToChangeProcessPriorityClass(DWORD pid,
DWORD priorityClassFlag);
static bool MyCheckPriorityClassSelection(DWORD priorityClassSelection);
static DWORD MyConvertPriorityClassSelectionToFlag(DWORD priorityClassSelection);
static wstring MyConvertProcessClassFlagToString(DWORD priorityClassFlag);
int wmain(int argc, const wchar_t** args) {
if (argc != 3) {
::MyPrintHelp();
return 0;
}
DWORD pid;
DWORD priorityClassFlag;
DWORD priorityClassSelection;
// Read the PID and the process priority class selection:
wstringstream wss;
wss << args[1] << L" " << args[2];
wss >> pid;
if (wss.fail() || wss.eof()) {
wcerr << L"Error: bad PID (" << args[1] << L"\n";
return EXIT_FAILURE;
}
wss >> priorityClassSelection;
if (wss.fail()) {
wcerr << L"Error: bad priority class selector (" << args[2] << L")\n";
return EXIT_FAILURE;
}
// Once here, reading and parsing the PID and the priority class succeeded:
if (!::MyCheckPriorityClassSelection(priorityClassSelection)) {
// Here, the priority class selection is out of bounds:
wcerr << L"Error: bad priority class selection: "
<< priorityClassSelection
<< L". Must be between 0 and 5, inclusively.\n";
return EXIT_FAILURE;
}
// Get the WinAPI flag for the selected priority class:
priorityClassFlag =
::MyConvertPriorityClassSelectionToFlag(priorityClassSelection); | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
if (priorityClassFlag == BAD_PRIORITY_CLASS_SELECTION) {
wcerr << L"Error: unknown priority class selection: "
<< priorityClassSelection
<< L"\n";
return EXIT_FAILURE;
}
return ::MyAttemptToChangeProcessPriorityClass(pid, priorityClassFlag) ?
EXIT_SUCCESS :
EXIT_FAILURE;
}
static void MyPrintHelp() {
wcout << L"prioset.exe PID PRIORITY_CLASS\n"
<< L"Where PRIORITY_CLASS is one of:\n"
<< L" 0 - IDLE_PRIORITY_CLASS\n"
<< L" 1 - BELOW_NORMAL_PRIORITY_CLASS\n"
<< L" 2 - NORMAL_PRIORITY_CLASS\n"
<< L" 3 - ABOVE_NORMAL_PRIORITY_CLASS\n"
<< L" 4 - HIGH_PRIORITY_CLASS\n"
<< L" 5 - REALTIME_PRIORITY_CLASS\n"
<< L" REALTIME_PRIORITY_CLASS requires administrator "
<< L"privileges.\n";
}
static wstring GetLastErrorAsString(DWORD errorMessageId)
{
LPWSTR messageBuffer = nullptr;
size_t size = ::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorMessageId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) &messageBuffer, 0, NULL);
// Copy the error message into a std::wstring:
wstring message(messageBuffer, size);
// Free the Win32's string's buffer:
::LocalFree(messageBuffer);
return message;
}
static bool MyAttemptToChangeProcessPriorityClass(DWORD pid, DWORD priorityClassFlag) {
HANDLE processHandle =
::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION,
false,
pid);
if (processHandle == NULL) {
wcout << L"Error: could not open a process with PID " << pid << "\n";
return false;
}
DWORD oldPriorityClass = ::GetPriorityClass(processHandle); | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
DWORD oldPriorityClass = ::GetPriorityClass(processHandle);
if (oldPriorityClass == 0) {
DWORD errorCode = ::GetLastError();
wcerr << L"Error: "
<< ::GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
return false;
}
if (!::SetPriorityClass(processHandle, priorityClassFlag)) {
DWORD errorCode = ::GetLastError();
wcerr << L"Error: "
<< ::GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
return false;
}
DWORD newPriorityClass = ::GetPriorityClass(processHandle);
if (newPriorityClass == 0) {
DWORD errorCode = ::GetLastError();
wcerr << L"Error: "
<< ::GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
return false;
}
::CloseHandle(processHandle);
if (newPriorityClass == oldPriorityClass) {
wcout << L"The requested priority class is the same "
<< L"as the current priority class ("
<< ::MyConvertProcessClassFlagToString(newPriorityClass)
<< L").\n";
return true;
} | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
return true;
}
if (newPriorityClass == priorityClassFlag) {
wcout << L"Successfully changed the priority class from "
<< ::MyConvertProcessClassFlagToString(oldPriorityClass)
<< L" ("
<< oldPriorityClass
<< L") to "
<< ::MyConvertProcessClassFlagToString(newPriorityClass)
<< L" ("
<< newPriorityClass
<< L")\n";
} else {
wcout << L"Warning: Could not change the priority class from "
<< ::MyConvertProcessClassFlagToString(oldPriorityClass)
<< L" ("
<< oldPriorityClass
<< L") to "
<< ::MyConvertProcessClassFlagToString(priorityClassFlag)
<< L" ("
<< priorityClassFlag
<< L"). Instead, "
<< ::MyConvertProcessClassFlagToString(newPriorityClass)
<< L" ("
<< newPriorityClass
<< L") is used as a new priority class.\n";
}
return true;
}
static bool MyCheckPriorityClassSelection(DWORD priorityClassSelection) {
return priorityClassSelection >= 0 || priorityClassSelection < 6;
}
static DWORD MyConvertPriorityClassSelectionToFlag(
DWORD priorityClassSelection) {
switch (priorityClassSelection) {
case 0:
return IDLE_PRIORITY_CLASS;
case 1:
return BELOW_NORMAL_PRIORITY_CLASS;
case 2:
return NORMAL_PRIORITY_CLASS;
case 3:
return ABOVE_NORMAL_PRIORITY_CLASS;
case 4:
return HIGH_PRIORITY_CLASS;
case 5:
return REALTIME_PRIORITY_CLASS;
default:
return BAD_PRIORITY_CLASS_SELECTION;
}
}
static wstring MyConvertProcessClassFlagToString(DWORD priorityClassFlag) {
switch (priorityClassFlag) {
case IDLE_PRIORITY_CLASS:
return L"IDLE_PRIORITY_CLASS"; | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
case BELOW_NORMAL_PRIORITY_CLASS:
return L"BELOW_NORMAL_PRIORITY_CLASS";
case NORMAL_PRIORITY_CLASS:
return L"NORMAL_PRIORITY_CLASS";
case ABOVE_NORMAL_PRIORITY_CLASS:
return L"ABOVE_NORMAL_PRIORITY_CLASS";
case HIGH_PRIORITY_CLASS:
return L"HIGH_PRIORITY_CLASS";
case REALTIME_PRIORITY_CLASS:
return L"REALTIME_PRIORITY_CLASS";
default:
return L"BAD_PRIORITY_CLASS";
}
}
Critique request
Please tell me anything that comes to mind.
Answer: General Observations
I think that I would have created most of this code as a class so that it could be reused by other programs. The code would also be better if it followed the SOLID programming principles. SOLID is 5 object oriented design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.
The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.
The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
The Interface segregation principle - states that no client should be forced to depend on methods it does not use.
The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
Code Organization
Function prototypes are very useful in large programs that contain multiple source files, and that in case they will be in header files. In a single file program like this it is better to put the main() function at the bottom of the file and all the functions that get used in the proper order above main(). Keep in mind that every line of code written is another line of code where a bug can crawl into the code.
Performance and Maintainability
Switch/case statements are harder to maintain for conversion functions then some other implementations of conversion. The fastest form of conversion is to use arrays (presented as old style C arrays but since this is C++, C++ container class arrays could also be used). By using arrays we remove one magic number (6), and the code is reduced in size. Maintenance is then limited to adding new constants to the arrays. This also allows the conversion to all be in terms of the user input, rather than converting from user input to a priority class and then converting the priority class to strings if necessary. The conversion functions could also be in a class of their own.
static DWORD priorityConversion[] =
{
IDLE_PRIORITY_CLASS,
BELOW_NORMAL_PRIORITY_CLASS,
NORMAL_PRIORITY_CLASS,
ABOVE_NORMAL_PRIORITY_CLASS,
HIGH_PRIORITY_CLASS,
REALTIME_PRIORITY_CLASS
};
static wstring priortyWStringConverter[] =
{
L"IDLE_PRIORITY_CLASS",
L"BELOW_NORMAL_PRIORITY_CLASS",
L"NORMAL_PRIORITY_CLASS",
L"ABOVE_NORMAL_PRIORITY_CLASS",
L"HIGH_PRIORITY_CLASS",
L"REALTIME_PRIORITY_CLASS"
};
static const size_t MaxPriorityClass = sizeof(priorityConversion) /
sizeof(*priorityConversion);
static bool MyCheckPriorityClassSelection(DWORD priorityClassSelection) {
return priorityClassSelection >= 0 || priorityClassSelection < MaxPriorityClass;
} | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
static DWORD MyConvertPriorityClassSelectionToFlag(DWORD priorityClassSelection)
{
if (!MyCheckPriorityClassSelection(priorityClassSelection))
{
return BAD_PRIORITY_CLASS_SELECTION;
}
else
{
return priorityConversion[priorityClassSelection];
}
}
static wstring MyConvertProcessClassFlagToString(DWORD priorityClassSelection)
{
if (!MyCheckPriorityClassSelection(priorityClassSelection))
{
return L"BAD_PRIORITY_CLASS";
}
else
{
return priortyWStringConverter[priorityClassSelection];
}
}
Complexity
Two of the functions, wmain(int argc, const wchar_t** args) and MyAttemptToChangeProcessPriorityClass(DWORD pid, DWORD priorityClassFlag) are too complex (they do too much, and the functions are too long). Both would benefit by creating smaller simpler functions that follow the Single Responsibility Principle and then calling those smaller functions in the larger functions. I suggest moving the error handling to the smaller functions, some examples are:
static HANDLE getProcessHandle(DWORD pid)
{
HANDLE processHandle =
::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION, false, pid);
if (processHandle == NULL) {
wcout << L"Error: could not open a process with PID " << pid << "\n";
}
return processHandle;
}
static DWORD getAndCheckOldPriority(HANDLE processHandle)
{
DWORD oldPriorityClass = ::GetPriorityClass(processHandle);
if (oldPriorityClass == 0) {
DWORD errorCode = ::GetLastError();
wcerr << L"Error: "
<< ::GetLastErrorAsString(errorCode)
<< L"Error code: "
<< errorCode
<< L"\n";
::CloseHandle(processHandle);
}
return oldPriorityClass;
}
static bool MyAttemptToChangeProcessPriorityClass(DWORD pid, DWORD priorityClassFlag)
{
HANDLE processHandle = getProcessHandle(pid);
if (processHandle == NULL) {
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
c++, console, winapi
DWORD oldPriorityClass = getAndCheckOldPriority(processHandle);
if (oldPriorityClass == 0) {
return false;
}
...
} | {
"domain": "codereview.stackexchange",
"id": 43592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, console, winapi",
"url": null
} |
python, strings, pandas, natural-language-processing
Title: Remove duplicates from a Pandas dataframe taking into account lowercase letters and accents
Question: I have the following DataFrame in pandas:
code
town
district
suburb
02
Benalmádena
Málaga
Arroyo de la Miel
03
Alicante
Jacarilla
Jacarilla, Correntias Bajas (Jacarilla)
04
Cabrera d'Anoia
Barcelona
Cabrera D'Anoia
07
Lanjarón
Granada
Lanjaron
08
Santa Cruz de Tenerife
Santa Cruz de Tenerife
Centro-Ifara
09
Córdoba
Córdoba
Cordoba
For each row in the suburb column, if the value it contains is equal (in lower case and without accents) to district or town columns, it becomes NaN.
This is the code I am using:
df['suburb'] = np.where(
((df['suburb'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8').str.lower() == df['town'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8').str.lower())
| (df['suburb'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8').str.lower() == df['district'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8').str.lower())
),
np.nan, df['suburb'])
df
Example result:
code
town
district
suburb
02
Benalmádena
Málaga
Arroyo de la Miel
03
Alicante
Jacarilla
Jacarilla, Correntias Bajas (Jacarilla)
04
Cabrera d'Anoia
Barcelona
NaN
07
Lanjarón
Granada
NaN
08
Santa Cruz de Tenerife
Santa Cruz de Tenerife
Centro-Ifara
09
Córdoba
Córdoba
NaN
I would like to reduce the amount of code, as I am sure it can be made shorter with the same performance.
Answer: Looks like you could use a function:
def accent_free(s: str):
return unicodedata.normalize('NFKD', s).encode('ascii', errors='ignore').decode('utf-8').lower()
Of course, you want this vectorized for numpy, so:
accent_free = np.vectorize(accent_free) | {
"domain": "codereview.stackexchange",
"id": 43593,
"lm_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, strings, pandas, natural-language-processing",
"url": null
} |
python, strings, pandas, natural-language-processing
Of course, you want this vectorized for numpy, so:
accent_free = np.vectorize(accent_free)
Now, you just need to use this function:
df['suburb'] = np.where(
((accent_free(df['suburb']) == accent_free(df['town'])) |
(accent_free(df['suburb']) == accent_free(df['district']))
),
np.nan, df['suburb'])
Complete working example:
import unicodedata
import numpy as np
import pandas as pd
def accent_free(s: str):
return unicodedata.normalize('NFKD', s).encode('ascii', errors='ignore').decode('utf-8').lower()
accent_free = np.vectorize(accent_free)
data = [
["02", "Benalmádena", "Málaga", "Arroyo de la Miel"],
["03", "Alicante", "Jacarilla", "Jacarilla, Correntias Bajas (Jacarilla)"],
["04", "Cabrera d'Anoia", "Barcelona", "Cabrera D'Anoia"],
["07", "Lanjarón", "Granada", "Lanjaron"],
["08", "Santa Cruz de Tenerife", "Santa Cruz de Tenerife", "Centro-Ifara"],
["09", "Córdoba", "Córdoba", "Cordoba"],
]
df = pd.DataFrame(data, columns=["code", "town", "district", "suburb"])
df['suburb'] = np.where(
((accent_free(df['suburb']) == accent_free(df['town'])) |
(accent_free(df['suburb']) == accent_free(df['district']))
),
np.nan, df['suburb'])
print(df.to_string()) | {
"domain": "codereview.stackexchange",
"id": 43593,
"lm_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, strings, pandas, natural-language-processing",
"url": null
} |
performance, image, rust, graphics
Title: Radial gradient image generator
Question: A function to create a radial gradient from one rgb colour to another and using rayon to improve performance. Are there better way to convert between some of the types / any obvious performance improvements I could implement?
use image::RgbImage;
use rayon::prelude::*;
fn radial_gradient(
geometry: (i32, i32),
inner_color: Vec<u8>,
outer_color: Vec<u8>,
foreground_size: i32,
) -> RgbImage {
let mut background: RgbImage = RgbImage::new(geometry.0 as u32, geometry.1 as u32);
let distance = |x: i32, y: i32| (((x).pow(2) + (y).pow(2)) as f64).sqrt();
// The background will adapt to the foreground size so that the inner_color will be at the edges of the art
// and not just at the centre of the image
let max_dist =
distance((geometry.0 / 2) as i32, (geometry.1 / 2) as i32) - (foreground_size / 2) as f64;
background
.par_chunks_exact_mut(3)
.enumerate()
.for_each(|(pixel_num, pixel)| {
let x_dist = i32::try_from(pixel_num).unwrap() % geometry.0 - geometry.0 / 2;
let y_dist = i32::try_from(pixel_num).unwrap() / geometry.0 - geometry.1 / 2;
let scaled_dist = (distance(x_dist, y_dist) - (foreground_size / 2) as f64) / max_dist;
for (i, subpix) in pixel.iter_mut().enumerate() {
*subpix = ((outer_color[i] as f64 * scaled_dist)
+ (inner_color[i] as f64 * (1.0 - scaled_dist)))
as u8
}
});
background
}
Answer: Things I changed:
x * x is faster than x.pow(2)
f64 is way overkill for this, use f32
Replace Vec<u8> inputs with [u8; 3]
Use fused-multiply-add to implement lerp
Move distance to separate function for readability
Move all constant values out of the loop
Pixel is too small for efficient parallelization, parallelize over rows instead. Now that we have .enumerate as row id, use simple counter to get column id. | {
"domain": "codereview.stackexchange",
"id": 43594,
"lm_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, image, rust, graphics",
"url": null
} |
performance, image, rust, graphics
Here's my benchmark suite:
use image::RgbImage;
use rayon::prelude::*;
fn radial_gradient_orig(
geometry: (i32, i32),
inner_color: Vec<u8>,
outer_color: Vec<u8>,
foreground_size: i32,
) -> RgbImage {
let mut background: RgbImage = RgbImage::new(geometry.0 as u32, geometry.1 as u32);
let distance = |x: i32, y: i32| (((x).pow(2) + (y).pow(2)) as f64).sqrt();
// The background will adapt to the foreground size so that the inner_color will be at the edges of the art
// and not just at the centre of the image
let max_dist =
distance((geometry.0 / 2) as i32, (geometry.1 / 2) as i32) - (foreground_size / 2) as f64;
background
.par_chunks_exact_mut(3)
.enumerate()
.for_each(|(pixel_num, pixel)| {
let x_dist = i32::try_from(pixel_num).unwrap() % geometry.0 - geometry.0 / 2;
let y_dist = i32::try_from(pixel_num).unwrap() / geometry.0 - geometry.1 / 2;
let scaled_dist = (distance(x_dist, y_dist) - (foreground_size / 2) as f64) / max_dist;
for (i, subpix) in pixel.iter_mut().enumerate() {
*subpix = ((outer_color[i] as f64 * scaled_dist)
+ (inner_color[i] as f64 * (1.0 - scaled_dist))) as u8
}
});
background
}
#[inline]
fn lerp(pct: f32, a: f32, b: f32) -> f32 {
pct.mul_add(b - a, a)
}
#[inline]
fn distance(x: i32, y: i32) -> f32 {
((x * x + y * y) as f32).sqrt()
}
fn radial_gradient_improved_1(
geometry: (u32, u32),
inner_color: [u8; 3],
outer_color: [u8; 3],
foreground_size: u32,
) -> RgbImage {
let mut background: RgbImage = RgbImage::new(geometry.0 as u32, geometry.1 as u32); | {
"domain": "codereview.stackexchange",
"id": 43594,
"lm_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, image, rust, graphics",
"url": null
} |
performance, image, rust, graphics
// The background will adapt to the foreground size so that the inner_color will be at the edges of the art
// and not just at the centre of the image
let center = (geometry.0 / 2, geometry.1 / 2);
let foreground_half = (foreground_size / 2) as f32;
let max_dist = distance(center.0 as i32, center.1 as i32) - foreground_half;
let inner_color = inner_color.map(|el| el as f32);
let outer_color = outer_color.map(|el| el as f32);
background
.par_chunks_exact_mut(3)
.enumerate()
.for_each(|(pixel_num, pixel)| {
let pixel_num = pixel_num as u32;
let pos_y = pixel_num / geometry.0;
let pos_x = pixel_num % geometry.0;
let dist_x = pos_x as i32 - center.0 as i32;
let dist_y = pos_y as i32 - center.1 as i32;
let scaled_dist = (distance(dist_x, dist_y) - foreground_half) / max_dist;
pixel[0] = lerp(scaled_dist, inner_color[0], outer_color[0]) as u8;
pixel[1] = lerp(scaled_dist, inner_color[1], outer_color[1]) as u8;
pixel[2] = lerp(scaled_dist, inner_color[2], outer_color[2]) as u8;
});
background
}
fn radial_gradient_improved_2(
geometry: (u32, u32),
inner_color: [u8; 3],
outer_color: [u8; 3],
foreground_size: u32,
) -> RgbImage {
let mut background: RgbImage = RgbImage::new(geometry.0 as u32, geometry.1 as u32);
// The background will adapt to the foreground size so that the inner_color will be at the edges of the art
// and not just at the centre of the image
let center = (geometry.0 / 2, geometry.1 / 2);
let foreground_half = (foreground_size / 2) as f32;
let max_dist = distance(center.0 as i32, center.1 as i32) - foreground_half;
let one_over_max_dist = 1.0 / max_dist;
let inner_color = inner_color.map(|el| el as f32);
let outer_color = outer_color.map(|el| el as f32); | {
"domain": "codereview.stackexchange",
"id": 43594,
"lm_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, image, rust, graphics",
"url": null
} |
performance, image, rust, graphics
background
.par_chunks_exact_mut(3 * geometry.0 as usize)
.enumerate()
.for_each(|(pos_y, row)| {
for pos_x in 0..geometry.0 {
let dist_x = pos_x as i32 - center.0 as i32;
let dist_y = pos_y as i32 - center.1 as i32;
let scaled_dist = (distance(dist_x, dist_y) - foreground_half) * one_over_max_dist;
let pixel_pos = (pos_x * 3) as usize;
let pixel = &mut row[pixel_pos..(pixel_pos + 3)];
pixel[0] = lerp(scaled_dist, inner_color[0], outer_color[0]) as u8;
pixel[1] = lerp(scaled_dist, inner_color[1], outer_color[1]) as u8;
pixel[2] = lerp(scaled_dist, inner_color[2], outer_color[2]) as u8;
}
});
background
}
const NUM_ITER: usize = 50; | {
"domain": "codereview.stackexchange",
"id": 43594,
"lm_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, image, rust, graphics",
"url": null
} |
performance, image, rust, graphics
const NUM_ITER: usize = 50;
fn main() {
{
let duration = (0..NUM_ITER)
.into_iter()
.map(|_| {
let t = std::time::Instant::now();
let _img =
radial_gradient_orig((1300, 1024), vec![255, 128, 0], vec![0, 128, 255], 30);
t.elapsed()
})
.min()
.unwrap();
println!("Original: {} ms", duration.as_secs_f32() * 1000.0);
}
{
let duration = (0..NUM_ITER)
.into_iter()
.map(|_| {
let t = std::time::Instant::now();
let _img =
radial_gradient_improved_1((1300, 1024), [255, 128, 0], [0, 128, 255], 30);
t.elapsed()
})
.min()
.unwrap();
println!("Improved 1: {} ms", duration.as_secs_f32() * 1000.0);
}
{
let duration = (0..NUM_ITER)
.into_iter()
.map(|_| {
let t = std::time::Instant::now();
let _img =
radial_gradient_improved_2((1300, 1024), [255, 128, 0], [0, 128, 255], 30);
t.elapsed()
})
.min()
.unwrap();
println!("Improved 2: {} ms", duration.as_secs_f32() * 1000.0);
}
radial_gradient_orig((1300, 1024), vec![255, 128, 0], vec![0, 128, 255], 30)
.save("img_orig.bmp")
.unwrap();
radial_gradient_improved_1((1300, 1024), [255, 128, 0], [0, 128, 255], 30)
.save("img_imp1.bmp")
.unwrap();
radial_gradient_improved_2((1300, 1024), [255, 128, 0], [0, 128, 255], 30)
.save("img_imp2.bmp")
.unwrap();
}
> cargo run --release
Original: 5.9073 ms
Improved 1: 4.4981 ms
Improved 2: 2.6811001 ms | {
"domain": "codereview.stackexchange",
"id": 43594,
"lm_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, image, rust, graphics",
"url": null
} |
c#, formatting
Title: IFormatProvider for double to engineering notation
Question: A c# format provider that formats a double into a string using engineering notation rules.
If the value is outside of the defined notation symbols it will default to using scientific notation.
I wrote this code to better handle a mess of case statements that previously handled the engineering notation formatting for an legacy project. The project preforms electrical measurements on a product under test, measurements like voltage, current, and resistance. These measurements are much easier for the test technicians to understand if presented in engineering notation.
class EngNotationFormatter : IFormatProvider, ICustomFormatter
{
private readonly Dictionary<double, string> notationSymbols = new Dictionary<double, string>
{
{double.NegativeInfinity, ""},
{-24, "y"},
{-21, "z"},
{-18, "a"},
{-15, "f"},
{-12, "p"},
{-9, "n"},
{-6, "μ"},
{-3, "m"},
{0, ""},
{3, "k"},
{6, "M"},
{9, "G"},
{12, "T"},
{15, "P"},
{18, "E"},
{21, "Z"},
{24, "Y"},
};
public string Format(string format, object arg, IFormatProvider formatProvider)
{
double value = Convert.ToDouble(arg);
double exponent = Math.Log10(Math.Abs(value));
double engExponent = Math.Floor(exponent / 3) * 3;
string symbol = notationSymbols.ContainsKey(engExponent) ? notationSymbols[engExponent] : "e" + engExponent;
return (value * Math.Pow(10, -(int)engExponent)).ToString("0.########") + symbol;
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
}
Example use:
Console.WriteLine(String.Format(new EngNotationFormatter(), "{0}Ω", 0.01234)); //result: 12.34mΩ | {
"domain": "codereview.stackexchange",
"id": 43595,
"lm_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#, formatting",
"url": null
} |
c#, formatting
original case statement that was placed through out code, dat here is the double to be formatted, and precision is the number of digits to display (this value is always the same)
Function formatData(ByVal dat As Single, ByVal precision As String) As String
Select Case System.Math.Abs(dat)
Case 0
formatData = "0"
Case Is < 0.000000000001
formatData = Format(dat * 1.0E+15, precision & "f")
Case Is < 0.000000001
formatData = Format(dat * 1000000000000.0#, precision & "p")
Case Is < 0.000001
formatData = Format(dat * 1000000000.0#, precision & "n")
Case Is < 0.001
formatData = Format(dat * 1000000.0#, precision & "u")
Case Is < 0.99
formatData = Format(dat * 1000.0#, precision & "m")
'Case Is < 1101#
Case Is < 1000.0#
formatData = Format(dat, precision & "")
Case Is < 1000000.0#
formatData = Format(dat / 1000.0#, precision & "k")
Case Is < 1000000000.0#
formatData = Format(dat / 1000000.0#, precision & "M")
Case Is < 1000000000000.0#
formatData = Format(dat / 1000000000.0#, precision & "G")
Case Else
formatData = ""
End Select
End Function
Answer: I'm not sure why you chose to use IFormatProvider, and why you manually add notation using string.Format.
Nevertheless, notationSymbols will be better if you use switch instead, to avoid unnecessary memory allocation. if you're planning on expanding it or you don't see that a switch would be a good fit for your use-case, then keep it but also cache it for a reuse.
double value = Convert.ToDouble(arg);
if arg is not valid integer (such as null) this would throw an exception.So, instead you can do this :
if(arg is double value)
{
// code
}
or this :
if(double.TryParse(arg?.ToString(), out var value))
{
// code
} | {
"domain": "codereview.stackexchange",
"id": 43595,
"lm_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#, formatting",
"url": null
} |
c#, formatting
or this :
if(double.TryParse(arg?.ToString(), out var value))
{
// code
}
the last note when converting from lower precision to a higher one, you need to ensure the value consistency between them, which is a very common issue. So, having a plan to ensure compatibility between old precision and the new one would safe you the hassle.
Lastly, instead of implementing IFormatProvider, you can implement an an abstract class for notation, then use extension methods to format the numbers.
Example :
public abstract class EngineeringNotation
{
private readonly char _notationSymbol;
protected EngineeringNotation(char notationSymbol) {
_notationSymbol = notationSymbol;
}
public string Format(double number)
{
double exponent = Math.Log10(Math.Abs(number));
double engExponent = Math.Floor(exponent / 3) * 3);
double result = number * Math.Pow(10, -(int)engExponent);
string symbol = GetSymbol(engExponent); | {
"domain": "codereview.stackexchange",
"id": 43595,
"lm_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#, formatting",
"url": null
} |
c#, formatting
return $"{result:0.########}{symbol}{_notationSymbol}";
}
private static string GetSymbol(double exponent)
{
switch (exponent)
{
case double.NegativeInfinity:
case 0:
return string.Empty;
case -24:
return "y";
case -21:
return "z";
case -18:
return "a";
case -15:
return "f";
case -12:
return "p";
case -9:
return "n";
case -6:
return "μ";
case -3:
return "m";
case 3:
return "k";
case 6:
return "M";
case 9:
return "G";
case 12:
return "T";
case 15:
return "P";
case 18:
return "E";
case 21:
return "Z";
case 24:
return "Y";
default:
return $"e{exponent}";
}
}
}
public class VoltNotation : EngineeringNotation
{
public VoltNotation() : base('V') { }
}
public class OhmNotation : EngineeringNotation
{
public OhmNotation() : base('Ω') { }
}
public static class NotationExtensions
{
public static string FormatNotation(this double value, EngineeringNotation notation)
{
return notation.Format(value);
}
public static string FormatAsVoltNotation(this double value)
{
return FormatNotation(value, new VoltNotation());
}
public static string FormatAsOhmNotation(this double value)
{
return FormatNotation(value, new OhmNotation());
}
}
now you can do this :
double number = 0.01234;
string formated = number.FormatAsOhmNotation(); | {
"domain": "codereview.stackexchange",
"id": 43595,
"lm_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#, formatting",
"url": null
} |
python, pandas
Title: Slow processing of a python dataframe when aggregating across rows and columns
Question: I would do this in SQL using string_agg but the server is SQL Server 2012 and beyond my control. So I'm trying a python approach.
I have a dataframe of shape [20225 rows x 7 columns], and there a bit of transformation required. There are sometimes duplicate rows, but only in one column. So what I want to do is find the duplicate rows (where the name is the same) and then
Concatenate all the email addresses in three columns and name matching rows into one string (dropping nulls)
Concatenate all the company names in three columns and name matching rows into one string (dropping nulls)
Create a new dataframe of shape [20106 rows x 3 columns] that then has one row per name, with a single string of email addresses in the second column, and a single string of companies in the third column.
Basically, the duplicate rows have been eliminated, and the different email addresses/companynames have been concatenated.
My code works, and takes about 6 minutes to run... I don't know enough about this, but I have a hunch it could be a lot faster. I'm just looking for some pointers as to maybe structuring it differently? Thanks for any guidance.
EXAMPLE DATA
Name
People1.Email
People1.CompanyName
People2.Email
People2.CompanyName
People3.Email
People3.CompanyName
Person A
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
Person A
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
Person B
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
Person C
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
email@somewhere.com CompanyName
Person D
email@somewhere.com
CompanyName
Person D
email@somewhere.com
CompanyName
Person D
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
Person E
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName | {
"domain": "codereview.stackexchange",
"id": 43596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, pandas
Person E
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
email@somewhere.com
CompanyName
Name
Emails
Companies
Person A
email@somewhere.com;email@somewhere.com;email@somewhere.com;email@somewhere.com
CompanyName; CompanyName;CompanyName; CompanyName
Person B
email@somewhere.com;email@somewhere.com
CompanyName; CompanyName;CompanyName
etc
*DATA TYPES*
Name object
People1.Email object
People2.CompanyName object
People1.Email object
People2.CompanyName object
People3.Email object
People4.CompanyName object
*CODE*
print (time.strftime("%H:%M:%S", time.localtime()) + " start")
pd_xl_file = pd.ExcelFile(r'C:\sample.xlsx')
df = pd_xl_file.parse(0)
listOfPeople = df['Name'].unique().tolist()
# Now creata new df to hold the final result
df_new = pd.DataFrame()
for person in listOfPeople:
lstCompanies =
df.loc[df['Name'] == person, 'People1.CompanyName'].unique().tolist() +
df.loc[df['Name'] == person, 'People2.CompanyName'].unique().tolist() +
df.loc[df['Name'] == person, 'People3.CompanyName'].unique().tolist()
Companies = [x for x in lstCompanies if pd.isnull(x) == False]
lstEmails =
df.loc[df['Name'] == person, 'People1.Email'].unique().tolist() +
df.loc[df['Name'] == person, 'People2.Email'].unique().tolist() +
df.loc[df['Name'] == person, 'People3.Email'].unique().tolist()
Emails = [x for x in lstEmails if pd.isnull(x) == False]
# initialize list of lists
c = ' '.join([item for item in Companies])
e = ' '.join([item for item in Emails])
# append to the final result
new_row = pd.DataFrame({'Name':person, 'Companies':c, 'Emails':e}, index=[0])
df_new = pd.concat([new_row,df_new.loc[:]]).reset_index(drop=True)
print ('.', end='')
print (df_new)
print (time.strftime("%H:%M:%S", time.localtime()) + " end") | {
"domain": "codereview.stackexchange",
"id": 43596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
python, pandas
print (df_new)
print (time.strftime("%H:%M:%S", time.localtime()) + " end")
Answer: Don't for in listOfPeople, and don't tolist.
Your data are misshapen. There should not be multiple Email and CompanyName columns; there should only be one each.
Group by the name, and then aggregate using a string join.
Suggested
import pandas as pd
df = pd.read_csv('278083.csv', index_col='Name')
to_concat = []
for i in range(1, df.shape[1]//2 + 1):
email = f'People{i}.Email'
company = f'People{i}.CompanyName'
sub = (
df[[email, company]]
.dropna()
.rename({
email: 'Email',
company: 'Company'
}, axis='columns')
)
sub['Contact'] = i
to_concat.append(sub)
df = pd.concat(to_concat).set_index(keys='Contact', append=True)
join = ';'.join
combined = df.groupby('Name').agg({
'Email': join, 'Company': join,
}) | {
"domain": "codereview.stackexchange",
"id": 43596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
c++, performance, array, deque
Title: Deque implementation using Arrays in C++
Question: I have written code for the basic implementation of a Deque in C++ using Array(pointer). Please review my code and suggest ways to make it simpler, compact, and efficient. Also would appreciate feedback on any aspect of my code.
#include <iostream>
#include <cstdlib>
class queue
{
private:
int size = 0, front = -1, rear = -1;
float *arr; | {
"domain": "codereview.stackexchange",
"id": 43597,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, array, deque",
"url": null
} |
c++, performance, array, deque
class queue
{
private:
int size = 0, front = -1, rear = -1;
float *arr;
public:
queue(int inputSize)
{
size = inputSize;
arr = (float *)malloc(size * sizeof(float));
}
int isEmpty(queue *q)
{
if (q->front == q->rear)
{
return 1;
}
return 0;
}
int isFull(queue *q)
{
if (q->rear == q->size - 1)
{
return 1;
}
return 0;
}
void enqueueR(queue *q, int data)
{
if (isFull(q))
{
std::cout << data << " cannot be entered as Queue is Full\n";
}
else
{
q->rear++;
q->arr[q->rear] = data;
}
}
void enqueueF(queue *q, int data)
{
if (isFull(q))
{
std::cout << data << " cannot be entered as Queue is Full\n";
}
else
{
for (int i = front + 1; i < size; i++)
{
q->arr[i + 1] = q->arr[i];
}
q->arr[q->front + 1] = data;
q->rear++;
}
}
void dequeueF(queue *q)
{
if (isEmpty(q))
{
std::cout << "Queue is Empty\n";
}
else
{
q->front++;
std::cout << "The removed value is: " << q->arr[q->front] << "\n";
}
}
void dequeueR(queue *q)
{
if (isEmpty(q))
{
std::cout << "Queue is Empty\n";
}
else
{
std::cout << "The removed value is: " << q->arr[q->rear] << "\n";
q->rear--;
}
}
void queueTraversal(queue *q)
{
std::cout << "The queue is as follows:\n";
for (int i = front + 1; i <= rear; i++)
{
std::cout << q->arr[i] << " ";
}
std::cout << std::endl;
}
}; | {
"domain": "codereview.stackexchange",
"id": 43597,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, array, deque",
"url": null
} |
c++, performance, array, deque
Answer: Advice 1
queue stores a queue of float values. Why not to rename to float_queue?
Advice 2
arr = (float *)malloc(size * sizeof(float));
You can write:
arr = new float[size];
Advice 3
Your class misses the destructor, which should call delete[] arr; on the queue. Thus, you leak RAM.
Advice 4
int size = 0, front = -1, rear = -1;
int supports some negative values, but they are meaningless in this context; change to size_t, which is concieved as the type for counting/indexing stuff.
Advice 5
int isEmpty(queue *q)
{
if (q->front == q->rear)
{
return 1;
}
return 0;
}
Why do you ask for queue* q argument when you can simply refer to the members of the class? Same observation applies to other relevant methods.
Advice 6
if (isFull(q))
{
std::cout << data << " cannot be entered as Queue is Full\n";
}
This is a no-no in the professional data structure development; throw an exception instead.
Advice 7
queueTraversal(queue *q)
This is asking for iterators.
Suggestion 1
I suggest you consult a professional C++-developer (obviously not me), whether it makes sense to implement:
copy constructor
copy assignment
move constructor
move assignment
All in all
I had this implementation in mind:
#include <algorithm>
#include <stdexcept>
using std::copy;
using std::logic_error;
class float_queue
{
private:
size_t size;
size_t max_capacity;
size_t front_index;
float* storage_array;
public:
float_queue(size_t _max_capacity) : size(0),
max_capacity(_max_capacity),
front_index(0),
storage_array(new float[_max_capacity]) {}
float_queue(const float_queue& other) :
size(other.size),
max_capacity(other.max_capacity),
front_index(other.front_index) { | {
"domain": "codereview.stackexchange",
"id": 43597,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, array, deque",
"url": null
} |
c++, performance, array, deque
storage_array = new float[other.max_capacity];
copy(other.storage_array,
other.storage_array + other.max_capacity,
storage_array);
}
float_queue(float_queue&& other) :
size(other.size),
max_capacity(other.max_capacity),
front_index(other.front_index),
storage_array(other.storage_array) {
other.size = 0;
other.max_capacity = 0;
other.front_index = 0;
other.storage_array = nullptr;
}
float_queue& operator=(const float_queue& other) {
if (this != &other) {
float* new_array = new float[other.max_capacity];
copy(other.storage_array,
other.storage_array + other.max_capacity,
new_array);
delete[] storage_array;
storage_array = new_array;
max_capacity = other.max_capacity;
size = other.size;
front_index = other.front_index;
}
return *this;
}
float_queue& operator=(float_queue&& other) {
if (&other != this) {
size = other.size;
front_index = other.front_index;
max_capacity = other.max_capacity;
storage_array = other.storage_array;
other.size = 0;
other.front_index = 0;
other.max_capacity = 0;
other.storage_array = nullptr;
}
return *this;
}
~float_queue() {
size = 0;
max_capacity = 0;
front_index = 0;
delete[] storage_array;
}
bool isEmpty()
{
return size == 0;
}
int isFull()
{
return size == max_capacity;
}
void prepend(float f) {
if (isFull()) {
throw logic_error{"Prepending while full."};
}
size_t new_front_index; | {
"domain": "codereview.stackexchange",
"id": 43597,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, array, deque",
"url": null
} |
c++, performance, array, deque
size_t new_front_index;
if (front_index == 0) {
new_front_index = max_capacity - 1;
}
else {
new_front_index = front_index - 1;
}
size++;
storage_array[new_front_index] = f;
front_index = new_front_index;
}
void append(float f) {
if (isFull()) {
throw logic_error{"Appending while full."};
}
size_t append_index = (front_index + size) % max_capacity;
size++;
storage_array[append_index] = f;
}
float removeHead() {
if (isEmpty()) {
throw logic_error{"Removing a head from empty queue."};
}
float rv = storage_array[front_index];
front_index = (front_index + 1) % max_capacity;
size--;
return rv;
}
float removeTail() {
if (isEmpty()) {
throw logic_error{"Removing a tail from empty queue."};
}
float rv = storage_array[(front_index + size - 1) % max_capacity];
size--;
return rv;
}
};
Note that the above code snippet is not tested for bugs/design errors; it's only for my semi-professional reference. Good luck! | {
"domain": "codereview.stackexchange",
"id": 43597,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, array, deque",
"url": null
} |
c++, c, macros, portability
Title: Portable noreturn in C/C++ between compilers
Question: I'm writing a C/C++ (intended to also be valid C code) for having a noreturn macro variable as widely portable as possible between C and C++ compilers.
#ifndef __has_include
#define __has_include(library) 0
#endif
#if __has_include(<stdnoreturn.h>)
#include <stdnoreturn.h>
#endif
#if __has_include(<stdnoreturn.h>) || defined(__cplusplus)
// `noreturn` is defined by C++, is available in the stdnoreturn.h standard
// library header for compilers that implement it.
// Uses `noreturn` if available.
#define BLK_NORETURN noreturn
#else
// Evaluates `BLK_NORETURN`. The GNU C library supports it via an
// `__attribute__` hint, while Microsoft MSVC can be hinted using `__declspec`.
#ifndef BLK_NORETURN
#if defined(_MSC_VER)
#define BLK_NORETURN __declspec(noreturn)
#elif defined(__clang__)
#define BLK_NORETURN _Noreturn
#elif defined(__GNUC__)
#define BLK_NORETURN __attribute__((noreturn))
#else
#define BLK_NORETURN
#endif
#endif
#endif
Also, this is intended to be portable all C and C++ standards.
Answer: ... intended to be portable all C and C++ standards.
The first # branching deserves to be based on the C/C++ revision and not compiler specific tests. Example: if code is using C11, use the _Noreturn keyword.
(Sample of C revision processing.)
After tests for revisions of C/C++ that support noreturn fail, then begin your #ifndef __has_include .... | {
"domain": "codereview.stackexchange",
"id": 43598,
"lm_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++, c, macros, portability",
"url": null
} |
python, python-3.x, file-system, linux
Title: Mount point API for Linux systems
Question: I have a use case where I need to check, whether / is mounted read-only.
Here's the module where I implemented this check:
"""Check mount points."""
from __future__ import annotations
from contextlib import suppress
from os import linesep
from pathlib import Path
from re import fullmatch
from subprocess import check_output
from typing import Any, Iterator, NamedTuple
__all__ = ['mount', 'root_mounted_ro']
MOUNT_REGEX = r'(.+) on (.+) type (.+) \((.+)\)'
class MountPoint(NamedTuple):
"""Representation of mount points."""
what: str
where: Path
type: str
flags: list[str]
@classmethod
def from_string(cls, string: str) -> MountPoint:
"""Creates a mount point from a string."""
if (match := fullmatch(MOUNT_REGEX, string)) is None:
raise ValueError('Invalid mount value:', string)
what, where, typ, flags = match.groups()
return cls(what, Path(where), typ, flags.split(','))
def to_json(self) -> dict[str, Any]:
"""Return a JSON-ish dict."""
return {
'what': self.what,
'where': str(self.where),
'type': self.type,
'flags': self.flags
}
def mount() -> Iterator[MountPoint]:
"""Yields mount points on the system."""
for line in check_output('mount', text=True).split(linesep):
with suppress(ValueError):
yield MountPoint.from_string(line)
def root_mounted_ro() -> bool | None:
"""Check whether / is mounted read-only."""
for mnt in mount():
if mnt.where == Path('/'):
return 'ro' in mnt.flags
return None
Is there a better approach than parsing the output of mount using a regex?
Answer:
Is there a better approach than parsing the output of mount using a regex? | {
"domain": "codereview.stackexchange",
"id": 43599,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system, linux",
"url": null
} |
python, python-3.x, file-system, linux
Answer:
Is there a better approach than parsing the output of mount using a regex?
Probably?
You care about machine legibility, not human legibility; so if you were sticking to a basic mountpoint search you should prefer reading /proc/mounts instead of calling mount.
However, you also only care about one specific path, so you might be better off calling findmnt --target /. This will require less parsing. | {
"domain": "codereview.stackexchange",
"id": 43599,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system, linux",
"url": null
} |
python, python-3.x, parsing
Title: Python function that parses a long string as key-value pairs for logging
Question: I noticed I tend to use many if-conditions in my code, and I know there is a way to simplify this with one-liners.
The function is iterating through configuration dictionaries so that I can log parameters in MLflow not as a long non-readable string:
but as key-value pairs:
!pip install mlflow
!python -m pip install -e detectron2
import mlflow
import detectron2
from detectron2.config import get_cfg, CfgNode
cfg = get_cfg()
for k, v in cfg.items():
# (1) check if params are being logged as a long hard-to-read string
if type(v) == detectron2.config.config.CfgNode:
# (1) if yes, iterate through it to log separately
for kk, vv in v.items():
# (2) check again if params are being logged as a long hard-to-read string
if type(vv) == detectron2.config.config.CfgNode: | {
"domain": "codereview.stackexchange",
"id": 43600,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing",
"url": null
} |
python, python-3.x, parsing
# (2) if yes, iterate through it to log separately
for kkk, vvv in vv.items():
# (3) check again if params are being logged as a long hard-to-read string
if type(vvv) == detectron2.config.config.CfgNode:
# (3) if yes, iterate through it to log separately
for kkkk, vvvv in vvv.items():
# (3) generate param_name
param_name = k + '.' + kk + '.' + kkk + '.' + kkkk
print(param_name, ':', vvvv)
# (3) log if exists
if vvvv:
mlflow.log_param(param_name, vvvv)
# (3) if not a dict
else:
# (3) generate param_name
param_name = k + '.' + kk + '.' + kkk
print(param_name, ':', vvv)
# (3) log if variable exists
if vvv:
mlflow.log_param(param_name, vvv)
# (2) if not a dict
else:
# (2) generate param_name
param_name = k + '.' + kk
print(param_name, ':', vv)
# (2) log if exists
if vv:
mlflow.log_param(param_name, vv) | {
"domain": "codereview.stackexchange",
"id": 43600,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing",
"url": null
} |
python, python-3.x, parsing
# (1) if not a dict
else:
print(k, ':', v)
# (1) log if exists
if v:
mlflow.log_param(k, v)
I would gladly provide you with more details if necessary. Thanks in advance for all the tips and suggestions!
Answer: It looks like you are basically trying to "flatten" a nested dict. A recursive generator works nicely. For each key,value pair in the dict, make a recursive call if the value is a dict, otherwise yield the key,value pair (the base case).
Note: you shouldn't use type(cfg) == some_class. Use isinstance() instead.
from collections.abc import Mapping
def flatten_cfg(cfg, keys=''):
for key, value in cfg.items():
new_keys = f"{keys}.{key}" if keys else key
if isinstance(value, Mapping):
yield from flatten_cfg(value, new_keys)
else:
yield (new_keys, value)
Use it like so:
cfg = {
"ANCHOR":{
"GENERATOR":{
"ANGLES":[[-90, 0, 90]],
"ASPECT_RATIOS":[[0,5, 1.0, 2.0]],
"NAME":"DefaultAnchorGenerator",
"SIZES":[[32], [64], [128], [256], [512]]
}
},
"AUG":{
"FLIP":True,
"MAX_SIZE":4000,
"MIN_SIZES":(400,500,600,700,800,900,1000,1100,1200)
},
"BACKBONE":{
"FREEZE_AT":2,
"NAME":"build_resnet_fpn_backbone"
}
}
flat_cfg = list(flatten_cfg(cfg))
width = max(len(name) for name,_ in flat_cfg)
for name, value in flat_cfg:
print(f"{name:{width}s} {value}") | {
"domain": "codereview.stackexchange",
"id": 43600,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing",
"url": null
} |
python, python-3.x, parsing
Output:
ANCHOR.GENERATOR.ANGLES [[-90, 0, 90]]
ANCHOR.GENERATOR.ASPECT_RATIOS [[0, 5, 1.0, 2.0]]
ANCHOR.GENERATOR.NAME DefaultAnchorGenerator
ANCHOR.GENERATOR.SIZES [[32], [64], [128], [256], [512]]
AUG.FLIP True
AUG.MAX_SIZE 4000
AUG.MIN_SIZES (400, 500, 600, 700, 800, 900, 1000, 1100, 1200)
BACKBONE.FREEZE_AT 2
BACKBONE.NAME build_resnet_fpn_backbone | {
"domain": "codereview.stackexchange",
"id": 43600,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing",
"url": null
} |
c#, playing-cards
Title: C# Singleplayer Blackjack Game
Question: I recently finished a simple Blackjack game that I made to get better at C#. I am wondering how I can better organize or simplify my code. There are 4 files:
Program.cs
/* Blackjack Game Copyright (C) 2018
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see<https://www.gnu.org/licenses/>. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Blackjack;
namespace Blackjack
{
public class Program
{
private static Deck deck = new Deck();
private static Player player = new Player();
private enum RoundResult
{
PUSH,
PLAYER_WIN,
PLAYER_BUST,
PLAYER_BLACKJACK,
DEALER_WIN,
SURRENDER,
INVALID_BET
}
/// <summary>
/// Initialize Deck, deal the player and dealer hands, and display them.
/// </summary>
static void InitializeHands()
{
deck.Initialize();
player.Hand = deck.DealHand();
Dealer.HiddenCards = deck.DealHand();
Dealer.RevealedCards = new List<Card>();
// If hand contains two aces, make one Hard.
if (player.Hand[0].Face == Face.Ace && player.Hand[1].Face == Face.Ace)
{
player.Hand[1].Value = 1;
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
if (Dealer.HiddenCards[0].Face == Face.Ace && Dealer.HiddenCards[1].Face == Face.Ace)
{
Dealer.HiddenCards[1].Value = 1;
}
Dealer.RevealCard();
player.WriteHand();
Dealer.WriteHand();
}
/// <summary>
/// Handles everything for the round.
/// </summary>
static void StartRound()
{
Console.Clear();
if (!TakeBet())
{
EndRound(RoundResult.INVALID_BET);
return;
}
Console.Clear();
InitializeHands();
TakeActions();
Dealer.RevealCard();
Console.Clear();
player.WriteHand();
Dealer.WriteHand();
player.HandsCompleted++;
if (player.Hand.Count == 0)
{
EndRound(RoundResult.SURRENDER);
return;
}
else if (player.GetHandValue() > 21)
{
EndRound(RoundResult.PLAYER_BUST);
return;
}
while (Dealer.GetHandValue() <= 16)
{
Thread.Sleep(1000);
Dealer.RevealedCards.Add(deck.DrawCard());
Console.Clear();
player.WriteHand();
Dealer.WriteHand();
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
if (player.GetHandValue() > Dealer.GetHandValue())
{
player.Wins++;
if (Casino.IsHandBlackjack(player.Hand))
{
EndRound(RoundResult.PLAYER_BLACKJACK);
}
else
{
EndRound(RoundResult.PLAYER_WIN);
}
}
else if (Dealer.GetHandValue() > 21)
{
player.Wins++;
EndRound(RoundResult.PLAYER_WIN);
}
else if (Dealer.GetHandValue() > player.GetHandValue())
{
EndRound(RoundResult.DEALER_WIN);
}
else
{
EndRound(RoundResult.PUSH);
}
}
/// <summary>
/// Ask user for action and perform that action until they stand, double, or bust.
/// </summary>
static void TakeActions()
{
string action;
do
{
Console.Clear();
player.WriteHand();
Dealer.WriteHand();
Console.Write("Enter Action (? for help): ");
Console.ForegroundColor = ConsoleColor.Cyan;
action = Console.ReadLine();
Casino.ResetColor(); | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
switch (action.ToUpper())
{
case "HIT":
player.Hand.Add(deck.DrawCard());
break;
case "STAND":
break;
case "SURRENDER":
player.Hand.Clear();
break;
case "DOUBLE":
if (player.Chips <= player.Bet)
{
player.AddBet(player.Chips);
}
else
{
player.AddBet(player.Bet);
}
player.Hand.Add(deck.DrawCard());
break;
default:
Console.WriteLine("Valid Moves:");
Console.WriteLine("Hit, Stand, Surrender, Double");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
break;
}
if (player.GetHandValue() > 21)
{
foreach (Card card in player.Hand)
{
if (card.Value == 11) // Only a soft ace can have a value of 11
{
card.Value = 1;
break;
}
}
}
} while (!action.ToUpper().Equals("STAND") && !action.ToUpper().Equals("DOUBLE")
&& !action.ToUpper().Equals("SURRENDER") && player.GetHandValue() <= 21);
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
/// <summary>
/// Take player's bet
/// </summary>
/// <returns>Was the bet valid</returns>
static bool TakeBet()
{
Console.Write("Current Chip Count: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(player.Chips);
Casino.ResetColor();
Console.Write("Minimum Bet: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(Casino.MinimumBet);
Casino.ResetColor();
Console.Write("Enter bet to begin hand " + player.HandsCompleted + ": ");
Console.ForegroundColor = ConsoleColor.Magenta;
string s = Console.ReadLine();
Casino.ResetColor();
if (Int32.TryParse(s, out int bet) && bet >= Casino.MinimumBet && player.Chips >= bet)
{
player.AddBet(bet);
return true;
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
/// <summary>
/// Perform action based on result of round and start next round.
/// </summary>
/// <param name="result">The result of the round</param>
static void EndRound(RoundResult result)
{
switch (result)
{
case RoundResult.PUSH:
player.ReturnBet();
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Player and Dealer Push.");
break;
case RoundResult.PLAYER_WIN:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Player Wins " + player.WinBet(false) + " chips");
break;
case RoundResult.PLAYER_BUST:
player.ClearBet();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Player Busts");
break;
case RoundResult.PLAYER_BLACKJACK:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Player Wins " + player.WinBet(true) + " chips with Blackjack.");
break;
case RoundResult.DEALER_WIN:
player.ClearBet();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Dealer Wins.");
break;
case RoundResult.SURRENDER:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Player Surrenders " + (player.Bet / 2) + " chips");
player.Chips += player.Bet / 2;
player.ClearBet();
break;
case RoundResult.INVALID_BET:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid Bet.");
break;
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
if (player.Chips <= 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine("You ran out of Chips after " + (player.HandsCompleted - 1) + " rounds.");
Console.WriteLine("500 Chips will be added and your statistics have been reset.");
player = new Player();
}
Casino.ResetColor();
Console.WriteLine("Press any key to continue");
Console.ReadKey();
StartRound();
}
static void Main(string[] args)
{
// Console cannot render unicode characters without this line
Console.OutputEncoding = Encoding.UTF8;
Casino.ResetColor();
Console.Title = "♠♥♣♦ Blackjack";
Console.WriteLine("♠♥♣♦ Welcome to Blackjack v" + Casino.GetVersionCode());
Console.WriteLine("Press any key to play.");
Console.ReadKey();
StartRound();
}
}
}
Casino.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
public class Casino
{
private static string versionCode = "1.0";
public static int MinimumBet { get; } = 10;
public static string GetVersionCode() { return versionCode; }
/// <param name="hand">The hand to check</param>
/// <returns>Returns true if the hand is blackjack</returns>
public static bool IsHandBlackjack(List<Card> hand)
{
if (hand.Count == 2)
{
if (hand[0].Face == Face.Ace && hand[1].Value == 10) return true;
else if (hand[1].Face == Face.Ace && hand[0].Value == 10) return true;
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
/// <summary>
/// Reset Console Colors to DarkGray on Black
/// </summary>
public static void ResetColor()
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.BackgroundColor = ConsoleColor.Black;
}
}
public class Player
{
public int Chips { get; set; } = 500;
public int Bet { get; set; }
public int Wins { get; set; }
public int HandsCompleted { get; set; } = 1;
public List<Card> Hand { get; set; }
/// <summary>
/// Add Player's chips to their bet.
/// </summary>
/// <param name="bet">The number of Chips to bet</param>
public void AddBet(int bet)
{
Bet += bet;
Chips -= bet;
}
/// <summary>
/// Set Bet to 0
/// </summary>
public void ClearBet()
{
Bet = 0;
}
/// <summary>
/// Cancel player's bet. They will neither lose nor gain any chips.
/// </summary>
public void ReturnBet()
{
Chips += Bet;
ClearBet();
}
/// <summary>
/// Give player chips that they won from their bet.
/// </summary>
/// <param name="blackjack">If player won with blackjack, player wins 1.5 times their bet</param>
public int WinBet(bool blackjack)
{
int chipsWon;
if (blackjack)
{
chipsWon = (int) Math.Floor(Bet * 1.5);
}
else
{
chipsWon = Bet * 2;
}
Chips += chipsWon;
ClearBet();
return chipsWon;
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
Chips += chipsWon;
ClearBet();
return chipsWon;
}
/// <returns>
/// Value of all cards in Hand
/// </returns>
public int GetHandValue()
{
int value = 0;
foreach(Card card in Hand)
{
value += card.Value;
}
return value;
}
/// <summary>
/// Write player's hand to console.
/// </summary>
public void WriteHand()
{
// Write Bet, Chip, Win, Amount with color, and write Round #
Console.Write("Bet: ");
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write(Bet + " ");
Casino.ResetColor();
Console.Write("Chips: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(Chips + " ");
Casino.ResetColor();
Console.Write("Wins: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(Wins);
Casino.ResetColor();
Console.WriteLine("Round #" + HandsCompleted);
Console.WriteLine();
Console.WriteLine("Your Hand (" + GetHandValue() + "):");
foreach (Card card in Hand) {
card.WriteDescription();
}
Console.WriteLine();
}
}
public class Dealer
{
public static List<Card> HiddenCards { get; set; } = new List<Card>();
public static List<Card> RevealedCards { get; set; } = new List<Card>();
/// <summary>
/// Take the top card from HiddenCards, remove it, and add it to RevealedCards.
/// </summary>
public static void RevealCard()
{
RevealedCards.Add(HiddenCards[0]);
HiddenCards.RemoveAt(0);
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
/// <returns>
/// Value of all cards in RevealedCards
/// </returns>
public static int GetHandValue()
{
int value = 0;
foreach (Card card in RevealedCards)
{
value += card.Value;
}
return value;
}
/// <summary>
/// Write Dealer's RevealedCards to Console.
/// </summary>
public static void WriteHand()
{
Console.WriteLine("Dealer's Hand (" + GetHandValue() + "):");
foreach (Card card in RevealedCards)
{
card.WriteDescription();
}
for (int i = 0; i < HiddenCards.Count; i++)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("<hidden>");
Casino.ResetColor();
}
Console.WriteLine();
}
}
}
Deck.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
public class Deck
{
private List<Card> cards;
/// <summary>
/// Initilize on creation of Deck.
/// </summary>
public Deck()
{
Initialize();
}
/// <returns>
/// Returns a Cold Deck-- a deck organized by Suit and Face.
/// </returns>
public List<Card> GetColdDeck()
{
List<Card> coldDeck = new List<Card>();
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
coldDeck.Add(new Card((Suit)j, (Face)i));
}
}
return coldDeck;
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
return coldDeck;
}
/// <summary>
/// Remove top 2 cards of Deck and turn it into a list.
/// </summary>
/// <returns>List of 2 Cards</returns>
public List<Card> DealHand()
{
// Create a temporary list of cards and give it the top two cards of the deck.
List<Card> hand = new List<Card>();
hand.Add(cards[0]);
hand.Add(cards[1]);
// Remove the cards added to the hand.
cards.RemoveRange(0, 2);
return hand;
}
/// <summary>
/// Pick top card and remove it from the deck
/// </summary>
/// <returns>The top card of the deck</returns>
public Card DrawCard()
{
Card card = cards[0];
cards.Remove(card);
return card;
}
/// <summary>
/// Randomize the order of the cards in the Deck.
/// </summary>
public void Shuffle()
{
Random rng = new Random();
int n = cards.Count;
while(n > 1)
{
n--;
int k = rng.Next(n + 1);
Card card = cards[k];
cards[k] = cards[n];
cards[n] = card;
}
}
/// <summary>
/// Replace the deck with a Cold Deck and then Shuffle it.
/// </summary>
public void Initialize()
{
cards = GetColdDeck();
Shuffle();
}
}
}
Card.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Blackjack.Suit;
using static Blackjack.Face; | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
using static Blackjack.Suit;
using static Blackjack.Face;
namespace Blackjack
{
public enum Suit
{
Clubs,
Spades,
Diamonds,
Hearts
}
public enum Face
{
Ace,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King
}
public class Card
{
public Suit Suit { get; }
public Face Face { get; }
public int Value { get; set; }
public char Symbol { get; }
/// <summary>
/// Initilize Value and Suit Symbol
/// </summary>
public Card(Suit suit, Face face)
{
Suit = suit;
Face = face;
switch (Suit)
{
case Clubs:
Symbol = '♣';
break;
case Spades:
Symbol = '♠';
break;
case Diamonds:
Symbol = '♦';
break;
case Hearts:
Symbol = '♥';
break;
}
switch (Face)
{
case Ten:
case Jack:
case Queen:
case King:
Value = 10;
break;
case Ace:
Value = 11;
break;
default:
Value = (int)Face + 1;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
/// <summary>
/// Print out the description of the card, marking Aces as Soft or Hard.
/// </summary>
public void WriteDescription()
{
if (Suit == Suit.Diamonds || Suit == Suit.Hearts)
{
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.White;
}
if (Face == Ace)
{
if (Value == 11)
{
Console.WriteLine(Symbol + " Soft " + Face + " of " + Suit);
}
else
{
Console.WriteLine(Symbol + " Hard " + Face + " of " + Suit);
}
}
else
{
Console.WriteLine(Symbol + " " + Face + " of " + Suit);
}
Casino.ResetColor();
}
}
}
Program.cs: This file controls the game by printing most text and taking > player input.
Casino.cs: This file contains "the rules of the house" as well as Player and > Dealer classes.
Deck.cs: This file contains the code for the Deck--drawing cards and
shuffling.
Card.cs: This file contains the code for the Card class. | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
c#, playing-cards
Answer: A few things I noticed:
Instead of adding one to the Face enum value, it would make sense to me to make Ace = 1,. This will automatically set all the rest to where you need them.
A Hand class would make sense. This could handle the sum of the cards as well keep track of which is hidden and which is revealed. This removes some redundancy between the player's hand and the dealers hand
I would suggest taking the decision of hard or soft sum away from Card and put it in Hand. The value of the Ace will be hard or soft depending on the other cards in the hand.
A Game to handle the play of the game would improve your design, as well as reduce the refactoring that would be needed to extend this to a GUI version.
I noticed you're printing various messages out in different colors. A separate Message class with properties to control the attributes of each message, would help. The messages could then be stored in a Dictionary<String,Message>
Instead of hard coding Console printing, change your methods to accept streams and pass those as arguments in the constructor of the game. Now you can interface with a console, network , or GUI. | {
"domain": "codereview.stackexchange",
"id": 43601,
"lm_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#, playing-cards",
"url": null
} |
algorithm, haskell, functional-programming
Title: Project Euler 11 Haskell - Largest product in a grid
Question: Intro
I have been learning haskell and functional programming using random Project Euler problems. Currently, I have solved Problem 11.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
My solution
My solution consists of 4 parts.
Finding the rows, columns and diagonals
Flattening them to a single list
Finding the product of sublists of 4, storing them in a list.
Returning the maximum product
module Main where
import Data.List (nub, transpose)
-- | Grid is just a 2-D List.
type Grid = [[Int]] | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
import Data.List (nub, transpose)
-- | Grid is just a 2-D List.
type Grid = [[Int]]
grid :: Grid
grid =
[ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
] | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
main :: IO ()
main = do
print $ maximum products
where
seqs = concatMap ($ grid) [rows, cols, diag]
products = subLists $ concat seqs
where
-- Function to operate on sublists of four
subLists :: [Int] -> [Int]
subLists xs
| null xs = []
| otherwise = (product . take 4 $ xs) : subLists (tail xs)
rows, cols, diag :: Grid -> Grid
-- | Rows returns all rows of Grid.
rows = id
-- | Columns can be defined as the transposition of rows
cols = Data.List.transpose
-- | Diagnoals of a Grid. (All directions: Up & Right, Down & Right, Up & Left, Down & Left)
diag grid =
Data.List.nub allDiags -- Deduplicate list of diagonals to reduce computation of products.
where
-- Concatenate all 4 Directions
allDiags =
(diags . rows) grid
++ (diags . cols) grid
++ (diags . rows) gridMirror
++ (diags . cols) gridMirror
gridMirror = mirror grid
-- Mirror of a grid just reflects it about its columns.
mirror :: Grid -> Grid
mirror = reverse . Data.List.transpose
-- Main logic to get Diagonals of a grid.
-- How this works is basically explained here: https://stackoverflow.com/a/2792547
-- Imagine this grid.
-- [X . . . . .]
-- [. X . . . .]
-- [. . X . . .]
-- [. . . X . .]
-- [. . . . X .]
-- [. . . . . X]
-- When you drop 0 elems from row 0, 1 elem from row 1 ...: You get:
-- [X . . . . .]
-- [X . . . .]
-- [X . . . ]
-- [X . .]
-- [X .]
-- [X]
-- Each of the columns is a diagonal. Repeat this for mirror, tranpose of mirror and transpose and you got all diagonals from all mirrors.
diags :: Grid -> Grid
diags [] = []
diags (xs : xss)
| null xs = []
| otherwise = getDiag (xs : xss) : diags (map (drop 1) (xs : xss)) | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
getDiag :: Grid -> [Int]
getDiag [] = []
getDiag xss
| null $ head xss = []
| otherwise = (head . head) xss : getDiag ((map (drop 1) . drop 1) xss)
What I woud like for review
As I said, I am new to haskell, therefore I would appreicate if somebody could tell me how idiomatic this code was and how to improve it.
Conciseness - I have seen some absolutely elegant 1-liners in haskell. Is there any way to make my diag function more concise?
Performance
On my system (i5-6200u), This particular grid takes 0.00s in user to execute according to time when compiled with -O2. Therefore, I have no qualms about that, althogh if I could reduce memory usage, I would gladly take it.
Answer: Remarks
Your code works! Software is hard, and working software deserves celebration
It is pretty easy to read
The code is reasonably-well structured and you make use of medium-level features (destructuring, where-clauses, etc)
Suggestions
In no particular order
The type Grid = [[Int]] should be a newtype Grid = Grid { rows :: [[Int]] }. A Grid is semantically distinct from an [[Int]], and therefore deserves its own type
I found some of your function name choices confusing. I would recommend renaming:
diags to upperFallingDiags, for clarity/precision
getDiag to fallingDiag, for clarity/precision
mirror to reflectHoriz, for clarity/precision
diag to diags, because it returns multiple diags, and to match the naming scheme of rows and cols
I could be wrong, but I don't think your comment explaining your diagonal-getting algorithm works is correct. The algorithm implemented seems to differ from the algorithm described. I've replaced the comment in the edited code (below)
You write that the diagonal-getting algorithm returns all directions: up & right, .... This strikes me as misleading. When applied to the grid
0 1 2
4 5 6
7 8 9 | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
your algorithm does not produce both [1, 6] and [6, 1], but only one of these. More accurate is that your algorithm produces both the up-left/down-right direction (falling diagonals) and the up-right/down-left direction (rising diagonals)
I don't think the application of Data.List.nub is worth it. I'd only expect two diagonals to be repeated (the two longest diagonals), and I don't think that's worth the O(n^2) runtime of nub. I could be wrong, though.
subLists can be implemented as
fmap product . filter (length >>> (== 4)) . fmap (take 4) . tails
or just
fmap product . fmap (take 4) . tails
since all the numbers are positive (so filter does not effect the final maximum)
Since you've imported Data.List (nub, transpose), you can refer to them simply as nub and transpose instead of as Data.List.nub and Data.List.transpose
Scoping: I would move mirror (renamed to reflectHoriz) outside of the where-clause, since it's a very generic operation not specific to the implementation of the diagonal-getting algorithm. Also, I would move the assignment of gridMirror inwards, to communicate that it's only used for a small part of the where block.
Indent where-blocks with only one level of indentation. Using two is just a waste of a level. (Admission: this is my preference; typically in Haskell where-blocks use two levels)
The code
diags [] = []
diags (xs : xss)
| null xs = []
| otherwise = ...
can be written more clearly as
diags [] = []
diags ([] : _) = []
diags grid = ...
Edited code
This code implements all the suggestions I've given as well as a small handful of other changes
Brownie points to you if you can figure out how fallingDiags works :-)
module Main where
import Data.List (nub, tails)
import qualified Data.List as List
newtype Grid = Grid { rows :: [[Int]] }
reflectHoriz :: Grid -> Grid
reflectHoriz = Grid . reverse . List.transpose . rows | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
reflectHoriz :: Grid -> Grid
reflectHoriz = Grid . reverse . List.transpose . rows
-- | Columns can be defined as the transposition of rows
transpose :: Grid -> Grid
transpose = Grid . List.transpose . rows
cols :: Grid -> [[Int]]
cols = rows . transpose
-- | Rising and falling diagnoals of a Grid
diags :: Grid -> [[Int]]
diags = \grid -> risingDiags grid ++ fallingDiags grid
where
risingDiags :: Grid -> [[Int]]
risingDiags = fallingDiags . reflectHoriz
fallingDiags :: Grid -> [[Int]]
fallingDiags = upperFallingDiags <> (upperFallingDiags . transpose)
-- Main logic to get Diagonals of a grid.
-- Imagine this grid.
-- [X . . . . .]
-- [. X . . . .]
-- [. . X . . .]
-- [. . . X . .]
-- [. . . . X .]
-- [. . . . . X]
-- When you drop 1 elem from all rows, the diagonal shifts:
-- [ X . . . .]
-- [ . X . . .]
-- [ . . X . .]
-- [ . . . X .]
-- [ . . . . X]
-- [ . . . . .]
-- Repeat to produce every upper falling diagonal of the grid
upperFallingDiags :: Grid -> [[Int]]
upperFallingDiags (Grid []) = []
upperFallingDiags (Grid ([] : _)) = []
upperFallingDiags grid = fallingDiag grid : upperFallingDiags (Grid $ map (drop 1) (rows grid))
fallingDiag :: Grid -> [Int]
fallingDiag (Grid []) = []
fallingDiag (Grid ([] : _)) = []
fallingDiag (Grid xss) = (head . head) xss : fallingDiag (Grid $ (map (drop 1) . drop 1) xss)
main :: IO ()
main = do
print $ maximum products
print $ maximum products == 70600674
where
seqs = concatMap ($ grid) [rows, cols, diags]
products = fmap product . fmap (take 4) . tails $ concat seqs | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
grid :: Grid
grid = Grid
[ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
] | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
algorithm, haskell, functional-programming
Closing
I had many suggestions, because your code had many rooms for improvement. This is not to say it was bad. It was not! I was impressed. But Haskell is an extremely featureful language, and there's almost always something more to be learned.
Cheers! | {
"domain": "codereview.stackexchange",
"id": 43602,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, haskell, functional-programming",
"url": null
} |
python, algorithm
Title: Finding all smaller digits for every entry in the array towards the right
Question: The array contains digits and it is unsorted. Its length could be as big as 120000. I need to count the smaller numbers to the right of each digit.
This is a coding challenge on Codewars which requires a specific code efficency to be completed (Solve X amount in Y time).
https://www.codewars.com/kata/56a1c63f3bc6827e13000006/train/python
Example:
100, 10, 10, 10, 10]should return 4, 0, 0, 0, 0
1, 2, 3 should return 0, 0, 0
1, 2, 0 should return 1, 1, 0
1, 2, 1 should return 0, 1, 0
My current approach is to sort the array and then do a binary search inside that array for the current number. Afterwards I skip over the possible duplicates of this number and search for the next smaller number and return the amount of all leftover entities.
I then remove the just used number out of the sorted array.
My question is mostly about using a fast approach to this problem, since the time needed with my program takes too long.
def smaller(arr):
sorted_arr = sorted(arr)
lenght = len(arr)
for i in range(lenght):
pos = binary_search(sorted_arr, arr[i])
while sorted_arr[pos] == sorted_arr[pos-1] and pos-1>=0:
pos -= 1
arr[i] = pos
sorted_arr.pop(pos)
return arr
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid-1
else:
return mid
return -1
Answer:
Don't reinvent the wheel. Python has a bisect module; use bisect_left.
Popping an arbitrary element from a list has a linear time complexity, which drives the total time complexity of your solution to quadratic. Unfortunately you have to reconsider an algorithm. | {
"domain": "codereview.stackexchange",
"id": 43603,
"lm_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, algorithm",
"url": null
} |
python, algorithm
The problem is very similar to counting inversions. The only difference is that you are interested not in a total amount of inversions, but in a per-element ones. This observation suggests yet another variation on a merge sort theme. I don't want to spell out the algorithm. As a hint, merge sort value, count tuples. | {
"domain": "codereview.stackexchange",
"id": 43603,
"lm_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, algorithm",
"url": null
} |
python, performance, beginner, pandas
Title: Obtaining error code information that occurs before, during, and after a fix/repair using date data | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
Question: I have completed a project I was working on using the methods I know how, but it is very inefficient. I am a beginner trying to figure out how I can improve my work by using software solutions.
I have a large dataset and I put it into smaller dataframes (grouped by part numbers) which I will loop through to perform the same task on all of them. The following is a small example of one of the individual dataframes:
import pandas as pd
from pandas import Timestamp
import numpy as np
data = {'Part': {0: 'QOL2',1: 'QOL2',2: 'QOL2',3: 'QOL2',4: 'QOL2',5: 'QOL2',6: 'QOL2',7: 'QOL2',8: 'QOL2',9: 'QOL2'},
'Start': {0: Timestamp('2021-09-25 00:00:00'),1: Timestamp('2021-09-30 00:00:00'),2: Timestamp('2021-10-04 00:00:00'),3: Timestamp('2021-10-04 00:00:00'),4: Timestamp('2021-11-03 00:00:00'),5: Timestamp('2021-11-03 00:00:00'),6: Timestamp('2021-12-22 00:00:00'),7: Timestamp('2021-12-22 00:00:00'),8: Timestamp('2021-12-24 00:00:00'),9: Timestamp('2022-03-21 00:00:00')},
'Finish': {0: Timestamp('2021-09-25 00:00:00'),1: Timestamp('2021-09-30 00:00:00'),2: Timestamp('2021-10-04 00:00:00'),3: Timestamp('2021-10-04 00:00:00'),4: Timestamp('2021-11-03 00:00:00'),5: Timestamp('2021-11-03 00:00:00'),6: Timestamp('2021-12-24 00:00:00'),7: Timestamp('2021-12-22 00:00:00'),8: Timestamp('2021-12-24 00:00:00'),9: Timestamp('2022-03-21 00:00:00')},
'Code': {0: 'SR2F',1: 'LS4DQ',2: 'DP2L',3: 'Testing Broke',4: 'SR2F',5: 'JKO2',6: 'Light Off',7: 'QFD3',8: 'A3SA',9: 'LA52'},
'Fix': {0: 'na',1: 'na',2: 'na',3: 'Testing Procedure Fixed',4: 'na',5: 'na',6: 'Light Repair',7: 'na',8: 'na',9: 'na'},
'Fixed': {0: 'No',1: 'No',2: 'No',3: 'Yes',4: 'No',5: 'No',6: 'Yes',7: 'No',8: 'No',9: 'No'},
'DateColumnTests': {0: 'None',1: 'None',2: 'None',3: 'None',4: 'None',5: 'None',6: 'None',7: 'None',8: 'None',9: 'None'},
'DuringTest': {0: False,1: False,2: False,3: False,4: False,5: False,6: False,7: False,8: False,9: False}} | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
df = pd.DataFrame.from_dict(data) | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
Part
Start
Finish
Code
Fix
Fixed
DateColumnTests
DuringTest
0
QOL2
2021-09-25 00:00:00
2021-09-25 00:00:00
SR2F
na
No
None
False
1
QOL2
2021-09-30 00:00:00
2021-09-30 00:00:00
LS4DQ
na
No
None
False
2
QOL2
2021-10-04 00:00:00
2021-10-04 00:00:00
DP2L
na
No
None
False
3
QOL2
2021-10-04 00:00:00
2021-10-04 00:00:00
Testing Broke
Testing Procedure Fixed
Yes
None
False
4
QOL2
2021-11-03 00:00:00
2021-11-03 00:00:00
SR2F
na
No
None
False
5
QOL2
2021-11-03 00:00:00
2021-11-03 00:00:00
JKO2
na
No
None
False
6
QOL2
2021-12-22 00:00:00
2021-12-24 00:00:00
Light Off
Light Repair
Yes
None
False
7
QOL2
2021-12-22 00:00:00
2021-12-22 00:00:00
QFD3
na
No
None
False
8
QOL2
2021-12-24 00:00:00
2021-12-24 00:00:00
A3SA
na
No
None
False
9
QOL2
2022-03-21 00:00:00
2022-03-21 00:00:00
LA52
na
No
None
False
I added the last 3 columns above for the analysis I do later so they are not necessarily needed. In the dataframe I have:
one part number in the first column
one code or fix in the fourth column
if there is a fix in fourth column, the fix name will be in fifth column
start and finish dates of the code/fix in the second and third columns
codes always have the same start/finish date
fixes can have the same start/finish date or last multiple days
The idea is to have an output dataframe that has the same number of rows as the number of fixes (in this case 2 fixes in indexes 3 and 6). For each row there is a fix, I want to see which codes happen before the current fix and the last one; the codes that happen during the current fix; and the codes that happen after the current fix and before the next one. The output would look like:
Part
FixName
BeforeFix
DuringFix
AfterFix
0
QOL2
Testing Broke
['SR2F', 'LS4DQ']
['DP2L']
['SR2F', 'JKO2']
1
QOL2
Light Off
['SR2F', 'JKO2']
['QFD3', 'A3SA']
['LA52'] | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
1
QOL2
Light Off
['SR2F', 'JKO2']
['QFD3', 'A3SA']
['LA52']
I was able to get this desired output first using iterrows(). I understood from some research that iterrows() was not very optimal. I then tried changing to itertuples() as it was a reasonable transition. Although it ran faster, it still took a very long time (total number of rows could be anywhere from 2,000 to 1,000,000). My code to get this output is:
uniqueFixes = df['Fixed'].value_counts() # Counting Yes/No
uniqueFixesNum = uniqueFixes[1] # Number of Yes
new_df = pd.DataFrame(
columns = ['Part', 'FixName', 'BeforeFix', 'DuringFix', 'AfterFix'],
index = range(uniqueFixesNum)) # New df
PartCol = [] # Used for number and names of Parts
FixCol = [] # Used for number and names of Fix Names
for rowQ in df.itertuples():
if rowQ.Fixed == 'Yes':
PartCol.append(rowQ.Part) # Appending Part Names
FixCol.append(rowQ.Code) # Appending Fix Names
new_df['Part'] = PartCol # Populating new df with Parts
new_df['FixName'] = FixCol # Populating new df with Fixes
# Find dates where codes occur during a fix:
for daterow1 in df.itertuples():
for daterow2 in df.itertuples():
# Comparing start date of row to start and finish date of every other row, to see if it is in a range of any Fix
# If it does fall in range of a Fix, change DateColumnTests row from None to Index of Fix
if daterow1.Start >= daterow2.Start and daterow1.Start < daterow2.Finish and daterow1.Fixed == 'No':
df.loc[daterow1.Index, 'DateColumnTests'] = daterow2.Index
elif daterow1.Start > daterow2.Start and daterow1.Start <= daterow2.Finish and daterow1.Fixed == 'No':
df.loc[daterow1.Index, 'DateColumnTests'] = daterow2.Index
elif daterow1.Start >= daterow2.Start and daterow1.Start <= daterow2.Finish and daterow2.Fixed == 'Yes':
df.loc[daterow1.Index, 'DateColumnTests'] = daterow2.Index
#display(df) | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
BeforeFix = [] # Column to append to
DuringFix = [] # Column to append to
AfterFix = [] # Column to append to
FixCount = 0 # Increases by 1 for every Fix
for row1 in df.itertuples():
if row1.Fixed == 'No' and row1.DateColumnTests == 'None': # If row has No Fix and 'None' in column, will be in BeforeFix
BeforeFix.append(row1.Code)
if row1.Fixed == 'Yes':
new_df.iat[FixCount, 2] = str(BeforeFix) # If row has Yes, BeforeFix column will become entry in new df at the FixCount
for row2 in df.itertuples(): # When row1 has a yes, will compare it against all rows in row2
# row2 finish is less than row1 finish, has false, has 'None', and row2 is not a fix
if row2.Finish < row1.Finish and row2.DuringTest == False and row2.DateColumnTests == 'None' and row2.Fixed != 'Yes':
df.loc[row2.Index, 'DuringTest'] = 'Before' # False becomes Before
# row2 finish is less than or equal to row1 finish, and row2 is not a fix
elif row2.Finish <= row1.Finish and row2.DuringTest == False and row2.Fixed != 'Yes':
df.loc[row2.Index, 'DuringTest'] = 'During' # False becomes during
DuringFix.append(row2.Code) # Appending these values to during column | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
new_df.iat[FixCount, 3] = str(DuringFix) # During Column added to new df
FixCount = FixCount + 1 # Adding 1 to Fix Count
BeforeFix.clear() # Clearing
DuringFix.clear() # Clearing
for row3 in df.itertuples(): # The last rows with a False and no Fix must be in the After Column
if row3.DuringTest == False and row3.Fixed == 'No':
AfterFix.append(row3.Code)
for row4 in new_df.itertuples(): # For After column, can duplicate the before column in the next row if the
if row4.Index != 0:
new_df.loc[row4.Index - 1, 'AfterFix'] = row4.BeforeFix
if row4.Index == len(new_df) - 1: # After the last fix, if there are codes after, will be in the last After Row
new_df.loc[row4.Index, 'AfterFix'] = str(AfterFix)
display(new_df) | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
This code does get me to the desired output, but from researching, it sounds like itertuples() is not often the best practice. In my case above, I used it 7 times to complete my task. I had used a nested for loop two different types that used itertuples() in each loop which I believe took the most amount of time (I compared each row to every other row in the dataframe). I also achieved my goal by changing the values in the final columns (during iteration) and using those values in conditional statements (which I believe is also bad practice).
After trying to think of a different way to do it instead of iterating through the rows I could not think of a different approach without having some way of keeping track of the index like I could in itertuples() (or iterrows()). I was wondering if I am missing something obvious (or if it is very complex) or if this is an example where you need to use iteration in a dataframe. I see examples of things like vectorization but they usually seem aimed at numerical operations and I'm not sure if it would work in my case.
One thing that I thought might work would be to use groupby to group the dates for when they occur before a Fix and during a Fix for each Fix. Then I might be able to get away without keeping track of the Index and would not have to iterate and just use the new "groupby" dataframe to fill the values in the output dataframe. Although, the only way I thought of being able to use groupby would be to iterate through the rows and classify each row as Before# or During# so then I would be back to square one. I apologize for the long question, I am new and although I solved my task, I have a feeling I'm going to run into this type of problem again in the future.
Answer:
I put it into smaller dataframes (grouped by part numbers) which I will loop through to perform the same task on all of them | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
That's not usually how Pandas is supposed to work. You should have one dataframe and call df.groupby('Part'). However, I did not demonstrate this in my suggested code because your sample data only show one part.
Don't represent Fixed as a yes/no string; represent it as a boolean (and probably don't include it in the dataframe at all; keep it as a free series).
It's generally not a very good idea to construct series of lists in Pandas. Instead, if you're at all able, just have one row per code, and only one code column (not separate columns for before, during and after). You could distinguish these categories by
holding separate dataframes (what I did); or
adding a categorical variable equal to 'before', 'during' or 'after'; or
inferring the before/during/after status based on the relationship of the code date to the fix date.
In general you should avoid itertuples (especially in multiple nested loops). But this is a nasty problem so I don't blame you for reaching for that. It's made nastier by the fact that you have an "after" category. I don't know what your use case is, but it seems strange to me to duplicate codes and have them "owned" by multiple fix events. Could you not reduce this to a "before" and a "during", and assume that the "before" of fix i is the same as the "after" of fix i - 1 ?
Anyway, due to all of the above, your code is a mess but so is mine. There are lots of edge cases and I'm not convinced that I've taken care of them all. Unit test thoroughly.
Suggested
import pandas as pd
from pandas import Timestamp
import numpy as np | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
data = {
'Part': {0: 'QOL2',1: 'QOL2',2: 'QOL2',3: 'QOL2',4: 'QOL2',5: 'QOL2',6: 'QOL2',7: 'QOL2',8: 'QOL2',9: 'QOL2'},
'Start': {0: Timestamp('2021-09-25 00:00:00'),1: Timestamp('2021-09-30 00:00:00'),2: Timestamp('2021-10-04 00:00:00'),3: Timestamp('2021-10-04 00:00:00'),4: Timestamp('2021-11-03 00:00:00'),5: Timestamp('2021-11-03 00:00:00'),6: Timestamp('2021-12-22 00:00:00'),7: Timestamp('2021-12-22 00:00:00'),8: Timestamp('2021-12-24 00:00:00'),9: Timestamp('2022-03-21 00:00:00')},
'Finish': {0: Timestamp('2021-09-25 00:00:00'),1: Timestamp('2021-09-30 00:00:00'),2: Timestamp('2021-10-04 00:00:00'),3: Timestamp('2021-10-04 00:00:00'),4: Timestamp('2021-11-03 00:00:00'),5: Timestamp('2021-11-03 00:00:00'),6: Timestamp('2021-12-24 00:00:00'),7: Timestamp('2021-12-22 00:00:00'),8: Timestamp('2021-12-24 00:00:00'),9: Timestamp('2022-03-21 00:00:00')},
'Code': {0: 'SR2F',1: 'LS4DQ',2: 'DP2L',3: 'Testing Broke',4: 'SR2F',5: 'JKO2',6: 'Light Off',7: 'QFD3',8: 'A3SA',9: 'LA52'},
'Fix': {0: 'na',1: 'na',2: 'na',3: 'Testing Procedure Fixed',4: 'na',5: 'na',6: 'Light Repair',7: 'na',8: 'na',9: 'na'},
'Fixed': {0: 'No',1: 'No',2: 'No',3: 'Yes',4: 'No',5: 'No',6: 'Yes',7: 'No',8: 'No',9: 'No'},
'DateColumnTests': {0: 'None',1: 'None',2: 'None',3: 'None',4: 'None',5: 'None',6: 'None',7: 'None',8: 'None',9: 'None'},
'DuringTest': {0: False,1: False,2: False,3: False,4: False,5: False,6: False,7: False,8: False,9: False}}
df = pd.DataFrame.from_dict(data)
# Start "from scratch"
df = df.drop(['Fixed', 'DateColumnTests', 'DuringTest'], axis='columns')
# The string 'na' should be an actual NaN
df['Fix'] = df.Fix.replace('na', np.nan)
# Fix-type rows
is_fix = df.Fix.notna()
fixes = df[is_fix] | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
# Fix-type rows
is_fix = df.Fix.notna()
fixes = df[is_fix]
# Back-fill fix event start and finish dates
# Ensure 'fix' events occur at the end of a date group
by_start = df.sort_values(by=['Start', 'Fix'], na_position='first')
by_finish = by_start.sort_values(by=['Finish', 'Fix'], na_position='first')
nat = np.datetime64('NaT')
df['StartFix'] = pd.Series(
np.where(by_start.Fix.isna(), nat, by_start.Start),
index=by_start.index,
).bfill().ffill()
df['FinishFix'] = pd.Series(
np.where(by_finish.Fix.isna(), nat, by_finish.Finish),
index=by_finish.index,
).bfill().ffill()
is_during = (
~is_fix
& ((df.Start >= df.StartFix) | df.StartFix.isna())
& (df.Finish <= df.FinishFix)
)
left_during = df[is_during]
during = (
pd.merge(
left=left_during, right=fixes,
suffixes=('', '_Fix'),
left_on=('Part', 'StartFix', 'FinishFix'),
right_on=('Part', 'Start', 'Finish')
)
.drop(columns=['Start_Fix', 'Finish_Fix', 'Fix'])
.set_index(left_during.index)
.rename({'Fix_Fix': 'Fix'}, axis='columns')
)
not_during = df[~(is_fix | is_during)].drop(columns='Fix')
before_left = not_during[not_during.Start < not_during.StartFix]
before = (
pd.merge(
left=before_left, right=fixes,
suffixes=('', '_Fix'),
left_on=('Part', 'StartFix', 'FinishFix'),
right_on=('Part', 'Start', 'Finish'),
)
.drop(columns=['Start_Fix', 'Finish_Fix'])
.set_index(before_left.index)
)
after = (
pd.merge_asof(
left=not_during, right=fixes,
suffixes=('', '_Fix'),
by='Part', on='Start', direction='backward', # allow_exact_matches=False,
)
.set_index(not_during.index)
)
after = (
after[after.Fix.notna()]
.drop(columns='FinishFix')
.rename({
'Finish_Fix': 'FinishFix'
}, axis='columns')
)
pd.set_option('display.max_columns', None)
print('Before:')
print(before, '\n')
print('During:')
print(during, '\n')
print('After:')
print(after, '\n') | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
python, performance, beginner, pandas
Output
Before:
Part Start Finish Code StartFix FinishFix Code_Fix \
0 QOL2 2021-09-25 2021-09-25 SR2F 2021-10-04 2021-10-04 Testing Broke
1 QOL2 2021-09-30 2021-09-30 LS4DQ 2021-10-04 2021-10-04 Testing Broke
4 QOL2 2021-11-03 2021-11-03 SR2F 2021-12-22 2021-12-24 Light Off
5 QOL2 2021-11-03 2021-11-03 JKO2 2021-12-22 2021-12-24 Light Off
Fix
0 Testing Procedure Fixed
1 Testing Procedure Fixed
4 Light Repair
5 Light Repair
During:
Part Start Finish Code StartFix FinishFix Code_Fix \
2 QOL2 2021-10-04 2021-10-04 DP2L 2021-10-04 2021-10-04 Testing Broke
7 QOL2 2021-12-22 2021-12-22 QFD3 2021-12-22 2021-12-24 Light Off
8 QOL2 2021-12-24 2021-12-24 A3SA 2021-12-22 2021-12-24 Light Off
Fix
2 Testing Procedure Fixed
7 Light Repair
8 Light Repair
After:
Part Start Finish Code StartFix FinishFix Code_Fix \
4 QOL2 2021-11-03 2021-11-03 SR2F 2021-12-22 2021-10-04 Testing Broke
5 QOL2 2021-11-03 2021-11-03 JKO2 2021-12-22 2021-10-04 Testing Broke
9 QOL2 2022-03-21 2022-03-21 LA52 2021-12-22 2021-12-24 Light Off
Fix
4 Testing Procedure Fixed
5 Testing Procedure Fixed
9 Light Repair | {
"domain": "codereview.stackexchange",
"id": 43604,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner, pandas",
"url": null
} |
c++, matrix, c++20
Title: A matrix class using const members
Question: I've long used a simple matrix class with a vector and rows/cols for the shape. But I've always disliked getters even when necessary to prevent exposing invariants. Then came c++20 which provided the ability to modify consts in a class with the change in Basic.Life. So then I modified my matrix class to get rid of the rows and cols getters. However, I was unable to use a const vector as the move operations could not be done hence pessimizing performance.
So I just use new with a const ptr instead of a vector. Now the entire matrix class, except for the dynamic memory (contents of the matrix), are declared const so safer programming in class code, friend functions, and no longer need getters for safe user code. And the sizeof each matrix object is 40% smaller than the vector version.
Note that declaring the values in the matrix class const is consistent with them being unchanged from start of lifetime to end of lifetime. I believe the code provides a string exception guarantee but haven't tested this. Also, the matrix multiply, has a transpose mode that aligns the matrixes such that multi-threading (not shown) them is fairly trivial and it also keeps the cache happy. Would like any comments, especially of flaws that might be left.
CompilerExplorer, gcc, clang, msvc
header file: matrix2db.h
#pragma once
#include <memory>
#include <numeric>
#include <initializer_list>
#include <exception>
#include <stdexcept>
namespace matrix_const
{
template <typename T>
class Matrix2D {
T* const pv;
public:
const size_t cols;
const size_t rows;
Matrix2D() noexcept : pv(nullptr), cols(0), rows(0) {}
Matrix2D(size_t a_rows, size_t a_cols) :
pv(new T[a_rows * a_cols]), cols(a_cols), rows(a_rows) {} | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
Matrix2D(const Matrix2D& rhs) : pv(new T[rhs.rows * rhs.cols]), cols(rhs.cols), rows(rhs.rows) {
std::copy(rhs.pv, rhs.pv + rows * cols, pv);
}
Matrix2D& operator=(const Matrix2D& rhs) {
T* newp = new T[rhs.rows * rhs.cols]; // if new fails, *this is unchanged
delete[] pv;
std::construct_at(&rows, rhs.rows);
std::construct_at(&cols, rhs.cols);
std::construct_at(&pv, newp);
std::copy(rhs.pv, rhs.pv + rows * cols, pv);
return *this;
}
Matrix2D(Matrix2D&& rhs) noexcept : pv(rhs.pv), cols(rhs.cols), rows(rhs.rows) {
std::construct_at(&rhs.rows, 0); // maintain invariants in remnant
std::construct_at(&rhs.pv, nullptr);
}
Matrix2D& operator=(Matrix2D&& rhs) noexcept {
delete[] pv;
std::construct_at(&rows, rhs.rows);
std::construct_at(&cols, rhs.cols);
std::construct_at(&rhs.rows, 0); // maintain invariants
std::construct_at(&pv, rhs.pv);
std::construct_at(&rhs.pv, nullptr);
return *this;
}
~Matrix2D() {
delete[] pv;
}
// additional ctor to provide list initialization
Matrix2D(std::initializer_list<std::initializer_list<T>> list) :
pv(new T[list.size() * (list.begin())->size()]),
cols((list.begin())->size()),
rows(list.size())
{
if (rows > 0 && cols > 0)
for (size_t row = 0; row < list.size(); row++)
{
if (list.begin()->size() != (list.begin() + row)->size())
throw std::runtime_error("number of columns in each row must be the same");
for (size_t col = 0; col < cols; col++)
pv[cols * row + col] = *((list.begin() + row)->begin() + col);
}
else | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
}
else
std::construct_at(&pv, nullptr);
} | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
// bracket access v[r][c]
T* operator[](size_t row) noexcept { return pv + row * cols; }
const T* operator[](size_t row) const noexcept { return pv + row * cols; }
// paren access v(r,c);
T& operator()(size_t row, size_t col) noexcept { return pv[row * cols + col]; }
const T& operator()(size_t row, size_t col) const noexcept { return pv[row * cols + col]; }
// insert a sub-matrix by overlaying a selected portion, returns the whole matrix
Matrix2D insert_matrix(const Matrix2D& mat, size_t row_start, size_t col_start)
{
if (row_start + mat.rows > rows || col_start + mat.cols > cols)
throw std::range_error("Requested extents exceed bounds");
Matrix2D ret(*this);
for (size_t row = row_start; row < row_start + mat.rows; row++)
for (size_t col = col_start; col < col_start + mat.cols; col++)
ret(row, col) = mat(row - row_start, col - col_start);
return ret;
}
// return a matrix subset
Matrix2D sub_matrix(size_t row_start, size_t col_start, size_t row_count, size_t col_count) const
{
Matrix2D ret(row_count, col_count);
if (row_start + row_count > rows || col_start + col_count > cols)
throw std::range_error("Requested extents exceed bounds");
for (size_t row = row_start; row < row_start + row_count; row++)
for (size_t col = col_start; col < col_start + col_count; col++)
ret[row - row_start][col - col_start] = (*this)(row, col);
return ret;
}
// negate
friend Matrix2D operator-(const Matrix2D& rhs)
{
Matrix2D ret(rhs.rows, rhs.cols);
for (size_t i = 0; i < ret.rows * ret.cols; i++)
ret.pv[i] = -rhs.pv[i];
return ret;
} | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
// add
friend Matrix2D operator+(const Matrix2D& lhs, const Matrix2D& rhs)
{
if (lhs.cols != rhs.cols && lhs.rows != rhs.rows)
throw std::range_error("matrixes must have same dims");
Matrix2D ret(lhs);
for (size_t i = 0; i < ret.rows * ret.cols; i++)
ret.pv[i] += rhs.pv[i];
return ret;
}
// add +=
Matrix2D& operator+=(const Matrix2D& lhs)
{
if (lhs.cols != cols && lhs.rows != rows)
throw std::range_error("matrixes must have same dims");
for (size_t i = 0; i < rows * cols; i++)
pv[i] += lhs.pv[i];
return *this;
}
// subtract
friend Matrix2D operator-(const Matrix2D& lhs, const Matrix2D& rhs)
{
if (lhs.cols != rhs.cols && lhs.rows != rhs.rows)
throw std::range_error("matrixes must have same dims");
Matrix2D ret(lhs);
for (size_t i = 0; i < ret.rows * ret.cols; i++)
ret.pv[i] -= rhs.pv[i];
return ret;
}
// sub -=
Matrix2D& operator-=(const Matrix2D& lhs)
{
if (lhs.cols != cols && lhs.rows != rows)
throw std::range_error("matrixes must have same dims");
for (size_t i = 0; i < rows * cols; i++)
pv[i] -= lhs.pv[i];
return *this;
}
}; | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
// multiply matrixes
template <typename T>
Matrix2D<T> operator*(const Matrix2D<T>& lhs, const Matrix2D<T>& rhs)
{
if (lhs.cols != rhs.rows)
throw std::range_error("cols of first must == rows of second");
Matrix2D<T> ret(lhs.rows, rhs.cols);
Matrix2D<T> mat_tmp = ~rhs; // transpose to improve cache locality
for (size_t row = 0; row < lhs.rows; row++)
for (size_t col = 0; col < rhs.cols; col++)
ret[row][col] = std::inner_product(lhs[row], lhs[row] + lhs.cols, mat_tmp[col], T(0));
return ret;
}
// transpose
template <typename T>
Matrix2D<T> operator ~(const Matrix2D<T>& rhs)
{
Matrix2D<T> ret(rhs.cols, rhs.rows);
for (size_t r = 0; r < rhs.rows; r++)
for (size_t c = 0; c < rhs.cols; c++)
ret(c, r) = rhs(r, c);
return ret;
}
}
And here's some short test code that exercises the special member functions:
#include "matrix2db.h"
#include <iostream>
void print(const auto& mat)
{
for (size_t r = 0; r < mat.rows; r++)
{
for (size_t c = 0; c < mat.cols; c++)
{
std::cout << mat[r][c] << " ";
}
std::cout << "\n";
}
std::cout << "\n";
} | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
int main()
{
using namespace matrix_const;
{
// Check move assignemnt operator
Matrix2D<int> x { {1, 2}, { 3, 4 } };
print(x);
x = Matrix2D<int>{ { 2, 3 }, { 4, 5 }, {6, 7 } };
print(x);
}
{
// multiply a row vector by a column vector to produce a 1x1 result
Matrix2D<int> x{ {1, 2, 3 } };
Matrix2D<int> y{ {1}, {2}, {3} };
print(x*y);
}
{
// check sub matrix operations
Matrix2D<int> z{ {1,2,3},{4,5,6},{7,8,9} };
Matrix2D<int> zi{ {9,10},{11,12} };
print(z.sub_matrix(0, 1, 2, 2)); // sub matrix starting at row 0, col 1 with 2 rows 2 cols
auto zz = z.insert_matrix(zi, 0, 1); // insert at row 0, col 1
print(zz);
}
{
// Check matrix of matrix operations
Matrix2D<Matrix2D<int>> zz = Matrix2D<Matrix2D<int>>{ { Matrix2D<int>{ {1}}, Matrix2D<int>{ {3}} } };
print(zz[0][0] + zz[0][1]); // add the two internal matrixes
}
{
// Check matrix add and multiply
Matrix2D<int> z1 = Matrix2D<int>{ {1,2},{3,4},{5,6},{7,8} };
Matrix2D<int> z2{ {1,2,3},{4,5,6} };
print(z1);
print(z2);
print(z2 + z2 + z2);
Matrix2D<int> z3 = z1 * z2; // z3: 4 rows, 3 cols
print(z3);
// product from separate math program product of z1 and z2
Matrix2D<int> ref{ {9,12,15},{19,26,33},{29,40,51},{39,54,69} };
print(z3 - ref); // s/b all zeros
}
}
Answer: Performance
Some operations look very inefficient. Consider subtracting two matrices, this involves:
Copying rhs into a new Matrix2D
Negating each element of that matrix
Copying lhs to a new Matrix2D
Adding the elements of the new matrix from step 1 to those of the matrix from step 3
Deleting the matrix from step 1 | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c++, matrix, c++20
Then there is matrix multiplication, where you do a straightforward multiplication for matrices with less than 200 elements, but in the name of cache locality you first transpose the rhs. Sure that will make the multiplication more efficient, but the transposing operation itself might not be cache friendly (consider that memory stores might end up in the cache as well), and then you just wasted memory bandwidth making and reading mat_tmp.
Furthermore, where does the number 200 come from? Consider that there is a huge variation in the design of CPU caches, and that the size of T can vary a lot (consider an int16_t versus a std::complex<double>).
If you really want to optimize cache locality of your matrix multiplication function, consider storing the matrix using a Z-order curve.
For large matrices, the fact that you do not implement operator+=() and related functions might mean you are leaving some performance on the table. | {
"domain": "codereview.stackexchange",
"id": 43605,
"lm_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++, matrix, c++20",
"url": null
} |
c#, object-oriented, parsing
Title: Password Validation Class
Question: I created a class designed to validate passwords based on user defined criteria. Each PasswordValidator object objects a minimum and maximum password length, a character blacklist, as well as customizable Uppercase, Lowercase, and digit requirements. I am well aware that I could have used regex but I wanted to avoid using it for extra practice with classes. Here is an example object I created as well as the class.
var passwordValidator = new PasswordValidator
{
MinLength = 6,
MaxLength = 13,
UpperRequirement = 1,
LowerRequirement = 1,
DigitRequirment = 1,
CharBlacklist = new char[] { 'T', '&' }
};
while (true)
{
var input = Console.ReadLine();
if (input == "exit")
{
break;
}
else
{
Console.WriteLine(passwordValidator.CheckPassword(input));
}
}
class PasswordValidator
{
public uint MinLength { get; init; }
public uint MaxLength { get; init; }
public uint UpperRequirement { get; init; }
public uint LowerRequirement { get; init; }
public uint DigitRequirment { get; init; }
public char[]? CharBlacklist { get; init; }
public bool CheckPassword(string password)
{
bool hasBlacklist = CharBlacklist != null;
bool hasMaxLength = MaxLength != 0;
// Length Checking
if (password.Length < MinLength || (hasMaxLength && password.Length > MaxLength))
{
return false;
}
uint upperCount = 0;
uint lowerCount = 0;
uint digitCount = 0; | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c#, object-oriented, parsing
uint upperCount = 0;
uint lowerCount = 0;
uint digitCount = 0;
foreach (char passwordChar in password)
{
if (hasBlacklist && !AllowedChar(passwordChar))
{
return false;
}
if (char.IsUpper(passwordChar))
{
upperCount++;
}
else if (char.IsLower(passwordChar))
{
lowerCount++;
}
else if (char.IsDigit(passwordChar))
{
digitCount++;
}
}
if (upperCount < UpperRequirement || lowerCount < LowerRequirement || digitCount < DigitRequirment)
{
return false;
}
else
{
return true;
}
}
private bool AllowedChar(char passwordChar)
{
foreach (var blacklistChar in CharBlacklist)
{
if (passwordChar == blacklistChar)
{
return false;
}
}
return true;
}
}
All types of feedback are appreciated but here are some questions I have about how I could improve my code. | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c#, object-oriented, parsing
My C# knowledge is fairly limited. The language I know the best is Java (0.5 years). Are there any language specific style issues you can see in my code? Did I get carried away with C# language features?
I chose not to create any constructors for my class in favor of object initializer syntax. I did this because All of the properties in the class are meant to be optional. Did I make the right move?
One design issue I see is that MinLength could be greater than MaxLength. How would I fix this?
My CheckPassword method is quite lengthy and contains a lot of if else statements. It also has two special cases where there is no MaxLength and where there is a Character Blacklist. What improvements (if any) should I make to that method.
Answer: You've mixed Requirement and Validator into one role. a Validator, should only read the requirements, and validate upon it, but in your class, you're setting the requirement from within the validator. So, what you need is to separate both Requirement and Validator given each one of them its own class. This would give more flexibility and better maintainability over them.
so, you should end-up having something like this :
public interface IPasswordRequirement { ... }
public class PasswordValidator
{
private readonly IPasswordRequirement _requirement;
// this constructor ensures this instance won't be initialized without providing a requirement.
public PasswordValidator(IPasswordRequirement requirement)
{
_requirement = requirement;
}
public bool Validate(string password)
{
// validate the password using _requirement instance.
}
} | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c#, object-oriented, parsing
Now, in the example above I've used an interface as baseline contract to validate upon. This would give you the ability to define different requirements such as (StrongPasswordRequirement, DefaultPasswordRequirement ..etc.), and can give you also the ability to expand the validator to accept multiple requirements at once (for instance, you can define three requirements, and validate the password against them, to see if the password matches any of them.).
CheckPassword should be renamed to ValidatePasswordRequirement, because CheckPassword by itself will give many meanings, such as checking the password hash, checking the password expiry, ...etc. All will go under password validity. So, it would be a good idea to tell which part of validation the method will process.
I chose not to create any constructors for my class in favor of object
initializer syntax. I did this because All of the properties in the
class are meant to be optional. Did I make the right move?
It's fine, as long as they're optional. You only need to consider the properties default values in your work and wither you need to use the system default value or use custom one. Also, if you're working with different .NET versions, you should consider a backward compatibility approach, where you would favor a default constructor over init only sitters.
One design issue I see is that MinLength could be greater than
MaxLength. How would I fix this?
just validate them before initializing something like this :
private uint _minLength;
private uint _maxLength;
public uint MinLength
{
get => _minLength;
init
{
if(_maxLength > 0 && value >= _maxLength)
throw new ArgumentOutOfRangeException(nameof(MinLength));
_minLength = value;
}
}
public uint MaxLength
{
get => _maxLength;
init
{
if(value <= _minLength)
throw new ArgumentOutOfRangeException(nameof(MaxLength));
_maxLength = value;
}
} | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c#, object-oriented, parsing
this way you would avoid overlapping between the two properties.
although, AllowedChar can be replaced with CharBlacklist.Contains(character)
your loop can be done like this :
foreach (char passwordChar in password)
{
if (hasBlacklist && CharBlacklist.Contains(passwordChar))
{
return false;
}
else if (upperCount < UpperRequirement && char.IsUpper(passwordChar))
{
upperCount++;
}
else if (lowerCount < LowerRequirement && char.IsLower(passwordChar))
{
lowerCount++;
}
else if (digitCount < DigitRequirment && char.IsDigit(passwordChar))
{
digitCount++;
}
}
this way, the upper, lower, and digit will only hit if their counter is less than their requirements, whenever any of them fulfil the requirement, it will be skipped in the upcoming iterations.
here is an example of the above points :
public interface IPasswordRequirement
{
int MinimumLength { get; }
int MaximumLength { get; }
int NumberOfUpperCase { get; }
int NumberOfLowerCase { get; }
int NumberOfDigits { get; }
char[]? BlacklistCharacters { get; }
}
/// this would be used as system default.
// then you can define another custom requirement
// that the consumer can customize, and use the default instance
// if the consumer did not provide any custom requirement.
public class DefaultPasswordRequirement : IPasswordRequirement
{
private static readonly _defaultBlacklistCharacters = new { 'T', '&' }
public int MinimumLength { get; } = 6;
public int MaximumLength { get; } = 13;
public int NumberOfUpperCase { get; } = 1;
public int NumberOfLowerCase { get; } = 1;
public int NumberOfDigits { get; } = 1;
public char[]? BlacklistCharacters { get; } = _defaultBlacklistCharacters;
} | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c#, object-oriented, parsing
public class PasswordRequirementValidator
{
// create the default instance, and reuse it.
private static readonly IPasswordRequirement _defaultPasswordRequirement = new DefaultPasswordRequirement();
private readonly IPasswordRequirement _requirement;
// when using the default constructor, it will apply the default requirement;
public PasswordRequirementValidator() : this(_defaultPasswordRequirement) { }
// use a custom requirement instead
public PasswordRequirementValidator(IPasswordRequirement requirement)
{
if(password == null)
throw new ArguementNullException(nameof(requirement));
_requirement = requirement;
}
public bool Validate(string password)
{
if(string.IsNullOrWhiteSpace(password))
return false;
if(password.Length < _requirement.MinimumLength || password.Length > _requirement.MaximumLength)
return false;
uint upperCount = 0;
uint lowerCount = 0;
uint digitCount = 0;
foreach (char passwordChar in password)
{
if (hasBlacklist && CharBlacklist.Contains(passwordChar))
{
return false;
}
else if (upperCount < NumberOfUpperCase && char.IsUpper(passwordChar))
{
upperCount++;
}
else if (lowerCount < NumberOfLowerCase && char.IsLower(passwordChar))
{
lowerCount++;
}
else if (digitCount < NumberOfDigits && char.IsDigit(passwordChar))
{
digitCount++;
}
}
return upperCount >= NumberOfUpperCase && lowerCount >= NumberOfLowerCase && digitCount >= NumberOfDigits;
}
} | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c#, object-oriented, parsing
also, you could see a way of replacing the bool to something more descriptive that would give more meaningful results. | {
"domain": "codereview.stackexchange",
"id": 43606,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, parsing",
"url": null
} |
c++, memory-management, c++20
Title: C++ disk-file memory resource
Question: After writing a C++ simulator for malloc() and free(), (C++ imitation of glibc malloc(), free()),
I thought: "My simulator cannot expand the initial arena. Then how about giving the initial arena a really big one from the beginning? If I can't put the arena in the main memory, I can just have it on a disk file!"
So I wrote a polymorphic memory resource that utilizes a disk file.
FileArenaResource.h
#include "MemoryMappedFile.h"
#include <filesystem>
#include <memory_resource>
#include <stdexcept>
namespace frozenca {
class FileArenaResource : public std::pmr::memory_resource {
private:
MemoryMappedFile file_;
public:
FileArenaResource(const std::filesystem::path &path) : file_{path} {}
private:
void *do_allocate(std::size_t bytes, std::size_t alignment) override {
if (bytes % alignment) {
throw std::invalid_argument("alloc bytes aren't aligned");
}
if (bytes > file_.size()) {
file_.resize(bytes);
}
return file_.data();
}
void do_deallocate(void *ptr, std::size_t bytes, std::size_t alignment) override {
if (bytes % alignment) {
throw std::invalid_argument("dealloc bytes aren't aligned");
}
if (ptr != file_.data()) {
throw std::invalid_argument("dealloc arena pointer is not equal to begin of the file");
}
if (bytes != static_cast<std::size_t>(file_.size())) {
throw std::invalid_argument("dealloc arena size is not equal to file size");
}
}
bool do_is_equal(const std::pmr::memory_resource &other) const noexcept override {
if (this == &other) {
return true;
}
auto op = dynamic_cast<const FileArenaResource *>(&other);
return op && op->file_ == file_;
}
};
} // namespace frozenca
MemoryMappedFile.h (mostly copy-and-paste from boost::mapped_file, you can skip this)
#include <cassert>
#include <filesystem>
#include <stdexcept> | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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, c++20",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.