text
stringlengths
1
2.12k
source
dict
c#, console PinList = (Black + White).PadRight(4); return ($"'{PinList}'"); } /// <summary> /// Shows the goal of the game and the rules. /// </summary> private static void ShowIntro() { Console.WriteLine("Welcome to this game of MasterMind."); Console.WriteLine("The goal of the game is to guess what colors and the correct order of colors I have hidden."); Console.WriteLine("You can choose between the colors: BLUE - RED - GREEN - WHITE - PINK - YELLOW"); Console.WriteLine("You provide input by taking the first letters of the colors; so for example for the color yellow, you need to press the Y-key."); Console.WriteLine("After every guess, I will tell you:"); Console.WriteLine("The number of correct colors in the correct place: a black pin"); Console.WriteLine("The number of correct colors not in the correct place: a white pin"); Console.WriteLine("Press a key to start"); Console.ReadLine(); Console.Clear(); } /// <summary> /// Asks for the balls you want to pick, using the readkey function, and creates a List of balls. /// </summary> /// <param name="NumberOfBalls"></param> /// <returns></returns> private static List<Ball> GetYourBalls(int NumberOfBalls) { var yourBalls = new List<Ball>(); for (int i = 0; i < NumberOfBalls; i++) { var yourBallColor = Console.ReadKey().Key;
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console switch (yourBallColor) { case ConsoleKey.W: yourBalls.Add(new(BallColor.White)); break; case ConsoleKey.R: yourBalls.Add(new(BallColor.Red)); break; case ConsoleKey.G: yourBalls.Add(new(BallColor.Green)); break; case ConsoleKey.B: yourBalls.Add(new(BallColor.Blue)); break; case ConsoleKey.P: yourBalls.Add(new(BallColor.Pink)); break; case ConsoleKey.Y: yourBalls.Add(new(BallColor.Yellow)); break; default: yourBalls.Add(new(BallColor.None)); break; } } return yourBalls; } /// <summary> /// Calculates the resulting pins of your guess. An exact match is a black pin, a non-exact match is a white pin. /// </summary> /// <param name="ballsToGuess"></param> /// <param name="ballsPicked"></param> /// <returns></returns> private static int[] CalculatePins(List<Ball> ballsToGuess, List<Ball> ballsPicked) { int blackPin = 0; int whitePin = 0; // First of all, create a duplicate of both ball objects, // as we don't want to change the balls of the original list var duplicateBallsToGuess = new List<Ball>(); for (int ballIndex = 0; ballIndex < ballsToGuess.Count; ballIndex++) { duplicateBallsToGuess.Add(new(ballsToGuess[ballIndex].Color)); }
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console var duplicateBallsPicked = new List<Ball>(); for (int ballIndex = 0; ballIndex < ballsPicked.Count; ballIndex++) { duplicateBallsPicked.Add(new(ballsPicked[ballIndex].Color)); } // First check all exact matches for (int i = 0; i < duplicateBallsPicked.Count; i++) { // check if there is an exact match if (duplicateBallsToGuess[i].Equals(duplicateBallsPicked[i])) { // Black pin, as it is found, and on the exact place blackPin++; duplicateBallsToGuess[i].Color = BallColor.None; duplicateBallsPicked[i].Color = BallColor.None; continue; } } // Now check all non-exact matches for (int i = 0; i < duplicateBallsPicked.Count; i++) { if (duplicateBallsPicked[i].Color == BallColor.None) { // Ball is already mapped to an exact match continue; } // Find the index of color to look for; index of -1 means it is not found int index = duplicateBallsToGuess.FindIndex(ball => ball.Color == duplicateBallsPicked[i].Color); if (index == -1) { // Nothing found, so moving to the next continue; } // White pin, as it is found, but not on the exact place duplicateBallsToGuess[index].Color = BallColor.None; whitePin++; } int[] ReturnedPins = { blackPin, whitePin }; return ReturnedPins; }
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console /// <summary> /// Converts a list of object balls into a string, where the colors are the first letters of their color name /// </summary> /// <param name="balls"></param> /// <returns></returns> public static string ConvertBallColorToString(List<Ball> balls) { string ballcolors = ""; for (int i = 0; i < balls.Count; i++) { switch (balls[i].Color) { case BallColor.White: ballcolors += "W "; break; case BallColor.Red: ballcolors += "R "; break; case BallColor.Blue: ballcolors += "B "; break; case BallColor.Green: ballcolors += "G "; break; case BallColor.Yellow: ballcolors += "Y "; break; case BallColor.Pink: ballcolors += "P "; break; default: ballcolors += "X "; break; } } return ballcolors.Trim(); } #endregion } Ball.cs internal class Ball { #region Properties /// <summary> /// The color you want the ball to have /// </summary> public BallColor Color { get; set; } #endregion
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console #endregion #region Constructors /// <summary> /// Empty Constructor - creates a ball with a random color /// </summary> public Ball() { Color = GetRandomColor(); } /// <summary> /// Constructor - creates a ball with a predefined color /// </summary> /// <param name="Color"></param> public Ball(BallColor color) { Color = color; } #endregion #region Methods /// <summary> /// Picks a random color /// </summary> public BallColor GetRandomColor() { // Convert the color enumeration to a list, as this is easier to work with List<BallColor> ballColors = Enum.GetValues(typeof(BallColor)).Cast<BallColor>().ToList(); // Remove the first value from the color enumaration, as it is not a color ballColors.Remove(BallColor.None); // Pick a random value Random random = new(); return ballColors[random.Next(ballColors.Count)]; } #endregion /// <summary> /// Override the Equal method, as we want to comapre ball colors /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { // If the passed object is null if (obj == null) { return false; } if (!(obj is Ball)) { return false; } return (this.Color == ((Ball)obj).Color); } public override int GetHashCode() { return Color.GetHashCode(); } } enum.cs public enum BallColor { None, White, Red, Blue, Green, Pink, Yellow }
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console Answer: static Members that do not make use of instance members should be static. For example, Ball.GetRandomColor() does not make any use of instance state or instance methods (in other words, it never uses this), so it should be static: public static BallColor GetRandomColor() This also applies to the Program class as a whole: it is never instantiated, and it only has static members, so it can be static as well: internal static class Program private Members that do not need to be accessed from the outside should be private. For example, Ball.GetRandomColor and Program.ConvertBallColorToString are never accessed from the outside, so they should be private: private static string ConvertBallColorToString(List<Ball> balls) private static BallColor GetRandomColor() Properties To me, GetRandomColor looks more like a property than a method. So, I would make it a property: public static BallColor RandomColor { get { // Convert the color enumeration to a list, as this is easier to work with List<BallColor> ballColors = Enum.GetValues(typeof(BallColor)).Cast<BallColor>().ToList(); // Remove the first value from the color enumaration, as it is not a color ballColors.Remove(BallColor.None); // Pick a random value Random random = new(); return ballColors[random.Next(ballColors.Count)]; } } The callsite also needs to be updated accordingly: Color = RandomColor
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console The callsite also needs to be updated accordingly: Color = RandomColor Note: this is somewhat controversial since properties should not have side-effects, but this property uses a PRNG. I can see both sides of the argument. PRNG management You are creating a new PRNG on every call to GetRandomColor. That is not only wasteful, but can also lead to bugs: the PRNG is seeded by default with a time-based seed. So, if you create PRNGs fast enough after each other, they will have the same seed and thus produce the same sequence of "random" numbers! You should only create the PRNG once and reuse it. I would simply store it in a private static field: private static readonly Random random = new(); // Pick a random value return ballColors[random.Next(ballColors.Count)]; Expression-bodied members For members whose body consists only of a single expression, there is an alternative syntax available which removes some "cruft". Ball.GetHashCode and the two Ball constructors fall into this category: public Ball() => Color = RandomColor; public Ball(BallColor color) => Color = color; public override int GetHashCode() => Color.GetHashCode(); this constructor initializer You can use a this constructor initializer to delegate from one constructor to another. In this case, we can delegate from the no-args constructor to the one that takes an argument: public Ball() : this(RandomColor) { } For this simple example, there is not much of a difference whether we call the constructor ourselves in the constructor body or if we let the compiler do it. But for more complex hierarchies with more complex initialization, this can make it much clearer to see what is going on. Generic Enum.GetValues<T> You can remove all the typeof and Casting from the conversion of the enum values to a list by using the generic version of Enum.GetValues<T>. Before: List<BallColor> ballColors = Enum.GetValues(typeof(BallColor)).Cast<BallColor>().ToList();
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console After: List<BallColor> ballColors = Enum.GetValues<BallColor>().ToList(); Simpler way to pick a random color If you move the None value to the end of enum BallColor, then, instead of filtering it out of a list, you can simply ignore the last element. Before: // Convert the color enumeration to a list, as this is easier to work with List<BallColor> ballColors = Enum.GetValues<BallColor>().ToList(); // Remove the first value from the color enumaration, as it is not a color ballColors.Remove(BallColor.None); // Pick a random value return ballColors[Random.Next(ballColors.Count)]; After: var ballColors = Enum.GetValues<BallColor>(); // Pick a random value return ballColors[random.Next(ballColors.Length - 1)]; record classes For simple data objects like Balls, C# has record classes and record structs. Converting Ball to a record class is relatively simple: Add the record keyword to the class declaration: internal record class Ball Delete GetHashCode and Equals. They are auto-generated for us, based on the properties of the record. (We also get auto-generated ==, != and an implementation of IEquatable, ToString(), and many others.) Positional record class We can even go one step further and make our record a positional record. Positional records declare positional members as part of their record declaration and get additional auto-implemented members for those (for example, constructors). We can make Ball a positional record by adding the Color member as a positional member to the declaration: internal record class Ball(BallColor Color) Now we can simply delete the Ball(BallColor) constructor: it will be autogenerated for us. We can not delete the property declaration, since positional record classes by default generate init-only properties, but we need our property to be settable. According to the rules of records, we also need to initialize our property from the positional member: public BallColor Color { get; set; } = Color;
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console Naming conventions for parameters and local variables Constructor and method parameters as well as local variables should use camelCase naming, not PascalCase. This applies to NumberOfBalls, NumberOfChances, Outcome, BallsToGuess, BallsPicked, ReturnedPins, Black, White, and PinList. Prefer string.Empty over "" for empty strings You should prefer the string.Empty property over an empty string literal for empty strings, for example here: string outcome = string.Empty; Unnecessary parentheses The parentheses here are unnecessary: return formerAttempt + (pinColors + ballColors) + "\n"; You can just remove them: return formerAttempt + pinColors + ballColors + "\n"; Implicit typing using var This is a controversial topic. I, personally, am a big fan of implicit typing / type inference using var. Whenever the type of a variable is obvious in context, I don't see why it should be spelled out. So, I would write var numberOfBalls = 4; var numberOfChances = 12; var outcome = string.Empty; for (var i = 0; i < numberOfChances; i++) var ballsPicked = GetYourBalls(ballsToGuess.Count); var pinList = string.Empty; for (var i = 0; i < numberOfBalls; i++) var blackPin = 0; var whitePin = 0; for (var ballIndex = 0; ballIndex < ballsToGuess.Count; ballIndex++) for (var ballIndex = 0; ballIndex < ballsPicked.Count; ballIndex++) for (var i = 0; i < duplicateBallsPicked.Count; i++) for (var i = 0; i < duplicateBallsPicked.Count; i++) var index = duplicateBallsToGuess.FindIndex(ball => ball.Color == duplicateBallsPicked[i].Color); var ballcolors = string.Empty; for (var i = 0; i < balls.Count; i++) But others may (and will) disagree. Target-typed new I am also a big fan of target-typed new in cases where the type is obvious from context. For example, here: string black = new('#', returnedPins[0]); string white = new('|', returnedPins[1]);
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console Unnecessary local variable I feel like the local variable here does not add much to readability: int[] returnedPins = { blackPin, whitePin }; return returnedPins; I would inline it: return new int[] { blackPin, whitePin }; Namespaces All types should be in namespaces, and there should be one top-level namespace for your project. (I notice you are actually doing this in your GitHub repository but not in the code you posted here.) As of C# 10, file-level namespaces allow us to get rid of the annoying extra level of nesting. Just add namespace MasterMind; to the top of every file. Unnecessary early declaration / initialization In Program.ConvertPinColorToString, pinList is declared and initialized at the top of the method, but never used until later, where it is immediately assigned to, thus overwriting the value it was initialized with. This makes the initialization unnecessary, and it can be removed. But even better, we can move the whole declaration of the variable down to where it is first used: var pinList = (black + white).PadRight(4);
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console StringBuilder Repeatedly concatenating strings is inefficient, since a new string is allocated for each concatenation. While I am generally a fan of purity and referential transparency, unfortunately, the implementation of the string datatype is not optimized for this kind of usage. (A Rope-based implementation would be much more efficient in this regard, for example.) That's why we have System.Text.StringBuilder: private static string ConvertBallColorToString(List<Ball> balls) { System.Text.StringBuilder ballcolors = new(8, 8); for (var i = 0; i < balls.Count; i++) { switch (balls[i].Color) { case BallColor.White: ballcolors.Append("W "); break; case BallColor.Red: ballcolors.Append("R "); break; case BallColor.Blue: ballcolors.Append("B "); break; case BallColor.Green: ballcolors.Append("G "); break; case BallColor.Yellow: ballcolors.Append("Y "); break; case BallColor.Pink: ballcolors.Append("P "); break; default: ballcolors.Append("X "); break; } } return ballcolors.ToString().Trim(); } Pattern Matching C# supports Pattern Matching, which can make Program.ConvertBallColorToString and Program.GetYourBalls easier to read: private static List<Ball> GetYourBalls(int numberOfBalls) { var yourBalls = new List<Ball>(); for (var i = 0; i < numberOfBalls; i++) { var yourBallColor = Console.ReadKey().Key;
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console for (var i = 0; i < numberOfBalls; i++) { var yourBallColor = Console.ReadKey().Key; Ball ball = new(yourBallColor switch { ConsoleKey.W => BallColor.White, ConsoleKey.R => BallColor.Red, ConsoleKey.G => BallColor.Green, ConsoleKey.B => BallColor.Blue, ConsoleKey.P => BallColor.Pink, ConsoleKey.Y => BallColor.Yellow, _ => BallColor.None, }); yourBalls.Add(ball); } return yourBalls; } private static string ConvertBallColorToString(List<Ball> balls) { System.Text.StringBuilder ballcolors = new(8, 8); for (var i = 0; i < balls.Count; i++) { var colorCode = balls[i].Color switch { BallColor.White => "W ", BallColor.Red => "R ", BallColor.Blue => "B ", BallColor.Green => "G ", BallColor.Yellow => "Y ", BallColor.Pink => "P ", _ => "X ", }; ballcolors.Append(colorCode); } return ballcolors.ToString().Trim(); } Use the enum member names for the color strings The string that is used for the color of the pins is actually mostly the first letter of the corresponding enum member. The only exception is None whose string representation is X. An easy way to make this more regular and remove the special case would be to rename BallColor.None to BallColor.XNone or maybe change the representation to _ and rename to _None. Once we do that, converting from the enum value to the string representation becomes much simpler: private static string ConvertBallColorToString(List<Ball> balls) { System.Text.StringBuilder ballcolors = new(8, 8); for (var i = 0; i < balls.Count; i++) { var colorCode = balls[i].Color.ToString().Substring(0, 1); ballcolors.Append(colorCode + "\n"); } return ballcolors.ToString().Trim(); }
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console return ballcolors.ToString().Trim(); } Some OOP Program does a lot of work to convert Balls to strings. This logic should be part of Ball itself. We can simply provide an override of ToString in Ball: public override string ToString() => Color.ToString().Substring(0, 1); and then Program.ConvertBallColorToString becomes just private static string ConvertBallColorToString(List<Ball> balls) => string.Join(" ", balls); And now, we are not using the fact that balls is a List anymore, we are only using it as an IEnumerable, so let's change the signature: private static string ConvertBallColorToString(IEnumerable<Ball> balls) => string.Join(" ", balls); Tuples The return value of CalculatePins is somewhat awkward. It is an array of integers, but unlike a normal array where every element has the same "meaning", here the elements mean different things. And the different meanings are only expressed through their index, but there is no "name" attached to the meaning. This would be much better expressed through a Tuple with named elements. Let's change the signature of Calculate Pins to return a Tuple: private static (int blackPins, int whitePins) CalculatePins(List<Ball> ballsToGuess, List<Ball> ballsPicked) Of course, we also need to change the return value accordingly: return (blackPin, whitePin); We need to change the callsite as well. In Main, let's change int[] returnedPins = CalculatePins(ballsToGuess, ballsPicked); to var (blackPins, whitePins) = CalculatePins(ballsToGuess, ballsPicked); and we also need to change all uses of returnedPins[0] to blackPins and returnedPins[1] to whitePins For dealing with ConvertPinColorToString and GetOutcome, we have three options:
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console Leave ConvertPinColorToString and GetOutcome alone and call them with an array, e.g. var pinColors = ConvertPinColorToString(new int[] { blackPins, whitePins }). Change the signature of ConvertPinColorToString and GetOutcome to take a Tuple. Change the signature of ConvertPinColorToString and GetOutcome to take the number of black pins and white pins separately. I decided to go for option #3. #regions I am not a big fan of #regions. In general, if your code is so complex that you need to break it down into #regions to understand it, then you should rather break it down into methods and objects. Comments You have a lot of comments in your code. Personally, I think a lot of comments are a Code Smell: your code already tells you what your code does, if you need comments to tell you what your code does, then your code is too complex. More precisely, well-written, well-factored, readable code should tell you how the code does things. Well-chosen, intention-revealing, semantic names should tell you what the code does. The only reason to have comments is to explain why the code does a certain thing in a certain, non-obvious way. For example, here: // Show the intro and game rules ShowIntro(); Do you really need a comment to explain that a method named ShowIntro shows the intro? Especially since the documentation of ShowIntro also says that it shows the intro? Or here: // If the passed object is null if (obj == null)
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console If someone cannot figure out that if (obj == null) means "if the object is null", then why are they reading C# source code in the first place? Mixing I/O and computation There are a couple of places where you are mixing I/O (specifically printing) and computations. Specifically, your Main method. You should try to keep those separate. Most of your methods should only perform computations. Only some methods at the boundary of the system should print or ask for input. OOP Your code is not very object-oriented. Almost everything is static. For example, we are talking about a game of MasterMind here, but there is no Game object to be found! I would expect, for example, to find at least a Game and Player object, likely a separate object representing GameState, and also some objects for handling input, output, display, and rendering. And note I wrote objects, not classes. OOP is about objects, it is not about classes. Classes are templates for objects and they are containers for methods, but they are not what OOP is about. Testing It is very hard to test your code. It is practically impossible to do any sort of meaningful testing without having to manually play through an entire game. This gets very tedious very quickly, and discourages from testing early and often. Ideally, tests should be automatic and fast, which allows them to run every couple of seconds after every change in the code. Overall design These last points are all intertwined with each other. Testing the logic in the code is hard because the logic is intermixed with the I/O, and so I can't simply call a method and pass in some fake data to test, e.g. the logic for losing the game, I have to actually play through the entire game and lose. I can't automatically play a game by passing in a "fake" player, because there is no such thing as a "player" in the code. It is also not easy to introduce these changes because most logic is contained in a single Main method.
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
c#, console I would start with breaking up the methods. You already have comments in some places that say something like "first do this", "now do that", "do A", "do B", etc. These comments are telling you that you have separate steps there … so make them separate methods. As a next step, I would strictly separate I/O and computation. Make sure that all methods take arguments and return values, so that you can easily test them by simply calling them and checking the return value instead of having to play the game. Then, I would introduce more objects: a game, two players, and whatever else you need. Note that objects represent domain concepts, not real-world physical things. For example, a certain kind of relationship between two objects can itself be an object. Once you have separated the game logic from the I/O, it should then also be possible to explore building a GUI for the game in WPF or MAUI, or turning the game into a web service that can be played remotely, or turning it into a web app, only by implementing the appropriate interfaces, but without touching the code of your game logic at all.
{ "domain": "codereview.stackexchange", "id": 42647, "lm_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", "url": null }
python, performance, python-3.x Title: print 10x10 random numbers from 1 to 3 table Question: The code below will print a 10x10 table of random numbers between 1-3. Is there something to make the code faster? Can the code be made more readable? import random import numpy as np x = str(np.reshape([random.randint(1, 3) for i in range(100)], (-1, 10)).tolist()).replace("[", "").replace("]", "\n").replace("\n,", ",\n").replace("\n ", "\n").replace("\n\n", "") print(end=x) Example output 2, 3, 2, 1, 2, 1, 1, 2, 2, 1, 2, 1, 3, 2, 2, 3, 3, 2, 3, 3, 2, 3, 1, 2, 2, 2, 2, 1, 3, 1, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 3, 1, 3, 1, 2, 3, 3, 3, 2, 2, 3, 3, 2, 3, 1, 3, 1, 2, 3, 3, 2, 2, 3, 3, 1, 3, 3, 1, 2, 2, 1, 1, 1, 2, 1, 2, 2, 3, 3, 2, 1, 3, 2, 2, 3, 1, 2, 2, 1, 2, 3, 1, 3, 1, 2, 3, 2, 1, 2, 3 Answer: Multiple lines First off, don't try to do everything on one line. This line is doing way too much: x = str(np.reshape([random.randint(1, 3) for i in range(100)], (-1, 10)).tolist()).replace("[", "").replace("]", "\n").replace("\n,", ",\n").replace("\n ", "\n").replace("\n\n", "") Instead, separate the matrix creation from the formatting: m = np.reshape([random.randint(1, 3) for i in range(100)], (-1, 10)) x = str(m.tolist()).replace("[", "").replace("]", "\n").replace("\n,", ",\n").replace("\n ", "\n").replace("\n\n", "") Matrix creation Numpy has built-in functions for generating random arrays, including random arrays of integers: m = np.random.randint(1, 4, (10,10)) Matrix to string Instead of converting the matrix to a list, and then to a string, simply use numpy's built-in array to string function np.array2string() print(np.array2string(m, separator=", ")) [[2, 1, 3, 3, 2, 1, 2, 3, 2, 1], [1, 1, 1, 3, 2, 2, 3, 2, 3, 2], [2, 1, 3, 2, 3, 1, 2, 2, 3, 1], [1, 1, 3, 3, 3, 2, 3, 3, 3, 2], [3, 3, 1, 3, 3, 2, 1, 1, 1, 3], [3, 3, 2, 2, 3, 1, 3, 2, 2, 2], [2, 2, 1, 3, 1, 3, 3, 1, 3, 2], [3, 2, 3, 1, 1, 1, 3, 3, 3, 1], [1, 3, 1, 2, 1, 2, 1, 2, 2, 2], [3, 3, 2, 2, 2, 1, 2, 2, 1, 2]]
{ "domain": "codereview.stackexchange", "id": 42648, "lm_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, python-3.x", "url": null }
python, performance, python-3.x That is 90% of the way to the desired result. Just need to rip off the two leading and trailing brackets, and adjust the line joining: print(np.array2string(m, separator=", ")[2:-2].replace("],\n [", ",\n")) 2, 1, 3, 3, 2, 1, 2, 3, 2, 1, 1, 1, 1, 3, 2, 2, 3, 2, 3, 2, 2, 1, 3, 2, 3, 1, 2, 2, 3, 1, 1, 1, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3, 3, 3, 2, 2, 3, 1, 3, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 1, 3, 2, 3, 2, 3, 1, 1, 1, 3, 3, 3, 1, 1, 3, 1, 2, 1, 2, 1, 2, 2, 2, 3, 3, 2, 2, 2, 1, 2, 2, 1, 2 Print without newline print(end=x) is being too obfuscated. You are not using the entire result as a line ending. If you want to print the result without a newline at the end, use end='', like: print(x, end='') Improved code import numpy as np m = np.random.randint(1, 4, (10,10)) x = np.array2string(m, separator=", ")[2:-2].replace("],\n [", ",\n") print(x, end='')
{ "domain": "codereview.stackexchange", "id": 42648, "lm_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, python-3.x", "url": null }
python, python-3.x Title: Password Hasher (obviously not secure) Question: How the program works is that the user sends 2 inputs over (userinput and passwordinput). These are compared against the filename of a textfile (which is the username) and the context (which is the hashed password). The passwordinput gets hashed and if it returns the same as the hashed original password "Access Granted" gets printed. If it doesn't match it prints "Wrong Password!1!!" if the filename doesn't exist it then prints "Username not found." This program is just me playing around with hashlib and trying to find out ways to store passwords on my website, I would like to know more secure ways of writing this code and vulnerabilities import os import hashlib username = "coolcat" password = "my secret password!!" result = hashlib.sha256(password.encode("utf-8")) if not os.path.exists(f"{username}.txt"): open(f"{username}.txt", 'w').close() with open(f"{username}.txt", "w") as file: file.write(str(result.digest())) userinput = input("Your username please : ") passwordinput = input("Your password please : ") resulte = hashlib.sha256(passwordinput.encode("utf-8")) print(str(resulte.digest())) try : with open(f"{userinput}.txt", "r") as file: hashed = file.read() print(hashed) if hashed == str(resulte.digest()): print("Access Granted") if hashed != str(resulte.digest()): print("Wrong password!!") except FileNotFoundError : print("Username not found!!1!") Answer: WET -vs- DRY As it stands, your code is very WET (Write Everything Twice). hashlib.sha256(variable.encode("utf-8")) appears twice, and str(variable.digest()) appears four times! DRY (Don't Repeat Yourself) up your code, by using functions: def password_hash(password: str) -> str: result = hashlib.sha256(password.encode("utf-8")) return str(result.digest())
{ "domain": "codereview.stackexchange", "id": 42649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x If and if not Consider these two back-to-back if statements: if hashed == str(resulte.digest()): print("Access Granted") if hashed != str(resulte.digest()): print("Wrong password!!") Assuming resulte.digest() doesn't return different results each time it is called, is there any way to get to both print statements, or neither? No. If you get to the first, you won't get to the second and vise versa. The else clause is used in these cases: if hashed == str(resulte.digest()): print("Access Granted") else: print("Wrong password!!") Pointless code This code is unnecessary. if not os.path.exists(f"{username}.txt"): open(f"{username}.txt", 'w').close() If the filename does not exist, it attempts to create an empty file by that name. If it does exist, nothing happens. The very next statement ... with open(f"{username}.txt", "w") as file: ... opens the file, whether one existed or not, and writes to it. Creating the file ahead of time was pointless. Reworked code import os import hashlib def password_hash(password: str) -> str: result = hashlib.sha256(password.encode("utf-8")) return str(result.digest()) username = "coolcat" password = "my secret password!!" hashed_password = password_hash(password) with open(f"{username}.txt", "w") as file: file.write(hashed_password) userinput = input("Your username please : ") passwordinput = input("Your password please : ") hashed_passwordinput = password_hash(passwordinput) print(hashed_passwordinput) try: with open(f"{userinput}.txt", "r") as file: hashed = file.read() print(hashed) if hashed == hashed_passwordinput: print("Access Granted") else: print("Wrong password!!") except FileNotFoundError: print("Username not found!!1!")
{ "domain": "codereview.stackexchange", "id": 42649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x Security This code will read any .txt file that is accessible to the process. If the user can upload a file /tmp/uploads/myhash.txt, then they can give "/tmp/uploads/myhash" as a "user name", type in the required text that hashes to the given result, and be granted access. You should sanitize the userinput to ensure it only contains valid username characters.
{ "domain": "codereview.stackexchange", "id": 42649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x Title: Converting string of comma-separated items into 2d table Question: I'm writing the following: def make_table(data: str, w: int) -> List[List]: pass data is a string containing items separated by ,. Some items may be an empty sequence so multiple commas are possible, the input can also start/end with comma which mean that first/last item is empty. w stands for width and is the number of columns of the output table. We're assuming the input is valid. Examples: In [1]: make_table("a,b,c,d,e,f,g,h,i",3) Out[1]: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] In [2]: make_table(",,1,,1,,1,,",3) Out[2]: [['', '', '1'], ['', '1', ''], ['1', '', '']] My first working solution is this: def make_table(data: str, w: int) -> list: data = data.split(",") return [data[i*w:(i+1)*w] for i in range(len(data)//w)] What I don't like here is that range(len(...)) gives me bad memories I feel like this could be done prettier. I know numpy could do it, but that's overkill. I'm looking through std libs but don't see anything related. My second solution is more efficient but a little roundabout, I was looking for some lazy split solution but found only some rejected proposals. I did this: def coma_split(data: str): i, j = 0, -1 while True: i, j = j + 1, data.find(",", j + 1) if j != -1: yield data[i:j] else: yield data[i:] break def make_3_column_table(data: str) -> list: g = coma_split(data) return list(zip(g,g,g)) But here I don't know how to make zip take arbitrary number of references to g. How can I improve any of those? Answer: I was looking for some lazy split solution but found only some rejected proposals If you are looking for a lazy split solution, omit the list(...) call in the return statement, and the zip object will be returned. def make_3_column_table(data: str) -> Iterator[tuple[str]]: g = coma_split(data) return zip(g,g,g) # No list() call here
{ "domain": "codereview.stackexchange", "id": 42650, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x It looks like you are looking for the grouper recipe of itertools. from more_itertools import grouper def make_table(data: str, w: int) -> list[tuple[str]]: return list(grouper(data.split(','), w)) Or without the additional library (and without the fill padding as you assert the data is well formed): def make_table(data: str, w: int) -> list[tuple[str]]: return list(zip(*[iter(data.split(','))] * w)) Note that the return type is not the requested original List[List] return type, but neither was the output of make_3_column_table(...). Again, if a lazy option is desired with an Iterable[...] return type instead of the list[...] return type, then omit the list(...) calls from the return statements and adjust the return signature.
{ "domain": "codereview.stackexchange", "id": 42650, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
c++, algorithm, graph, depth-first-search, breadth-first-search Title: Find the shortest path from bottom left to top right in a maze using dfs and bfs algorithm Question: The following code is applying the depth-first search and breadth-first search algorithm to find the shortest path from bottom left to top right in a 10 x 10 grid. I need reviews to improve my implementation and code quality. Graph.h: #include <iostream> #pragma once using namespace std; struct point{ int x, y; bool operator>(point pnt){ return (this->x > pnt.x) && (this->y > pnt.y); } }; struct node{ char val; bool visited; point prev; node(char v = 0){ val = v; visited = false; prev = {-1, -1}; } }; class GRAPH{ size_t rows, cols; char route; node** nodes = nullptr; public: GRAPH(size_t n, size_t m, char **vals = nullptr, char rout = '*'){ rows = n; cols = m; route = rout; if(vals){ nodes = new node*[rows]; for(size_t i = 0; i < rows; i++){ nodes[i] = new node[cols]; for(size_t j = 0; j < cols; j++){ nodes[i][j] = (vals[i][j]); } } for(size_t i = 0; i < rows; i++) delete vals[i]; delete[]vals; } } void display(){ for(size_t i = 0; i < rows; i++){ for(size_t j = 0; j < cols; j++) cout << nodes[i][j].val << ' '; cout << '\n'; } cout << '\n'; } bool inside_graph(point pnt){ return pnt.x < rows && pnt.y < cols; } bool is_on_route(point pnt){ return this->inside_graph(pnt) && this->at(pnt).val == route; } node& at(point pnt){ return nodes[pnt.x][pnt.y]; } point size(){ return {rows, cols}; } ~GRAPH(){ for(size_t i = 0; i < rows; i++) delete nodes[i]; delete[]nodes; } };
{ "domain": "codereview.stackexchange", "id": 42651, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph, depth-first-search, breadth-first-search", "url": null }
c++, algorithm, graph, depth-first-search, breadth-first-search Solve.cpp #include <iostream> #include <queue> #include <fstream> #include "graph.h" using namespace std; int dfs_cnt = 0, bfs_cnt = 0; GRAPH init_graph(); void DFS(GRAPH&, point, point); void BFS(GRAPH&, point, point); void solve(GRAPH&, bool); void mark(GRAPH&, char); int main() { GRAPH graph_for_DFS = init_graph(); DFS(graph_for_DFS, {graph_for_DFS.size().x - 1, 0}, {0, graph_for_DFS.size().y - 1}); mark(graph_for_DFS, '+'); graph_for_DFS.display(); solve(graph_for_DFS, 0);
{ "domain": "codereview.stackexchange", "id": 42651, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph, depth-first-search, breadth-first-search", "url": null }
c++, algorithm, graph, depth-first-search, breadth-first-search GRAPH graph_for_BFS = init_graph(); BFS(graph_for_BFS, {graph_for_BFS.size().x - 1, 0}, {0, graph_for_BFS.size().y - 1}); mark(graph_for_BFS, '+'); graph_for_BFS.display(); solve(graph_for_BFS, 1); return 0; } GRAPH init_graph(){ dfs_cnt = bfs_cnt = 0; ifstream maze("Maze.txt"); size_t n, m; maze >> n >> m; char **grid = new char* [n]; for(size_t i = 0; i < n; i++){ grid[i] = new char[m]; maze >> grid[i]; } maze.close(); return GRAPH(n, m, grid); } void DFS(GRAPH& graph, point src, point dest){ dfs_cnt++; if(src > dest) return; point tmp = {src.x - 1, src.y}; if(graph.is_on_route(tmp) && !graph.at(tmp).visited){ graph.at(tmp).visited = true; graph.at(tmp).prev = src; DFS(graph, tmp, dest); } tmp = {src.x, src.y + 1}; if(graph.is_on_route(tmp) && !graph.at(tmp).visited){ graph.at(tmp).visited = true; graph.at(tmp).prev = src; DFS(graph, tmp, dest); } } void BFS(GRAPH& graph, point src, point dest){ queue<point> q; q.push(src); point curr = src; while(!q.empty() && !(curr > dest)){ curr = q.front(); graph.at(curr).visited = true; q.pop(); point tmp = {curr.x - 1, curr.y}; bfs_cnt++; if(graph.is_on_route(tmp) && !graph.at(tmp).visited){ q.push(tmp); graph.at(tmp).visited = true; graph.at(tmp).prev = curr; bfs_cnt++; } tmp = {curr.x, curr.y + 1}; if(graph.is_on_route(tmp) && !graph.at(tmp).visited){ q.push(tmp); graph.at(tmp).visited = true; graph.at(tmp).prev = curr; bfs_cnt++; } } } void mark(GRAPH& graph, char mrk){ for(node *tmp = &graph.at({0, graph.size().y - 1}); tmp != &graph.at({graph.size().x - 1, 0}); tmp = &graph.at(tmp->prev)) tmp->val = mrk; graph.at({graph.size().x - 1, 0}) = mrk; }
{ "domain": "codereview.stackexchange", "id": 42651, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph, depth-first-search, breadth-first-search", "url": null }
c++, algorithm, graph, depth-first-search, breadth-first-search tmp->val = mrk; graph.at({graph.size().x - 1, 0}) = mrk; } void solve(GRAPH& graph, bool is_BFS){ ofstream sol(is_BFS ? "BFS_Solved_Maze.txt" : "DFS_Solved_Maze.txt"); size_t n = graph.size().x, m = graph.size().y; sol << (is_BFS? bfs_cnt : dfs_cnt) << '\n'; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) sol << graph.at({i, j}).val << ' '; sol <<'\n'; } }
{ "domain": "codereview.stackexchange", "id": 42651, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph, depth-first-search, breadth-first-search", "url": null }
c++, algorithm, graph, depth-first-search, breadth-first-search Maze.txt 10 10 ########** ########** #######**# ##******## ##*****### ##*****### #***###### #*######## **######## **######## Answer: The comparison operator in point is broken, as you have many points that are not equal (equivalent) but neither is greater that the other. The usual way for comparing two values in a struct like this is to only look at the second element if the first values are equal. You could make a std::pair from the two points and compare those. Using std::tie is an easy way to do this. The member function should be const, and the parameter should be passed by a const reference (although some would disagree when passing a small struct such as point). bool operator>(const point &pnt) const { return std::tie(x, pnt.x) > std::tie(y, pnt.y); } You use a lot of manual memory management in GRAPH. You're missing copy and move constructors and assignment operators, which will lead to memory problems. This violates the Rule of Three (or five). Replace it all with std::vector, and the memory management will all be taken care of for you (also, the destructor could then be omitted or defaulted). The constructor for GRAPH assumes that the values have been allocated. As it does not own the memory passed in by vals, it should not attempt to free it. It might also be helpful (for the longer term use of the class) to have a default constructor and a way to resize an existing GRAPH object. display, inside_graph, and is_on_route should also be const member functions. Consider adding in an overload of at that is a const member function that returns by value (or const reference). In the standard library, member functions named at will perform bounds checking, and throw an exception if a subscript is out of bounds. You could add that to at, and add two overloads for operator[] that would not perform the bounds checking.
{ "domain": "codereview.stackexchange", "id": 42651, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph, depth-first-search, breadth-first-search", "url": null }
c++, template, generics, palindrome, c++20 Title: Checking whether a string is a permutation of a palindrome in C++20 - follow-up Question: This post is the follow-up of Checking whether a string is a permutation of a palindrome in C++20. So, what's new? Well, nothing else except that the procedure is now generic and accepts all string_views of char, char8_t, wchar_t, char16_t and char32_t: string_utils.h: #ifndef COM_GITHUB_CODERODDE_STRING_UTILS_HPP #define COM_GITHUB_CODERODDE_STRING_UTILS_HPP #include <cstddef> // std::size_t #include <string_view> #include <unordered_map> namespace com::github::coderodde::string_utils { template<typename CharType = char> bool is_permutation_palindrome(const std::basic_string_view<CharType>& text) { std::unordered_map<CharType, std::size_t> counter_map; for (const auto ch : text) ++counter_map[ch]; std::size_t number_of_odd_chars = 0; for (const auto& [ch, cnt] : counter_map) if (cnt % 2 == 1 && ++number_of_odd_chars > 1) return false; return true; } } // namespace com::github::coderodde::string_utils #endif // !COM_GITHUB_CODERODDE_STRING_UTILS_HPP main.cpp: #include "string_utils.h" #include <iostream> namespace su = com::github::coderodde::string_utils; int main() { std::cout << std::boolalpha; std::cout << su::is_permutation_palindrome(std::wstring_view(L"")) << "\n"; std::cout << su::is_permutation_palindrome(std::u8string_view(u8"yash")) << "\n"; std::cout << su::is_permutation_palindrome(std::u16string_view(u"vcciv")) << "\n"; std::cout << su::is_permutation_palindrome(std::u32string_view(U"abnnab")) << "\n"; } Critique request I would like to know how to improve my solution code-wise. I don't care much about performance.
{ "domain": "codereview.stackexchange", "id": 42652, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, generics, palindrome, c++20", "url": null }
c++, template, generics, palindrome, c++20 Answer: There isn't much to talk about, the code is good. Drop in ergonomics The template now disallows usage of std::string directly, as the CharType is not automatically deduced. Some other calls where the string view could be converted to are now prohibited as well (C strings, for example). It might make sense to provide some overloads that take C strings and std strings to facilitate easier use. Missing traits as type parameter for the string_view I honestly do not know if anybody uses them, but I'll leave it here for completeness. Mixing two responsibilities I believe that histogram calculation deserves separation from this function. Perhaps having one easy to use function that composes from them is great, but not having the building blocks separately might cause problems. I haven't worked with ranges, but what if it would be possible to actually create another view from the input that is histogram of the original, then just apply the algorithm? This might solve the problem that @Toby is mentioning, perhaps the ignoring functions could be written as part of the pipeline. This might make it viable to accept any range type that has needed properties (foreshadowing concepts).
{ "domain": "codereview.stackexchange", "id": 42652, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, generics, palindrome, c++20", "url": null }
javascript Title: JavaScript dynamic Question: I've been focusing on my PHP skills lately but have been shifting to JavaScript. I'm familiar with the bare-bone basics of jQuery. I'm not as familiar with JavaScript as I'd like to be. I'm a solo-developer so I'd just like somebody to take a look at this and point out any mistakes or things I could be doing better. What the code does Creates an arbitrary number of <script> elements, assigns a type and src attribute to each one and then inserts that <script> element before the </body>. The code See Better Code below! function async_init() { var element, type, src; var parent = document.getElementsByTagName('body'); var cdn = new Array; cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js'; cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js'; for (var i in cdn) { element = document.createElement('script'); type = document.createAttribute('type'); src = document.createAttribute('src'); type.nodeValue = 'text/javascript'; src.nodeValue = cdn[i]; element.setAttributeNode(type); element.setAttributeNode(src); document.body.insertBefore(element, parent); } } <body onload="async_init()"> Right now the code is working, which is great. But my questions: Is this the "best" way to do this? I define best as optimum user experience and efficient code. Are there any obvious "noobie" flaws in my JavaScript? Is there anyway I could get the onload attribute out of the body? I used Mozilla Developer Network as my JavaScript reference. If there are any other references that are accurate, documented & useful I would love to have more information. Thanks for checking the code out and your feedback, even if its pointing out how my code sucks! Better code after critique function async_init() { var element; var cdn = new Array;
{ "domain": "codereview.stackexchange", "id": 42653, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js'; cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js'; for (var i in cdn) { element = document.createElement('script'); element.setAttribute('type', 'text/javascript'); element.setAttribute('src', cdn[i]); document.body.appendChild(element); } } Answer: You've erred many times in the above code. However, that means you get to learn a lot about how to properly interact with the DOM. In many instances, there are built-ins that quickly and efficiently get the job done. First off, you're incorrectly accessing the body. document.body is a well-supported reference to the body that's been around since at least DOM Level 1. Secondly, you're taking the hard route towards creating an array. In his book, "JavaScript: The Good Parts", Douglas Crockford insists on using literals instead of constructors. In this case, an array literal is []. This is an easier way of calling new Array(). Thirdly, you're incorrectly iterating over the cdn array with a for...in loop instead of a for loop. A for...in loop is meant for objects as it iterates over the properties of an object. Not only is it slower than a normal for loop, but it also is very susceptible to prototype modification. For example, try running this code with a build of MooTools (jsFiddle has one enabled by default): for(var key in []) { console.log(key); } You'll get a ton of hits because MooTools modifies the Array prototype. You'd have to do a hasOwnProperty check for each property just to avoid those pitfalls. Avoid for...in on anything but objects. Next, declaring the i variable inside of the for...in loop gives the illusion of block scope. This isn't the case, since i is available anywhere in the function after it's been defined. Only functions have scope in JavaScript. Here are Crockford's thoughts via "...The Good Parts" (page 102):
{ "domain": "codereview.stackexchange", "id": 42653, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript In most languages, it is generally best to declare variables at the first site of use. That turns out to be a bad practice in JavaScript because it does not have block scope. It is better to declare all variables at the top of each function. Finally, setting the attributes for each script tag isn't necessary. Since you're already interacting with the DOM, setting their cousin, the DOM property is a better idea. The DOM provides shortcuts to node properties and is more stable than setting attributes. get/set/removeAttribute all have the unfortunate shortcoming of being very weird in various Internet Explorer builds. They're best avoided unless completely necessary. Fixed + optimized: function async_init() { var element; var parent = document.body; var cdn = ["http://code.jquery.com/jquery-1.6.2.js", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"]; var i = 0, file; for (i;i<cdn.length;i++) { file = cdn[i]; element = document.createElement("script"); element.type = "text/javascript"; element.src = file; parent.appendChild(element); //free file's value file = null; } /* * Cleanup at end of function, which isn't necessary unless lots of memory is being * used up. * No point nulling a Number, however. In some ECMAScript implementations * (ActionScript 3), this throws a warning. */ //empty array cdn.splice(0, cdn.length); //clear variable values element = null; parent = null; cdn = null; }
{ "domain": "codereview.stackexchange", "id": 42653, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript Also note that since you're adding these scripts asynchronously, there's no stable way to detect when the file has loaded, short of a script loader or a timer (my opinion is neither are stable). An alternative is to use document.write to append these scripts synchonously. However, you'll have to use a DOMString and escape the forward slash in the script's end tag. This will append it to the end of the body tag. Example: document.write("<script type=\"text/javascript\" src=\"\"><\/script>"); Note that the backslash character (\) escapes characters in JavaScript. I've used it to escape the double quotes for each attribute along with the forward slash in the end tag. If you have any more questions regarding JavaScript or the DOM, feel free to ask in the comments. -Matt
{ "domain": "codereview.stackexchange", "id": 42653, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript, unit-testing, properties Title: Sanitize object to only include specific properties Question: Object Property Sanitization I'm learning to code servers using JavaScript, Node, and Express. While writing controllers that create new entries in the database, the need to sanitize the user input arised. Take this post controller as an example. const Model = require('./Model') const post = (req, res, nxt) => Model .create(req.body) .then(createdItem => res.json(createdItem)) .catch(err => nxt(err)) Ideally, we'd like to sanitize the req.body object (that is parsed from JSON, and is provided by the user) before passing it to the create method of the model, to only include specific properties, so the users can't mess with the database schema or change values they aren't supposed to. I experimented a little, and came up with four different solutions, and a test suite for them. I'm using Jest as test framework, Standard as code style, and JSDoc for documentation comments. Here is the code: ops-for-each.js /** * Creates a new object with the specified properties of the * input object, if they are present. * @param {object} object Object to sanitize. * @param {string[]} properties Properties to copy. * @returns Object with the specified properties if present in * original object. */ const sanitizeObjectProperties = (object, properties) => { const accumulator = {} properties.forEach(property => { if (property in object) accumulator[property] = object[property] }) return accumulator } module.exports = { fun: sanitizeObjectProperties, id: 'for each' }
{ "domain": "codereview.stackexchange", "id": 42654, "lm_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, unit-testing, properties", "url": null }
javascript, unit-testing, properties return accumulator } module.exports = { fun: sanitizeObjectProperties, id: 'for each' } ops-reduce.js /** * Creates a new object with the specified properties of the * input object, if they are present. * @param {object} object Object to sanitize. * @param {string[]} properties Properties to copy. * @returns Object with the specified properties if present in * original object. */ const sanitizeObjectProperties = (object, properties) => { const reducer = (copy, property) => { if (property in object) copy[property] = object[property] return copy } return properties.reduce(reducer, {}) } module.exports = { fun: sanitizeObjectProperties, id: 'reduce' } ops-filter-reduce.js /** * Creates a new object with the specified properties of the * input object, if they are present. * @param {object} object Object to sanitize. * @param {string[]} properties Properties to copy. * @returns Object with the specified properties if present in * original object. */ const sanitizeObjectProperties = (object, properties) => properties .filter(property => property in object) .reduce((copy, property) => { copy[property] = object[property] return copy }, {}) module.exports = { fun: sanitizeObjectProperties, id: 'filter reduce' } ops-entries-filter-map.js /** * Creates a new object with the specified properties of the * input object, if they are present. * @param {object} object Object to sanitize. * @param {string[]} properties Properties to copy. * @returns Object with the specified properties if present in * original object. */ const sanitizeObjectProperties = (object, properties) => Object.fromEntries( properties .filter(property => property in object) .map(property => [property, object[property]]) ) module.exports = { fun: sanitizeObjectProperties, id: 'Object.fromEntries filter map' }
{ "domain": "codereview.stackexchange", "id": 42654, "lm_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, unit-testing, properties", "url": null }
javascript, unit-testing, properties module.exports = { fun: sanitizeObjectProperties, id: 'Object.fromEntries filter map' } ops.test.js const testSubjects = [ require('./ops-for-each'), require('./ops-reduce'), require('./ops-filter-reduce'), require('./ops-entries-filter-map') ] testSubjects.forEach(({ fun, id }) => { test(`${id} sanitizes properly`, () => { const object = { title: 'One', year: 2021, hack: true } const properties = ['title', 'year'] const sanitizedCopy = fun(object, properties) // Must not have the 'hack' property expect(sanitizedCopy).toEqual({ title: 'One', year: 2021 }) }) }) Specific Review I have some specific questions, but you can safely ignore some or all of them if you have something else to share about this code. Is this code readable? If not, what would you change to make it more readable? Is this code maintainable? If not, what would you change to make it more maintainable? Is there a more efficient solution? Is there a more concise or idiomatic alternative to these solutions? Perhaps using Object.assign, or object deconstruction, or other techniques? Which solution do you prefer, in terms of readability and/or efficiency and/or conciseness? Are the tests written correctly? Should other test scenarios be considered? Are the documentation comments written correctly? Are there any anti-patterns, code smells, or anything that I should not be doing? Am I missing any best practices? Would you approach this problem in a different way? I'm not mutating the original object, but creating a new one and inserting the specified properties. Is that ok? Are there advantages to mutating the original object instead? General Review While I have some specific questions, I want this to be an open review. Please share anything you'd do differently, maybe as an improvement, or maybe as an alternative worth considering. I'm interested in observations of the code in general, including the solutions, the tests, and the documentation comments.
{ "domain": "codereview.stackexchange", "id": 42654, "lm_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, unit-testing, properties", "url": null }
javascript, unit-testing, properties Answer: I prefer either the reduce or fromEntries approaches. The first, ops-for-each.js, is really just an awkward reduce. You should think about whether you really need the "filter" concept at all. Since you have a list of acceptable properties, as long as you are iterating through those, you will get the right answer. Consider the two cases of: if (property in object) copy[property] = object[property] The first, is where property is present, in which case the property is copied. Otherwise, it is not assigned, and therefore undefined. You'll notice you get the same answer without the if statement, as in simply copy[property] = object[property]. Consider anonymous functions that are only called once shorter variable names if the function is small more standard variable names. I found it helpful to use accumulator in the first function, but was surprised when it wasn't named that in the reduce function, where that's the normal name. I find the following easier to get through than the more verbose one: const sanitizeObjectProperties = (obj, props) => { return props.reduce((acc, p) => { acc[p] = obj[p] return acc }, {}) } As long as you're making just one pass through the properties, you should be relatively good in terms of efficiency. The test looks good, and by having tests, you are improving your maintainability. There are a couple other tests: empty object and pre-sanitized object, which you'll want to have. Your approach of creating a new object is solid and safer than removing extra properties. It's Javascript, so there's lots of ways to do the same thing. There's probably a clever way to do this with rest/spread, but what you have done (#2 or #4) are pretty clear.
{ "domain": "codereview.stackexchange", "id": 42654, "lm_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, unit-testing, properties", "url": null }
javascript, sorting, css Title: Sorting table rows visually with animation while keeping them intact in the DOM Question: I have a table which i want to sort the rows visually according to a column while the rows remain intact in the DOM structure. So nodes aren't moving in the DOM or getting replaced with eachother at all. Table rows can be sorted by clicking at the column's header as of now, which is the simplest case. In future i hope to add further functionalities such as sorting ascending/descending or sorting dynamically whenever a <td> element which belongs to the designated column gets updated. In fact i plan to turn this into a <sortable-table> custom element. As you may notice, CSS is not my strong suit, while the code is working, the borders are a little problematic. For instance I can't tell why the row transitions has no effect on row borders or why rows do not get perfectly alligned after moving etc. In short, i need to know if this is a proper way to approach to this task before further ado? var rows = [...document.querySelectorAll("tbody tr")], sorters = { coin : rs => rs.sort((a,b) => a.querySelector("[headers='coin']").textContent < b.querySelector("[headers='coin']").textContent ? -1 : 1 ) , change: rs => rs.sort((a,b) => parseFloat(a.querySelector("[headers='change']").textContent) - parseFloat(b.querySelector("[headers='change']").textContent) ) , price : rs => rs.sort((a,b) => parseFloat(a.querySelector("[headers='price']").dataset.price) - parseFloat(b.querySelector("[headers='price']").dataset.price) ) }, listen = e => ( sorters[e.target.id](rows) , requestAnimationFrame(setupTable) ), ruler;
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
javascript, sorting, css function setupTable(){ var cell; rows.forEach((row,i) => ( cell = row.querySelector("[data-price]") , cell.textContent = parseFloat(cell.dataset.price).toLocaleString("tr-TR",{minimumFractionDigits:2}) , row.style.transform = `translateY(${ruler[i]-row.dataset.originalTop}px)` ) ); } document.getElementById("coin") .addEventListener("click", listen); document.getElementById("change") .addEventListener("click", listen); document.getElementById("price") .addEventListener("click", listen); requestAnimationFrame(_ => ( ruler = rows.map(row => row.dataset.originalTop = row.getBoundingClientRect().top) , setupTable() )); table { border-collapse: collapse; border: 2px solid green; text-align: left; width: 21vw; } tbody tr { background-color: pink; border: 2px solid green; transition: transform 1s; transition-timing-function: ease-in-out; transform: translateY(0); } th { text-align: center; border: 2px solid green; padding: 0.2em; cursor: pointer; width: 7vw; } td { padding: 0.2em; width: 7vw; border: 2px solid green; border-width: 2px 0 2px 0; } tr td:nth-child(2) { text-align: right; } tr td:nth-child(3) { text-align: right; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>replit</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="script.js" defer></script> </head>
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
javascript, sorting, css <body> <table id="sorted"> <thead> <tr> <th id="coin">Coin</th> <th id="change">Change</th> <th id="price">Price USD</th> </tr> </thead> <tbody> <tr> <td headers="coin">BTC</td> <td headers="change">2%</td> <td headers="price" data-price="47594.70"></td> </tr> <tr> <td headers="coin">ETH</td> <td headers="change">2.11%</td> <td headers="price" data-price="3972.46"></td> </tr> <tr> <td headers="coin">BNB</td> <td headers="change">0.1%</td> <td headers="price" data-price="538.72"></td> </tr> <tr> <td headers="coin">USDT</td> <td headers="change">0%</td> <td headers="price" data-price="0.9997"></td> </tr> <tr> <td headers="coin">SOL</td> <td headers="change">-2%</td> <td headers="price" data-price="187.39"></td> </tr> <tr> <td headers="coin">ADA</td> <td headers="change">1.67%</td> <td headers="price" data-price="1.29"></td> </tr> </tbody> </table> </body> </html>
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
javascript, sorting, css Answer: I have been working on this for a while. Since nobody have answered i just would like to share my solution to my both problems. 1. tbody tr {transform: translateY();} doesn't effect row borders: In order to be able to apply borders to a tr element, the table has to have {border-collapse:collapse;} in the first place. However when borders are collapsed, the table rows start sharing borders with their neigbouring rows. So when a transition is applied to a row, since the border is not solely owned by that row, stays still. My solution was, replacing border-collapse:collapse with borders-spacing:0. Now that I can not have borders around rows, I applied borders to the necessary sides of the table, th and td elements to get the same effect. 2. Some rows do not move to the exact position that they should: Despite all calculations being correct some of the rows wouldn't move to the exact location but shifting up or down by a tiny amount. I concluded that this is originated from sub pixel rendering. To fix it, i explicitly had to set the row height to an integer value. 27px was OK right away and it worked perfectly. I suspect the origin of the subpixel rendering should be the font size. So if we correlate the row height with the font size then perhaps we can solve the problem while maintaining the responsiveness. Let's try em units. As it turns out a tr height of 1.75, 2, 2.25, 2.5, 2.75, 3... ems do perfectly work.
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
javascript, sorting, css var rows = [...document.querySelectorAll("tbody tr")], sorters = { coin : rs => rs.sort((a,b) => a.querySelector("[headers='coin']").textContent < b.querySelector("[headers='coin']").textContent ? -1 : 1 ) , change: rs => rs.sort((a,b) => parseFloat(a.querySelector("[headers='change']").textContent) - parseFloat(b.querySelector("[headers='change']").textContent) ) , price : rs => rs.sort((a,b) => parseFloat(a.querySelector("[headers='price']").dataset.price) - parseFloat(b.querySelector("[headers='price']").dataset.price) ) }, listen = e => ( sorters[e.target.id](rows) , requestAnimationFrame(setupTable) ), ruler; function setupTable(){ var cell; rows.forEach((row,i) => ( cell = row.querySelector("[data-price]") , cell.textContent = parseFloat(cell.dataset.price).toLocaleString("tr-TR",{minimumFractionDigits:2}) , row.style.transform = `translateY(${ruler[i]-row.dataset.originalTop}px)` ) ); } document.getElementById("coin") .addEventListener("click", listen); document.getElementById("change") .addEventListener("click", listen); document.getElementById("price") .addEventListener("click", listen);
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
javascript, sorting, css requestAnimationFrame(_ => ( ruler = rows.map(row => row.dataset.originalTop = row.getBoundingClientRect().top) , setupTable() )); table { border: solid green; border-width: 2px 2px 1px 2px; border-spacing: 0; text-align: left; width: 21vw; } tr { height:1.75em; } tbody tr { background-color: pink; transition: transform 1s; transition-timing-function: ease-in-out; transform: translateY(0px); } th { text-align: center; padding: 0.2em; width: 7vw; border-bottom: 1px solid green; cursor: pointer; } td { padding: 0.2em; width: 7vw; border: solid green; border-width: 1px 0px 1px 0px; } tr td:nth-child(2) { text-align: right; } tr td:nth-child(3) { text-align: right; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>replit</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="script.js" defer></script> </head>
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
javascript, sorting, css <body> <table id="sorted"> <thead> <tr> <th id="coin">Coin</th> <th id="change">Change</th> <th id="price">Price USD</th> </tr> </thead> <tbody> <tr> <td headers="coin">BTC</td> <td headers="change">2%</td> <td headers="price" data-price="47594.70"></td> </tr> <tr> <td headers="coin">ETH</td> <td headers="change">2.11%</td> <td headers="price" data-price="3972.46"></td> </tr> <tr> <td headers="coin">BNB</td> <td headers="change">0.1%</td> <td headers="price" data-price="538.72"></td> </tr> <tr> <td headers="coin">USDT</td> <td headers="change">0%</td> <td headers="price" data-price="0.9997"></td> </tr> <tr> <td headers="coin">SOL</td> <td headers="change">-2%</td> <td headers="price" data-price="187.39"></td> </tr> <tr> <td headers="coin">ADA</td> <td headers="change">1.67%</td> <td headers="price" data-price="1.29"></td> </tr> </tbody> </table> </body> </html> Any ideas, simplifications are most welcome.
{ "domain": "codereview.stackexchange", "id": 42655, "lm_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, sorting, css", "url": null }
c++, unit-testing, classes, c++20, overloading Title: Operator overloading in Image class implementation in C++ Question: This is a follow-up question for Dictionary based non-local mean implementation in C++. There are some issues about operators (operator+ and operator-) mentioned by Edward's answer and JDługosz's comment. I am trying to propose the fixed version of Image class as below. operator+ and operator- operator overloading: friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } The full Image class implementation: template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector<ElementT> input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return image_data[y * width + x]; } constexpr std::size_t getWidth() const { return width; } constexpr std::size_t getHeight() const { return height; }
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading constexpr std::size_t getHeight() const { return height; } constexpr auto getSize() { return std::make_tuple(width, height); } std::vector<ElementT> const& getImageData() const { return image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; return; } // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; for (std::size_t y = 0; y < rhs.height; ++y) { for (std::size_t x = 0; x < rhs.width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +rhs.at(x, y) << separator; } os << "\n"; } os << "\n"; return os; }
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; }
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data; void checkBoundary(const size_t x, const size_t y) const { assert(x < width); assert(y < height); } }; Unit tests for operator+and operator-: void operatorAddInImageClassTest(const std::size_t sizex, const std::size_t sizey) { // Assign auto test_image1 = TinyDIP::Image(sizex, sizey, 1); auto test_image2 = TinyDIP::Image(sizex, sizey, 2); // Action auto actual_result = test_image1 + test_image2; // Assert auto expected_result = TinyDIP::Image(sizex, sizey, 3); assert(actual_result == expected_result); return; } void operatorMinusInImageClassTest(const std::size_t sizex, const std::size_t sizey) { // Assign auto test_image1 = TinyDIP::Image(sizex, sizey, 1); auto test_image2 = TinyDIP::Image(sizex, sizey, 2); // Action auto actual_result = test_image1 - test_image2; // Assert auto expected_result = TinyDIP::Image(sizex, sizey, -1); assert(actual_result == expected_result); return; } Full Testing Code The full tests for operator+and operator-: #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <cmath> #include <concepts> #include <exception> #include <fstream> #include <iostream> #include <limits> #include <numeric> #include <ranges> #include <type_traits> #include <utility> #include <vector> using BYTE = unsigned char; struct RGB { BYTE channels[3]; }; using GrayScale = BYTE;
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading using BYTE = unsigned char; struct RGB { BYTE channels[3]; }; using GrayScale = BYTE; namespace TinyDIP { #define is_size_same(x, y) {assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight());} template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector<ElementT> input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return image_data[y * width + x]; } constexpr std::size_t getWidth() const { return width; } constexpr std::size_t getHeight() const { return height; } constexpr auto getSize() { return std::make_tuple(width, height); } std::vector<ElementT> const& getImageData() const { return image_data; } // expose the internal data
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; return; } // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; for (std::size_t y = 0; y < rhs.height; ++y) { for (std::size_t x = 0; x < rhs.width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +rhs.at(x, y) << separator; } os << "\n"; } os << "\n"; return os; }
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; }
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data; void checkBoundary(const size_t x, const size_t y) const { assert(x < width); assert(y < height); } }; } void operatorAddInImageClassTest(const std::size_t sizex, const std::size_t sizey) { // Assign auto test_image1 = TinyDIP::Image(sizex, sizey, 1); auto test_image2 = TinyDIP::Image(sizex, sizey, 2); // Action auto actual_result = test_image1 + test_image2; // Assert auto expected_result = TinyDIP::Image(sizex, sizey, 3); assert(actual_result == expected_result); return; } void operatorMinusInImageClassTest(const std::size_t sizex, const std::size_t sizey) { // Assign auto test_image1 = TinyDIP::Image(sizex, sizey, 1); auto test_image2 = TinyDIP::Image(sizex, sizey, 2); // Action auto actual_result = test_image1 - test_image2; // Assert auto expected_result = TinyDIP::Image(sizex, sizey, -1); assert(actual_result == expected_result); return; }
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading int main() { auto start = std::chrono::system_clock::now(); operatorAddInImageClassTest(10, 10); operatorMinusInImageClassTest(10, 10); auto max_size = std::numeric_limits<std::size_t>::max(); operatorAddInImageClassTest(max_size, max_size); operatorMinusInImageClassTest(max_size, max_size); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } The output of the testing code above: Computation finished at Sat Dec 25 07:08:32 2021 elapsed time: 1.2452e-05 A Godbolt link is here. TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? Dictionary based non-local mean implementation in C++ What changes has been made in the code since last question? Update and fix the operator+ and operator- implementation in Image class. Why a new review is being asked for? If there is any possible improvement, please let me know. Answer: Build script review Build scripts are major part of the software, so I will review it along with the main code. Avoid CMAKE_CXX_FLAGS, include_dirs and other globals There is target_compile_options to not make things global. Optimization flags are better ommitted altogether. The testing code uses assert, but build script always specifies optimization flag. Are tests really not failing? (perhaps the script was modified after testing) Use Threads package instead of pthreads find_package(Threads REQUIRED) target_link_libraries(TARGET PUBLIC Threads::Threads)
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading I believe there was something similar to filesystem, but I couldn't find it. Unfortunately libm does have better linking mechanism. Use generator expressions where appropriate There are some pieces with if() else() chains. It might be better to use generator expressions in those cases. Since generator expression becomes nothing if not evaluated to 1, it just becomes empty (not even a space, literally empty, IIRC). This matches the build script pieces where some branches empty and some branches are not (there is a generator expression for compiler ID). Code Review Don't move from const variable image_data = std::move(input); This will not move from input because input is const and overload resolution will lead to copy. I guess originally it was a reference, then it was migrated into copy and move idiom. Just drop the const from the declaration. Don't forget noexcept There are multiple one-liners that clearly don't throw exceptions Subscript operator conventions My initial expectation was to search for operator()(std::size_t, std::size_t). In all of the BLAS-like libraries I used, the function call operator was the subscript operator. at() implies always-on bound checking, but that is not the case. Although this is just a convention, it might surprise users.
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
c++, unit-testing, classes, c++20, overloading Benchmark? review Not sure if the tests were a benchmark. Understand performance metrics It is important to know what is being measured and why it is being measured. The current code seems to be to just "gauge" at how it behaves. Perhaps it would be better to pit it against OpenCV. The heavy hitters like MKL, Blaze, Eigen and uBLAS would be great too. Don't expect the compiler generated code to be as fast as those libraries, but it might provide good insight into future considerations. Run it multiple times The first run might step on page faults and OS/runtime facility initialization. There might be context switches (one context switch can skew results tremendeously). Be careful with clocks Non-monotonic clocks have a bad habit of getting calibrated in the most inopportune moments. Vector instructions It might make sense to examine the assembly output to see if there are any AVX instructions, at least AVX2. If there are none, it might be worth it to have a look at vectorization libraries.
{ "domain": "codereview.stackexchange", "id": 42656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, unit-testing, classes, c++20, overloading", "url": null }
rust, floating-point Title: Floating point addition algorithm Question: I made a function in Rust to add two floating point numbers (f32s) together using only their bit representation and integer operations. I have tested it for a quite a few different cases but I'm not sure how I can efficiently test it for all floating point numbers without it taking ages. fn add_f32(mut a: f32, mut b: f32) -> f32 { if b > a { // If b has a larger exponent than a, swap a and b so that a has the larger exponent core::mem::swap(&mut a, &mut b); } let a_normal = a.is_normal(); let b_normal = b.is_normal(); let a_bits = a.to_bits(); let b_bits = b.to_bits(); let mut a_exp = (a_bits << 1) >> (23 + 1); let mut b_exp = (b_bits << 1) >> (23 + 1); let mut a_mant = a_bits & 0x007fffff; let mut b_mant = b_bits & 0x007fffff; if a_exp == 0 { a_exp += 1; } if b_exp == 0 { b_exp += 1; } let exp_diff = a_exp - b_exp; let sticky_bit = b_mant.trailing_zeros() + 1 < exp_diff; // Add the implicit leading 1 bit to the mantissas if a_normal { a_mant |= 1 << 23; } if b_normal { b_mant |= 1 << 23; } // Append extra bits to the mantissas to ensure correct rounding a_mant <<= 2; b_mant <<= 2; // If the shift causes an overflow, the b_mant is too small so is set to 0 b_mant = b_mant.checked_shr(exp_diff).unwrap_or(0); if sticky_bit { b_mant |= 1; } let mut mant = a_mant + b_mant;
{ "domain": "codereview.stackexchange", "id": 42657, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, floating-point", "url": null }
rust, floating-point if sticky_bit { b_mant |= 1; } let mut mant = a_mant + b_mant; let overflow = (mant >> 26) != 0; if !overflow { if mant & 0b11 == 0b11 { mant += 0b100; if (mant >> 26) != 0 { mant >>= 1; a_exp += 1; } } else if mant & 0b110 == 0b110 { mant += 0b100; if (mant >> 26) != 0 { mant >>= 1; a_exp += 1; } } } else { match mant & 0b111 { 0b111 | 0b110 | 0b101 => { mant += 0b1000; }, 0b100 => { if mant & 0b1000 == 0b1000 { mant += 0b1000; } }, _ => {}, } mant >>= 1; a_exp += 1; } mant >>= 2; if mant >> 23 == 0 { a_exp = 0; } else { mant <<= 9; mant >>= 9; } f32::from_bits(mant | (a_exp << 23)) } ``` Answer: I have tested it for a quite a few different cases but I'm not sure how I can efficiently test it for all floating point numbers without it taking ages. I would use something like the quickcheck crate (a port of Haskell's QuickCheck) to test the property of whether your addition function has the same results as ordinary f32 addition. If you don't know what quickcheck is, then this video might help. Fuzzing your function as described in this video about Fuzz-Driven Development (FDD) might be another option.
{ "domain": "codereview.stackexchange", "id": 42657, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, floating-point", "url": null }
python, symbolic-math, sympy Title: Polynomial calculation in SymPy Question: Thie programs is written in Sympy 1.9 and it should find a polynomial g of degree dim for a given polynomial f such that f o g = g o f as described here, where I already posted program written in Maxima. This is my first program in SymPy so I am interested in your feedback on this program except on the algorithm itself. from sympy import symbols, pprint, expand, Poly, IndexedBase, Idx,Eq,solve from sympy.abc import x,f,g,i fg,gf,d=symbols('fg gf d') f=x**3+3*x # a polynomial g exists #f=x**3+4*x # a polynomial g does not exist dim=5 a=IndexedBase('a') i=Idx('i',dim) # create a polynomial of degree dim # with unknown coefficients, # but the coefficient of the highest power is 1 # an the lowest power is 1 g=a[0]+x**dim for i in range(1,dim): g+=x**i*a[i] # calculate fg = f o g # and gf = g o f fg=f gf=g fg=expand(f.subs(x,g)) gf=expand(g.subs(x,f)) # calculate the difference d=(f o g) - (g o f) # and check how to choose the coefficients of g # such that it will become 0 difference=(fg-gf).as_poly(x) candidates=solve(difference.all_coeffs()[:dim],[a[i] for i in range(dim)]) replacements=[(a[i],candidates[0][i]) for i in range(dim)] if (difference.subs(replacements)==0): pprint(g.subs(replacements)) else: print("no solution exists") Answer: Turning into a Function I would advise turning your program into a function. This allows people to use your function in other Python scripts. That is: def poly_commute(f, dim): a=IndexedBase('a') i=Idx('i',dim) g=a[0]+x**dim for i in range(1,dim): g+=x**i*a[i] # calculate fg = f o g # and gf = g o f fg=f gf=g fg=expand(f.subs(x,g)) gf=expand(g.subs(x,f)) # calculate the difference d=(f o g) - (g o f) # and check how to choose the coefficients of g # such that it will become 0
{ "domain": "codereview.stackexchange", "id": 42658, "lm_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, symbolic-math, sympy", "url": null }
python, symbolic-math, sympy difference=(fg-gf).as_poly(x) candidates=solve(difference.all_coeffs()[:dim],[a[i] for i in range(dim)]) replacements=[(a[i],candidates[0][i]) for i in range(dim)] if (difference.subs(replacements)==0): return g.subs(replacements) else: return None Also, you should add some documentation so others can understand what your function does. Related: Removing Global Variables Managing state can be a pain. Keeping track of what can be in which state can be a headache. It isn't of course unmanageable in this case, but it would be useful to get rid of the state. To do so, I would add a main function. def main(): f = x**3 + 3*x dim = 5 g = poly_commute(f, dim) if g: pprint(g) else: print("No solution exists.") if __name__ == '__main__': main() PEP 8: There is some spacing of equations that seem to be off. This is explained in "Other recommendations" of PEP 8: If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator: # Correct: i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) # Wrong: i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b)
{ "domain": "codereview.stackexchange", "id": 42658, "lm_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, symbolic-math, sympy", "url": null }
c#, thread-safety, asp.net-core Title: C# Thread-safe singleton service for caching data used during lifetime of ASP.NET Core MVC application Question: Basic Background I have an ASP.NET Core MVC application that uses Client (e.g., "customer") information for every HTTP request. The collection of Clients, as well as their information, rarely changes and is stored in a database. If it does change and some subsequent requests still use the old information, or even if the application throws an exception because of the change, that is OK. Goal I would like my ClientService class to cache the Client information to remove making a database call on every request. However, I believe that making this class a singleton in the DI container means that it needs to be thread-safe. (If I am wrong about this, I am still interested in whether the code below would be.) The thread-safety of this code and its conformance to best practices for thread-safety is my primary goal, although performance considerations would also be appreciated. Code Below is the ClientService class, which is the primary class that I am working on. I have also included the Clone method of the Client class since it is referenced. ClientService is added to the DI container as a singleton in Startup. One pretty significant question... Are locks even needed here? This is my first time using them. First time Code Review post- please advise of any improvements that this site would prefer. Thanks in advance for your time reading! public class ClientService { private readonly IServiceProvider _serviceProvider; private readonly string _key; public ClientService( IKeyProvider keyProvider, IServiceProvider serviceProvider ) { _serviceProvider = serviceProvider; _key = keyProvider.GetKey(); } private readonly object _cachedClientsLock = new object(); private Dictionary<int, Client> _cachedClients = null;
{ "domain": "codereview.stackexchange", "id": 42659, "lm_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#, thread-safety, asp.net-core", "url": null }
c#, thread-safety, asp.net-core public async Task<Client> GetClient(int clientId) { await EnsureCache(); lock (_cachedClientsLock) { return _cachedClients[clientId].Clone(); } } public async Task<Client> GetClientByCode(string code) { await EnsureCache(); lock (_cachedClientsLock) { foreach (Client client in _cachedClients.Values) if (client.Code == code) return client.Clone(); } return null; } private async Task EnsureCache() { bool clientsAreCached; lock (_cachedClientsLock) { clientsAreCached = _cachedClients != null; } if (!clientsAreCached) { Dictionary<int, Client> clients = await GetClients(); lock (_cachedClientsLock) { _cachedClients = clients; } } } private async Task<Dictionary<int, Client>> GetClients() { using (IServiceScope scope = _serviceProvider.CreateScope()) { ConnectionStringProvider connectionStringProvider = scope.ServiceProvider.GetRequiredService<ConnectionStringProvider>(); string connectionString = await connectionStringProvider.GetConnectionString(); // SQL execution using SqlCommand and SqlDataReader Dictionary<int, Client> results = new Dictionary<int, Client>(); // SqlDataReader populates the dictionary // _key is used here return results; } } } public class Client { // Properties public Client Clone() { return new Client() { Id = this.Id, Code = this.Code, // etc. for remaining properties, which are all strings }; } }
{ "domain": "codereview.stackexchange", "id": 42659, "lm_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#, thread-safety, asp.net-core", "url": null }
c#, thread-safety, asp.net-core public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IClientService, ClientService>(); // other services and configuration } } ``` Answer: The locks on the read are not needed since the cache is only created once and the rest is just readonly access. If wanting locks since most of these calls is read access then the ReaderWriterLockSlim class would be an option to not serilize the reading of the dictionary. Another option that would IMO simplify the code is to use the Lazy class. We can combine the Lazy with Task to make sure we only ever make one Task that all the threads share. Once the Task is complete it will just return the same result when awaited again. I changed the code to return IReadOnlyDictionary as it tells others coming after you the dictionary should only be read and not updated. Also GetClient I used TryGetValue as to not throw keynotfound. Even if wanting to throw an exception when the key isn't found that generic error isn't helpful when debugging. Throwing a custom ClientNotFoundException or at least change the message so it's clear what the problem is. A downside of this approach is if the GetClients throws that exception would be cached for all calls. If wanting to retry if exception I would suggest adding the Polly nuget package and using it in the GetClients code. Example code of using Lazy<Task<>> public class ClientService { private readonly IServiceProvider _serviceProvider; private readonly string _key; private readonly Lazy<Task<IReadOnlyDictionary<int, Client>>> _cachedClients; public ClientService( IKeyProvider keyProvider, IServiceProvider serviceProvider ) { _serviceProvider = serviceProvider; _key = keyProvider.GetKey(); _cachedClients = new Lazy<Task<IReadOnlyDictionary<int, Client>>>(GetClients); }
{ "domain": "codereview.stackexchange", "id": 42659, "lm_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#, thread-safety, asp.net-core", "url": null }
c#, thread-safety, asp.net-core public async Task<Client> GetClient(int clientId) { var cachedClients = await _cachedClients.Value; if (cachedClients.TryGetValue(clientId, out Client client)) { return client.Clone(); } return null; } public async Task<Client> GetClientByCode(string code) { var cachedClients = await _cachedClients.Value; return cachedClients.Values.FirstOrDefault(client => client.Code == code); }
{ "domain": "codereview.stackexchange", "id": 42659, "lm_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#, thread-safety, asp.net-core", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer Title: Lock-free multi-producer / multi-consumer queue in C++ Question: I've been working on a lockless multi-producer, multi-consumer queue in an effort to learn as much as I can about concurrency, without the use of mutual exclusion. The queue uses a bounded ring buffer to store/load the data from. Two cursors are used two track the next available index on the buffer, one for producers and one for consumers. The cursors are a custom sequential container type, which uses memory barriers to order access to some data. Inspiration is taken from the LMAX Disruptor here. Once a producer or consumer has successfully incremented the cursor, it can then safely do its work on the "claimed" index, knowing any following producer or consumer will be accessing a higher index. The queue size is specified by the user, but ceiled up to the nearest power of two, so a bitwise-and can be used in place of modulo to automatically wrap the index back to zero.. The queue works as it is right now, I've got two different version of the enqueu/dequeue functions, with one using a CAS loop to increment the cursor, and the other using a fetch_add. The main issue I'm having is that the fetch_add version of enqueue is about 10x faster than the CAS version, which I don't really understand. Then second, I'm getting quite a bit of false sharing reported in Intel VTune Profiler, even though I've padded everything. Anyway, here's the code: The Enqueue/Dequeue & EnqueueCAS/DequeueCAS functions are inside the TMPMCQueue class at the bottom. // SPDX-License-Identifier: GPL-2.0-or-later /** Lockless Multi-Producer Multi-Consumer Queue Type. * Author: Primrose Taylor */ #ifndef MPMCQUEUE_H #define MPMCQUEUE_H #include "stdio.h" #include "stdlib.h" #include <atomic> #define PLATFORM_CACHE_LINE_SIZE 64
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer #include "stdio.h" #include "stdlib.h" #include <atomic> #define PLATFORM_CACHE_LINE_SIZE 64 /** * A container which can ensure that access to it's data will be sequentially consistent across all accessing threads, * but allows for getting the data via a custom memory order. */ template <typename T> class TSequentialContainer { public: TSequentialContainer() { static_assert( std::is_copy_constructible_v<T> || std::is_copy_assignable_v<T> || std::is_move_assignable_v<T> || std::is_move_constructible_v<T>, "Can't use non-copyable, non-assignable, non-movable, or non-constructible type!" ); } explicit TSequentialContainer(const T& InitialValue) { TSequentialContainer(); Data.store(InitialValue, std::memory_order_seq_cst); } /** * Get the data, using an acquire fence to ensure that any prior write is visible to this load. */ T Get() const { const T OutCopy = Data.load(std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire); return OutCopy; }
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer /** * Load the data with relaxed semantics. NOTE: NOT THREAD SAFE! */ T GetRelaxed() const { return Data.load(std::memory_order_relaxed); } T GetCustom(const std::memory_order MemoryOrder) const { return Data.load(MemoryOrder); } /** * Set the data, first performing a release fence. * The release fence will ensure that any subsequent read will see this write. */ void Set(const T& NewData) { std::atomic_thread_fence(std::memory_order_release); Data.store(NewData, std::memory_order_relaxed); } /** * Set the data by first performing a release fence, then storing the data, * then performing a full fence. */ void SetFullFence(const T& NewData) { std::atomic_thread_fence(std::memory_order_release); Data.store(NewData, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_seq_cst); } void SetCustom(const T& NewData, const std::memory_order MemoryOrder) { Data.store(NewData, MemoryOrder); } /** * Perform a CAS operation on the stored data. * Uses release semantics if works. * Uses relaxed semantics if failed. */ bool CompareAndSet(T& Expected, const T& NewValue) { return Data.compare_exchange_weak(Expected, NewValue, std::memory_order_release, std::memory_order_relaxed); } protected: uint_fast8_t PadToAvoidContention0[PLATFORM_CACHE_LINE_SIZE] = { }; /** * An atomic variable which holds the data. */ std::atomic<T> Data; uint_fast8_t PadToAvoidContention1[PLATFORM_CACHE_LINE_SIZE] = { }; private: TSequentialContainer(const TSequentialContainer&) = delete; TSequentialContainer& operator=(const TSequentialContainer&) = delete; };
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer /** * A simple child class of the @link TSequentialContainer which uses an int64 instead of a template. * Providing some extra functions specific to modifying an integer. */ class FSequentialInteger : public TSequentialContainer<int_fast64_t> { public: FSequentialInteger(const int_fast64_t InitialValue = 0) : TSequentialContainer() { SetFullFence(InitialValue); } /** * Uses a fetch_add with Acquire/Release semantics to increment the integer. * * @return Returns the original value of the integer. */ int_fast64_t AddAndGetOldValue(const int_fast64_t Value) { return Data.fetch_add(Value, std::memory_order_acq_rel); } /** * @link AddAndGetOldValue() */ int_fast64_t AddAndGetNewValue(const int_fast64_t Value) { return AddAndGetOldValue(Value) + Value; } /** * @link AddAndGetNewValue() * @link AddAndGetOldValue() */ int_fast64_t IncrementAndGetOldValue() { return AddAndGetOldValue(1); } /** * @link IncrementAndGetOldValue() */ void Increment() { IncrementAndGetOldValue(); } void IncrementRelaxed() { Data.fetch_add(1, std::memory_order_relaxed); } void operator=(const int_fast64_t NewValue) { SetFullFence(NewValue); } }; /** * Enum used to represent each status output from the Enqueue/Dequeue functions inside @link TMPMCQueue */ enum class EMPMCQueueErrorStatus : uint_fast8_t { TRANSACTION_SUCCESS, BUFFER_FULL, BUFFER_EMPTY, BUFFER_NOT_INITIALIZED, COPY_FAILED, COPY_SUCCESS, BUFFER_COPY_FAILED, BUFFER_COPY_SUCCESS };
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer /** * A Lockless Multi-Producer, Multi-Consumer Queue that uses * a bounded ring buffer to store the data. * @link TSequentialContainer A sequential container of type T, which uses memory barriers to sync access to it's data. * @link FSequentialInteger A sequential integer container, which uses memory barriers to sync access to it's data. * @link EMPMCQueueErrorStatus Enum used to represent each status output from the Enqueue/Dequeue functions. * * @template T The type to use for the queue. * @template TQueueSize The size you want the queue to be. This will be rounded UP to the nearest power of two. * * @biref A Lockless Multi-Producer, Multi-Consumer Queue. */ template <typename T, uint_fast64_t TQueueSize> class TMPMCQueue final { private: using FElementType = T; using FCursor = FSequentialInteger; public: TMPMCQueue() { if(TQueueSize == 0 || TQueueSize == UINT64_MAX) { return; } /** * Ceil the queue size to the nearest power of 2 * @cite https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */ uint_fast64_t NearestPower = TQueueSize; { NearestPower--; NearestPower |= NearestPower >> 1; // 2 bit NearestPower |= NearestPower >> 2; // 4 bit NearestPower |= NearestPower >> 4; // 8 bit NearestPower |= NearestPower >> 8; // 16 bit NearestPower |= NearestPower >> 16; // 32 bit NearestPower |= NearestPower >> 32; // 64 bit NearestPower++; } IndexMask.store(NearestPower - 1); // Set the IndexMask to be one less than the NearestPower
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer IndexMask.store(NearestPower - 1); // Set the IndexMask to be one less than the NearestPower /** Allocate the ring buffer. */ RingBuffer = (FBufferNode*)calloc(NearestPower, sizeof(FBufferNode)); for(uint_fast64_t i = 0; i < NearestPower; ++i) { RingBuffer[i].Data = (FElementType*)malloc(sizeof(FElementType)); } ConsumerCursor.SetFullFence(0); ProducerCursor.SetFullFence(0); } ~TMPMCQueue() { if(RingBuffer == nullptr) return; free(RingBuffer); RingBuffer = nullptr; } /** * Add a new element to the queue. * * @link Dequeue() * @link FSequentialInteger::Get() * @link TSequentialContainer::IncrementAndGetOldValue() * @param NewElement The new element to add to the queue. * * @return An error status, used to check if the add worked. */ EMPMCQueueErrorStatus Enqueue(const FElementType& NewElement) { /** Get the Consumer & Producer cursor values, using an acquire fence */ const int_fast64_t CurrentConsumerCursor = ConsumerCursor.Get(); const int_fast64_t CurrentProducerCursor = ProducerCursor.Get(); /** Return false if the buffer is full */ if((CurrentProducerCursor + 1) == CurrentConsumerCursor) { return EMPMCQueueErrorStatus::BUFFER_FULL; } /** Perform a fetch_add with acquire_release semantics */ const int_fast64_t ClaimedIndex = ProducerCursor.IncrementAndGetOldValue(); // fetch_add /** Calculate the index, avoiding the use of modulo */ const int_fast64_t ClaimedIndexMask = ClaimedIndex & IndexMask.load(std::memory_order_relaxed); /** Update the index on the ring buffer with the new element */ *RingBuffer[ClaimedIndexMask].Data = NewElement; return EMPMCQueueErrorStatus::TRANSACTION_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer EMPMCQueueErrorStatus EnqueueCAS(const FElementType& NewElement) { /** Get the Consumer & Producer cursor values, using an acquire fence */ const int_fast64_t CurrentConsumerCursor = ConsumerCursor.Get(); const int_fast64_t CurrentProducerCursor = ProducerCursor.Get(); /** Return false if the buffer is full */ if((CurrentProducerCursor + 1) == CurrentConsumerCursor) { return EMPMCQueueErrorStatus::BUFFER_FULL; } int_fast64_t ClaimedIndex = CurrentProducerCursor; while(!ProducerCursor.CompareAndSet(ClaimedIndex, ClaimedIndex + 1)) // CAS loop { ClaimedIndex = ProducerCursor.Get(); _mm_pause(); } /** Calculate the index, avoiding the use of modulo */ const int_fast64_t ThisIndexMask = ClaimedIndex & IndexMask.load(std::memory_order_relaxed); /** Update the index on the ring buffer with the new element */ *RingBuffer[ThisIndexMask].Data = NewElement; return EMPMCQueueErrorStatus::TRANSACTION_SUCCESS; } /** * Claim an element from the queue. * * @link Enqueue() * @link FSequentialInteger::Get() * @link TSequentialContainer::IncrementAndGetOldValue() * @param Output A reference to the variable to store the output in. * * @link EMPMCQueueErrorStatus * @return An error status, used to check if the add worked. */ EMPMCQueueErrorStatus Dequeue(FElementType& Output) { /** Get the Consumer & Producer cursor values, using an acquire fence */ const int_fast64_t CurrentConsumerCursor = ConsumerCursor.Get(); const int_fast64_t CurrentProducerCursor = ProducerCursor.Get(); // Check if the buffer is empty if(CurrentConsumerCursor == CurrentProducerCursor) { return EMPMCQueueErrorStatus::BUFFER_EMPTY; }
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer /** Perform a fetch_add with acquire_release semantics */ const int_fast64_t ClaimedIndex = ConsumerCursor.IncrementAndGetOldValue(); // fetch_add /** Calculate the index, avoiding the use of modulo */ const int_fast64_t ClaimedIndexMask = ClaimedIndex & IndexMask.load(std::memory_order_relaxed); /** Store the claimed element from the ring buffer in the Output var */ Output = *RingBuffer[ClaimedIndexMask].Data; return EMPMCQueueErrorStatus::TRANSACTION_SUCCESS; } EMPMCQueueErrorStatus DequeueCAS(FElementType& Output) { const int_fast64_t CurrentConsumerCursor = ConsumerCursor.Get(); const int_fast64_t CurrentProducerCursor = ProducerCursor.Get(); if(CurrentConsumerCursor == CurrentProducerCursor) { return EMPMCQueueErrorStatus::BUFFER_EMPTY; } int_fast64_t ClaimedIndex = CurrentConsumerCursor; while(!ConsumerCursor.CompareAndSet(ClaimedIndex, ClaimedIndex + 1)) // CAS loop { ClaimedIndex = ConsumerCursor.Get(); _mm_pause(); } /** Calculate the index, avoiding the use of modulo */ const int_fast64_t ThisIndexMask = ClaimedIndex & IndexMask.load(std::memory_order_relaxed); /** Update the index on the ring buffer with the new element */ Output = *RingBuffer[ThisIndexMask].Data; return EMPMCQueueErrorStatus::TRANSACTION_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer private: struct FBufferNode { FBufferNode() noexcept : Data(nullptr) { } uint_fast8_t PadToAvoidContention0[PLATFORM_CACHE_LINE_SIZE] = { }; FElementType* Data; uint_fast8_t PadToAvoidContention1[PLATFORM_CACHE_LINE_SIZE] = { }; }; private: uint_fast8_t PadToAvoidContention0[PLATFORM_CACHE_LINE_SIZE] = { }; /** Stores a value that MUST be one less than a power of two e.g 1023. * Used to calculate an index for access to the @link RingBuffer. */ std::atomic<uint_fast64_t> IndexMask; uint_fast8_t PadToAvoidContention1[PLATFORM_CACHE_LINE_SIZE] = { }; /** * This is the pointer to the ring buffer which holds the queue's data. * This is allocated in the default constructor using calloc. */ FBufferNode* RingBuffer; uint_fast8_t PadToAvoidContention2[PLATFORM_CACHE_LINE_SIZE] = { }; /** * The cursor that holds the next available index on the ring buffer for Consumers. */ FCursor ConsumerCursor; uint_fast8_t PadToAvoidContention3[PLATFORM_CACHE_LINE_SIZE] = { }; /** * The cursor that holds the next available index on the ring buffer for Producers. */ FCursor ProducerCursor; uint_fast8_t PadToAvoidContention4[PLATFORM_CACHE_LINE_SIZE] = { }; private: TMPMCQueue(const TMPMCQueue&) = delete; TMPMCQueue& operator=(const TMPMCQueue&) = delete; }; #endif // MPMCQUEUE_H A quick example usage, use TIMES_TO_CYCLE and THREAD_COUNT macros to try different workloads: #include "MPMCQueue.h" /** Define how many times to Produce/Consume an element. */ #define TIMES_TO_CYCLE 10000000 /** Total number of threads. Must be a multiple of two for this example. */ #define THREAD_COUNT 16
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer /** Declare a queue which stores data of type int, and has a size of 500,000. * The size will be ceiled up to the nearest power of two. */ static TMPMCQueue<int, 500000> MyQueue; /** Atomic counter used to track how many threads have completed. */ static FSequentialInteger ThreadsCompleteCount; int main() { /** Create a producer & consumer each iteration. */ for(int_fast64_t i = 0; i < (THREAD_COUNT / 2); ++i) { // Create a Producer std::thread([]() { const int NumberToAddLoads = 100; /** Execute TIMES_TO_CYCLE Enqueue operations. */ for(int_fast64_t j = 0; j < TIMES_TO_CYCLE; ++j) { MyQueue.Enqueue(NumberToAddLoads); // fetch_add version // MyQueue.EnqueueCAS(NumberToAddLoads); // CAS version } /** Increment the counter to indicate that this thread has finished. */ ThreadsCompleteCount.Increment(); }).detach(); // Detach the thread from the main thread. // Create a Consumer std::thread([]() { int NumberToHoldLoads = 0; /** Execute TIMES_TO_CYCLE Dequeue operations. */ for(int_fast64_t j = 0; j < TIMES_TO_CYCLE; ++j) { MyQueue.Dequeue(NumberToHoldLoads); // fetch_add version // MyQueue.DequeueCAS(NumberToHoldLoads); // CAS version } /** Increment the counter to indicate that this thread has finished. */ ThreadsCompleteCount.Increment(); }).detach(); // Detach the thread from the main thread. } /** Spin pause until threads are complete. */ while(ThreadsCompleteCount.GetRelaxed() < THREAD_COUNT) { _mm_pause(); } return 0; }
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer return 0; } fetch_add enqueue assembly: mov rdx, qword ptr [rip+0x3fb9] nop mov rcx, qword ptr [rip+0x4079] nop inc rcx cmp rcx, rdx jz 0x140001317 <Block 4> Block 3: mov rdx, r8 lock xadd qword ptr [rip+0x4064], rdx mov rcx, qword ptr [rip+0x3ec5] and rcx, rdx imul rdx, rcx, 0x88 mov rcx, qword ptr [rip+0x3efc] mov rdx, qword ptr [rdx+rcx*1+0x40] mov dword ptr [rdx], 0x64 And here's the much larger enqueue using a CAS loop: mov rdx, qword ptr [rip+0x3f89] nop mov rcx, qword ptr [rip+0x4049] nop lea rax, ptr [rcx+0x1] cmp rax, rdx jz 0x140001362 <Block 7> Block 3: nop dword ptr [rax], eax Block 4: lea rdx, ptr [rcx+0x1] mov rax, rcx lock cmpxchg qword ptr [rip+0x4028], rdx jz 0x14000133e <Block 6> Block 5: mov rcx, qword ptr [rip+0x401f] nop pause jmp 0x140001320 <Block 4> Block 6: mov rax, qword ptr [rip+0x3e7b] nop and rax, rcx imul rcx, rax, 0x88 mov rax, qword ptr [rip+0x3eb1] mov rcx, qword ptr [rcx+rax*1+0x40] mov dword ptr [rcx], 0x64 I'm on Windows 10 with an i9 9900k. I hope the above information is useful. I'm not used to profiling something like this, so please forgive any naiveity. Any help would be great, cheers.
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer Answer: Your Template Constraints Could be Requirements You could turn your static_assert check into either a requires clause on the template, or a concept. The compiler will still reject any type that does not meet the requirements, but you would be able to prove and overload, and also, you will get a better error message about which constraint a class that doesn’t compile fails to meet. In particular, you could write a version that updates the data in the array directly if that is a wait-free operation, and a version that updates a pointer to data if not. Your Safety Check is not Correct You use two separate operations to retrieve the two cursors, compare their values (which might not both have been updated) to see whether it is safe to proceed, then increment the producer cursor (which might have changed in the interim). Without having done a rigorous analysis, it appears at a glance that one thing that might go wrong with this enqueue or dequeue is that you might not have seen an update to the producer cursor, leading you to spuriously conclude that the buffer is not full when it is, and then increment the producer cursor again after it updates, causing the cursor to wrap around and the container to believe the buffer is empty. What you want is to store the counters in a struct. (See update below.) Even then, I don’t see what prevents an element from being dequeued before it is fully enqueued. TMPMCQueue::dequeue only checks that its retrieved values of the two cursors (at separate times) are not equal. They are not necessarily equal after the producer has incremented the producer cursor. So what prevents a consumer from seeing that the producer has moved the producer cursor past the element it is writing, then moving the consumer cursor to the element and reading it before it is fully written? The Element Type
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer The Element Type I’m not sure why you store pointers, as you are not doing receive-copy-update by atomically updating the pointer. You instead malloc dynamic memory for each, then dereference and copy the source data to this buffer. You also add roughly twice as much padding as you need, but not an exact multiple of the padding size. Your elements should be aligned with alignas. If you need to pad, which you probably don’t, you could add an array of char[cache_size - sizeof(T)%cache_size]. One approach you could take would be to store the elements in a properly-aligned struct containing the data, and make the array of those. If the algorithm is correct, overwriting the data in the array should be more efficient than retrieving and writing through a pointer. If you do it this way, you must ensure the read cursor does not reach your slot until you have updated. Another approach you could take is to move a std::atomic<std::unique_ptr> that you receive from the producers into the buffer, thus updating a large element in a singe wait-free atomic operation without copying the data. These smart pointers would need to allocate from some thread-local pool of memory if the threads are not to contend for the heap. Dequeueing an element then transfers ownership of the pointer to the consumer thread, which can recycle the memory, or free it by letting the smart pointer expire. Alternatively, you could receive a weak pointer to the producer data, which must live long enough to be read. Minor Stylistic Nits Your spin locks could use the STL to call std::this_thread::yield in the idle-lock, rather than use a non-standard function. You don’t need to restrict yourself to powers of two when you do compare-and-swap. If you do, though, there are bit-twiddling tricks involving -x^~x that can get you the bitmask you want. Update on Atomically Updating the Counters
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer Update on Atomically Updating the Counters I’d previously suggested a data structure for the counters that did not work properly on some compilers. If you want to load or update two 64-bit counters with a single atomic operation, you need to declare a struct containing two counters as members, then wrap that in std::atomic. ICC 2021 is the best at optimizing atomic updates to this structure, compiling compare_exchange_weak to a lock cmpxchg16b instruction on x86_64-v4. Clang++ 13.0.0 can also make the same optimization, but only if you align your struct to 16-byte boundaries. G++ 11.2 cannot. The following code: #include <atomic> #include <cassert> #include <stddef.h> #include <thread>
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
c++, thread-safety, concurrency, queue, producer-consumer /* Clang++ 13.0.0 needs alignas(16) to inline atomic updates to cmpxchg16b, on x86_64-v4. * ICC 2021 does not. g++ 11.2 fails to, either way. */ #if __clang__ && __x86_64__ # define COUNTER_ALIGNMENT alignas(16) #else # define COUNTER_ALIGNMENT /**/ #endif struct COUNTER_ALIGNMENT counter_pair { size_t producer_counter; size_t consumer_counter; }; static_assert( std::atomic<counter_pair>::is_always_lock_free, "" ); std::atomic<counter_pair> counters(counter_pair{}); size_t inc_producer_counter() { counter_pair current_counters = counters.load(std::memory_order_acquire); const size_t new_producer_counter = current_counters.producer_counter + 1; if ( counters.compare_exchange_weak(current_counters, { new_producer_counter, current_counters.consumer_counter }, std::memory_order_release ) ) { return new_producer_counter; } else { std::this_thread::yield(); return inc_producer_counter(); } } compiles to the following assembly on clang++ -std=c++20 -O3 -march=x86_64-v4 with version 13.0.0: inc_producer_counter(): # @inc_producer_counter() push rbx .LBB0_2: # =>This Inner Loop Header: Depth=1 xor eax, eax xor edx, edx xor ecx, ecx xor ebx, ebx lock cmpxchg16b xmmword ptr [rip + counters] lea rbx, [rax + 1] mov rcx, rdx lock cmpxchg16b xmmword ptr [rip + counters] je .LBB0_3 call sched_yield jmp .LBB0_2 .LBB0_3: mov rax, rbx pop rbx ret counters: .zero 16 Or, if 32-bit counters are enough, you can change size_t to uint_least32_t.
{ "domain": "codereview.stackexchange", "id": 42660, "lm_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++, thread-safety, concurrency, queue, producer-consumer", "url": null }
performance, beginner, apl Title: Print square numbers from 1 to 9999 (non-tradfn) Question: I'm making a simple program that outputs the squares. I have a question: Is there a way to improve the speed but make the Code readable? Code ∇F f ← 1 :While f ≢ 100 ⎕ ← f × f f ← f + 1 :EndWhile ∇ F Output: a lot of squares Answer: When optimising APL programs, always strive for few computations on large arrays. Here, you want to compute the first 99 squares, so start by generating the 99 first integers: ⍳99 Now square them, either with (⍳99)*2 or 2*⍨⍳99 or by multiplying them with themselves: ×⍨99 Ideally, you'd want to print them as a single printing action (⎕←) too, so format the list into a character array, which puts single spaces between the numbers: ⍕×⍨⍳99 Then substitute linebreaks at all positions that are equal to spaces: (⎕UCS 10)@{' '=⍵}⍕×⍨⍳99 This gives us our complete solution: ⎕←(⎕UCS 10)@{' '=⍵}⍕×⍨⍳99 Try it online!
{ "domain": "codereview.stackexchange", "id": 42661, "lm_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, beginner, apl", "url": null }
php, array Title: a php function to check a 'deep' array value Question: I've just coded a little function to check and get a deep array value. Basically, I need to return the value or null if it's not set or does not exists, or in general not useful for databases records. I need to check things like $myarray[key1][key2][key3] etc.. function get_array_deep_value(array $array, array $fields){ $value = $array; foreach($fields as $field){ $v = $value[$field] ?? null; if(empty($v) && $v != 0){ // note: using != operator because it will convert '0' to 0 (while !== does not) $value = null; break; } $value = $v; } return $value; } Any possible improvements? :) Answer: I recommend avoiding declaring single-use variables. I also recommend throwing an exception when a broken path is passed into your function. Better variable naming will help others to instantly understand your code. Code: (Demo) function get_array_deep_value(array $array, array $levelKeys) { foreach ($levelKeys as $index => $key) { if (!key_exists($key, $array)) { throw new Exception("key $key not found at level index $index"); } $array = $array[$key]; } return $array; } $myArray = [ 'one' => [ 'two' => [ 'three' => [ 4 ] ] ] ]; $pathArrays = [ ['one', 'two', 'three'], ['one', 'two'], ['one'], ['two'] ]; foreach ($pathArrays as $pathArray) { try { var_export(get_array_deep_value($myArray, $pathArray)); } catch (Exception $e) { echo $e->getMessage(); } echo "\n---\n"; }
{ "domain": "codereview.stackexchange", "id": 42662, "lm_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, array", "url": null }
c++, template-meta-programming, c++20 Title: c++20 compile time string utility Question: While upgrading some meta-program running in production for years to the latest (c++20) standard, I rewrote this particular compile time string utility. Even though this new version produces desired output and correctly evaluates at compile time as well as dynamically, it's difficult to get a grasp on a new standard as always. This example is sufficient for my particular use case. And for now I can only spot three inconsistencies I'd like to improve: two of them are marked in the code snippet with TODO, and the third one is tiding it up with concepts (like convertable_to, which is deliberately omitted in the code for simplicity sake) I'm looking for a general case advice on how this code can be improved further. Any other weighted criticism will be much appreciated. UPDATE: New question with all of the suggestions integrated Original code: Live @godbolt #ifndef META_STRING_H_INCLUDED #define META_STRING_H_INCLUDED #include <cstddef> #include <algorithm> #include <functional> #include <tuple> namespace meta { template <std::size_t N> struct string; constexpr auto to_string(const auto& input) { return string(input); } constexpr auto concat(const auto&... input) { return string(to_string(input)...); } template <std::size_t N> struct string { char elems[N]; // string() = delete; string() { elems[N - 1] = '\0'; } // used for CTAD guide for tuples. can't we avoid object construction there? constexpr string(const char (&s)[N]) { std::copy_n(s, N, this->elems); } constexpr string(const string<N> (&s)) { std::copy_n(s.elems, N, this->elems); } constexpr string(const std::array<char, N> (&s)) { std::copy_n(s.data(), N, this->elems); } template <std::size_t... Ni> constexpr void _copy(const string<Ni> (&... input)) { auto pos = elems; ((pos = std::copy_n(input.elems, Ni - 1, pos)), ...); *pos = 0; }
{ "domain": "codereview.stackexchange", "id": 42663, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 constexpr string(const auto&... input) requires (sizeof...(input) > 1) { std::invoke([this](const auto&... s) constexpr { this->_copy(s...); }, to_string(input)...); } template <template <typename...> typename container, typename... T> constexpr string(const container<T...>& input) { std::apply([this](const auto&... s) constexpr { this->_copy(to_string(s)...); }, input); } constexpr auto operator + (const auto& rhs) const { return concat(*this, rhs); } constexpr operator const char* () const { return elems; } }; template<std::size_t N> string(const char (&)[N]) -> string<N>; template<std::size_t N> string(const std::array<char, N>& input) -> string<N>; string(const auto&... input) -> string<((sizeof(to_string(input).elems) - 1) + ... + 1)>; template<template <typename...> typename container, typename... T> string(const container<T...>& input) -> string<((sizeof(to_string(T()).elems) - 1) + ... + 1)>; // TODO: avoid constructing object here inline namespace meta_string_literals { template<string ms> inline constexpr auto operator"" _ms() noexcept { return ms; } } // inline namespace meta_string_literals } // namespace meta #endif // META_STRING_H_INCLUDED ////////////////////////////////////////////////////////////////////// // #include "meta_string.h" #include <iostream> template<meta::string str> struct X { static constexpr auto value = str; operator const char* () { return str.elems; } }; template <auto value> constexpr inline auto constant = value; int main() { using namespace meta::meta_string_literals; X<"a message"> xxx; X<"a massage"> yyy; X<meta::concat(xxx.value, " is not ", yyy.value)> zzz; X<"a message"_ms + " is " + "a massage"> zzz2; std::cout << xxx << std::endl; std::cout << yyy << std::endl; std::cout << zzz << std::endl; std::cout << zzz2 << std::endl;
{ "domain": "codereview.stackexchange", "id": 42663, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 static constexpr auto x = meta::string("1"_ms, "22"); static constexpr auto y = meta::concat("11", "22"); static constexpr auto z = meta::string(std::tuple{"1xx1"_ms, std::array<char, 6>{"2qqq2"}}); std::cout << sizeof(x.elems) << ": " << x << std::endl; std::cout << sizeof(y.elems) << ": " << y << std::endl; std::cout << sizeof(z.elems) << ": " << z << std::endl; static constexpr auto a = "1"_ms; static constexpr auto b = a + "22"_ms; std::cout << b << std::endl; // TODO: Can't it be implicitly forced to constexpr? std::cout << meta::string("this one "_ms, "is not ", "constant evaluated"_ms) << std::endl; std::cout << constant<meta::string("this one "_ms, "is ", "constant evaluated"_ms)> << std::endl; return 0; }
{ "domain": "codereview.stackexchange", "id": 42663, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 return 0; } Answer: This looks more messy than I would prefer, partly because of limitations in C++, partly because you have a constructor that takes a container as an argument. So I don't see another way to do it, just small things that could be improved here and there. Unnecessary use of this-> It is almost never necessary to write this-> in C++. I would remove its use everywhere. to_string() is not necessary I see you have a free function to_string() to ensure you can cast something to a string with a different N than is used in the templated code you are in, and also to "escape" the deduction guides. This is not a bad approach, but it might not be necessary to use it. Inside class string you can avoid calling to_string(input) by writing meta::string(input). In the deduction guides it is harder to work around this, you can't just write meta::string(input).elems. But see below for a possible solution that also gets rid of the default constructor. I would be OK with leaving it as you wrote it though, but if it is only intended to be used as a helper function for struct string, consider wrapping it inside a namespace detail to signal it should not be used by external code directly. Unnecessary use of std::invoke() You don't need std::invoke() at all, the constructor that uses it can just be rewritten as: constexpr string(const auto&... input) requires (sizeof...(input) > 1) { _copy(to_string(input)...); }
{ "domain": "codereview.stackexchange", "id": 42663, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 Make _copy() private The member function _copy() is just a helper function used by the constructors, so it should be made private. I would also remove the leading underscore from the name of this function, as some uses of leading and double underscores in identifiers are reserved, and the simplest way to avoid any issues is to avoid all leading and double underscores. Consider adding size() and other const member functions from std::string I noticed the sizeof(to_string(input).elems) in the deduction guides, and I thought that looked a bit awkward; if there was a size() member function it would be nicer to be able to write to_string(input).size(). Unfortunately, even with a static constexpr size() function, this is not considered a constant expression, so that won't compile. But it will make some of your example usage cleaner: meta::string x(...); std::cout << x.size() << ": " << x << '\n'; You might consider other const member functions from std::string as well, like empty(), data(), operator[] and so on, to make it a better drop-in replacement for const std::strings. Deleting the default constructor To be able to delete the default constructor, you need to avoid default constructing meta::strings. That means you can't use to_string(T()) if T is a meta::string. There is a very simple solution here, just use sizeof(T): template<template <typename...> typename container, typename... T> string(const container<T...>& input) -> string<((sizeof(T) - 1) + ... + 1)>;
{ "domain": "codereview.stackexchange", "id": 42663, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 The drawback, as user17732522 mentioned, is that it doesn't seem to work when constructing a meta::string with nested std::tuples. Forcing constant evaluation of rvalue I don't think this is possible. At the same time I don't understand why the compiler wouldn't be able to optimize this at compile time, even without using constexpr. Avoid using std::endl Prefer using \n instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and hurts performance.
{ "domain": "codereview.stackexchange", "id": 42663, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c, console, c99 Title: C99 - An alphanumeric random char generator Question: I have built a very small program that is a command line utility for generating alphanumeric characters of a certain length (up to a max. length) called randchars. $ randchars 12 Prints twelve pseudo-random upper-/lower-case alphanumeric characters to stdout. The command line options -l and -u can be given, if somebody wishes to have only lower- or uppercase alphanumeric characters. Here is the code, this is my first project while reading K&R. I know that in C99 I do not need to declare the variables on top of the functions, but I somehow grew to like it this way^^ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define MAX_CHARS 32 int is_lowercase(char c); int is_uppercase(char c); int is_digit(char c); enum OPTS { MIXED, // default UPPERCASE, // -u LOWERCASE, // -l }; int main(int argc, char *argv[]) { unsigned i, size, char_ok; srand(time(0)); char chars[MAX_CHARS + 1]; char rchar, c; enum OPTS mode; // get options if (argc < 2 || 3 < argc) goto error_argc; // size is last arg size = atoi(argv[argc - 1]); if (size == 0) goto usage; if (size > MAX_CHARS) goto error_size; mode = MIXED; if (argc == 3) { if (strcmp(argv[1], "-l") == 0) mode = LOWERCASE; else if (strcmp(argv[1], "-u") == 0) mode = UPPERCASE; else goto error_opt; } // do actual computation of random chars for (i = 0; i < size; i++) { do { c = rand() % ('z' + 1); chars[i] = c;
{ "domain": "codereview.stackexchange", "id": 42664, "lm_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, c99", "url": null }
c, console, c99 switch(mode) { case MIXED: char_ok = is_digit(c) || is_uppercase(c) || is_lowercase(c); break; case LOWERCASE: char_ok = is_digit(c) || is_lowercase(c); break; case UPPERCASE: char_ok = is_digit(c) || is_uppercase(c); break; } } while (!char_ok); // repeat if char is not ok } chars[size] = '\0'; printf("%s\n", chars); return 0; error_size: printf("error: maximum sequence length: %u\n", MAX_CHARS); goto usage; error_opt: printf("error: invalid option: %s\n", argv[1]); goto usage; error_argc: printf("error: invalid amount of arguments: %u\n", argc); goto usage; usage: printf("usage:\n\t%s [ -u | -l ] <n>\n", argv[0]); return 1; } int is_lowercase(char c) { if ('a' <= c && c <='z') return 1; else return 0; } int is_uppercase(char c) { if ('A' <= c && c <='Z') return 1; else return 0; } int is_digit(char c) { if ('0' <= c && c <='9') return 1; else return 0; } Answer: First of all, this is well written and organized code. Except for one part. A dreadful part. A part, that was and is the cause for many issues, even today. Don't use goto Using goto brings multiple problems. While I won't repeat the statements from the linked question, I can certainly tell that it slowed me down: to understand your code, I had to repeatedly jump between lines 32+ and lines 72+. Compare this // size is last arg size = atoi(argv[argc - 1]); if (size == 0) goto usage; if (size > MAX_CHARS) goto error_size; to this: // size is last arg size = atoi(argv[argc - 1]); if (size == 0) { usage(); return 1; } if (size > MAX_CHARS) { fprintf(stderr, "error: maximum sequence length: %u\n", MAX_CHARS); usage(); return 1; }
{ "domain": "codereview.stackexchange", "id": 42664, "lm_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, c99", "url": null }
c, console, c99 usage(); return 1; } The latter one does not force me to read other parts of the code, I immediately know what will happen, and I also know all effects around the used variables. goto does not yield any benefit here. Don't use rand() % NUM for random numbers That's covered by the C FAQ. Instead, use something along c = '0' + rand() / (RAND_MAX / ('z' - '0' + 1) + 1) This has the nice effect that all except 13 of the possible cs are already alphanumeric. Use stderr for error messages For errors, you want to use stderr instead of stdout. And that's all. As I said, the code itself is well-written. I would prefer late declared variables instead of the K&R-style early one, but that's personal preference. For argument parsing, you might want to have a look at getopt.
{ "domain": "codereview.stackexchange", "id": 42664, "lm_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, c99", "url": null }
html, css, html5 Title: Are there any redundant divs in my first proper webpage? Or any way to group classes in my CSS file Question: This is my first full formatted webpage done while doing the odin project. Is there any redundant divs? Can I reduce my css file by grouping some classes? And how to give styles to a button under a specific div without using class?
{ "domain": "codereview.stackexchange", "id": 42665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, css, html5", "url": null }
html, css, html5 html{ font-family: 'Roboto',sans-serif; } body{ margin:0; display: flex; flex-direction: column; justify-content: space-between; } .header{ background-color: #1f2937; padding-top:10px; display: flex; align-items: center; justify-content: space-between; } .logo{ color:#f9faf8; font-size: 24px; padding-left: 35px; font-weight: bolder; } a{ color:#e5e7eb; font-size: 18px; text-decoration: none; padding:7px; } .hero{ background-color: #1f2937; display:flex; padding:70px 90px 80px 90px; gap:20px; } .hero-image{ display: flex; justify-content: center; align-items: center; background-color: gray; height:30vh; width: 45vw; color: #e5e7eb; } h2{ font-size: 48px; font-weight: bold; color:#f9faf8; margin:0; } .random{ display: flex; flex-direction: column; align-items: center; padding:20px 20px 100px 20px; } .info{ font-size: 32px; color: #1f2937; font-weight: bolder; padding-bottom: 30px; } .random-image{ border-width: 2px; border-radius: 15px; border-color: #3882f6; height:105px; width:105px; border-style: solid; } .quote{ background-color:#e5e7eb; display:flex; flex-direction: column; justify-content: space-around; padding: 60px 250px 60px 250px; } .quote-text{ font-size: 32px; font-style: italic; color: #1f2937; } p{ color:#e5e7eb; font-size: 18px; margin:0; } .action{ background-color: #3882f6; margin: 80px 110px 80px 110px; padding: 50px 90px 50px 90px; color: #f9faf8; display: flex; gap:300px; border-radius: 10px; } button{ background-color:#3882f6; color:#f9faf8; border-radius: 25px; padding:7px 25px 7px 25px; }
{ "domain": "codereview.stackexchange", "id": 42665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, css, html5", "url": null }
html, css, html5 .footer{ background-color: #1f2937; color:#e5e7eb; font-size: 18px; display: flex; justify-content: center; padding:20px 0; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Odin-Webpage</title> </head> <body> <div class='header'> <div class='logo'> <u>ONE PIECE</u> </div> <div> <a href="">Manga</a> <a href="">Anime</a> <a style="padding-right:35px" href="">About</a> </div> </div> <div class='hero'> <div style="width:80vh"> <h2>One Piece is really awesome </h2> <p>One Piece written by Eichiro Oda is the most popular manga in the world, surpassing the likes of Batman and other multi-author comics. </p> <button style="border-width: 0;margin-top: 4px;">Sign up</button> </div> <div class='hero-image'>
{ "domain": "codereview.stackexchange", "id": 42665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, css, html5", "url": null }
html, css, html5 <img src='one-piece.jpg' style="height:45vh;width: 45vw;"> </div> </div> <div class='random'> <div class='info'>Some random information.</div> <div style="display: flex;justify-content: space-around;text-align: center;"> <div style="padding-left: 100px;"> <img class='random-image' src='luffy.png'> <div>The protaganist Monkey D.Luffy aka Rubber boy</div> </div> <div> <img class='random-image' src='wings.png'> <div>The wings of the future Pirate King</div> </div> <div> <img class='random-image' src='whitebeard.png'> <div>The strongest man in the world</div> </div> <div style="padding-right:100px;"> <img class='random-image' src='usopp.png'> <div>The only God in one piece universe</div> </div> </div> </div> <div class='quote'> <div class='quote-text'>Pirates are evil? The Marines are righteous?… Justice will prevail, you say? But of course it will! Whoever wins this war becomes justice!</div> <div style="text-align:right;font-size: 25px;"><b>-Donquixote Doflamingo</b></div> </div> <div class='action'> <div> <b>Call to action! It's time!</b><br> Support one piece by clicking that button right over there! </div> <div> <button style="border-color: white;border-style: solid;">Sign up</button> </div> </div> <div class='footer'> Copyright Gagan Karanth 2021 </div> </body> </html> Is there any standard order in arranging the css classes among professionals? Answer: And how to give styles to a button under a specific div without using class? You can do this: .action button { /* styles */ }
{ "domain": "codereview.stackexchange", "id": 42665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, css, html5", "url": null }
html, css, html5 You can do this: .action button { /* styles */ } The selector selects all buttons that’re decendants of elements that have the class action. Your HTML contains many inline styles (style="…"); it’s generally best to avoid doing that. for instance: <div class='info'>Some random information.</div> <div style="display: flex;justify-content: space-around;text-align: center;"> … </div> Consider using a class for the 4-column section instead of inline styles. <div class='header'> … </div> … <div class='footer'> Copyright Gagan Karanth 2021 </div> These divs can be replaced with HTML5 <header> and <footer> tags. <div> <a href="">Manga</a> <a href="">Anime</a> <a style="padding-right:35px" href="">About</a> </div> … <div style="display: flex;justify-content: space-around;text-align: center;"> <div style="padding-left: 100px;"> <img class='random-image' src='luffy.png'> <div>The protaganist Monkey D.Luffy aka Rubber boy</div> </div> … <div style="padding-right:100px;"> <img class='random-image' src='usopp.png'> <div>The only God in one piece universe</div> </div> </div> padding-left and padding-right should usually be applied to parent elements rather than to the first children and to the last children. I would change the navigation links’ (Manga, Anime, and About)’s container element from a div to a nav, then delete the inline style padding-right:35px from the "About" link and declare it in nav’s CSS. <nav> <a href="">Manga</a> <a href="">Anime</a> <a href="">About</a> </nav> nav { padding-right: 35px; }
{ "domain": "codereview.stackexchange", "id": 42665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, css, html5", "url": null }
html, css, html5 nav { padding-right: 35px; } Likewise to the 4-columns part (adding a class and moving the inline styles to the CSS per a previous suggestion): <div class='images'> <div> <img class='random-image' src='luffy.png'> <div>The protaganist Monkey D.Luffy aka Rubber boy</div> </div> <div> <img class='random-image' src='wings.png'> <div>The wings of the future Pirate King</div> </div> <div> <img class='random-image' src='whitebeard.png'> <div>The strongest man in the world</div> </div> <div> <img class='random-image' src='usopp.png'> <div>The only God in one piece universe</div> </div> </div> .images { display: flex; justify-content: space-around; text-align: center; padding-left: 100px; padding-right: 100px; } Some colors in the CSS are repeated throughout the file. CSS variables are useful for keeping all colors’ definitions in 1 place. :root { --dark-bg: #1f2937; } … .header, .hero { background-color: var(--dark-bg); } .info, .quote-text { color: var(--dark-bg); } But old browsers can’t do CSS custom properties, or variables.
{ "domain": "codereview.stackexchange", "id": 42665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, css, html5", "url": null }
javascript, api, vue.js Title: Vue 3 audio player Question: I have been working on an audio player with Vue 3 and the Napster API.
{ "domain": "codereview.stackexchange", "id": 42666, "lm_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, api, vue.js", "url": null }
javascript, api, vue.js Question: I have been working on an audio player with Vue 3 and the Napster API. const musicApp = { data() { return { player: new Audio(), trackCount: 0, tracks: [], muted: false, autoAdvance: true, isPlaying: false, currentTime: 0 }; }, methods: { async getTracks() { try { const response = await axios .get( "https://api.napster.com/v2.1/tracks/top?apikey=ZTk2YjY4MjMtMDAzYy00MTg4LWE2MjYtZDIzNjJmMmM0YTdm" ) .catch((error) => { console.log(error); }); this.tracks = response; this.tracks = response.data.tracks; } catch (error) { console.log(error); } }, nextTrack() { if (this.trackCount < this.tracks.length - 1) { this.trackCount++; this.setPlayerSource(); this.playPause(); } }, prevTrack() { if (this.trackCount >= 1) { this.trackCount--; this.setPlayerSource(); this.playPause(); } }, setPlayerSource() { this.player.src = this.tracks[this.trackCount].previewURL; }, playPause() { if (this.player.paused) { this.isPlaying = true; this.player.play(); } else { this.isPlaying = false; this.player.pause(); } }, skipProgress(e) { let barWidth = e.target.clientWidth; let rect = e.target.getBoundingClientRect(); let clickPositionX = e.pageX - rect.left; this.player.currentTime = (clickPositionX / barWidth) * this.player.duration; }, toggleMute() { this.player.muted = !this.player.muted; this.muted = this.player.muted; } }, async created() { await this.getTracks(); this.setPlayerSource(); this.$refs.progressBar.addEventListener("click", (e) => { this.skipProgress(e); }); this.player.addEventListener("ended", () => { this.isPlaying = false;
{ "domain": "codereview.stackexchange", "id": 42666, "lm_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, api, vue.js", "url": null }
javascript, api, vue.js if (this.autoAdvance) { this.nextTrack(); } }); this.player.addEventListener("timeupdate", () => { this.currentTime = this.player.currentTime; }); }, computed: { trackProgress() { return (this.currentTime / this.player.duration) * 100; } } }; Vue.createApp(musicApp).mount("#audioPlayer"); html, body { margin: 0; padding: 0; font-size: 16px; } body * { box-sizing: border-box; font-family: "Montserrat", sans-serif; } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .player-container { display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: #2998ff; background-image: linear-gradient(62deg, #2998ff 0%, #5966eb 100%); } #audioPlayer { width: 300px; height: 300px; border-radius: 8px; position: relative; overflow: hidden; background-color: #00ca81; background-image: linear-gradient(160deg, #00ca81 0%, #ffffff 100%); box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); display: flex; flex-direction: column; align-items: center; } .volume { color: #ff0057; opacity: 0.9; display: inline-block; width: 20px; font-size: 20px; position: absolute; top: 5px; right: 6px; cursor: pointer; } .album { width: 100%; flex: 1; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; } .album-items { padding: 0 10px; text-align: center; }
{ "domain": "codereview.stackexchange", "id": 42666, "lm_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, api, vue.js", "url": null }
javascript, api, vue.js .album-items { padding: 0 10px; text-align: center; } .cover { width: 150px; height: 150px; margin: auto; box-shadow: 0px 5px 12px 0px rgba(0, 0, 0, 0.17); border-radius: 50%; background: url("https://w7.pngwing.com/pngs/710/955/png-transparent-vinyl-record-artwork-phonograph-record-compact-disc-lp-record-disc-jockey-symbol-miscellaneous-classical-music-sound.png") center top transparent; background-size: cover; } .cover.spinning { webkit-animation: spin 6s linear infinite; /* Safari */ animation: spin 6s linear infinite; } .info { width: 100%; padding-top: 5px; color: #000; opacity: 0.85; } .info h1 { font-size: 11px; margin: 5px 0 0 0; } .info h2 { font-size: 10px; margin: 3px 0 0 0; } .to-bottom { width: 100%; margin-top: auto; display: flex; flex-wrap: wrap; justify-content: center; } .progress-bar { background-color: #ff0057; opacity: 0.9; height: 3px; width: 100%; cursor: pointer; } .progress-bar span { display: block; height: 3px; width: 0; background: rgba(255, 255, 255, 0.4); } .controls { width: 150px; display: flex; height: 60px; justify-content: space-between; align-items: center; } .controls .navigate { display: flex; box-shadow: 1px 2px 7px 2px rgba(0, 0, 0, 0.09); width: 33px; height: 33px; line-height: 1; color: #ff0057; cursor: pointer; background: #fff; opacity: 0.9; border-radius: 50%; text-align: center; justify-content: center; align-items: center; } .controls .navigate.disabled { pointer-events: none; color: #606060; background-color: #f7f7f7; } .controls .navigate.navigate-play { width: 38px; height: 38px; }
{ "domain": "codereview.stackexchange", "id": 42666, "lm_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, api, vue.js", "url": null }