body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am a Rust newbie and I am not familiar with all the iterator options. This is what I have so far. How can I make this better or at least avoid collecting twice into a Vec?</p> <pre><code>let num: u16 = 0b0010001000100010; // input number let bin = format!("{:016b}", num); let parsed = bin .split("") .filter_map(|s| s.parse().ok()) .collect::&lt;Vec&lt;u8&gt;&gt;(); let mat = parsed.chunks(4).collect::&lt;Vec&lt;_&gt;&gt;(); println!("{:?}", mat); // outputs [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]] </code></pre>
[]
[ { "body": "<p>One thing I'm going to do first is create an enum with only two values. This represents a binary value and is more memory-efficient than passing around a bunch of <code>u8</code>s. This way 16 <code>Bit</code>s can be represented as 16 actual bits in memory (though this isn't guaranteed).</p>\n\n<...
{ "AcceptedAnswerId": "206274", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T02:28:50.223", "Id": "206236", "Score": "1", "Tags": [ "strings", "matrix", "iterator", "rust", "vectors" ], "Title": "Convert a type u16 number to a matrix (Vec<Vec<u8>> or array) of 4 x 4" }
206236
<p>I just completed my pong game. I'm trying follow the <a href="https://www.edx.org/course/cs50s-introduction-to-game-development" rel="nofollow noreferrer">CS50 Introduction to Game Design</a> course. The course uses LUA and LÖVE, but I'm trying to just transfer the concepts to C++ and SDL2. The game is pretty straight forward. There are 2 paddles on each side, one controlled by the player, the other by an AI. there is a ball in the middle that will travel towards a player and bounce off walls and paddles. If the ball passes a paddle, the opposing player gets a point. First to 10 wins.</p> <p>I know I could have created an input, update, and render loop for each state, but I decided against it because there isn't too much that differs between states. </p> <p>I did, however, try to split the <code>Paddle</code>, <code>Ball</code>, and <code>Game</code> struct into their own files but I had a lot of trouble getting it to work. </p> <p>For instance, my <code>Texture</code> and <code>SDLInit</code> files work fine right now, but when I tried to move the <code>AssetManager</code> struct to it's own header file, the <code>Texture</code> class would suddenly have an issue with undefined variables or issues with the std namespace. I couldn't quite figure it out.</p> <p>And if I tried keeping the <code>AssetManager</code> in <code>main</code> but move <code>Paddle</code> to it's own file, then there would be an issue with the <code>Paddle::render</code> not knowing what the <code>AssetManager</code> is. I tried declaring <code>struct AssetManager;</code> at the top of <code>Paddle.h</code> but it didnt seem to help.</p> <p>Questions about the actual game code:</p> <ol> <li>Every time I the ball hits a paddle, I increase it's x velocity by a small percentage. However, I ran into the issue of tunneling when the ball got too fast. I looked it up and learned about continuous collision detection to help fix the problem. A lot of examples of seemed very complicated but I thought I understood the gist of it. My solution was to draw lines from opposite corners of the current ball position to the future ball position and see if either of those lines intersected a paddle. The solution seems to work fine, but is there a more efficient or better way I could have avoided the tunneling problem?</li> <li><p>Is there a better way of doing this:</p> <pre><code>if (game.ball_.yPos_ &lt;= 0 || game.ball_.yPos_ + game.ball_.height_ &gt;= VIRTUAL_HEIGHT) { //move ball based on which wall was hit if (game.ball_.yPos_ &lt;= 0) { game.ball_.yPos_ = 0; } else ... } </code></pre> <p>Where I want to know if either wall gets hit because I need to play sound or change the ball direction, but I still need to know which wall so that I can move the balls position properly.</p></li> </ol> <p>Besides this, any general input or feedback would also be greatly appreciated.</p> <p><strong>main.h</strong></p> <pre><code>#include &lt;string&gt; #include &lt;random&gt; #include &lt;SDL.h&gt; #include &lt;SDL_image.h&gt; #include &lt;SDL_ttf.h&gt; #include &lt;SDL_mixer.h&gt; #include "SDLInit.h" #include "Texture.h" constexpr int SCREEN_WIDTH = 1024; constexpr int SCREEN_HEIGHT = 576; constexpr int VIRTUAL_WIDTH = 432; constexpr int VIRTUAL_HEIGHT = 243; constexpr int PADDLE_WIDTH = 5; constexpr int PADDLE_HEIGHT = 20; constexpr int PADDLE_SPEED = 200; constexpr int BALL_SIZE = 4; std::mt19937&amp; random_engine() { static std::mt19937 mersenne(std::random_device{}()); return mersenne; } int getRandomNumber(int x, int y) { std::uniform_int_distribution&lt;&gt; dist{ x,y }; return dist(random_engine()); } struct AssetManager { std::unique_ptr&lt;SDL_Window, sdl_deleter&gt; window_{ SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN) }; std::unique_ptr&lt;SDL_Renderer, sdl_deleter&gt; renderer_{ SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_PRESENTVSYNC) }; std::unique_ptr&lt;TTF_Font, sdl_deleter&gt; smallFont_{ TTF_OpenFont("resources/font.ttf", 8) }; std::unique_ptr&lt;TTF_Font, sdl_deleter&gt; largeFont_{ TTF_OpenFont("resources/font.ttf", 16) }; std::unique_ptr&lt;TTF_Font, sdl_deleter&gt; scoreFont_{ TTF_OpenFont("resources/font.ttf", 32) }; std::unique_ptr&lt;Mix_Chunk, sdl_deleter&gt; paddleHitSound_{ Mix_LoadWAV("resources/paddlehit.wav") }; std::unique_ptr&lt;Mix_Chunk, sdl_deleter&gt; wallHitSound_{ Mix_LoadWAV("resources/wallhit.wav") }; std::unique_ptr&lt;Mix_Chunk, sdl_deleter&gt; scoreSound_{ Mix_LoadWAV("resources/score.wav") }; SDL_Color whiteFont_ = { 0xff, 0xff, 0xff }; int fontWrapWidth_ = SCREEN_WIDTH; LTexture welcomeText_ = { from_text, smallFont_.get(), renderer_.get(), "Welcome to Pong!", whiteFont_, fontWrapWidth_ }; LTexture startGameText_ = { from_text, smallFont_.get(), renderer_.get(), "Press Enter to begin.", whiteFont_, fontWrapWidth_ }; LTexture serveText_ = { from_text, smallFont_.get(), renderer_.get(), "Press Enter to serve.", whiteFont_, fontWrapWidth_ }; LTexture restartText_ = { from_text, smallFont_.get(), renderer_.get(), "Press Enter to restart.", whiteFont_, fontWrapWidth_ }; }; struct Paddle { Paddle(int xPos, float yPos, int width, float height) : xPos_(xPos), yPos_(yPos), width_(width), height_(height) {} void update(float deltaTime) { if (yVel_ &lt; 0) { yPos_ = std::max(0.0f, yPos_ + yVel_ * deltaTime); } else { yPos_ = std::min(VIRTUAL_HEIGHT - height_, yPos_ + yVel_ * deltaTime); } } void render(AssetManager &amp;assets) { SDL_SetRenderDrawColor(assets.renderer_.get(), 255, 255, 255, 255); SDL_Rect rect_{ xPos_, static_cast&lt;int&gt;(yPos_), width_, static_cast&lt;int&gt;(height_) }; SDL_RenderFillRect(assets.renderer_.get(), &amp;rect_); } int xPos_; float yPos_; int width_; float height_ = 0.0f; float yVel_ = 0.0f; }; struct Ball { Ball(float xPos, float yPos, int width, int height) : xPos_(xPos), yPos_(yPos), width_(width), height_(height) {} float xPos_; float yPos_; int width_; int height_; float xVel_ = 0.0f; float yVel_ = 0.0f; bool hasCollision(Paddle paddle, float deltaTime) { SDL_Rect paddleRect{ paddle.xPos_, static_cast&lt;int&gt;(paddle.yPos_), paddle.width_, static_cast&lt;int&gt;(paddle.height_) }; //if ball is going to upper left or bottom right, //draw lines using top right and bottom left corners //from current position to future position if ((xVel_ &lt; 0 &amp;&amp; yVel_ &lt;= 0) || (xVel_ &gt; 0 &amp;&amp; yVel_ &gt;= 0)) { //get x and y pos or current and future frame int currUpRightX = static_cast&lt;int&gt;(xPos_ + width_); int currUpRightY = static_cast&lt;int&gt;(yPos_); int futureUpRightX = static_cast&lt;int&gt;(xPos_ + width_ + (xVel_ * deltaTime)); int futureUpRightY = static_cast&lt;int&gt;(yPos_ + (yVel_ * deltaTime)); int currBotLeftX = static_cast&lt;int&gt;(xPos_); int currBotLeftY = static_cast&lt;int&gt;(yPos_ + height_); int futureBotLeftX = static_cast&lt;int&gt;(xPos_ + (xVel_ * deltaTime)); int futureBotLeftY = static_cast&lt;int&gt;(yPos_ + height_ + (yVel_ * deltaTime)); if (SDL_IntersectRectAndLine(&amp;paddleRect, &amp;currUpRightX, &amp;currUpRightY, &amp;futureUpRightX, &amp;futureUpRightY) || SDL_IntersectRectAndLine(&amp;paddleRect, &amp;currBotLeftX, &amp;currBotLeftY, &amp;futureBotLeftX, &amp;futureBotLeftY)) { return true; } } //if ball is going to upper right or bottom left, //draw lines using top left and bottom right corners //from current position to future position if ((xVel_ &lt; 0 &amp;&amp; yVel_ &gt; 0) || (xVel_ &gt; 0 &amp;&amp; yVel_ &lt; 0)) { //get x and y pos or current and future frame int currUpLeftX = static_cast&lt;int&gt;(xPos_); int currUpLeftY = static_cast&lt;int&gt;(yPos_); int futureUpLeftX = static_cast&lt;int&gt;(xPos_ + (xVel_ * deltaTime)); int futureUpLeftY = static_cast&lt;int&gt;(yPos_ + (xVel_ * deltaTime)); int currBotRightX = static_cast&lt;int&gt;(xPos_ + width_); int currBotRightY = static_cast&lt;int&gt;(yPos_ + height_); int futureBotRightX = static_cast&lt;int&gt;(xPos_ + width_ + (xVel_ * deltaTime)); int futureBotRightY = static_cast&lt;int&gt;(yPos_ + height_ + (yVel_ * deltaTime)); if (SDL_IntersectRectAndLine(&amp;paddleRect, &amp;currUpLeftX, &amp;currUpLeftY, &amp;futureUpLeftX, &amp;futureUpLeftY) || SDL_IntersectRectAndLine(&amp;paddleRect, &amp;currBotRightX, &amp;currBotRightY, &amp;futureBotRightX, &amp;futureBotRightY)) { return true; } } return false; } void render(AssetManager &amp;assets) { SDL_SetRenderDrawColor(assets.renderer_.get(), 255, 255, 255, 255); SDL_Rect rect_{ static_cast&lt;int&gt;(xPos_), static_cast&lt;int&gt;(yPos_), width_, height_ }; SDL_RenderFillRect(assets.renderer_.get(), &amp;rect_); } void reset() { xPos_ = VIRTUAL_WIDTH / 2 - BALL_SIZE / 2; yPos_ = VIRTUAL_HEIGHT / 2 - BALL_SIZE / 2; xVel_ = 0; yVel_ = 0; } void update(float deltaTime) { xPos_ += xVel_ * deltaTime; yPos_ += yVel_ * deltaTime; } }; struct Game { enum GameState { EXIT, START, SERVE, PLAY, DONE }; Paddle player1_{ 10, VIRTUAL_HEIGHT / 2 - PADDLE_HEIGHT / 2, PADDLE_WIDTH, PADDLE_HEIGHT}; Paddle player2_{ VIRTUAL_WIDTH - 10 - PADDLE_WIDTH, VIRTUAL_HEIGHT / 2 - PADDLE_HEIGHT / 2, PADDLE_WIDTH , PADDLE_HEIGHT}; Ball ball_{ VIRTUAL_WIDTH / 2 - BALL_SIZE / 2 , VIRTUAL_HEIGHT / 2 - BALL_SIZE / 2, BALL_SIZE, BALL_SIZE }; int player1Score_ = 0; int player2Score_ = 0; int servingPlayer_ = getRandomNumber(1,2); int winningPlayer_ = 1; float thenTime_ = 0.0f; float nowTime_ = 0.0f; float deltaTime_ = 0.0f; GameState state_ = START; }; void AI_Play(Game&amp; game, Paddle&amp; paddle) { if (game.ball_.xPos_ &gt; VIRTUAL_WIDTH / 5) { if (game.ball_.yPos_ + game.ball_.height_ &gt; paddle.yPos_ + paddle.height_) { paddle.yVel_ = PADDLE_SPEED - 50; } else if (game.ball_.yPos_ &lt; paddle.yPos_) { paddle.yVel_ = -(PADDLE_SPEED - 50); } else { paddle.yVel_ = 0; } } } bool render(Game&amp; game, AssetManager&amp; assets) { SDL_SetRenderDrawColor(assets.renderer_.get(), 40, 45, 52, 0xff); SDL_RenderClear(assets.renderer_.get()); if (game.state_ == Game::START) { assets.welcomeText_.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - assets.welcomeText_.width_ / 2, 10); assets.startGameText_.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - assets.startGameText_.width_ / 2, 20); } if (game.state_ == Game::SERVE) { LTexture playersServeText_ = { from_text, assets.smallFont_.get(), assets.renderer_.get(), "Player " + std::to_string(game.servingPlayer_) + "'s turn to serve.", assets.whiteFont_, assets.fontWrapWidth_ }; playersServeText_.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - playersServeText_.width_ / 2, 10); assets.serveText_.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - assets.serveText_.width_ / 2, 20); } if (game.state_ == Game::DONE) { LTexture playerWonText_ = { from_text, assets.smallFont_.get(), assets.renderer_.get(), "PLAYER " + std::to_string(game.winningPlayer_) + "WINS!", assets.whiteFont_, assets.fontWrapWidth_ }; playerWonText_.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - playerWonText_.width_ / 2, 10); assets.restartText_.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - assets.restartText_.width_ / 2, 20); } SDL_SetRenderDrawColor(assets.renderer_.get(), 255, 255, 255, 225); LTexture player1Score = { from_text, assets.scoreFont_.get(), assets.renderer_.get(), std::to_string(game.player1Score_), assets.whiteFont_, assets.fontWrapWidth_ }; LTexture player2Score = { from_text, assets.scoreFont_.get(), assets.renderer_.get(), std::to_string(game.player2Score_), assets.whiteFont_, assets.fontWrapWidth_ }; player1Score.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 - 50, VIRTUAL_HEIGHT / 8); player2Score.render(assets.renderer_.get(), VIRTUAL_WIDTH / 2 + 30, VIRTUAL_HEIGHT / 8); game.player1_.render(assets); game.player2_.render(assets); game.ball_.render(assets); SDL_RenderPresent(assets.renderer_.get()); return true; } bool update(Game&amp; game, AssetManager&amp; assets) { if (game.state_ == Game::PLAY) { if (game.ball_.hasCollision(game.player1_, game.deltaTime_) || game.ball_.hasCollision(game.player2_, game.deltaTime_)) { //if ball going was going to the left //move in front of left paddle and vice versa if (game.ball_.xVel_ &lt; 0) { game.ball_.xPos_ = static_cast&lt;float&gt;(game.player1_.xPos_ + 5); } else { game.ball_.xPos_ = static_cast&lt;float&gt;(game.player2_.xPos_ - 4); } if (game.ball_.yVel_ &lt; 0) { game.ball_.yVel_ = static_cast&lt;float&gt;(getRandomNumber(-150, 0)); } else { game.ball_.yVel_ = static_cast&lt;float&gt;(getRandomNumber(0, 150)); } //change direction and speed up ball game.ball_.xVel_ *= -1.05f; Mix_PlayChannel(-1, assets.paddleHitSound_.get(), 0); } //if hits walls if (game.ball_.yPos_ &lt;= 0 || game.ball_.yPos_ + game.ball_.height_ &gt;= VIRTUAL_HEIGHT) { //move ball based on which wall was hit if (game.ball_.yPos_ &lt;= 0) { game.ball_.yPos_ = 0; } else { game.ball_.yPos_ = VIRTUAL_HEIGHT - 4; } game.ball_.yVel_ *= -1; Mix_PlayChannel(-1, assets.wallHitSound_.get(), 0); } //if score if (game.ball_.xPos_ &lt;= 0 || game.ball_.xPos_ &gt;= VIRTUAL_WIDTH - 4) { //if player2 scored if (game.ball_.xPos_ &lt;= 0) { game.servingPlayer_ = 1; game.player2Score_++; } else { game.servingPlayer_ = 2; game.player1Score_++; } game.ball_.reset(); game.state_ = Game::SERVE; Mix_PlayChannel(-1, assets.scoreSound_.get(), 0); } if (game.player1Score_ == 10) { game.winningPlayer_ = 1; game.state_ = Game::DONE; } if (game.player2Score_ == 10) { game.winningPlayer_ = 2; game.state_ = Game::DONE; } } AI_Play(game, game.player2_); game.ball_.update(game.deltaTime_); game.player1_.update(game.deltaTime_); game.player2_.update(game.deltaTime_); return true; } bool input(Game&amp; game) { SDL_Event e; game.nowTime_ = static_cast&lt;float&gt;(SDL_GetTicks()); game.deltaTime_ = (game.nowTime_ - game.thenTime_) / 1000; game.thenTime_ = game.nowTime_; while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { game.state_ = Game::EXIT; return false; } else if (e.type == SDL_KEYDOWN &amp;&amp; e.key.repeat == 0) { switch (e.key.keysym.sym) { case SDLK_RETURN: if (game.state_ == Game::START) { game.state_ = Game::SERVE; } else if (game.state_ == Game::SERVE) { game.ball_.yVel_ = static_cast&lt;float&gt;(getRandomNumber(-50, 50)); if (game.servingPlayer_ == 1) { game.ball_.xVel_ = static_cast&lt;float&gt;(getRandomNumber(-200, -140)); } else { game.ball_.xVel_ = static_cast&lt;float&gt;(getRandomNumber(140, 200)); } game.state_ = Game::PLAY; } else if (game.state_ == Game::DONE) { game.state_ = Game::SERVE; game.ball_.reset(); game.winningPlayer_ = 0; game.servingPlayer_ = getRandomNumber(1, 2); game.player1Score_ = 0; game.player2Score_ = 0; } break; case SDLK_UP: game.player1_.yVel_ -= PADDLE_SPEED; break; case SDLK_DOWN: game.player1_.yVel_ += PADDLE_SPEED; break; } } else if (e.type == SDL_KEYUP &amp;&amp; e.key.repeat == 0) { switch (e.key.keysym.sym) { case SDLK_UP: game.player1_.yVel_ += PADDLE_SPEED; break; case SDLK_DOWN: game.player1_.yVel_ -= PADDLE_SPEED; break; } } } return true; } int main(int argc, char* args[]) { sdl sdlinit; sdl_img img; sdl_ttf ttf; sdl_mix music; AssetManager assets; Game game; SDL_RenderSetLogicalSize(assets.renderer_.get(), VIRTUAL_WIDTH, VIRTUAL_HEIGHT); while(game.state_ != Game::EXIT) { while (input(game) &amp;&amp; update(game, assets) &amp;&amp; render(game, assets)) { } } return 0; } </code></pre> <p><strong>SDLInit.h</strong></p> <pre><code>#pragma once class sdl { public: sdl(); sdl(sdl&amp;&amp; other) noexcept; ~sdl(); auto operator=(sdl&amp;&amp; other) noexcept-&gt;sdl&amp;; // Non-copyable sdl(sdl const&amp;) = delete; auto operator=(sdl const&amp;)-&gt;sdl&amp; = delete; friend void _swap(sdl&amp; a, sdl&amp; b) noexcept; private: bool _own = false; }; class sdl_img { public: sdl_img(); sdl_img(sdl_img&amp;&amp; other) noexcept; ~sdl_img(); auto operator=(sdl_img&amp;&amp; other) noexcept-&gt;sdl_img&amp;; // Non-copyable sdl_img(sdl_img const&amp;) = delete; auto operator=(sdl_img const&amp;)-&gt;sdl_img&amp; = delete; friend void _swap(sdl_img&amp; a, sdl_img&amp; b) noexcept; private: bool _own = false; }; class sdl_ttf { public: sdl_ttf(); sdl_ttf(sdl_ttf&amp;&amp; other) noexcept; ~sdl_ttf(); auto operator=(sdl_ttf&amp;&amp; other) noexcept-&gt;sdl_ttf&amp;; // Non-copyable sdl_ttf(sdl_ttf const&amp;) = delete; auto operator=(sdl_ttf const&amp;)-&gt;sdl_ttf&amp; = delete; friend void _swap(sdl_ttf&amp; a, sdl_ttf&amp; b) noexcept; private: bool _own = false; }; class sdl_mix { public: sdl_mix(); sdl_mix(sdl_mix&amp;&amp; other) noexcept; ~sdl_mix(); auto operator=(sdl_mix&amp;&amp; other) noexcept-&gt;sdl_mix&amp;; // Non-copyable sdl_mix(sdl_mix const&amp;) = delete; auto operator=(sdl_mix const&amp;)-&gt;sdl_mix&amp; = delete; friend void _swap(sdl_mix&amp; a, sdl_mix&amp; b) noexcept; private: bool _own = false; }; struct sdl_deleter { void operator()(SDL_Window* p) noexcept; void operator()(SDL_Renderer* p) noexcept; void operator()(TTF_Font* p) noexcept; void operator()(Mix_Chunk* p) noexcept; }; </code></pre> <p><strong>SDLInit.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;SDL.h&gt; #include &lt;SDL_image.h&gt; #include &lt;SDL_ttf.h&gt; #include &lt;SDL_mixer.h&gt; #include "SDLInit.h" //Initialize SDL sdl::sdl() { auto const result = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE); if (result != 0) std::cout &lt;&lt; "SDL could not initialize"; } sdl::sdl(sdl&amp;&amp; other) noexcept { _swap(*this, other); } sdl::~sdl() { if (_own) SDL_Quit(); } auto sdl::operator=(sdl&amp;&amp; other) noexcept -&gt; sdl&amp; { _swap(*this, other); return *this; } void _swap(sdl&amp; a, sdl&amp; b) noexcept { using std::swap; swap(a._own, b._own); } //Initialize SDL Image sdl_img::sdl_img() { auto const result = IMG_Init(IMG_INIT_PNG); if (result == 0) std::cout &lt;&lt; "SDL Image could not initialize"; if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) std::cout &lt;&lt; "Could not set texture filtering"; } sdl_img::sdl_img(sdl_img&amp;&amp; other) noexcept { _swap(*this, other); } sdl_img::~sdl_img() { if (_own) IMG_Quit(); } auto sdl_img::operator=(sdl_img&amp;&amp; other) noexcept -&gt; sdl_img&amp; { _swap(*this, other); return *this; } void _swap(sdl_img&amp; a, sdl_img&amp; b) noexcept { using std::swap; swap(a._own, b._own); } //Initialize SDL True Type Fonts sdl_ttf::sdl_ttf() { auto const result = TTF_Init(); if (result != 0) std::cout &lt;&lt; "SDL TTF could not initialize"; } sdl_ttf::sdl_ttf(sdl_ttf&amp;&amp; other) noexcept { _swap(*this, other); } sdl_ttf::~sdl_ttf() { if (_own) TTF_Quit(); } auto sdl_ttf::operator=(sdl_ttf&amp;&amp; other) noexcept -&gt; sdl_ttf&amp; { _swap(*this, other); return *this; } void _swap(sdl_ttf&amp; a, sdl_ttf&amp; b) noexcept { using std::swap; swap(a._own, b._own); } //Initialize SDL Mixer sdl_mix::sdl_mix() { auto const result = Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048); if (result == -1) std::cout &lt;&lt; "SDL Mixer could not initialize"; } sdl_mix::sdl_mix(sdl_mix&amp;&amp; other) noexcept { _swap(*this, other); } sdl_mix::~sdl_mix() { if (_own) Mix_Quit(); } auto sdl_mix::operator=(sdl_mix&amp;&amp; other) noexcept -&gt; sdl_mix&amp; { _swap(*this, other); return *this; } void _swap(sdl_mix&amp; a, sdl_mix&amp; b) noexcept { using std::swap; swap(a._own, b._own); } //used with std::unique_ptr void sdl_deleter::operator()(SDL_Window* p) noexcept { if (p) SDL_DestroyWindow(p); } void sdl_deleter::operator()(SDL_Renderer* p) noexcept { if (p) SDL_DestroyRenderer(p); } void sdl_deleter::operator()(TTF_Font* p) noexcept { if (p) TTF_CloseFont(p); } void sdl_deleter::operator()(Mix_Chunk* p) noexcept { if (p) Mix_FreeChunk(p); } </code></pre> <p><strong>Texture.h</strong></p> <pre><code>#pragma once //used to tag how the texture was rendered enum TextureType { from_surface, from_text }; class LTexture { public: LTexture(); LTexture(TextureType type, SDL_Renderer* renderer, std::string const&amp; path); LTexture(TextureType type, TTF_Font* font, SDL_Renderer* renderer, std::string const&amp; text, SDL_Color color, int width); LTexture(LTexture&amp;&amp; other) noexcept { swap(*this, other); } ~LTexture(); void render(SDL_Renderer* renderer, int x, int y, SDL_Rect* clip = nullptr, double angle = 0.0, SDL_Point* center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE); void loadfromsurface(SDL_Renderer* renderer, std::string const&amp; path); void loadfromtext(TTF_Font* font, SDL_Renderer* renderer, std::string const&amp; text, SDL_Color color, int width); LTexture&amp; operator=(LTexture&amp;&amp; other) noexcept { swap(*this, other); return *this; } friend void swap(LTexture&amp; a, LTexture&amp; b) noexcept; SDL_Texture* texture_ = nullptr; int width_ = 0; int height_ = 0; SDL_Rect button_ = {}; bool own_ = false; LTexture(LTexture const&amp;) = delete; auto operator=(LTexture const&amp;) = delete; }; </code></pre> <p><strong>Texture.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;SDL.h&gt; #include &lt;SDL_image.h&gt; #include &lt;SDL_ttf.h&gt; #include "Texture.h" LTexture::LTexture() { own_ = true; } LTexture::LTexture(TextureType type, SDL_Renderer* renderer, std::string const&amp; path) { SDL_Surface *surface = IMG_Load(path.c_str()); if (!surface) std::cout &lt;&lt; "Failed to create surface"; texture_ = SDL_CreateTextureFromSurface(renderer, surface); if (!texture_) std::cout &lt;&lt; "Failed to create texture"; width_ = surface-&gt;w; height_ = surface-&gt;h; SDL_FreeSurface(surface); own_ = true; } LTexture::LTexture(TextureType type, TTF_Font* font, SDL_Renderer* renderer, std::string const&amp; text, SDL_Color color, int width) { SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(font, text.c_str(), color, width); if (!textSurface) std::cout &lt;&lt; "Failed to create surface"; texture_ = SDL_CreateTextureFromSurface(renderer, textSurface); if (!texture_) std::cout &lt;&lt; "Failed to created texture"; width_ = textSurface-&gt;w; height_ = textSurface-&gt;h; SDL_FreeSurface(textSurface); own_ = true; } void LTexture::render(SDL_Renderer* renderer, int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip) { SDL_Rect destRect = { x, y, width_, height_ }; if (clip != nullptr) { destRect.w = clip-&gt;w; destRect.h = clip-&gt;h; } SDL_RenderCopyEx(renderer, texture_, clip, &amp;destRect, angle, center, flip); //create a rectangle that coincides with texture to check for button presses button_ = { x, y, destRect.w, destRect.h }; } void LTexture::loadfromsurface(SDL_Renderer* renderer, std::string const&amp; path) { SDL_Surface *surface = IMG_Load(path.c_str()); if (!surface) std::cout &lt;&lt; "Failed to create surface"; texture_ = SDL_CreateTextureFromSurface(renderer, surface); if (!texture_) std::cout &lt;&lt; "Failed to create texture"; width_ = surface-&gt;w; height_ = surface-&gt;h; SDL_FreeSurface(surface); } void LTexture::loadfromtext(TTF_Font* font, SDL_Renderer* renderer, std::string const&amp; text, SDL_Color color, int width) { SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(font, text.c_str(), color, width); if (!textSurface) std::cout &lt;&lt; "Failed to create surface"; texture_ = SDL_CreateTextureFromSurface(renderer, textSurface); if (!texture_) std::cout &lt;&lt; "Failed to created texture"; width_ = textSurface-&gt;w; height_ = textSurface-&gt;h; SDL_FreeSurface(textSurface); } void swap(LTexture&amp; a, LTexture&amp; b) noexcept { using std::swap; swap(a.texture_, b.texture_); swap(a.width_, b.width_); swap(a.height_, b.height_); swap(a.button_, b.button_); swap(a.own_, b.own_); } LTexture::~LTexture() { if (texture_) SDL_DestroyTexture(texture_); } </code></pre> <p><a href="https://github.com/games50/pong/tree/master/pong-final" rel="nofollow noreferrer">Here is the link to the LUA/LÖVE code this is based on.</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T05:46:30.257", "Id": "206240", "Score": "2", "Tags": [ "c++", "sdl" ], "Title": "SDL2/C++ Pong Game" }
206240
<p>In my project, there is an internal cache api to use. I have noticed an emerging pattern such that:</p> <pre><code>class SomeService { private final CacheApi cache = CacheApi.newCache(); private final Object cacheAccessLock = new Object(); public List&lt;Something&gt; getSomethings() { synchronized (cacheAccessLock) { if (cache.exists("cache-key")) { return cache.get("cache-key"); } List&lt;Something&gt; somethings = loadSomethingsQuiteSlow(); cache.put("cache-key", somethings); return somethings; } } } </code></pre> <p>This pattern is implemented on several places. So I wrote a class called <code>CacheReadWriteGuard</code> to see if such task can be abstracted into an utility class.</p> <p>The usage of the class</p> <pre><code>class SomeService { private final CacheApi cache = CacheApi.newCache(); private final CacheReadWriteGuard&lt;List&lt;Something&gt;&gt; cacheGuard = new CacheReadWriteGuard.Builder&lt;List&lt;Something&gt;&gt;() .readBy(() -&gt; cache.get("cache-key")) .expiredWhen(() -&gt; cache.exists("cache-key") == false) .writeIfExpired(() -&gt; { List&lt;Something&gt; somethings = loadSomethingsQuiteSlow(); cache.put("cache-key", somethings); }); public List&lt;Something&gt; getSomethings() { return cacheGuard.get(); } } </code></pre> <p>The idea is to use <code>ReadWriteLock</code> to guard access to the cache such that if a write-action is needed, all Threads attempting to read will be halted until the write-action completes.</p> <p>The implementation of the class is as follow:</p> <pre><code>public class CacheReadWriteGuard&lt;T&gt; { @FunctionalInterface public static interface ExpiredCacheCondition { boolean isExpired(); } @FunctionalInterface public static interface CacheRead&lt;T&gt; { T read(); } @FunctionalInterface public static interface CacheWrite extends Runnable { } public static class Builder&lt;T&gt; { private ExpiredCacheCondition cacheCondition; private CacheRead&lt;T&gt; readAction; private CacheWrite writeAction; public Builder() { } /** * Provides a way that the guard can tell if the cache is expired. * In case if no {@code ExpiredCacheCondition} is supplied, this * builder by default will use CacheRead.read() == null as the condition. */ public Builder&lt;T&gt; expiredIf(ExpiredCacheCondition cacheCondition) { this.cacheCondition = cacheCondition; return this; } public Builder&lt;T&gt; readBy(CacheRead&lt;T&gt; cacheRead) { this.readAction = cacheRead; return this; } public Builder&lt;T&gt; writeOnExpired(CacheWrite cacheWrite) { this.writeAction = cacheWrite; return this; } public CacheReadWriteGuard&lt;T&gt; build() { Objects.requireNonNull(readAction, "CacheRead must not be null"); Objects.requireNonNull(writeAction, "CacheWrite must not be null"); if (cacheCondition == null) { cacheCondition = () -&gt; readAction.read() == null; } return new CacheReadWriteGuard&lt;&gt;(cacheCondition, readAction, writeAction); } } private final ExpiredCacheCondition cacheCondition; private final CacheRead&lt;T&gt; readAction; private final CacheWrite writeAction; private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock readLock = readWriteLock.readLock(); private final Lock writeLock = readWriteLock.writeLock(); private CacheReadWriteGuard( ExpiredCacheCondition condition, CacheRead&lt;T&gt; readAction, CacheWrite writeAction) { this.cacheCondition = condition; this.readAction = readAction; this.writeAction = writeAction; } /** * Returns a new Builder. The {@code Class&lt;T&gt;} is solely * for ensuring the compiler can infer the type of the * cached value. */ public static &lt;T&gt; Builder&lt;T&gt; of(Class&lt;T&gt; type) { return new Builder&lt;&gt;(); } public T get() { T cachedValue = null; loadCache(); try { readLock.lock(); cachedValue = readAction.read(); } finally { readLock.unlock(); } return cachedValue; } private void loadCache() { /* * Keeping all the other threads which don't hold the * write lock busy in the while loop until the one * which holds finish the writeAction. * * If the cacheCondition returns false, the loop exits * immediately, thus making no attempt acquiring * the writeLock. */ while (cacheCondition.isExpired()) { try { /* * Attempts to get the write lock within 5 seconds. * * If the current Thread fails to get the lock, it will * be kept busy by the outer while loop. * * And yes, the comment block wrapping the number 5 is * for visual effect making the number 5 stand out. */ if (writeLock.tryLock(/**/ 5 /**/, SECONDS)) { try { /* * Re-check the state of the cache in case if some other * Thread has acquired the writeLock and * finish loading the cache _before_ this Thread's turn. */ if(cacheCondition.isExpired()) { writeAction.run(); } } finally { writeLock.unlock(); } } } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); } } } } </code></pre> <p>I have tested this class and it works.</p> <p>I just don't know whether:</p> <ul> <li>it is the right approach to go?</li> <li>it is implemented correctly? Did I miss something that could cause a locking issue (deadlock, etc) in the future?</li> <li>how should <code>InterruptedException</code> be handled in this situation?</li> </ul> <p>Thanks a lot for your time. Genzer</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T13:51:59.040", "Id": "397951", "Score": "0", "body": "Why is that builder so complicated? You should only need to pass `cache` object, key(\"cache-key\") and loadSomethingsQuiteSlow()" }, { "ContentLicense": "CC BY-SA 4.0",...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T06:43:16.350", "Id": "206244", "Score": "1", "Tags": [ "java", "concurrency", "cache", "locking" ], "Title": "Using ReadWriteLock to implement a cache access guard" }
206244
<p>For our Django app running on AWS Elastic Beanstalk, we use a web-server/worker setup. The same code is deployed to the web-server and worker environments, and environment-specific configuration is achieved with <code>.ebextensions</code> config files, using the <code>test</code> option for <code>container_commands</code>, among other things.</p> <p>Now there are <em>some</em> container commands we would like to execute <em>only</em> during deployment or environment-creation (so we use <code>leader_only: true</code>, see bottom), but, <em>in addition</em>, they should never be executed on the worker environment. </p> <p>The latter could be achieved using the <code>test</code> option, but that cannot be used not in combination with <code>leader_only</code>, according to the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#linux-container-commands-options" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>... A command can be leader-only or have a test, but not both (leader_only takes precedence).</p> </blockquote> <p>Now, to work around this, we do something like the following, in <code>.ebextensions/foo.config</code>:</p> <pre><code>option_settings: aws:elasticbeanstalk:application:environment: ENV_NAME: '`{ "Ref" : "AWSEBEnvironmentName" }`' # get the current environment name container_commands: 0100_set_flag_if_instance_is_leader: command: touch /tmp/is_leader # create empty file leader_only: true 0200_execute_command_on_leader_only_but_never_on_worker: command: foo bar test: '[[ $ENV_NAME != "worker" &amp;&amp; -e /tmp/is_leader ]]' </code></pre> <p>where <code>ENV_NAME</code> contains the environment name, which is automatically retrieved with the help of <code>option_settings</code> (see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions-optionsettings.html" rel="nofollow noreferrer">docs</a>).</p> <p>Note that the config file is in <code>YAML</code> format and the commands and tests execute in a shell (I assume <code>bash</code>, since the extended test construct <code>[[</code> works, but could not find any specifics in the AWS docs).</p> <p>As I am <em>not</em> an expert, I would really appreciate your comments on the following points:</p> <ol> <li><p>The solution above works, but is this the simplest way to do it?</p></li> <li><p>Are there any compelling reasons <em>not</em> to use this kind of set-up?</p></li> <li><p>I tried setting a variable instead of creating a file (in command <code>0100</code>), but the variable does not appear to persist between container commands. Is there some way to achieve this? (I tried to <code>export</code>, but that didn't help. Is each container command executed in a separate shell, or how does this work?)</p></li> </ol> <p>Some general background from the AWS <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#linux-container-commands" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>You can use leader_only to only run the command on a single instance, or configure a test to only run the command when a test command evaluates to true. Leader-only container commands are only executed during environment creation and deployments, while other commands and server customization operations are performed every time an instance is provisioned or updated. Leader-only container commands are not executed due to launch configuration changes, such as a change in the AMI Id or instance type.</p> </blockquote>
[]
[ { "body": "<p>It turns out there is an environment variable called <code>EB_IS_COMMAND_LEADER</code> which can be used in a test. See e.g. <a href=\"https://forums.aws.amazon.com/thread.jspa?threadID=224630\" rel=\"nofollow noreferrer\">this post</a> on AWS forums.</p>\n<p>So, the two container commands from th...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T07:23:39.620", "Id": "206246", "Score": "2", "Tags": [ "bash", "configuration", "amazon-web-services", "yaml" ], "Title": "Elastic Beanstalk configuration using ebextensions container_commands combining leader_only and test" }
206246
<p>I've written the following Python module to iterate over field values in the following two fields: "NAME_LABEL", "CATEGORY". I'm using regular expressions in the following function: "<strong>correct_invalid_char</strong>", to substitute characters over three expressions that are dependent on each other. The first expression replaces the following characters "/-space" with an underscore, the result is then passed onto the second expression to remove non-alphanumeric and non-numeric characters. The last regular expression removes duplicate underscores that were originally in the field values or generated due to the first regular expression.</p> <p>Is there more Pythonic way of writing the following regular expressions to achieve the same result, that would allow me to write better unit tests for the following function?</p> <p><a href="https://i.stack.imgur.com/Y7fBT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y7fBT.png" alt="enter image description here"></a> Original field values:</p> <pre><code>OBJECTID,NAME,NAME_LABEL,FACILITY_TYPE,CATEGORY,SHAPE_Length,SHAPE_Area 1,Ward 27 - New 1,Ward 27 - New 1,Settlements,Settlements 2,533.176039669,12288.746516 2,429 (Block R),(Block R) 429,Settlements,Settlements 4,508.411033555,9622.22635621 3,Kondelelani (Block 1),Kondelelani (Block 1),Settlements,Settlements 4,738.203751902,22815.0234794 4,Yebo Gogo,Yebo \ Gogo,Settlements,Settlements 1,674.979301727,23413.6988572 5,Tebogo Bottle Store,Tebogo / Bottle Store,Settlements,Settlements 1,329.239037836,7157.39741934 6,Block 1 Y,Block 1 [Y],Settlements,Settlements 2,1893.89651205,82883.9076782 7,Stand 1427, Ga-Rankuwa X25,Stand_ 1427, Ga-Rankuwa X25,Settlements,Settlements 3,1209.46585836,66852.9597381 8,Stand 1719, Ga-Rankuwa X23,Stand 1719, Ga-Rankuwa X23,Settlements,Settlements 3,997.901714538,51299.0275644 </code></pre> <p>Original values: CSV</p> <p><a href="https://i.stack.imgur.com/i6c4o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i6c4o.png" alt="enter image description here"></a> Updated field values:</p> <pre><code>""" Created on 23 Oct 2018 Remove invalid characters found in SAA fields values: NAME_LABEL; CATEGORY @author: Peter Wilson """ # import site-packages and modules import re import argparse import arcpy # set environment settings arcpy.env.overwriteOutput = True def sites_fields_list(sites): """ Validate fields found and create list for update cursor. """ fields = ['NAME_LABEL', 'CATEGORY'] sites_fields = [f.name for f in arcpy.ListFields(sites) if f.name in fields] return sites_fields def correct_invalid_char(field_value): """ Correct field values by replacing characters, removing non-alphanumeric, non-numeric characters, duplicate underscores, and changing to title case. """ try: underscore = re.sub('[/\- ]', '_', field_value) illegal_char = re.sub('[^0-9a-zA-Z_]+', '', underscore) dup_underscore = re.sub(r'(_)+', r'\1', illegal_char) update_value = dup_underscore.title() return update_value except TypeError as e: print("There's no value in the field: {0}".format(e)) raise def update_field_values(sites): """ Iterate over field values in: NAME_LABEL; CATEGORY and correct field values by replacing characters. """ sites_fields = sites_fields_list(sites) with arcpy.da.UpdateCursor(sites, sites_fields) as cursor: for row in cursor: for idx, val in enumerate(row): row[idx] = correct_invalid_char(val) cursor.updateRow(row) if __name__ == '__main__': description = 'Remove invalid characters in SAA fields NAME_LABEL and CATEGORY' parser = argparse.ArgumentParser(description) parser.add_argument('--sites', metavar='path', required=True, help='path to input sites feature class') args = parser.parse_args() update_field_values(sites=args.sites) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T08:36:03.940", "Id": "397909", "Score": "0", "body": "can you copy-paste the values instead of putting screen shots?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T08:48:07.580", "Id": "397911", ...
[ { "body": "<p>I can't say it would be more Pythonic, but we can reduce your number of <code>re.sub()</code> calls from 3 down to 2.</p>\n\n<p>First, we just eliminate all of the invalid letters:</p>\n\n<pre><code>valid_chars = re.sub('[^-/_ 0-9a-zA-Z]', '', field_value)\n</code></pre>\n\n<p>Then, replace occurr...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T07:31:09.943", "Id": "206247", "Score": "1", "Tags": [ "python", "python-2.x", "regex" ], "Title": "Replace characters using multiple dependent regular expression substitutions" }
206247
<p>I've developed a function in the Julia language, using the <code>SymEngine</code> library, which builds an equation. This function works quite quickly, returning a lambdified equation.</p> <p>The problem is, calculation of the value of this equation in the point takes too long time! And as the equation becomes longer, the calculation time also increases.</p> <p>Is there a way to optimize the equation, generated by the function?</p> <pre><code>function func() @vars x y z myu longitude=atan(y/x)+pi*sign(y)*(1-sign(x))/2 r=(x^2+y^2+z^2)^(1/2) dUx=0 dUy=0 dUz=0 for i=2:degree for j=0:degree index=1+j; for ll=2:i-1 index+=ll+1; end P_i=(myu^2-1)^i for k=1:i+j P_i=diff(P_i,myu) end if(i&gt;20) F=factorial(Int128(i)); else F=factorial(i); end P_ij=(((1-myu^2)^(j/2))/(F*2^i))*P_i if(P_ij!=0) CS_exp=CS[index,3]*cos(j*longitude)+CS[index,4]*sin(j*longitude) CS_diff_x= j*CS[index,4]*cos(j*longitude)*(-y/(x^2+y^2)) - j*CS[index,3]*sin(j*longitude)*(-y/(x^2+y^2)) CS_diff_y= j*CS[index,4]*cos(j*longitude)*( x/(x^2+y^2)) - j*CS[index,3]*sin(j*longitude)*( x/(x^2+y^2)) CS_diff_z= 0 L=P_ij(z/r) dUx+= GMe*(diff((L*(Req/r)^i)/r,x)*CS_exp + CS_diff_x*(L*(Req/r)^i)/r) dUy+= GMe*(diff((L*(Req/r)^i)/r,y)*CS_exp + CS_diff_y*(L*(Req/r)^i)/r) dUz+= GMe*(diff((L*(Req/r)^i)/r,z)*CS_exp + CS_diff_z*(L*(Req/r)^i)/r) end end end return lambdify(dUx, [x,y,z], cse=true),lambdify(dUy, [x,y,z], cse=true),lambdify(dUz, [x,y,z], cse=true) end dU=func(); dy= [ dU[1](y[1],y[2],y[3]), dU[2](y[1],y[2],y[3]), dU[3](y[1],y[2],y[3]) ] </code></pre> <p>The calculation of <code>dy</code> takes too long. Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T11:14:41.743", "Id": "397935", "Score": "4", "body": "You need to tell us what you are actually calculating there. Just saying _this function is too slow_ is not enough and off-topic for the lack of context." }, { "ContentLi...
[ { "body": "<p>I've also commented on the julia slack, but just if anyone else is reading, as I see you've not updated the question according to my comments. </p>\n\n<p>You can see Julia's general performance tips <a href=\"https://docs.julialang.org/en/v1/manual/performance-tips/index.html\" rel=\"nofollow nore...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T07:56:51.350", "Id": "206249", "Score": "0", "Tags": [ "performance", "julia", "symbolic-math" ], "Title": "Building an equation" }
206249
<p>So I got a project to refactor and I can't figure out what the best solution for this specific problem would be. I'm trying to reach some kind of elegant few-line-solution, but every idea I have seems to be a dead end. My brain does not work anymore... The original state:</p> <pre><code>public SearchParameterSet(ProviderRequestParameters requestParameters) { ProviderParameters = requestParameters; if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByPatient])) { string patient = requestParameters.RequestParameters[FhirResourceNames.FhirResourcePatient]; string[] ids = patient.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in ids) PatientIds.Add(id); } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByCase])) { string patient = requestParameters.RequestParameters[Constants.QueryParamCaseId]; string[] ids = patient.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in ids) CaseIds.Add(id); } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByDateFrom])) { string value = requestParameters.RequestParameters[FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByDateFrom]]; DateTime df = DateTime.MinValue; if (DateTime.TryParse(value, out df)) DateFrom = df; } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByDateTo])) { string value = requestParameters.RequestParameters[FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByDateTo]]; DateTime df = DateTime.MinValue; if (DateTime.TryParse(value, out df)) DateTo = df; } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.Profile])) { string value = requestParameters.RequestParameters[FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.Profile]]; Profile = value; } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.Format])) { string value = requestParameters.RequestParameters[FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.Format]]; Format = value; } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ResourceType])) { string value = requestParameters.RequestParameters[FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ResourceType]]; ResourceType = value; } if (requestParameters.RequestParameters.ContainsKey(FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByUser])) { string value = requestParameters.RequestParameters[FhirSearchExtensions.RequestParameterNames[FhirRequestParameters.ByUser]]; User = value; } } </code></pre> <p>Currently I am iterating through requestParameters and call the appropriate function depending on the Parameter itself. Also wrote an extension method to be able to get the name of the parameter more nicely. But there has to be a more elegant and complex solution.</p> <pre><code>private List&lt;String&gt; ExtractParametersAsListOfString(string input) { var ret = new List&lt;string&gt;(); string[] ids = input.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in ids) ret.Add(id); return ret; } private DateTime ExtractParametersAsDateTime(string input) { DateTime df = DateTime.MinValue; if (DateTime.TryParse(input, out df)) DateFrom = df; return df; } public SearchParameterSet(ProviderRequestParameters requestParameters) { ProviderParameters = requestParameters; foreach (var parameter in requestParameters.RequestParameters) { if (parameter.Key == FhirRequestParameters.ByPatient.GetName()) PatientIds = ExtractParametersAsListOfString(parameter.Value); if (parameter.Key == FhirRequestParameters.ByCase.GetName()) CaseIds = ExtractParametersAsListOfString(parameter.Value); if (parameter.Key == FhirRequestParameters.ByDateFrom.GetName()) DateFrom = ExtractParametersAsDateTime(parameter.Value); if (parameter.Key == FhirRequestParameters.ByDateTo.GetName()) DateTo = ExtractParametersAsDateTime(parameter.Value); if (parameter.Key == FhirRequestParameters.Profile.GetName()) Profile = parameter.Value; if (parameter.Key == FhirRequestParameters.Format.GetName()) Format = parameter.Value; if (parameter.Key == FhirRequestParameters.ResourceType.GetName()) ResourceType = parameter.Value; if (parameter.Key == FhirRequestParameters.ByUser.GetName()) User = parameter.Value; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T11:38:13.887", "Id": "397938", "Score": "0", "body": "Is `requestParameters.RequestParameters[FhirResourceNames.FhirResourcePatient];` a typo (same for ByCase) as everywhere else you've used the format `requestParameters.RequestPara...
[ { "body": "<p>Update: Runnable Example: <a href=\"https://dotnetfiddle.net/qPCoKu\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/qPCoKu</a></p>\n\n<p>Update: 2018-10-26 Tweaked code slightly so the CSV piece returns an array then uses <code>AddRange</code> to add values to the lists, instead of having t...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T11:31:15.873", "Id": "206258", "Score": "2", "Tags": [ "c#" ], "Title": "C# legacy project to be refactored, but stuck at a basic if stacking" }
206258
<h2>Original Problem</h2> <p>The original problem is parsing/generation of the transport header of the RTSP protocol, see RFC 2326 12.39 Transport, Page 60. The transport header is defined of multiple transport specs, at least one, and either comma separated or by repetition of the transport header. The transport specs are again a complex text based language, which also could be structs. Since the solution is relevant for all one list of items based grammars in conjunction with the used library, an example was extracted, with foo instead of RTSP, <code>foo_struct</code> instead of Transport, and integers instead of transport specs.</p> <h2>Generalised Problem</h2> <p>For the sake of an example assume we got a text based grammar/language for data exchange, like HTTP. But right now, this protocol called "foo" is consists of a comma separated list of numbers like "5,3,2" in decimal notation.</p> <p>The internal representation of the data of this langauge in C++ is defined as <code>foo_struct</code>.</p> <p><strong>A.</strong> We want to parse individual <code>int</code>s from the list while also adding them as items to the <code>std::vector&lt;int&gt;</code>, inside of the struct <code>foo_struct::bar_vector</code>.</p> <p><strong>B</strong>. We want to generate a valid text string out from a <code>foo_struct</code>, so at the moment again just a list of comma separated numbers.</p> <h2>Approach</h2> <p>The C++ library boost has a very powerfull parsing and generating section, called spirit, which has it subparts qi for parsing and karma for generating. </p> <h2>Specific Problem</h2> <p>Qi and karma has some ways to make it easy for the user, to stuff the atomic items from the sub parsers/generators, like the number and list ones, into custom structs. This works well for structs which more than one member to put data into. However both libraries have some ugly caveats in the corner case of structs consisting simply out of one member, because then, they assume it follows the concepts of a container like <code>std::list</code> or <code>std::vector</code></p> <p>How to solve this for <strong>A.</strong> (Qi) was already discussed in <a href="https://stackoverflow.com/q/19823413/3537677">https://stackoverflow.com/q/19823413/3537677</a>, but now this code below solved this in a not so satisfying way for <strong>B.</strong> (Karma). </p> <hr> <p>So all the code intents to do is to define the <code>foo_struct</code> with just one member, define the Qi grammar for demonstration purposes, like in the solution for A. and also a Karma Generator, which is the troublemaker. </p> <p>The <code>main</code> routine is then just for demonstrating i.e. testing this example.</p> <p><strong>The ugly solution for B.</strong></p> <p>I have a one member struct that I am using with <code>boost::spirit::karma</code>, but, as far as I could get it to work, I have to use a <code>boost::spirit::karma::attr_cast</code> with a coustom <code>boost::spirit::traits::transform_attribute&lt;T, std::vector&lt;u&gt;&gt;{static std::vector&lt;U&gt; pre (const &amp;T)</code> function, </p> <p>which is very ugly and error prone. <strong>If you know how to write it as simple as in the parsing case, that would be much more readable i.e. maintainable.</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;boost/spirit/include/karma.hpp&gt; #include &lt;boost/spirit/include/qi.hpp&gt; struct foo_struct { std::vector&lt;int&gt; bar_vector; foo_struct() = default; explicit foo_struct(std::vector&lt;int&gt; v) : bar_vector(std::move(v)) {} }; template&lt;typename Iterator&gt; struct foo_parser_grammar : ::boost::spirit::qi::grammar&lt;Iterator, foo_struct()&gt; { foo_parser_grammar() : foo_parser_grammar::base_type(start) { start %= boost::spirit::qi::as&lt;std::vector&lt;int&gt;&gt;()[ boost::spirit::qi::int_ % ","]; } boost::spirit::qi::rule&lt;Iterator, foo_struct()&gt; start; }; namespace boost { namespace spirit { namespace traits { template&lt;&gt; struct transform_attribute&lt;foo_struct const, std::vector&lt;int&gt;, karma::domain&gt; { typedef int type; static std::vector&lt;int&gt; pre(foo_struct const &amp;d) { return d.bar_vector; } }; } } } template&lt;typename OutputIterator&gt; struct foo_generator_grammar : boost::spirit::karma::grammar&lt;OutputIterator, foo_struct()&gt; { foo_generator_grammar() : foo_generator_grammar::base_type(start) { start = boost::spirit::karma::attr_cast&lt;std::vector&lt;int&gt;&gt;( boost::spirit::karma::int_ % ","); } boost::spirit::karma::rule&lt;OutputIterator, foo_struct()&gt; start; }; int main(int argc, char *argv[]) { foo_struct foo{}; std::string input{"5,3,2"}; foo_parser_grammar&lt;std::string::const_iterator&gt; parse_grammar{}; boost::spirit::qi::phrase_parse(input.cbegin(), input.cend(), parse_grammar, boost::spirit::ascii::space, foo); std::cout &lt;&lt; "Input\""; std::for_each(foo.bar_vector.cbegin(), foo.bar_vector.cend(), [](const auto &amp;i) { std::cout &lt;&lt; i &lt;&lt; ","; }); std::cout &lt;&lt; "\"\n"; std::string output; foo_generator_grammar&lt;std::back_insert_iterator&lt;std::string&gt;&gt; gen_grammar{}; boost::spirit::karma::generate(std::back_inserter(output), gen_grammar, foo); std::cout &lt;&lt; "Output\"" &lt;&lt; output &lt;&lt; "\"\n"; return 0; } </code></pre>
[]
[ { "body": "<p>Here's what I'd do:</p>\n\n<p><strong><kbd><a href=\"http://coliru.stacked-crooked.com/a/023fe3ef59ecc614\" rel=\"nofollow noreferrer\">Live On Coliru</a></kbd></strong></p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n\nstruct foo_struct {\n std::vector&lt;int&gt; bar_vector...
{ "AcceptedAnswerId": "206281", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T12:03:39.583", "Id": "206259", "Score": "0", "Tags": [ "c++", "boost" ], "Title": "Use of a single member struct as an attribute with boost::spirit::karma generators" }
206259
<p>I have three methods to get the user details based on attributes:</p> <ul> <li>Find user details by id,</li> <li>Find user details by username,</li> <li>Find user details by email</li> </ul> <p>Here is the program class:</p> <pre><code>using System; using System.Data; using System.Linq; using System.Data.DataSetExtensions; public class Program { public static void Main() { Console.WriteLine("Hello World"); var user = GetUserById(1); Console.WriteLine(user.Name); var user1 = GetUserByUsername("user3"); Console.WriteLine(user1.Name); var user2 = GetUserByEmail("user5@gmail.com"); Console.WriteLine(user2.Name); } public static User GetUserById(int id) { var users = GetUsers().AsEnumerable().Where(row =&gt; row.Field&lt;int&gt;("Id") == id); var userInfo = users.Select(s =&gt; new User{ Id = s.Field&lt;int&gt;("Id"), Username = s.Field&lt;string&gt;("Username"), Name = s.Field&lt;string&gt;("Name"), Email = s.Field&lt;string&gt;("Email"), CreatedDate = s.Field&lt;DateTime&gt;("CreatedDate"), Phone = s.Field&lt;string&gt;("Phone"), City = s.Field&lt;string&gt;("City"), State = s.Field&lt;string&gt;("State"), Country = s.Field&lt;string&gt;("Country") }).FirstOrDefault(); return userInfo; } public static User GetUserByUsername(string username) { var users = GetUsers().AsEnumerable().Where(row =&gt; row.Field&lt;string&gt;("Username") == username); var userInfo = users.Select(s =&gt; new User{ Id = s.Field&lt;int&gt;("Id"), Username = s.Field&lt;string&gt;("Username"), Name = s.Field&lt;string&gt;("Name"), Email = s.Field&lt;string&gt;("Email"), CreatedDate = s.Field&lt;DateTime&gt;("CreatedDate"), Phone = s.Field&lt;string&gt;("Phone"), City = s.Field&lt;string&gt;("City"), State = s.Field&lt;string&gt;("State"), Country = s.Field&lt;string&gt;("Country") }).FirstOrDefault(); return userInfo; } public static User GetUserByEmail(string email) { var users = GetUsers().AsEnumerable().Where(row =&gt; row.Field&lt;string&gt;("Email") == email); var userInfo = users.Select(s =&gt; new User{ Id = s.Field&lt;int&gt;("Id"), Username = s.Field&lt;string&gt;("Username"), Name = s.Field&lt;string&gt;("Name"), Email = s.Field&lt;string&gt;("Email"), CreatedDate = s.Field&lt;DateTime&gt;("CreatedDate"), Phone = s.Field&lt;string&gt;("Phone"), City = s.Field&lt;string&gt;("City"), State = s.Field&lt;string&gt;("State"), Country = s.Field&lt;string&gt;("Country") }).FirstOrDefault(); return userInfo; } static DataTable GetUsers() { // Consider these are the data from the SQL table. DataTable table = new DataTable(); table.Columns.Add("Id", typeof(int)); table.Columns.Add("Username", typeof(string)); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Email", typeof(string)); table.Columns.Add("CreatedDate", typeof(DateTime)); table.Columns.Add("Phone", typeof(string)); table.Columns.Add("City", typeof(string)); table.Columns.Add("State", typeof(string)); table.Columns.Add("Country", typeof(string)); // Here we add five DataRows. table.Rows.Add(1, "user1", "David", "user1@gmail.com", DateTime.Now, "9999999999", "City 1", "State 1", "India"); table.Rows.Add(2, "user2", "Sam", "user2@gmail.com", DateTime.Now, "8888888888", "City 2", "State 2", "USA"); table.Rows.Add(3, "user3", "Christoff", "user3@gmail.com", DateTime.Now, "7777777777", "City 3", "State 3", "UK"); table.Rows.Add(4, "user4", "Janet", "user4@gmail.com", DateTime.Now, "6666666666", "City 4", "State 4", "Germany"); table.Rows.Add(5, "user5", "Melanie", "user5@gmail.com", DateTime.Now, "5555555555", "City 5", "State 5", "France"); return table; } } public class User { public int Id {get;set;} public string Username {get;set;} public string Name {get;set;} public string Email {get;set;} public DateTime CreatedDate {get;set;} public string Phone {get;set;} public string City {get;set;} public string State {get;set;} public string Country {get;set;} } </code></pre> <p>Is there any possibility to reuse the below object in LINQ using predicate?</p> <pre><code>new User{ Id = s.Field&lt;int&gt;("Id"), Username = s.Field&lt;string&gt;("Username"), Name = s.Field&lt;string&gt;("Name"), Email = s.Field&lt;string&gt;("Email"), CreatedDate = s.Field&lt;DateTime&gt;("CreatedDate"), Phone = s.Field&lt;string&gt;("Phone"), City = s.Field&lt;string&gt;("City"), State = s.Field&lt;string&gt;("State"), Country = s.Field&lt;string&gt;("Country") } </code></pre> <p>DotNet Fiddle: <a href="https://dotnetfiddle.net/psiBtv" rel="nofollow noreferrer">https://dotnetfiddle.net/psiBtv</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T14:11:48.273", "Id": "397952", "Score": "4", "body": "Please post real code that does compile. This code is incomplete and does not compile. This question seems more suited for stackoverflow. Btw., a solution would be to add a const...
[ { "body": "<p>I've used <strong>Func&lt;></strong> to reuse the object in Linq. Here is the working sample. </p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Linq;\nusing System.Data.DataSetExtensions;\n\npublic class Program\n{\n private static readonly Func&lt;DataRow, User&gt; fnUserInfo ...
{ "AcceptedAnswerId": "206369", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T13:48:09.050", "Id": "206267", "Score": "-1", "Tags": [ "c#", "linq" ], "Title": "Reuse Select Expression in LINQ" }
206267
<p>I read quick sort algorhitm and implemented in like this:</p> <pre><code>public List&lt;Integer&gt; sort(List&lt;Integer&gt; list) { if (list.size() &lt;= 1) { return list; } int pivotalValue = list.get(list.size() / 2); List&lt;Integer&gt; left = new ArrayList&lt;&gt;(); List&lt;Integer&gt; pivotalValues = new ArrayList&lt;&gt;(); List&lt;Integer&gt; right = new ArrayList&lt;&gt;(); for (Integer element : list) { if (element &lt; pivotalValue) { left.add(element); } else if (element &gt; pivotalValue) { right.add(element); } else { pivotalValues.add(element); } } List&lt;Integer&gt; sortedLeft = sort(left); List&lt;Integer&gt; sortedRight = sort(right); sortedLeft.addAll(pivotalValues); sortedLeft.addAll(sortedRight); return sortedLeft; } </code></pre> <p>What do you think about my implementation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T11:21:09.137", "Id": "422970", "Score": "0", "body": "Once upon a time Niklaus Wirth said: _\"Algorithms + Data Structures = Programs\"_. Your code is a nice example how forcing an algorithm on an inappropriate data structure leads ...
[ { "body": "<blockquote>\n <p>What do you think about my implementation?</p>\n</blockquote>\n\n<p>To tell you the truth, I don't think much of your implementation. Instead of in-place swaps you're creating a bunch of temporary lists and combining them after. It probably more closely resembles a merge sort tha...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T14:39:40.517", "Id": "206270", "Score": "2", "Tags": [ "java", "algorithm", "sorting", "quick-sort" ], "Title": "Quicksort implementation with pivotal calculated as middle element" }
206270
<p>I am doing some online exercises, and I came across this: "Your job is to write a program for a speed camera. For simplicity, ignore the details such as camera, sensors, etc and focus purely on the logic. Write a program that asks the user to enter the speed limit. Once set, the program asks for the speed of a car. If the user enters a value less than the speed limit, program should display Ok on the console. If the value is above the speed limit, the program should calculate the number of demerit points. For every 5km/hr above the speed limit, 1 demerit points should be incurred and displayed on the console. If the number of demerit points is above 12, the program should display License Suspended."</p> <pre><code> Console.Write("Speed Limit :"); int speedLimit = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("SPEED LIMIT : " + speedLimit); Console.WriteLine("***********************"); Console.Write("Car Speed : "); int carSpeed = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("CAR SPEED : " + carSpeed); Console.WriteLine("***********************"); Console.WriteLine("***********************"); int demeritPoints = 0; if (carSpeed &lt; speedLimit) { Console.WriteLine("Ok. You are good to go"); } else { int speedDifference = carSpeed - speedLimit; for (int counter = 5; counter &lt;= speedDifference; counter += 1) { if (counter % 5 == 0) { demeritPoints++; } } } Console.Write("Demerit Points :"); Console.WriteLine(demeritPoints); if (demeritPoints &gt;= 12) { Console.WriteLine("Your license is suspended"); } else { Console.WriteLine("You are not suspened"); } </code></pre> <p><a href="https://i.stack.imgur.com/1bUK2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1bUK2.jpg" alt="The program will look like this."></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T15:07:16.560", "Id": "397968", "Score": "1", "body": "`\"You are not suspened\"` People don't get suspen**d**ed. Licenses do. Might want to fix that, including the spelling." } ]
[ { "body": "<p>Not much to say I think, but here goes:</p>\n\n<ul>\n<li>You're using clear, descriptive variable names, which is good. Such names make code easier to understand, which is especially important when you're working on large, complex projects.</li>\n<li>Calculating the number of demerit points can be...
{ "AcceptedAnswerId": "206273", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T14:54:37.407", "Id": "206272", "Score": "1", "Tags": [ "c#", "console" ], "Title": "Program for a speed camera" }
206272
<p>Following code works and i am simply looking for ways to not repeat myself as well keep to code clean and readable. Would love to see what methods that can be utilized to make it prettier.</p> <pre><code>const util = require("util"); const fs = require("fs"); const reader = util.promisify(fs.readFile); const simpleParser = require('mailparser').simpleParser; async function readFile(filepath) { try { return await reader(filepath) } catch (err) { return err } }; async function getAttachment(filepath) { let file, email; try { file = await readFile(filepath); } catch (err) { return err } try { email = await simpleParser(file) return email.attachments[0].content.toString() } catch (err) { return err } } async function getFileName(filepath) { let file, email; try { file = await readFile(filepath); } catch (err) { return err } try { email = await simpleParser(file) return email.attachments[0].filename.toString() } catch (err) { return err } } async function main() { let attachment = await getAttachment('./mock-data/google-report.email') let filename = await getFileName('./mock-data/google-report.email') console.log(filename) } main() module.exports = { getAttachment } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T19:03:51.040", "Id": "398008", "Score": "2", "body": "Welcome to Code Review. Please change the title to be a description of the problem the code is solving instead of what you want changed. On a similar note, giving a little bit of...
[ { "body": "<h1>DRY review</h1>\n<ul>\n<li><p>You don't need to wrap <code>try</code> <code>catch</code> around <code>async function</code> or <code>promise</code>. The errors will all get passed onto the final <code>promise.catch</code>. So can remove all 5 try catches.</p>\n</li>\n<li><p>The function <code>rea...
{ "AcceptedAnswerId": "206296", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T18:50:25.047", "Id": "206287", "Score": "0", "Tags": [ "javascript" ], "Title": "What is an optimal way of not repeating myself in the following code?" }
206287
<p>Recently I wrote a back_inserter with the same interface as the <a href="https://en.cppreference.com/w/cpp/iterator/back_insert_iterator" rel="nofollow noreferrer">std::back_inserter</a> just for supporting several containers in the constructor and doing push_back for each. The solution needs C++17. Please give me some feedback! Thanks.</p> <pre><code>#include &lt;iterator&gt; #include &lt;tuple&gt; namespace stx { template &lt;class Container, class... Containers&gt; class back_insert_iterator { public: using value_type = void; using difference_type = void; using pointer = void; using reference = void; using iterator_category = std::output_iterator_tag; explicit back_insert_iterator(Container&amp; container, Containers&amp;... containers) : containers(container, containers...) { } back_insert_iterator&amp; operator=(const typename Container::value_type&amp; value) { std::apply([&amp;](auto&amp;... container) { ((container.push_back(value)), ...); }, containers); return *this; } back_insert_iterator&amp; operator=(typename Container::value_type&amp;&amp; value) { std::apply([&amp;](auto&amp;... container) { ((container.push_back(std::move(value))), ...); }, containers); return *this; } back_insert_iterator&amp; operator*() { return *this; } back_insert_iterator&amp; operator++() { return *this; } back_insert_iterator&amp; operator++(int) { return *this; } private: std::tuple&lt;Container&amp;, Containers&amp;...&gt; containers; }; template &lt;class Container, class... Containers&gt; auto back_inserter(Container&amp; container, Containers&amp;... containers) { return back_insert_iterator&lt;Container, Containers...&gt;(container, containers...); } } </code></pre> <p>And you can use it like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; auto main() -&gt; int { const auto numbers = std::vector&lt;int&gt;{ 1, 2, 3, 4, 5 }; std::vector&lt;int&gt; copy1, copy2; std::copy(numbers.begin(), numbers.end(), stx::back_inserter(copy1, copy2)); std::cout &lt;&lt; "(numbers == copy1) = " &lt;&lt; std::boolalpha &lt;&lt; (numbers == copy1) &lt;&lt; '\n'; std::cout &lt;&lt; "(numbers == copy2) = " &lt;&lt; std::boolalpha &lt;&lt; (numbers == copy2) &lt;&lt; '\n'; }; </code></pre> <p>A front_inserter would of course look similar, just calling push_front instead. Some specific additional questions:</p> <ul> <li>does the operator= method with the r-value work as intended or do I need to pass the value differently to the lambda?</li> <li>do I need an extra static_assert to check that each Container supports the same value_type or at least some that are convertible to avoid overloading the user with template errors in case they are different?</li> <li>is there another solution where I could let the user provide and optional argument for execution policy, for example std::execution::par</li> <li>the original std::back_inserter saves the container as pointer - is there any advantage versus my inserter which saves them per reference? </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T08:37:35.420", "Id": "398039", "Score": "2", "body": "> `(container.push_back(std::move(value))), ...)`: moving `value`'s content several times is a bad idea. After the first move, `value`'s state is valid but unspecified. It doesn'...
[ { "body": "<p>The general structure seems fine to me. However, some things can still be improved!</p>\n<h1>Iterator requirements</h1>\n<p><a href=\"https://en.cppreference.com/w/cpp/named_req/Iterator\" rel=\"nofollow noreferrer\">Iterators</a> are required to satisfy the <a href=\"https://en.cppreference.com/w...
{ "AcceptedAnswerId": "206305", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T18:58:16.303", "Id": "206288", "Score": "4", "Tags": [ "c++", "iterator", "c++17" ], "Title": "back_inserter for several container arguments" }
206288
<p>I made a rock climbing simulator game for fun. Below is a function from the program, which works. But I can't help but think it could be refactored or more pythonic. </p> <p>Namely, I open the data with <code>csv.DictReader</code> and read through the data, which add to a blank dictionary called route_info. Is this step necessary?</p> <p>The function has a with-open block, which opens a .csv file, but a link to the data is <a href="https://github.com/epurpur/Seneca-Gumbies/blob/master/SenecaGumbiesCode/seneca_routes.csv" rel="nofollow noreferrer">here</a>.</p> <pre><code>import csv import time routes_climbed = [] pitches_climbed = 0 def choose_route(): """After deciding about the weather, you come here and choose a route to climb. Reads list of routes from .csv file with names, grades, and pitches.""" global routes_climbed, pitches_climbed route_info = {} with open('seneca_routes.csv', 'r', encoding='utf-8-sig') as f: #weird encoding from excel? reader = csv.DictReader(f, ('route_name', 'route_grade', 'pitches')) print("Choose a route to climb from the following list of classics.") print() for row in reader: print(row['route_name'],row['route_grade']) route_info[row['route_name']] = row['pitches'] route_choice = input("Which route do you want to climb? : ") if route_choice in route_info.keys(): routes_climbed.append(route_choice) pitches_climbed += int(route_info[route_choice]) climb_route(route_choice) else: print("Incorrect route name") time.sleep(3) choose_route() choose_route() </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li>Pass the code through at least one linter such as pycodestyle or flake8 to get more idiomatic Python.</li>\n<li>Don't use <code>global</code>. Returning two values, while ugly, is preferable to having global state.</li>\n<li>You can add <code>\\n</code> to the en...
{ "AcceptedAnswerId": "206304", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T19:43:37.140", "Id": "206290", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Adding values from DictReader to empty dictionary" }
206290
<p>This jQuery code submits a form using AJAX. The server response should return JSON.</p> <pre><code>addNewOutreach = function(node) { var form = node.find('form'); var data = form.serialize(); $.post('ajax.php', {action:'addNewOutreach',string:data}, function(response) { if(response!=null &amp;&amp; response.status=='success') { message_return('success',response.message); unfreezeModal(node); node.modal('hide'); } else if(response!=null &amp;&amp; response.status=='error') { message_return('error',response.message); unfreezeModal(node); } else { message_return('error','Error saving outreach.'); unfreezeModal(node); } },'json'); } </code></pre> <p><code>message_return()</code> is a function that displays feedback on the page.</p> <p><code>unfreezeModal()</code> is a function that locks the form (avoiding double submits) until the request is finished.</p> <p>Where this code lacks:</p> <ul> <li>What if the server does not respond with valid JSON?</li> <li>What if the AJAX request keeps hanging?</li> <li>The <code>function(response)</code> block can probably be isolated from this block so it can be used in other AJAX request</li> <li>Can probably be written cleaner with Promises</li> </ul>
[]
[ { "body": "<ol>\n<li><p>You should first check if the response is null. If not, then check for a success or error response.</p></li>\n<li><p>You can use a <code>try</code>-<code>catch</code> block to check if it is valid JSON:</p>\n\n<pre><code>Try{\n JSON.parse(response);\n catch(Exception){\n console...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T20:24:30.163", "Id": "206291", "Score": "0", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "jQuery AJAX submit form" }
206291
<p>In this program you have to solve 20 exercises. The time you need will be measured. If you break a record, you'll get an entry in the highscore list.</p> <p><a href="https://www.dropbox.com/s/sowvhn0010jinn9/Mathematician.jar?dl=0" rel="nofollow noreferrer">The program can be downloaded here.</a> You can only start it via command line, not by double-click.</p> <p>If I can improve my code to make it more readable, please tell me how.</p> <p><strong>Main.java</strong></p> <pre><code>import java.time.Duration; import java.time.Instant; import java.util.Scanner; import java.io.File; import java.io.ObjectOutputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.IOException; public class Main { public static void main(String[] args) { new Main().mainLoop(); } private static String saveName = ".mathematicianSave"; private static Scanner scanner = new Scanner(System.in); private RecordList recordList; public Main() { if (new File(saveName).exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(saveName))) { recordList = (RecordList)ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { recordList = new RecordList(5); } } private void mainLoop() { System.out.println("[0] Leave\n"); while(true) { System.out.println("[1] Play"); System.out.println("[2] Highscore"); System.out.print("Input: "); String decision = scanner.nextLine(); System.out.println(); if (decision.equals("1")) { calculate(); } else if (decision.equals("2")) { showHighscore(); } else if (decision.equals("0")) { save(); break; } } } private void calculate() { System.out.println("Division exercises have to be solved without rest."); System.out.println("You have to solve twenty exercises."); System.out.println("Be as fast as you can!\n"); Instant startTime = Instant.now(); for (int i = 0; i &lt; 20; i++) { Exercise exercise = Exercise.getRandomExercise(); System.out.print(exercise); int guess = Integer.parseInt(scanner.nextLine()); exercise.solve(guess); if (!exercise.solve(guess)) { System.out.println("\nYou have made a mistake."); System.out.println("More luck next time.\n"); return; } } System.out.println(); Instant endTime = Instant.now(); Duration timeElapsed = Duration.between(startTime, endTime); double seconds = timeElapsed.toMillis() / 1000.0; Record record = new Record(seconds); System.out.println("You have needed " + seconds + " seconds."); if (recordList.add(record)) { System.out.println("You have set a new record!"); System.out.print("Your name: "); record.setName(scanner.nextLine()); } System.out.println(); } private void showHighscore() { System.out.println(recordList); } private void save() { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(saveName))) { oos.writeObject(recordList); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p><strong>Exercise.java</strong></p> <pre><code>import java.util.Random; public class Exercise { private int number1; private int number2; private int solution; private String operationSymbol; private Exercise(int number1, int number2, int solution, String operationSymbol) { this.number1 = number1; this.number2 = number2; this.solution = solution; this.operationSymbol = operationSymbol; } public static Exercise getRandomExercise() { Random random = new Random(); int choice = random.nextInt(4); int number1; int number2; int solution; String operationSymbol; if (choice == 0) { number1 = random.nextInt(26); number2 = random.nextInt(26); solution = number1 + number2; operationSymbol = "+"; } else if (choice == 1) { number1 = random.nextInt(16) + 10; number2 = random.nextInt(26); solution = number1 - number2; operationSymbol = "-"; } else if (choice == 2) { number1 = random.nextInt(15) + 1; number2 = random.nextInt(15) + 1; solution = number1 * number2; operationSymbol = "*"; } else { number1 = random.nextInt(151); number2 = random.nextInt(15) + 1; solution = number1 / number2; operationSymbol = "/"; } return new Exercise(number1, number2, solution, operationSymbol); } public boolean solve(int guess) { return solution == guess; } @Override public String toString() { return number1 + " " + operationSymbol + " " + number2 + " = "; } } </code></pre> <p><strong>Record.java</strong></p> <pre><code>import java.io.Serializable; public class Record implements Serializable { private String name; private double seconds; public Record(double seconds) { name = null; this.seconds = seconds; } public Record(String name, double seconds) { this.name = name; this.seconds = seconds; } public void setName(String name) { this.name = name; } public String getName() { return name; } public double getSeconds() { return seconds; } } </code></pre> <p><strong>RecordList.java</strong></p> <pre><code>import java.util.Comparator; import java.util.List; import java.util.ArrayList; import java.io.Serializable; public class RecordList implements Serializable { private List&lt;Record&gt; records; private int limit; public RecordList(int limit) { records = new ArrayList&lt;&gt;(); this.limit = limit; } private void sort() { records.sort(new Comparator&lt;Record&gt;() { @Override public int compare(Record record1, Record record2) { Double double1 = record1.getSeconds(); Double double2 = record2.getSeconds(); return double1.compareTo(double2); } }); } public boolean add(Record record) { if (records.size() &lt; limit) { records.add(record); sort(); return true; } Record lowestRecord = records.get(records.size() - 1); if (record.getSeconds() &lt; lowestRecord.getSeconds()) { records.remove(lowestRecord); records.add(record); sort(); return true; } return false; } @Override public String toString() { if (records.isEmpty()) { return "No records.\n"; } StringBuilder returnValue = new StringBuilder("--- Records ---\n\n"); for (int i = 0; i &lt; records.size(); i++) { returnValue.append(i+1); returnValue.append(". "); returnValue.append(records.get(i).getName()); returnValue.append(" - "); returnValue.append(records.get(i).getSeconds()); returnValue.append("\n"); } return returnValue.toString(); } } </code></pre>
[]
[ { "body": "<p>I find your code very readable.</p>\n\n<ul>\n<li>\"Division exercises have to be solved without rest\" should instead read \"division exercises should be solved without remainders\" or something. \"without rest\" doesn't mean anything to me.</li>\n<li>It is crashing when symbols like / and . are...
{ "AcceptedAnswerId": "206299", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T21:25:33.550", "Id": "206292", "Score": "1", "Tags": [ "java", "timer", "quiz" ], "Title": "Timed arithmetic quiz" }
206292
<p>I wrote the equivalent to the split() in python for C++. I would like to know how I can make it better:</p> <pre><code>static constexpr auto whitespace = " \t\v\r\n\f"; static constexpr auto npos = std::string::npos; std::vector&lt;std::string&gt; split(std::string_view str, std::string_view sep = "", std::size_t maxsplit = std::numeric_limits&lt;std::size_t&gt;::max()) { std::vector&lt;std::string&gt; result; if (sep.empty()) { for (std::size_t start = str.find_first_not_of(whitespace), splits = 0; start != npos; ++splits) { if (auto end = str.find_first_of(whitespace, start); end != npos &amp;&amp; splits &lt; maxsplit) { result.emplace_back(str.substr(start, end - start)); start = str.find_first_not_of(whitespace, end); } else { result.emplace_back(str.substr(start)); break; } } } else { for (std::size_t start = 0, splits = 0; start &lt; str.size(); ++splits) { if (auto end = str.find(sep, start); end != npos &amp;&amp; splits &lt; maxsplit) { result.emplace_back(str.substr(start, end - start)); start = end + sep.size(); } else { result.emplace_back(str.substr(start)); break; } } } return result; } </code></pre> <p>I tried to keep all variables as local as possible and use standard algorithms.</p>
[]
[ { "body": "<p>I would use a const reference here:</p>\n\n<pre><code>static constexpr auto npos = std::string::npos;\n\n// I would do this.\nstatic constexpr auto const&amp; npos = std::string::npos;\n</code></pre>\n\n<p>No point in duplicating storage.<br>\nAlso declaring global variables is a frowned upon. Esp...
{ "AcceptedAnswerId": "206971", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T22:06:17.810", "Id": "206297", "Score": "2", "Tags": [ "c++", "strings" ], "Title": "C++ split function (equivalent to python string.split())" }
206297
<p>Not much formal education in programming. One year in school. We did C++ classes for most user defined objects. I've written a few different class variations for matrices but wonder about how useful that really is. Array pointers vs. STL containers, all this wrapper around an array or <code>std::&lt;vector&gt;</code> or <code>std::vector&lt;std::vector&gt;&gt;</code>.</p> <p>So I decided maybe a struct, but then found myself with the same thought. The struct just made accessing the point of the matrix (the underlying data) more annoying.</p> <p>I wrote this namespace instead to have a bunch of vector operators and just use a typedef, but wonder if there are some downsides? Also, is it possible to not have to <code>typedef</code> and declare the <code>using LMath::operator+</code> in the main .cpp? So if the main function <code>#include "LMath.H"</code> (crrently Matrix.h, found out can't <code>typedef</code> <code>Matrix</code> AND call the namespace <code>Matrix::</code>).</p> <p>Matrix.h</p> <pre><code>#include &lt;vector&gt; namespace LMath { typedef std::vector&lt;std::vector&lt;float&gt;&gt; Matrix; typedef std::vector&lt;float&gt; Vector; void printMatrix(const Matrix&amp;); Matrix createMatrix(const Vector&amp;, int rows, int cols); Matrix createMatrix(const Matrix&amp;); Matrix transpose(const Matrix&amp;); Matrix dotMatrix(const Matrix&amp;,const Matrix&amp;); Matrix addMatrix(const Matrix&amp;,const Matrix&amp;); Matrix multMatrix(float,const Matrix&amp;); Matrix hadamard(const Matrix&amp;,const Matrix&amp;); Matrix concat(const Matrix&amp;,const Matrix&amp;); Matrix stack(const Matrix&amp;,const Matrix&amp;); Matrix subtractMatrix(const Matrix&amp;,const Matrix&amp;); bool isEqual(const Matrix&amp;,const Matrix&amp;); bool operator==(const Matrix&amp;,const Matrix&amp;); Matrix operator+(const Matrix&amp;,const Matrix&amp;); //Matrix operator-(const Matrix&amp;,const Matrix&amp;); //Matrix operator*(const Matrix&amp;,const Matrix&amp;); //Matrix operator*(float,const Matrix&amp;); float dotVectors(const Vector&amp;,const Vector&amp;); Vector subVectors(const Vector&amp;,const Vector&amp;); } </code></pre> <p>Matrix.cpp</p> <pre><code>#include "Matrix.h" #include &lt;iostream&gt; #include &lt;vector&gt; namespace LMath { typedef std::vector&lt;std::vector&lt;float&gt;&gt; Matrix; typedef std::vector&lt;float&gt; Vector; void printMatrix(const Matrix&amp; matrix) { for(unsigned int i = 0; i &lt; matrix.size(); i++) { for(unsigned int j = 0; j &lt; matrix[i].size(); j++) std::cout &lt;&lt; matrix[i][j] &lt;&lt; ", "; std::cout &lt;&lt; std::endl; } return; } //This function was a lot more useful when I was not just the 2d vector directly as a matrix... //Might have some utility still.. Matrix createMatrix(const Vector &amp; data, int rows, int cols) { Matrix matrix; Vector temp; for(unsigned int i = 0; i &lt; data.size(); i++) { temp.push_back(data[i]); if((i+1) % cols == 0) { matrix.push_back(temp); temp.clear(); } } return matrix; } //This function was a lot more useful when I was not using the 2d vector directly as a matrix... //Now it's really just a copy function. Matrix createMatrix(const Matrix&amp; formattedMatrix) { Matrix matrix; int Cols = formattedMatrix[0].size(); Vector temp; for(unsigned int i = 0; i &lt; formattedMatrix.size(); i++) { for(unsigned int j = 0; j &lt; formattedMatrix[0].size(); j++) { if(Cols != formattedMatrix[i].size()) { std::cout &lt;&lt; "Irregular Matrix Detectd!" &lt;&lt; std::endl &lt;&lt; "Not allowed!" &lt;&lt; std::endl; matrix.clear(); temp.clear(); temp.push_back(0); matrix.push_back(temp); return matrix; } temp.push_back(formattedMatrix[i][j]); } matrix.push_back(temp); temp.clear(); } return matrix; } Matrix transpose(const Matrix &amp; matrix) { Vector temp; Matrix transposeMatrix; for(unsigned int i = 0; i &lt; matrix[0].size(); i++) { for(unsigned int j = 0; j &lt; matrix.size(); j++) { temp.push_back(matrix[j][i]); } transposeMatrix.push_back(temp); temp.clear(); } return transposeMatrix; } Matrix dotMatrix(const Matrix&amp; lhs,const Matrix&amp; rhs) { if(lhs[0].size() != rhs.size()) { std::cout &lt;&lt; "ERROR: Matrix incompatible for dot product" &lt;&lt; std::endl; std::cout &lt;&lt; "Operation requested: Mat[" &lt;&lt; lhs.size() &lt;&lt; "x" &lt;&lt; lhs[0].size() &lt;&lt; "] . Mat[" &lt;&lt; rhs.size() &lt;&lt; "x" &lt;&lt; rhs[0].size() &lt;&lt; "]" &lt;&lt; std::endl; Vector temp; temp.push_back(0.0f); return createMatrix(temp,1,1); } Matrix matrix; Vector temp; for(unsigned int k = 0; k &lt; lhs.size(); k++) { for(unsigned int i = 0; i &lt; rhs[0].size(); i++) { Vector tempRHS; for(unsigned int j = 0; j &lt; rhs.size(); j++) { tempRHS.push_back(rhs[j][i]); } temp.push_back(dotVectors(lhs[k],tempRHS)); } matrix.push_back(temp); temp.clear(); } return matrix; } Matrix addMatrix(const Matrix&amp; lhs,const Matrix&amp; rhs) { Matrix matrix; Vector temp; if(lhs.size() != rhs.size() || lhs[0].size() != rhs[0].size()) { std::cout &lt;&lt; "WARNING: matrices are not compatible for addition!" &lt;&lt; std::endl; std::cout &lt;&lt; "Operation requested: Mat[" &lt;&lt; lhs.size() &lt;&lt; "x" &lt;&lt; lhs[0].size() &lt;&lt; "] + Mat[" &lt;&lt; rhs.size() &lt;&lt; "x" &lt;&lt; rhs[0].size() &lt;&lt; "]" &lt;&lt; std::endl; temp.push_back(0.0f); return createMatrix(temp,1,1); } for(unsigned int i = 0; i &lt; lhs.size(); i++) { for(unsigned int j = 0; j &lt; lhs[i].size(); j++) { temp.push_back(lhs[i][j]+rhs[i][j]); } matrix.push_back(temp); temp.clear(); } return matrix; } Matrix multMatrix(float scalar,const Matrix&amp; matrix) { Matrix scaledMatrix; Vector temp; for(unsigned int i = 0; i &lt; matrix.size(); i++) { for(unsigned int j = 0; j &lt; matrix[i].size(); j++) { temp.push_back(matrix[i][j]*scalar); } scaledMatrix.push_back(temp); temp.clear(); } return scaledMatrix; } Matrix hadamard(const Matrix&amp; lhs,const Matrix&amp; rhs) { if(lhs.size() != rhs.size() || lhs[0].size() != rhs[0].size()) { std::cout &lt;&lt; "WARNING: matrices are not compatible for Hadamard Multiplication!" &lt;&lt; std::endl; std::cout &lt;&lt; "Operation requested: Mat[" &lt;&lt; lhs.size() &lt;&lt; "x" &lt;&lt; lhs[0].size() &lt;&lt; "] * Mat[" &lt;&lt; rhs.size() &lt;&lt; "x" &lt;&lt; rhs[0].size() &lt;&lt; "]" &lt;&lt; std::endl; Vector temp; temp.push_back(0.0f); return createMatrix(temp,1,1); } Matrix matrix; Vector temp; for(unsigned int i = 0; i &lt; lhs.size(); i++) { for(unsigned int j = 0; j &lt; lhs[i].size(); j++) { temp.push_back(lhs[i][j]*rhs[i][j]); } matrix.push_back(temp); temp.clear(); } return matrix; } Matrix concat(const Matrix&amp; lhs,const Matrix&amp; rhs) { if(lhs.size() != rhs.size()) { std::cout &lt;&lt; "WARNING: matrices are not compatible for concatenation" &lt;&lt; std::endl; std::cout &lt;&lt; "Operation requested: Mat[" &lt;&lt; lhs.size() &lt;&lt; "x" &lt;&lt; lhs[0].size() &lt;&lt; "] + Mat[" &lt;&lt; rhs.size() &lt;&lt; "x" &lt;&lt; rhs[0].size() &lt;&lt; "]" &lt;&lt; std::endl; Vector temp; temp.push_back(0.0f); return createMatrix(temp,1,1); } Matrix matrix; Vector temp; for(unsigned int i = 0; i &lt; lhs.size(); i++) { for(unsigned int j = 0; j &lt; lhs[i].size(); j++) { temp.push_back(lhs[i][j]); } for(unsigned int j = 0; j &lt; rhs[i].size(); j++) { temp.push_back(rhs[i][j]); } matrix.push_back(temp); temp.clear(); } return matrix; } Matrix stack(const Matrix&amp; lhs,const Matrix&amp; rhs) { if(lhs[0].size() != rhs[0].size()) { std::cout &lt;&lt; "WARNING: matrices are not compatible for stacking" &lt;&lt; std::endl; std::cout &lt;&lt; "Operation requested: Mat[" &lt;&lt; lhs.size() &lt;&lt; "x" &lt;&lt; lhs[0].size() &lt;&lt; "] on Mat[" &lt;&lt; rhs.size() &lt;&lt; "x" &lt;&lt; rhs[0].size() &lt;&lt; "]" &lt;&lt; std::endl; Vector temp; temp.push_back(0.0f); return createMatrix(temp,1,1); } Matrix temp; for(unsigned int i = 0; i &lt; lhs.size(); i++) { temp.push_back(lhs[i]); } for(unsigned int i = 0; i &lt; rhs.size(); i++) { temp.push_back(rhs[i]); } return temp; } Matrix subtractMatrix(const Matrix&amp; lhs,const Matrix&amp; rhs) { if(lhs.size() != rhs.size() || lhs[0].size() != rhs[0].size()) { std::cout &lt;&lt; "WARNING: matrices are not compatible for subtraction!" &lt;&lt; std::endl; std::cout &lt;&lt; "Operation requested: Mat[" &lt;&lt; lhs.size() &lt;&lt; "x" &lt;&lt; lhs[0].size() &lt;&lt; "] - Mat[" &lt;&lt; rhs.size() &lt;&lt; "x" &lt;&lt; rhs[0].size() &lt;&lt; "]" &lt;&lt; std::endl; Vector temp; temp.push_back(0.0f); return createMatrix(temp,1,1); } Matrix matrix; Vector temp; for(unsigned int i = 0; i &lt; lhs.size(); i++) { for(unsigned int j = 0; j &lt; lhs[i].size(); j++) { temp.push_back(lhs[i][j] - rhs[i][j]); } matrix.push_back(temp); temp.clear(); } return matrix; } bool isEqual(const Matrix&amp; lhs, const Matrix&amp; rhs) { if(lhs.size() != rhs.size() || lhs[0].size() != rhs[0].size()) return false; for(unsigned int i = 0; i &lt; lhs.size(); i++) { for(unsigned int j = 0; j &lt; lhs[0].size(); j++) { if(lhs[i][j] != rhs[i][j]) return false; } } return true; } float dotVectors(const Vector&amp; vec1,const Vector&amp; vec2) { if(vec1.size() != vec2.size()) { std::cout &lt;&lt; "ERROR: Vectors of unequal size!" &lt;&lt; std::endl; return 0.0f; } float temp = 0.0f; for(unsigned int i = 0; i &lt; vec1.size(); i++) { temp += vec1[i] * vec2[i]; } return temp; } Vector subVectors(const Vector&amp; lhs,const Vector&amp; rhs) { Vector temp; if(lhs.size() != rhs.size()) { std::cout &lt;&lt; "ERROR: Vectors of unequal size!" &lt;&lt; std::endl; return temp; } for(unsigned int i = 0; i &lt; lhs.size(); i++) { temp.push_back(lhs[i] - rhs[i]); } return temp; } Matrix operator+(const Matrix&amp; lhs,const Matrix&amp; rhs) { return addMatrix(lhs,rhs); } bool operator==(const Matrix&amp; lhs, const Matrix&amp; rhs) { return isEqual(lhs,rhs); } } </code></pre> <p>Souce.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "Matrix.h" #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; //TODO: Find alternatives to these... typedef std::vector&lt;std::vector&lt;float&gt;&gt; Matrix; typedef std::vector&lt;float&gt; Vector; using LMath::operator+; using LMath::operator==; void testMatrix(); //testing function. Matrix loadData(std::string); //Not implemented yet bool saveData(Matrix, std::string); //Not implemented yet int main() { testMatrix(); return 0; } Matrix loadData(std::string) { //TODO: Implement file loading and data parsing Matrix matrix; return matrix; } bool saveData(Matrix, std::string) { return true; } void testMatrix() { std::vector&lt;float&gt; temp; temp.push_back(1.0); temp.push_back(1.0); temp.push_back(1.0); temp.push_back(0.0); temp.push_back(1.0); temp.push_back(1.0); temp.push_back(1.0); temp.push_back(0.0); temp.push_back(1.0); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 1 (3 rows, 3 cols): " &lt;&lt; std::endl; Matrix matrix1 = LMath::createMatrix(temp,3,3); LMath::printMatrix(matrix1); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 2 (3 rows, 3 cols): " &lt;&lt; std::endl; Matrix matrix2 = LMath::transpose(matrix1); LMath::printMatrix(matrix2); temp.clear(); temp.push_back(1.0); temp.push_back(1.0); temp.push_back(1.0); temp.push_back(0.0); temp.push_back(1.0); temp.push_back(1.0); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 3 (2 rows, 3 cols): " &lt;&lt; std::endl; Matrix matrix3 = LMath::createMatrix(temp, 2, 3); LMath::printMatrix(matrix3); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 4 (3 rows, 2 cols): " &lt;&lt; std::endl; Matrix matrix4 = LMath::transpose(matrix3); LMath::printMatrix(matrix4); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 5 (3 rows, 3 cols) = Matrix1 . Matrix2" &lt;&lt; std::endl; Matrix matrix5 = LMath::dotMatrix(matrix1,matrix2); LMath::printMatrix(matrix5); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 6 (2 rows, 2 cols) = Matrix3 . Matrix4" &lt;&lt; std::endl; Matrix matrix6 = LMath::dotMatrix(matrix3,matrix4); LMath::printMatrix(matrix6); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 7 (3 rows, 3 cols) = Matrix4 . Matrix3" &lt;&lt; std::endl; Matrix matrix7 = LMath::dotMatrix(matrix4,matrix3); LMath::printMatrix(matrix7); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 8 (Error Test) = Matrix1 . Matrix3" &lt;&lt; std::endl; Matrix matrix8 = LMath::dotMatrix(matrix1,matrix3); LMath::printMatrix(matrix8); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 9 (3 rows, 3 cols) = Matrix1 + Matrix2" &lt;&lt; std::endl; Matrix matrix9 = LMath::addMatrix(matrix1, matrix2); LMath::printMatrix(matrix9); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 10 (3 rows, 3 cols) = -1 * Matrix9" &lt;&lt; std::endl; Matrix matrix10 = LMath::multMatrix(-1, matrix9); LMath::printMatrix(matrix10); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 11 (3 rows, 3 cols) = Matrix9 + Matrix10" &lt;&lt; std::endl; Matrix matrix11 = LMath::addMatrix(matrix9, matrix10); LMath::printMatrix(matrix11); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 12 (3 rows, 3 cols) = Hadamard(Matrix1 * Matrix9)" &lt;&lt; std::endl; Matrix matrix12 = LMath::hadamard(matrix1, matrix9); LMath::printMatrix(matrix12); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 13 (3 rows, 3 cols) = concat(Matrix1 + Matrix2)" &lt;&lt; std::endl; Matrix matrix13 = LMath::concat(matrix1, matrix2); LMath::printMatrix(matrix13); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 14 (5 rows, 3 cols) = stack(Matrix2 + Matrix3)" &lt;&lt; std::endl; Matrix matrix14 = LMath::stack(matrix2, matrix3); LMath::printMatrix(matrix14); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 15 (Error Test) = stack(Matrix2 + Matrix8)" &lt;&lt; std::endl; Matrix matrix15 = LMath::stack(matrix2, matrix8); LMath::printMatrix(matrix15); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 16 (3x3) = createMatrix(formatted vector matrix)" &lt;&lt; std::endl; std::vector&lt;std::vector&lt;float&gt;&gt; formattedMat; temp.clear(); for(int j = 0; j &lt; 3; j++) { for(int i = 0; i &lt; 3; i++) { temp.push_back((float)(i+2*j)); } formattedMat.push_back(temp); temp.clear(); } Matrix matrix16 = LMath::createMatrix(formattedMat); LMath::printMatrix(matrix16); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 17 (Error Test) = createMatrix(formatted vector matrix)" &lt;&lt; std::endl; formattedMat[1].pop_back(); Matrix matrix17 = LMath::createMatrix(formattedMat); LMath::printMatrix(matrix17); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix16 again:" &lt;&lt; std::endl; LMath::printMatrix(matrix16); std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 18 (3x3) = Matrix16 - Matrix1" &lt;&lt; std::endl; Matrix matrix18 = LMath::subtractMatrix(matrix16,matrix1); LMath::printMatrix(matrix18); //Todo: Implement Load/Save matrices //std::cout &lt;&lt; std::endl &lt;&lt; "Matrix 19 (3x3) - Load/Save data" &lt;&lt; std::endl; //std::cout &lt;&lt; saveData(matrix18,"Meh.data"); //Matrix matrix19 = loadData("Meh.data"); //LMath::printMatrix(matrix19); Matrix matrix20, matrix21, matrix22; Vector vec, vec2, vec3; for(unsigned int i = 0; i &lt; 3; i++) { vec.clear(); vec2.clear(); vec3.clear(); for(unsigned int j = 0; j &lt; 3; j++) { float temp = float(i+j); vec.push_back(temp); vec2.push_back(2*temp); vec3.push_back(3*temp); } matrix20.push_back(vec); matrix21.push_back(vec2); matrix22.push_back(vec3); } Matrix matrix23 = matrix20 + matrix21; if(matrix22 == matrix23) std::cout &lt;&lt; "Operators success" &lt;&lt; std::endl; else std::cout &lt;&lt; "Operators failure" &lt;&lt; std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T18:12:20.923", "Id": "398089", "Score": "0", "body": "std::vector<std::vector<float>> is not the way I'd do it, what happens if the inner vectors contain a different number of elemens each? not just that, you're having multiple allo...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T23:33:45.207", "Id": "206301", "Score": "2", "Tags": [ "c++", "beginner", "matrix", "namespaces" ], "Title": "C++ matrix operations" }
206301
<p>I have ack (the searching tool) "installed" as a single file at <code>C:\ack\bin\ack.pl</code> on a Windows 10 machine and was wondering how to make it executable from the powershell window and other terminals.</p> <p>I wanted to do it ideally without touching the <code>PATHEXT</code> variable and associating an interpreter to the extension because that has system-wide consequences. I'm only really after a shebang workalike.</p> <p>First I wrote a batch script wrapper around it (<code>ack.bat</code>).</p> <pre><code>@echo off perl.exe %~dp0\ack.pl %* </code></pre> <p>But that has the annoying property of handling interruptions via <code>^C</code> with an <code>are you sure?</code> prompt.</p> <pre><code>Terminate batch job (Y/N)? y </code></pre> <p>I was curious how to make something interruptible without prompting and tried looking for an equivalent of the <code>exec*</code> system calls on Windows. Then I came across <a href="https://serverfault.com/a/567393/388804">this answer on ServerFault</a> which complains about the same problem and suggests generating a C program as a potential solution. </p> <p>I wrote a C++ wrapper that does the trick, but it turned out quite a bit uglier than I would have liked.</p> <hr> <pre><code>// The strings in this file are UTF-16LE for compat with the win32 api // The source code itself is in UTF-8. #include &lt;windows.h&gt; // GetCommandLineW #include &lt;iostream&gt; // wcout #include &lt;string&gt; // wstring #include &lt;cassert&gt; // assert #include &lt;utility&gt; // pair #include &lt;deque&gt; // deque, size_type // always debug. Assert is only used when we actually want to // crash the wrapper process. #undef NDEBUG // unsigned index type, probably good enough for traversing // a vector or deque typedef std::deque&lt;char&gt;::size_type uidx; // interpreter_name must be absolute path std::wstring interpreter_name = %%%%INTERPETER_NAME%%%% ; std::wstring script_name = %%%%SCRIPT_NAME%%%% ; class Reaper { public: HANDLE job_handle; JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info; Reaper() { job_handle = CreateJobObject(NULL, NULL); assert(job_handle != NULL); limit_info = { 0 }; limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; DWORD set_success = SetInformationJobObject( job_handle, JobObjectExtendedLimitInformation, &amp;limit_info, sizeof(limit_info)); assert(set_success); } }; Reaper&amp; get_reaper(void) { static Reaper r; return r; } // the leading int is the error code. std::pair&lt;DWORD, std::deque&lt;std::wstring&gt;&gt; argvw_of_cmdline(std::wstring command_line) { LPCWSTR cmd_line = command_line.c_str(); int count = 0; LPWSTR *the_processed_args = CommandLineToArgvW( cmd_line, &amp;count ); // first we handle the error case if (the_processed_args == nullptr) { return {GetLastError(), std::deque&lt;std::wstring&gt;()}; } else { std::deque&lt;std::wstring&gt; s; for (int i = 0; i &lt; count; ++i) { s.push_back(the_processed_args[i]); } return {0, s}; } } std::wstring escape_string(std::wstring ws) { bool contains_suspect_char = (std::wstring::npos != ws.find_first_of(L"\"" L"\\")); if (contains_suspect_char) { std::wstring out(L"\""); for (uidx i = 0; i &lt; ws.size(); ++i) { if (ws[i] == L'"' || ws[i] == L'\\') { out += L'\\'; out += ws[i]; } else { out += ws[i]; } } out += L'"'; return out; } else { return ws; } } std::wstring cmdline_of_argvw(const std::deque&lt;std::wstring&gt; &amp;argvw) { std::wstring the_line(L""); // this is okay even if the deque is empty // because the loop will be traversed zero times. uidx last_index = argvw.size() - 1; for (uidx i = 0; i &lt; argvw.size() ; i++) { the_line += escape_string(argvw[i]); if (i != last_index) { the_line += L' '; } } return the_line; } struct RawWinProcessCreatorW { LPCWSTR app_name = NULL; LPWSTR command_line = NULL; LPSECURITY_ATTRIBUTES process_attributes = NULL; LPSECURITY_ATTRIBUTES thread_attributes = NULL; BOOL inherit_handles = false; DWORD creation_flags = 0; LPVOID environment = NULL; LPCWSTR current_directory = NULL; LPSTARTUPINFOW startup_info = NULL; LPPROCESS_INFORMATION process_information = NULL; bool run() { return CreateProcessW( app_name, command_line, process_attributes, thread_attributes, inherit_handles, creation_flags, environment, current_directory, startup_info, process_information ); } }; std::wstring current_exe_directory(void) { HMODULE h_module = GetModuleHandleW(nullptr); WCHAR path[MAX_PATH]; memset(path, 0, sizeof(path)); GetModuleFileNameW(h_module, path, MAX_PATH); std::wstring w_path(path); // if the last character is a path separator // remove it. if (w_path.back() == L'\\') { w_path.pop_back(); } // keep popping until the last character is a \ -- thwart line continuation while (!w_path.empty()) { if (w_path.back() == L'\\') { w_path.pop_back(); return w_path; } else { w_path.pop_back(); } } return w_path; } int main(int argc, char **argv) { std::wstring exe_dir(current_exe_directory()); std::wstring fullpath; fullpath += exe_dir; fullpath += std::wstring(L"\\"); fullpath += script_name; std::wstring old_command_line(GetCommandLineW()); std::pair&lt;DWORD, std::deque&lt;std::wstring&gt;&gt; p = argvw_of_cmdline(old_command_line); DWORD err = p.first; assert(err == 0); std::deque&lt;std::wstring&gt; split_cl = p.second; // remove old executable (it's the current one) split_cl.pop_front(); // need to push interpreter_name and script_name. // but the order is reversed. split_cl.push_front(fullpath); split_cl.push_front(interpreter_name); std::wstring command_line = cmdline_of_argvw(split_cl); // make sure to zero-initialize these things. STARTUPINFOW si = { 0 }; PROCESS_INFORMATION pi = { 0 }; RawWinProcessCreatorW r; r.app_name = (interpreter_name.c_str()); r.command_line = const_cast&lt;LPWSTR&gt;(command_line.c_str()); r.inherit_handles = true; r.startup_info = &amp;si; r.process_information = &amp;pi; r.creation_flags |= CREATE_SUSPENDED; bool success = r.run(); assert(success); // DWORD last_error = GetLastError(); // assign to the job object whatever. DWORD assign_status = AssignProcessToJobObject( get_reaper().job_handle, pi.hProcess ); assert(assign_status); // resume the process. DWORD resume_status = ResumeThread(pi.hThread); // wait for the process we spawned. DWORD wait_res = WaitForSingleObject(pi.hProcess, INFINITE); assert(wait_res != WAIT_ABANDONED); assert(wait_res != WAIT_TIMEOUT); assert(wait_res != WAIT_FAILED); // after the process is gone, try to figure out whether it succeeded // and use that information when deciding how to exit yourself. // we're using 10, bad environment, as a sentinel. DWORD child_exit_status = 10; bool recover_exit_status_success = GetExitCodeProcess( pi.hProcess, &amp;child_exit_status ); assert(recover_exit_status_success); assert(child_exit_status != 10); return child_exit_status; } </code></pre> <hr> <p>And here's a Perl script <code>make_wrapper.pl</code> that generates and compiles a wrapper script.</p> <p>The template is concatenated underneath the end of the <code>__DATA__</code> token with <code>%%%%INTERPETER_NAME%%%%</code> appearing where the interpreter name is and <code>%%%SCRIPT_NAME%%%%</code> appearing where the script name is.</p> <pre><code>#! /usr/bin/env perl use strict; use warnings; use utf8; use Getopt::Long; use File::Spec; my $interpreter; my $script; my $cxx_compiler; my $output; GetOptions( "int|i=s" =&gt; <span class="math-container">\$interpreter, "script|s=s" =&gt; \$</span>script, "cxx|c=s" =&gt; <span class="math-container">\$cxx_compiler, "output|o=s" =&gt; \$</span>output, ); sub escape_wide_string_literal { my ($contents) = @_; my $out = q[]; $out .= 'L"'; $out .= ($contents =~ s/([\"\\])/\\$1/gr); $out .= '"'; return $out; } sub defined_and_nonempty { my ($x) = @_; return (defined $x) &amp;&amp; ($x ne q[]); } die "need interpreter (--int|-i)" unless defined_and_nonempty($interpreter); die "need script (--script|-s)" unless defined_and_nonempty($script); die "need C++ compiler (--cxx|-c)" unless defined_and_nonempty($cxx_compiler); die "need output file (--output|-o)" unless defined_and_nonempty($output); die "interpreter must exist (--int|-i)" unless (-f $interpreter); die "script must exist (--script|-s)" unless (-f $script); die "C++ compiler must exist (--cxx|-c)" unless (-f $cxx_compiler); die "intepreter must be absolute path (--int|-i)" unless (File::Spec-&gt;file_name_is_absolute($interpreter)); die "script should be relative path with no separators (.\\ is okay) (--script|-s)" if ($script =~ /\\/ and not $script =~ /\A[.][\\][^\\]*\z/); my $cxx_template; do { local $/; $cxx_template = &lt;DATA&gt;; }; close(DATA); die "internal error" unless defined $cxx_template; my $interpreter_literal = escape_wide_string_literal($interpreter); $cxx_template =~ s/%%%%INTERPETER_NAME%%%%/$interpreter_literal/g; my $script_literal = escape_wide_string_literal($script); $cxx_template =~ s/%%%%SCRIPT_NAME%%%%/$script_literal/g; open my $fh, '&gt;', "temp.cpp"; print $fh $cxx_template; close($fh); system($cxx_compiler, "-o", $output, "temp.cpp"); die "did not create file" unless (-f $output); __DATA__ </code></pre>
[]
[ { "body": "<h1>Disclaimer</h1>\n\n<p>It isn't clear to me what part you want reviews to focus on. I'm not a C++ on Windows person so I can't say much about that part of things. Your C++ is nicely formatted. The <code>main()</code> function could be broken down more, but it is commented well enough that it wo...
{ "AcceptedAnswerId": "206833", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T00:41:35.240", "Id": "206302", "Score": "8", "Tags": [ "c++", "windows", "perl", "wrapper", "child-process" ], "Title": "Executable wrapper around Perl script on Windows" }
206302
<p>I've written a solution to the leetcode problem <a href="https://leetcode.com/problems/median-of-two-sorted-arrays/description/" rel="nofollow noreferrer">Median of Two Sorted arrays</a>. The solution I anticipated coming up with initially was going to features some kind of binary search on both arrays based on the range of numbers (given that the question calls for a runtime of O(log (m+n))).</p> <p>Along the way, I thought of another, simpler solution that featured averaging the largest number of both arrays (the last element of one of the arrays) and the smallest number of the two arrays (index 0 of one of the arrays). I also include a number of if statements to handle the possible different array lengths that could be passed in. I'm particularly interested in the approach of this solution since it would have a faster runtime than what was suggested.</p> <p>This solution surprisingly passes 2056 / 2084 of the test cases. It fails, however, on the input arrays of <code>[3],[-2,-1]</code>, which leads me to believe that the code will fail only when there exist negative numbers in either array. <strong><em>Is this the case, or is it just that the test cases used for the question aren't wide-ranging enough?</em></strong></p> <pre><code>class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ if len(nums1) == 0 and len(nums2) == 0: return None if len(nums1) == 0 and len(nums2) &gt; 0: if len(nums2) == 1: return nums2[0] elif len(nums2) &gt; 1 and len(nums2) % 2 == 1: lo,hi = 0,len(nums2)-1 mid = (hi+lo)//2 return nums2[mid] elif len(nums2) &gt; 1 and len(nums2) % 2 == 0: lo,hi = 0,len(nums2)-1 mid = (hi+lo)//2 return (nums2[mid] + nums2[mid+1])/2 if len(nums1) &gt; 0 and len(nums2) == 0: if len(nums1) == 1: return nums1[0] elif len(nums1) &gt; 1 and len(nums1) % 2 == 1: lo,hi = 0,len(nums1)-1 mid = (hi+lo)//2 return nums1[mid] elif len(nums1) &gt; 1 and len(nums1) % 2 == 0: lo,hi = 0,len(nums1)-1 mid = (hi+lo)//2 return (nums1[mid] + nums1[mid+1])/2 l1A,l2A,l1B,l2B = 0,0,len(nums1)-1,len(nums2)-1 arrBeg = nums1[l1A] if nums1[l1A] &lt;nums2[l2A] else nums2[l2A] arrEnd = nums1[l1B] if nums1[l1B] &gt; nums2[l2B] else nums2[l2B] target = (arrEnd+arrBeg)/2 return target </code></pre>
[]
[ { "body": "<p>I believe the test cases are not generated randomly. Your code will fail on almost all cases if the cases are generated in a random way.\nFor instance,\nif array A is [0, 10000], and array B contains an arbitrary number of elements with arbitrary values from (0, 10000) except 5000, your code will ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T04:27:46.097", "Id": "206306", "Score": "0", "Tags": [ "python", "algorithm", "array" ], "Title": "Median of two sorted arrays (optimal runtime)" }
206306
<p>I have a program that does some matrix computations using MPI (MPICH). Each rank has a slice of the matrix and does the computations on their slice to get a new slice of the matrix. Sometimes I need to synchronize the matrix on the manager for snapshotting, output, etc. so I need all ranks to send their current matrix slice back to the manager. </p> <p>I've come up with a solution to do this, and it seems to work OK; but I wanted to know whether this is a good approach or if I'm doing something stupid since I've never worked with MPI before. One thing I'm particularly curious about is whether I'm deleting my requests vector correctly. Thanks in advance!</p> <p>Here's the code:</p> <pre><code>#define __WORLD MPI_COMM_WORLD // reconstructs the matrix on the manager node void reconstructMatrix(double** current, const int COLS, const int ROWS, const int MY_RANK, const int MPI_SIZE) { auto requests = new std::vector&lt;MPI_Request*&gt;(); requests-&gt;reserve(COLS); // Manager receives data from all ranks if (MY_RANK == 0) { // number of columns assigned to all ranks const auto SLICE_SIZE = COLS / MPI_SIZE; // receive from rank 1 to rank n-1 for (auto src = 1; src &lt; MPI_SIZE; src++) { for (auto i = (SLICE_SIZE * src); (i &lt; COLS) &amp;&amp; (i &lt; SLICE_SIZE * (src + 1)); i++) { auto temp = new MPI_Request(); MPI_Irecv(current[i], ROWS, MPI_DOUBLE, src, 1, __WORLD, temp); requests-&gt;push_back(temp); } } } else // Workers send data to manager { // index 0 and COLS + 1 are ghost columns for (auto i = 1; i &lt;= COLS; i++) { auto temp = new MPI_Request(); MPI_Isend(current[i], ROWS, MPI_DOUBLE, 0, 1, __WORLD, temp); requests-&gt;push_back(temp); } } // wait for sync to finish waitAll(requests); requests-&gt;clear(); delete requests; requests = nullptr; } // waits for all MPI requests and deletes the vector void waitAll(std::vector&lt;MPI_Request*&gt;*&amp; requests) { for (auto&amp; req : *requests) { MPI_Status stat; MPI_Wait(req, &amp;stat); if (stat.MPI_ERROR != MPI_SUCCESS) { std::cerr &lt;&lt; "MPI Request failed!\n\tCode: " &lt;&lt; stat.MPI_ERROR &lt;&lt; "\n\tFrom: " &lt;&lt; stat.MPI_SOURCE; } delete req; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T07:41:27.273", "Id": "398035", "Score": "0", "body": "One thing I should mention is, I know sending a bunch of messages like this is inefficient. I saw that most of the time people store matrices in a 1D array with MPI to send many ...
[ { "body": "<p>Note: I've written a matrix multiplication benchmark program in C and MPI:<a href=\"https://github.com/thefangbear/matrix-mpi\" rel=\"nofollow noreferrer\">https://github.com/thefangbear/matrix-mpi</a>. It uses a row-major format to store the two matrices in 1D arrays for better cache coherency. I...
{ "AcceptedAnswerId": "206513", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T07:32:38.840", "Id": "206310", "Score": "2", "Tags": [ "c++", "performance", "memory-management", "mpi" ], "Title": "Reconstructing Matrix scattered over many MPI ranks" }
206310
<p>I have made this program to simulate polybar's bspwm module. So far, it works flawlessly, however it consumes too much ram and cpu ie 16-30%. I suspect it is the while loop causing the trouble but what can be done to reduce resource usage ?</p> <pre><code>use strict; use warnings; use Switch; use List::MoreUtils qw(first_index); $SIG{INT}=sub{ die "goodnight !\n $!"; }; my $underline='#ffffff'; my $default_background='#51002f'; my $default_workspace_background='#727272'; my $default_workspace_foreground='#ffffff'; my $default_foreground='#ffffff'; my $focussed_background='#000000'; my $focussed_foreground='#ffffff'; my $occupied_background='#3a3a3a'; my $occupied_foreground='#ffffff'; my @desktops=qx/ bspc query -D /; my @lemonbar_array=(); my $lemonbar_string="%{B$default_background}%{F$default_foreground}%{+u}  0x00400004 %{-u}%{B-}%{F-}"; my $date_string="%{c}%{B$focussed_background}%{F$default_foreground}%{+u} %date %{-u}%{B-}%{F-}"; my $add_this="%{+u}%{B$default_background}%{F$default_foreground} %{A:firefox:} web %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:evince:} pdf %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:libreoffice:} doc %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox youtube.com:} youtube %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox netflix.com:} netflix %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox gmail.com:} gmail %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox protonmail.com:} protonmail %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:nautilus:} files %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:urxvt:} terminal %{A} %{B-}%{F-}%{-u}"; for(my $i=0;$i&lt;=9;$i++){ push(@lemonbar_array,$lemonbar_string); } my $current_monitor=''; while() { my $date=gmtime(); $date_string=~s/%date/$date/; $current_monitor=qx/bspc query -D -d/; my $index_current_monitor=first_index { $_ eq $current_monitor } @desktops; my $index_print=$index_current_monitor+1; $lemonbar_array[$index_current_monitor]=~s/(?&lt;=B)#.{6}/$focussed_background/; $lemonbar_array[$index_current_monitor]=~s/(?&lt;=F)#.{6}/$focussed_foreground/; $lemonbar_array[$index_current_monitor]=~s/0x00.{6}/$index_print/; for(my $i=0;$i&lt;10;$i++){ if($desktops[$i] ne $current_monitor){ my $i1=$i+1; $lemonbar_array[$i]=~s/0x00.{6}/$i1/; if(scalar(my @n=qx/bspc query -N -d $desktops[$i]/) gt 0){ $lemonbar_array[$i]=~s/(?&lt;=B)#\w{6}/$occupied_background/; $lemonbar_array[$i]=~s/(?&lt;=F)#\w{6}/$occupied_foreground/; } else{ $lemonbar_array[$i]=~s/(?&lt;=B)#\w{6}/$default_workspace_background/; $lemonbar_array[$i]=~s/(?&lt;=F)#\w{6}/$default_workspace_foreground/; } } } print "%{l}@lemonbar_array $date_string %{r}$add_this\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T18:52:13.970", "Id": "398170", "Score": "1", "body": "As for cpu, cut down number of shell calls per minute." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T08:14:43.493", "Id": "206311", "Score": "2", "Tags": [ "performance", "gui", "perl", "x11" ], "Title": "Lemonbar + perl scripting for workspaces" }
206311
<p>I have been lurking on the C++ side of stack-overflow only long enough to know there are a <em>lot</em> of beginners and intermediate programmers baffled by multi-dimensional arrays. I've seen <a href="//stackoverflow.com/q/27998546">a lot</a> <a href="//stackoverflow.com/q/6226490">of monstrosities</a> : <a href="//stackoverflow.com/q/26127076">three-star programmers</a>, <a href="//stackoverflow.com/q/21643846">cache-unfriendly implementations</a>, <a href="//stackoverflow.com/q/17079146">vectors of vectors of vectors</a> ..., <em><a href="//stackoverflow.com/q/33113403">etc</a></em>.</p> <p>I thought to provide them with a basic multi-dimensional array:</p> <ul> <li>open for extensions,</li> <li>fit for production and experimentation, </li> <li>working without allocations,</li> <li>and cache-friendly.</li> </ul> <p>Before I do so, I'd like some advice from the community.</p> <blockquote> <ol> <li>What can I improve in the provided features of this class?</li> <li>What new feature could one add, and why would it be useful?</li> </ol> </blockquote> <pre><code>#include &lt;array&gt; #include &lt;numeric&gt; namespace ysc { namespace _details { template&lt;class InputIt, class OutputIt&gt; OutputIt partial_product(InputIt first, InputIt last, OutputIt output) { *output++ = 1; return partial_sum(first, last, output, std::multiplies&lt;&gt;{}); } // cache-friendly: // neighbor objects within the right-most coordinate are neighbors in memory template&lt;class TDim, class TCoord&gt; auto coordinates_to_index(TDim const&amp; dimensions, TCoord const&amp; coords) { std::array&lt;std::size_t, dimensions.size()&gt; dimension_product; using std::crbegin, std::crend, std::prev; partial_product(crbegin(dimensions), prev(crend(dimensions)), begin(dimension_product)); return std::inner_product(cbegin(dimension_product), cend(dimension_product), crbegin(coords), 0); } } constexpr struct matrix_zero_t {} matrix_zero; template&lt;class T, std::size_t... Dimensions&gt; class matrix { template&lt;class, std::size_t...&gt; friend class matrix; public: static constexpr std::size_t order = sizeof...(Dimensions); static constexpr std::array dimensions = { Dimensions... }; private: std::array&lt;T, (Dimensions * ...)&gt; _data; public: friend void swap(matrix&amp; lhs, matrix&amp; rhs) { using std::swap; swap(lhs._data, rhs._data); } public: matrix() = default; matrix(matrix&amp;&amp; other) = default; matrix&amp; operator=(matrix&amp;&amp; other) = default; matrix(matrix_zero_t) : _data({}) {} template&lt;class U&gt; matrix(matrix&lt;U, Dimensions...&gt; const&amp; other) { std::copy(cbegin(other._data), cend(other._data), begin(_data)); } template&lt;class U&gt; matrix&amp; operator=(matrix&lt;U, Dimensions...&gt; const&amp; other) { matrix o{other}; swap(*this, o); return *this; } public: template&lt;class... Args&gt; T const&amp; operator()(Args... coordinates) const { return _data[_details::coordinates_to_index(dimensions, std::array{coordinates...})]; } template&lt;class... Args&gt; T&amp; operator()(Args... coordinates) { return _data[_details::coordinates_to_index(dimensions, std::array{coordinates...})]; } }; } // namespace ysc </code></pre> <p>Usage demo: <a href="http://coliru.stacked-crooked.com/a/1652451c78275436" rel="nofollow noreferrer">http://coliru.stacked-crooked.com/a/1652451c78275436</a></p> <p>This is a C++17 implementation; this itself is not set in stone.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T08:45:51.247", "Id": "398041", "Score": "0", "body": "How would this be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T08:50:51.887", "Id": "398043", "Score": "0", "body": "@Mast I'...
[ { "body": "<p>Here are some suggestions:</p>\n\n<ol>\n<li><p><code>coordinates_to_index</code> should return <code>std::size_t</code> instead of <code>int</code> because <code>int</code> may not be able to hold the required values.</p>\n\n<pre><code>return std::inner_product(cbegin(dimension_product), cend(dime...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T08:16:23.160", "Id": "206312", "Score": "5", "Tags": [ "c++", "array", "template", "c++17" ], "Title": "A basic multi-dimensional array" }
206312
<p>This is a simple toy downloader using python's <code>requests</code> library.</p> I’ve monitored the download process is slower on an ethernet connected box. The realtime speed is measured both on <code>stdout</code>, using <code>get_net_speed()</code> function, and <code>conky</code>. </p> <p>I’m using a 4Mbps connection. </p> <p>When downloading a file using <code>wget</code>, the downloading gets full bandwidth as expected. But when using my own <code>downloader</code> script, it gets highest 1Mbps speed. </p> Here's the code. Review and optimisation are warmly welcome. </p> <pre><code>#!/usr/bin/env python3 ### get details of a requested file and download if a media one import requests import sys from urllib.parse import urlparse import socket import re import time import psutil #===================== Main Routine =================================== def down_in_chunks(resp,file_name,conSize): downloaded = 0 file_descriptor = open(file_name,'wb') chunk_size = 1024 * 1024 # 1MB for chunk in resp.iter_content(chunk_size=chunk_size): downloaded += int(len(chunk)) # get update how much downloaded per_cent = 100 * downloaded / int(conSize) speed = get_net_speed() print("downloading %.2f pc speed %s" %(per_cent,speed),end='\r') file_descriptor.write(chunk) file_descriptor.close() #================== Auxilary Routines ================================== def get_net_speed(): rcv = psutil.net_io_counters() sp0 = rcv[1] time.sleep(1) rcv = psutil.net_io_counters() sp1 = rcv[1] speed = sp1 - sp0 return convert_size(speed) def convert_size(file_size): for unit in ["B","KiB","MiB","GiB","Tib","PiB","EiB","Zib"]: if abs(file_size) &lt;= 1024.0 or abs(file_size) == 0: return "%3.1f%s" %(file_size,unit) else: file_size /= 1024.0 #return "%3.1f%s" %(file_size,unit) def get_file_details(resp,url): file_type = resp.headers["Content-Type"] if re.match(r'^html|text',file_type): # perhaps we're not interested in the page only print("header info... ", resp.headers) else: file_name = url.split("/")[-1] print("file name: %s" % file_name) conDate = resp.headers["Date"] conType = resp.headers["Content-Type"] conTn = resp.headers["Connection"] conSize = resp.headers["Content-Length"] conUnit = resp.headers["Accept-Ranges"] humane = convert_size(int(conSize)) print("time: %s type: %s size: %s (%s) unit: %s connection: %s " %(conDate,conType,conSize,humane,conUnit,conTn)) return file_name , conSize # ========== Action =========== try: url = sys.argv[1] # get the url urlObj = urlparse(url) addr = urlObj.netloc ip = socket.gethostbyname(addr.split(":")[0]) # get the ip address print("connecting to %s | %s |... " %(addr,ip)) user_agent = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; hu-HU; rv:1.7.8) Gecko/20050511 Firefox/1.0.4'} resp = requests.get(sys.argv[1],stream=True,timeout=15,headers=user_agent) # I'm not a bot Maa'm print("status: %s " %(resp.status_code)) file_name,file_size = get_file_details(resp,url) print("downloading.......... %s" %file_name) start = time.time() down_in_chunks(resp,file_name,file_size) end = time.time() total_time = end - start if total_time &gt;= 60: print("download time: %.2f min" %(total_time/60)) else: print("download time: %.2f secs") resp.close() except requests.exceptions.RequestException as E: print("Error: ", E) sys.exit(0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T13:25:04.010", "Id": "398061", "Score": "0", "body": "How is `get_net_speed` measuring the download speed when it pauses the download?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T17:47:48.970", ...
[ { "body": "<p>By using <code>time.sleep(1)</code> on <code>get_net_speed</code> you are limiting your download speed to the block size per second, since your block has 1MB you are limited to 1Mbps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-04T09...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T10:13:47.183", "Id": "206315", "Score": "1", "Tags": [ "python", "python-3.x", "http", "network-file-transfer" ], "Title": "Python requests downloading big files in slower speed than wget" }
206315
<blockquote> <p>Given a list of numbers, place signs <code>+</code> or <code>-</code> in order to get the required number. </p> <p>If it's possible then return <code>true</code>, otherwise return <code>false</code> </p> <p><code>[1, 2, 3, 4, 5, 7]; 12</code> -> <code>true</code>, because 1 + 2 + 3 + 4 - 5 + 7 = 12</p> <p><code>[5, 3]; 7</code> -> <code>false</code>, because 5 + 3 != 7 and 5 - 3 != 7</p> </blockquote> <p>I came up with the following brute force solution:</p> <pre><code>public static boolean trueOrNot(int number, List&lt;Integer&gt; numbers) { boolean found = false; int i = 0; while (!found &amp;&amp; i &lt; (1 &lt;&lt; numbers.size())) { int tmpResult = 0; for (int j = 0; j &lt; numbers.size(); j++) { int num = numbers.get(j); if ((i &amp; (1 &lt;&lt; j)) &gt; 0) { num = -num; } tmpResult += num; } found = tmpResult == number; i++; } return found; } </code></pre> <p>Basically, I took for consideration binary representations of numbers <code>0000</code>, <code>0001</code>, <code>0010</code>...<code>2^n</code> and iterate over every bit, thus getting all possible combinations. <code>0</code> is a <code>+</code> sign and <code>1</code> is <code>-</code> sign. Then I calculate temporal result and once it is equal to the sought number I break out from loop.</p> <p>Time complexity: O(2<sup>n</sup>)<br> Space complexity: O(1)</p> <p>I just wondering is there any more effective solution with the help of Dynamic Programming, for example?</p> <p>Feedback for the current solution?</p>
[]
[ { "body": "<p>There is one technique, of transforming a problem to a more comfortable one.\nHere one could do it a couple of times:</p>\n\n<p>First the original problem <code>sum = term[0] ± term[1] ± ...</code>.</p>\n\n<pre><code>static boolean additive(int sum, int... terms) {\n if (terms.length == 0) {\n ...
{ "AcceptedAnswerId": "206810", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T10:35:53.293", "Id": "206316", "Score": "3", "Tags": [ "java", "algorithm", "complexity" ], "Title": "Place arithmetic signs in correct order to get the number" }
206316
<p>This is my java implementation based on the solution of Aasmund Eldhuset <a href="https://stackoverflow.com/questions/14997262/how-to-find-the-longest-substring-containing-two-unique-repeating-characters">here</a>.<br> Please give your opinion on my code (correctness, efficiency and coding conventions): </p> <pre><code>public static String longest2Str(String s){ int len; int i = 1; int subStart = 0; int nextGroupStart = 0; int longestStart = 0; int longestEnd = 0; char firstUnique, secondUnique, c; if ( (s == null) || (s.length() &lt; 2) ) { return null; } len = s.length(); firstUnique = s.charAt(subStart); // find first letter in s that isn't equal to the firstUnique for (; (i &lt; len) &amp;&amp; (s.charAt(i) == firstUnique); i++); secondUnique = s.charAt(i); for (; i &lt; len; i++) { c = s.charAt(i); if ( (c == firstUnique) || (c == secondUnique) ) { if (c != s.charAt(i - 1)) { nextGroupStart = i; } } else { if ( i - subStart &gt; longestEnd - longestStart ){ longestStart = subStart; longestEnd = i; } subStart = nextGroupStart; nextGroupStart = i; firstUnique = s.charAt(subStart); secondUnique = c; } } return s.substring(longestStart, longestEnd); } </code></pre>
[]
[ { "body": "<h3>Corner cases</h3>\n\n<p>You correctly handle the corner cases of too short input and null input.\nBut you forgot to handle the case of all same characters, for example \"aaa\".\nOn such input the program throws <code>StringIndexOutOfBoundsException</code> on line <code>secondUnique = s.charAt(i);...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T11:19:10.210", "Id": "206317", "Score": "2", "Tags": [ "java", "performance", "strings" ], "Title": "Longest substring with 2 unique characters in a given string at linear time" }
206317
<p>I wanted to create a FizzBuzz in Java that is supposed to be open for extension.</p> <p>So the initial problem is the good old, if divisible by 3 print fizz, if divisible by 5 print buzz, if divisible by both print fizzbuzz, otherwise print the number itself. </p> <p>But I want to be able to change the numbers that we test against (3 and 5 can become 4 and 6) and the words we print (fizz and buzz may be come foo and bar). And there may be new ones added, such as 7, qux..</p> <p>Here is what I came up with, any suggestions are welcome: </p> <pre><code>import java.util.*; import java.util.function.Function; import java.util.function.IntPredicate; class App { public static void main(String[] args) { Function&lt;Integer, IntPredicate&gt; divisibilityPredicateBuilder = isDivisibleBy -&gt; x -&gt; x % isDivisibleBy == 0; final Map&lt;Integer, String&gt; fizzersBuzzers = new HashMap&lt;&gt;(); fizzersBuzzers.put(3, "fizz"); fizzersBuzzers.put(5, "buzz"); for (int i = 1; i &lt; 101; i++) { String fizzBuzz = ""; for (Integer fizzerBuzzer : fizzersBuzzers.keySet()) { if (divisibilityPredicateBuilder.apply(fizzerBuzzer).test(i)) { fizzBuzz += fizzersBuzzers.get(fizzerBuzzer); fizzBuzz += " "; } } if (fizzBuzz.isEmpty()) { fizzBuzz = String.valueOf(i); } System.out.println(fizzBuzz.trim()); } } } </code></pre>
[]
[ { "body": "<p>You used a HashMap, where the iteration order is arbitrary. There is no guarantee whether you'll get \"fizz buzz\" or \"buzz fizz\"!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T14:00:13.860", "Id": "398064", "Score...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T12:50:06.627", "Id": "206321", "Score": "1", "Tags": [ "java", "functional-programming", "fizzbuzz", "lambda" ], "Title": "FizzBuzz with Lambda Expressions in Java" }
206321
<p><strong>Problem</strong> - Given a chess board and the position of only one queen piece in it, mark all the position where the queen can move with <strong>X</strong>. </p> <p>Kindly review this Scala code and suggest improvements.</p> <pre><code>import scala.collection.mutable._ object ChessQueenAttack { val board = Array.fill(8)(Array.fill(8)('0')) def printBoard = { println println board foreach { row =&gt; println(row.mkString(" "))} } def main(args: Array[String]): Unit = { printBoard val qR = args(0).toInt val qC = args(1).toInt board(qR)(qC) = 'Q' printBoard var (r,c) = (qR, qC) // horizontal for ( i &lt;- 0 until 8 ) { if (i != qC) board(qR)(i) = 'X' if (i != qR) board(i)(qC) = 'X' } // top left r = qR -1 c = qC -1 while (r &gt;= 0 &amp;&amp; c &gt;= 0) { board(r)(c) ='X' r -= 1 c -= 1 } // top right r = qR - 1 c = qC + 1 while (r &gt;= 0 &amp;&amp; c &lt; 8) { board(r)(c) = 'X' r -= 1 c += 1 } // bottom right r = qR + 1 c = qC + 1 while (r &lt; 8 &amp;&amp; c &lt; 8 ) { board(r)(c) = 'X' r += 1 c += 1 } // bottom left r = qR + 1 c = qC - 1 while (r&lt;8 &amp;&amp; c&gt;=0) { board(r)(c) = 'X' r += 1 c -= 1 } printBoard } } </code></pre> <p>Output -</p> <pre><code>scalac ChessQueenAttack.scala scala ChessQueenAttack 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Q 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X 0 0 X 0 0 X 0 0 X 0 X 0 X 0 0 0 0 X X X 0 0 0 X X X Q X X X X 0 0 X X X 0 0 0 0 X 0 X 0 X 0 0 X 0 0 X 0 0 X 0 0 0 0 X 0 0 0 X </code></pre>
[]
[ { "body": "<p>Your solution is very procedural, and more like how a C program would be written. I don't consider it to be idiomatic Scala. You should decompose the problem into functions, such as <code>isQueen</code> and <code>isAttacked</code> in my solution below.</p>\n\n<p>There should be very little code ...
{ "AcceptedAnswerId": "206338", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T13:02:54.493", "Id": "206322", "Score": "3", "Tags": [ "interview-questions", "matrix", "scala", "chess" ], "Title": "Mark positions attacked by a queen on a chess board" }
206322
<p>Following code is solving n queen problem with c++ using backtracking. I saw other people solution they are very short like 20 to 30 lines. Is there way improve following code?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; bool put_in(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Board, std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col, int n); void insert_into_stack(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col); bool check_horizontal(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row); bool check_vertical(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int col); bool check_diagonal_left_to_right(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col, int n); bool check_diagonal_right_to_left(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col, int n); void print_board(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Board); void print_stack(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack); void reset_board(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Board, std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack); void reset_stack(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int &amp;row, int &amp;col, int n); main() { // Board size int n = 10; int number_of_solution = 1; // Stack std::vector&lt;std::vector&lt;int&gt;&gt; Stack; Stack.reserve(n); for (auto &amp;it : Stack) it.resize(2); // Board std::vector&lt;std::vector&lt;int&gt;&gt; Board(n); for (auto &amp;it : Board) it.resize(n); for (int row = 0; row &lt; n; row++) { for (int col = 0; col &lt; n + 1; col++) { if (col == n) { // ! IMPORTANT // * Ends when row is 0 and col is n! if (row == 0 &amp;&amp; col == n) { return 0; } // * End condition // ! IMPORTANT Board[Stack[Stack.size() - 1][0]][Stack[Stack.size() - 1][1]] = 0; row = Stack[Stack.size() - 1][0]; col = Stack[Stack.size() - 1][1]; Stack.pop_back(); continue; } if (check_horizontal(Stack, row)) { continue; } if (check_vertical(Stack, col)) { continue; } if (check_diagonal_left_to_right(Stack, row, col, n)) { continue; } if (check_diagonal_right_to_left(Stack, row, col, n)) { continue; } if (put_in(Board, Stack, row, col, n)) { if (Stack.size() == n) { std::cout &lt;&lt; std::endl; std::cout &lt;&lt; number_of_solution++ &lt;&lt; std::endl; print_board(Board); reset_board(Board, Stack); reset_stack(Stack, row, col, n); continue; } break; } } } print_board(Board); return 0; } bool put_in(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Board, std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col, int n) { if (Board[row][col] == 0) { Board[row][col] = 1; insert_into_stack(Stack, row, col); return true; } else return false; } void insert_into_stack(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col) { std::vector&lt;int&gt; position; position.reserve(2); position.push_back(row); position.push_back(col); Stack.push_back(position); } bool check_horizontal(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row) { for (auto &amp;s : Stack) { if (s[0] == row) return true; } return false; } bool check_vertical(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int col) { for (auto &amp;s : Stack) { if (s[1] == col) return true; } return false; } bool check_diagonal_left_to_right(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col, int n) { int c_row = row, c_col = col; while (c_row &gt;= 0 &amp;&amp; c_col &gt;= 0) { for (auto &amp;s : Stack) { if (s[0] == c_row &amp;&amp; s[1] == c_col) return true; } c_row--; c_col--; } c_row = row; c_col = col; while (c_row &lt;= n &amp;&amp; c_col &lt;= n) { for (auto &amp;s : Stack) { if (s[0] == c_row &amp;&amp; s[1] == c_col) return true; } c_row++; c_col++; } return false; } bool check_diagonal_right_to_left(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int row, int col, int n) { int c_row = row, c_col = col; while (c_row &lt;= n &amp;&amp; c_col &gt;= 0) { for (auto &amp;s : Stack) { if (s[0] == c_row &amp;&amp; s[1] == c_col) return true; } c_row++; c_col--; } c_row = row; c_col = col; while (c_row &gt;= 0 &amp;&amp; c_col &lt;= n) { for (auto &amp;s : Stack) { if (s[0] == c_row &amp;&amp; s[1] == c_col) return true; } c_row--; c_col++; } return false; } void print_board(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Board) { // Print Board for (auto &amp;it : Board) { for (auto &amp;val : it) { std::cout &lt;&lt; val; } std::cout &lt;&lt; std::endl; } } void print_stack(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack) { for (auto &amp;it : Stack) { for (auto &amp;val : it) { std::cout &lt;&lt; val; } std::cout &lt;&lt; std::endl; } } void reset_stack(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack, int &amp;row, int &amp;col, int n) { col = Stack[Stack.size() - 1][1]; Stack.pop_back(); } void reset_board(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Board, std::vector&lt;std::vector&lt;int&gt;&gt; &amp;Stack) { Board[Stack[Stack.size() - 1][0]][Stack[Stack.size() - 1][1]] = 0; } </code></pre>
[]
[ { "body": "<p>Welcome to Code Review. This post is a mixture between review, remarks, tutorial and general guidelines. Overall, your code has two complexity issues: space complexity due to types (see \"Tip: Use implicit data\") and algorithmic complexity due to algorithms (see \"Diagonals\"). Several of your re...
{ "AcceptedAnswerId": "206349", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T13:30:59.283", "Id": "206325", "Score": "7", "Tags": [ "c++", "backtracking", "n-queens" ], "Title": "N Queen Problem C++" }
206325
<p>I wrote code to calculate PI to a user specified number of decimal places. It works fine. I wanted to add a progress indication so that the user doesn't have to stare at a flashing cursor for hours on end with no indication of progress. I got something working but it makes the code much, much too slow. In the code below I have commented out the progress indicator section with a double line of ******'s before and after the "offending" piece of code. I suspect it is the log10 calculation that makes things too slow. Any suggestions:</p> <pre><code># A program to calculate PI to a user specified number of decimal digits # The program uses the Chudnovsky algorithm. # Further details on the algorithm are availabler here: # https://en.wikipedia.org/wiki/Chudnovsky_algorithm # A generator which divides the user requested number of decimal places into 10% increments def ten_percent(places): for i in range(int(places/10),int(places+1),int(places/10)): yield i def pi_calc(places): # places is user specified number of decimal places that should be calculated. import decimal import time import numpy as np start_time = time.time() decimal.getcontext().prec = places + 3 # The function makes succesive calculations of PI using the algorithm. # The current calculated PI value is subtracted from the succesive PI value # If the difference is less than the 1 x 10**(-places) the result is returned # Initialise some variables current_pi = 3 next_pi = 3 precision = 1 * 10**(-places-3) counter = 1 precision_step = ten_percent(places) precision_check = next(precision_step) # Initialise terms used in the itteration L = 13591409 X = 1 M = 1 K = 6 S = decimal.Decimal(M*L)/X next_pi = 426880*decimal.Decimal(10005).sqrt()/S # Perform the itterative calculation until the required precision is achieved while abs(next_pi - current_pi) &gt; precision: current_pi = next_pi # Calculate the next set of components for the PI approximation L += 545140134 X *= -262537412640768000 M = M*(K**3-16*K)//(counter)**3 S += decimal.Decimal(M*L)/X K += 12 counter += 1 # Calculate the next approximation of PI next_pi = 426880*decimal.Decimal(10005).sqrt()/S #****************************************************************************************************************************** #****************************************************************************************************************************** # This progress indication slows the code down too much to be practical # # # # Give the user some feedback on progress of the calculation # # # The try statement is required because the error between successive pi calculations can become # # "infintly" small and then a string is returned instead of a number. # # try: # test_num = abs(round(np.log10(abs(decimal.Decimal(next_pi - current_pi))))) # except: # pass # # if test_num &gt;= precision_check: # print('Calculation steps: ' + str(counter-1) + ' Approximate decimal places: ' + str(precision_check)) # if precision_check &lt; places: # precision_check = next(precision_step) #******************************************************************************************************************************* #******************************************************************************************************************************* return decimal.Decimal(str(next_pi)[:places+2]) # Get the required number of decimal places from the user and call the function to perform # the calculation while True: try: places = int(input('To how many decimal places would you like to calculate PI? ')) except: print('Please provide a valid integer value.') continue else: break calculated_pi = pi_calc(places) print('The value of PI to '+ str(places) + ' decimal places is:\n%s' % (calculated_pi)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T20:31:19.977", "Id": "398117", "Score": "1", "body": "Have you done any profiling? Any timing numbers you could share?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T11:20:54.203", "Id": "398321"...
[ { "body": "<p>This answers suggests various strategies for fixing performance. It does not consider other aspects of the code. It does not look at numerical analysis. (If there is a cheaper way to do the actual calculation to measure progress, that's not something I can tell you.)</p>\n\n<p>First, this code goe...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T13:42:08.457", "Id": "206326", "Score": "1", "Tags": [ "python", "beginner" ], "Title": "Progress Indicator Makes PI Calculation too Slow" }
206326
<p>My HTML:</p> <pre><code> &lt;div class="text-left pb-5"&gt; &lt;h6&gt;Aantal&lt;/h6&gt; &lt;input type="text" class="calc" id="aantal" name="aantal" value="100" style="padding-left: 5px"&gt; &lt;/div&gt; &lt;div class="text-left pb-5"&gt; &lt;h6&gt;Kleur&lt;/h6&gt; &lt;input type="text" class="calc" id="kleur" name="kleur" value="5" style="padding-left: 5px"&gt; &lt;/div&gt; &lt;div class="text-left pb-5"&gt; &lt;h6&gt;Grootte&lt;/h6&gt; &lt;input type="text" class="calc" id="grootte" name="grootte" value="50" style="padding-left: 5px"&gt; &lt;/div&gt; &lt;div class="text-left pt-5"&gt; &lt;h6&gt;Prijs&lt;/h6&gt; &lt;input type="text" id="prijs" name="prijs" readonly style="padding-left: 5px"&gt; &lt;/div&gt; </code></pre> <p>My jQuery code:</p> <pre><code> $(".calc").on('change keydown paste input', function(){ if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 1) { $("#prijs").val('7.35'); } else if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 2) { $("#prijs").val('8.60'); } else if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 3) { $("#prijs").val('10.30'); } else if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 4) { $("#prijs").val('12.40'); } else if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 5) { $("#prijs").val('14.80'); } else if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 6) { $("#prijs").val('17.80'); } else if($('#grootte').val() &lt;= 50 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 7) { $("#prijs").val('14.85'); } }); $(".calc").on('change keydown paste input', function(){ if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 1) { $("#prijs").val('7.95'); } else if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 2) { $("#prijs").val('8.60'); } else if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 3) { $("#prijs").val('10.30'); } else if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 4) { $("#prijs").val('12.40'); } else if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 5) { $("#prijs").val('14.80'); } else if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 6) { $("#prijs").val('17.80'); } else if($('#grootte').val() &gt;= 50 &amp;&amp; $('#grootte').val() &lt;= 150 &amp;&amp; $('#aantal').val() &lt;= 25 &amp;&amp; $('#kleur').val() == 7) { $("#prijs").val('14.85'); } }); </code></pre> <p>This jQuery code is very repetitive and I would like to simplify it, but I am not really sure how I could do this. Could anyone help me out? This is only part of the jQuery code, all the inputs will have different values and outcomes.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T15:32:37.120", "Id": "398074", "Score": "2", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the titl...
[ { "body": "<p>The way to approach this kind of thing is to look for commonalities in your code. So taking just a part of the first handler my first step would be:</p>\n\n<pre><code> $(\".calc\").on('change keydown paste input', function() {\n bar kleur = $('#kleur').val(); \n var in_range = $('#grootte...
{ "AcceptedAnswerId": "206360", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T15:04:31.717", "Id": "206332", "Score": "-2", "Tags": [ "javascript", "jquery", "html" ], "Title": "How can I write this jQuery code different and more simple?" }
206332
<p>A few months back, I posted a <a href="https://codereview.stackexchange.com/questions/201528/finite-state-automata">state machine</a> for review. Thanks to the feedback, I was able to greatly simplify the implementation. I am posting the revised version, together with the Regex class which calls it.</p> <p>I think I'm mainly looking for feedback on structure. The relationship between my <code>Node</code> class and <code>StateMachine</code> class feels a little tangled; I'm not always sure which method ought to belong to which class. I think the way I communicate the next token of my lexer is also cumbersome.</p> <p><strong><code>state_machine.py</code></strong></p> <pre><code>class Node: def __init__(self, value): self.value = value self.children = set() def empty(self): return self.value == '' def add_child(self, other): self.children.add(other) def find_parent_of_terminal(self, terminal): """ We assume that there shall only be one node leading to the terminal and that there is only one terminal """ visited = set() to_explore = {self} while to_explore: current = to_explore.pop() visited.add(current) if terminal in current.children: # If this fails, then there is a bug in union, concat, or kleene assert len(current.children) == 1 return current to_explore.update({node for node in current.children if node not in visited}) return None def leads_to(self, value): """ Return True iff argument can be reached by traversing empty nodes """ return bool(self._get_node_if_reachable(value)) def _get_node_if_reachable(self, value): for node in self.children: while node and node.empty(): if node == value: return node node = node._get_node_if_reachable(value) return None def __repr__(self): result = '{} : ['.format(self.value) for node in self.children: result += str(node.value) + ', ' result += ']\n' return result def EmptyNode(): return Node('') class StateMachine: def __init__(self): self.initial = EmptyNode() self.terminal = EmptyNode() def __repr__(self): return str(self.initial) @staticmethod def from_string(source): dfa = StateMachine() nodes = [Node(char) for char in source] dfa.initial.add_child(nodes[0]) for i in range(len(source) - 1): nodes[i].add_child(nodes[i + 1]) nodes[-1].add_child(dfa.terminal) return dfa @staticmethod def from_set(chars): dfa = StateMachine() first = EmptyNode() penultimate = EmptyNode() dfa.initial.children = {first} for char in chars: char_node = Node(char) first.add_child(char_node) char_node.add_child(penultimate) penultimate.add_child(dfa.terminal) return dfa def concat(self, other): other.initial.find_parent_of_terminal(other.terminal).children = {self.terminal} self.initial.find_parent_of_terminal(self.terminal).children = other.initial.children return self def union(self, other): self.initial.children.update(other.initial.children) this_last = self.initial.find_parent_of_terminal(self.terminal) other_last = other.initial.find_parent_of_terminal(other.terminal) empty_node = EmptyNode() empty_node.add_child(self.terminal) this_last.children = {empty_node} other_last.children = {empty_node} return self def kleene(self): penultimate_node = self.initial.find_parent_of_terminal(self.terminal) dummy = EmptyNode() penultimate_node.children = {dummy} dummy.add_child(self.terminal) penultimate_node.add_child(self.initial) self.initial.add_child(dummy) return self def _get_next_state(self, nodes, value, visited=None): if visited is None: visited = set() result = set() for node in nodes: visited.add(node) for child in node.children: if child.empty() and child not in visited: result.update(self._get_next_state([child], value, visited)) elif child.value == value: result.add(child) return result def is_match(self, nodes): for node in nodes: if node .leads_to(self.terminal): return True return False def match(self, source): """ Match a target string by simulating a NFA :param source: string to match :return: Matched part of string, or None if no match is found """ result = '' last_match = None current = {self.initial} for char in source: next_nodes = self._get_next_state(current, char) if next_nodes: current = next_nodes result += char if self.is_match(current): last_match = result else: break if self.is_match(current): last_match = result return last_match </code></pre> <p><strong><code>regex.py</code></strong></p> <pre><code>import collections import enum import string from state_machine import StateMachine class Token(enum.Enum): METACHAR = 0 CHAR = 1 ERROR = 2 class LexResult(collections.namedtuple('LexResult', ['token', 'lexeme'])): def __bool__(self): return self.token != Token.ERROR class RegexLexer(object): metachars = '-|[]^().*' def __init__(self, pattern: str): self._pattern = pattern self._pos = 0 self._stack = [] def peek(self) -&gt; LexResult: if self._pos &gt;= len(self._pattern): return LexResult(Token.ERROR, '') next_char = self._pattern[self._pos] if next_char in self.metachars: token = Token.METACHAR else: token = Token.CHAR return LexResult(token, next_char) def _eat_token_type(self, token: Token) -&gt; LexResult: next_match = self.peek() if next_match.token != token: return LexResult(Token.ERROR, next_match.lexeme) self._pos += 1 return next_match def _eat_token(self, match: LexResult) -&gt; LexResult: next_match = self.peek() if next_match == match: self._pos += 1 return next_match return LexResult(Token.ERROR, next_match.lexeme) def mark(self): self._stack.append(self._pos) def clear(self): self._stack.pop() def backtrack(self): self._pos = self._stack.pop() def eat_char(self, char=''): if char: return self._eat_token(LexResult(Token.CHAR, char)) return self._eat_token_type(Token.CHAR) def eat_metachar(self, metachar): return self._eat_token(LexResult(Token.METACHAR, metachar)) class Regex(object): CHARACTERS = string.printable def __init__(self, pattern: str): """ Initialize regex by compiling provided pattern """ self._lexer = RegexLexer(pattern) self._state_machine = self.parse() def match(self, text: str) -&gt; str: """ Match text according to provided pattern. Returns matched substring if a match was found, or None otherwise """ assert self._state_machine return self._state_machine.match(text) def parse(self): nfa = self.parse_simple_re() if not nfa: return None while True: self._lexer.mark() if not self._lexer.eat_metachar('|'): self._lexer.backtrack() return nfa next_nfa = self.parse_simple_re() if not next_nfa: self._lexer.backtrack() return nfa nfa = nfa.union(next_nfa) self._lexer.clear() def parse_simple_re(self): """ &lt;simple-re&gt; = &lt;basic-re&gt;+ """ nfa = self.parse_basic_re() if not nfa: return None while True: next_nfa = self.parse_basic_re() if not next_nfa: break nfa = nfa.concat(next_nfa) return nfa def parse_basic_re(self): """ &lt;elementary-re&gt; "*" | &lt;elementary-re&gt; "+" | &lt;elementary-re&gt; """ nfa = self.parse_elementary_re() if not nfa: return None next_match = self._lexer.peek() if not next_match or next_match.token != Token.METACHAR: return nfa if next_match.lexeme == '*': self._lexer.eat_metachar('*') return nfa.kleene() if next_match.lexeme == '+': self._lexer.eat_metachar('+') return nfa.union(nfa.kleene()) return nfa def parse_elementary_re(self): """ &lt;elementary-RE&gt; = &lt;group&gt; | &lt;any&gt; | &lt;char&gt; | &lt;set&gt; :return: DFA """ self._lexer.mark() nfa = self.parse_group() if nfa: self._lexer.clear() return nfa self._lexer.backtrack() if self._lexer.eat_metachar('.'): return StateMachine.from_set({x for x in self.CHARACTERS}) char = self._lexer.eat_char() if char: return StateMachine.from_string(char.lexeme) set_chars = self.parse_set() if not set_chars: return None return StateMachine.from_set(set_chars) def parse_group(self): """ &lt;group&gt; = "(" &lt;RE&gt; ")" :return: DFA """ if not self._lexer.eat_metachar('('): return None state_machine = self.parse() if not state_machine: return None if not self._lexer.eat_metachar(')'): return None return state_machine def parse_range(self) -&gt; {str}: """ &lt;range&gt; = &lt;CHAR&gt; "-" &lt;CHAR&gt; """ first = self._lexer.eat_char() if not first: return set() if not self._lexer.eat_metachar('-'): return set() last = self._lexer.eat_char() if not last: return set() return {chr(x) for x in range(ord(first.lexeme), ord(last.lexeme) + 1)} def parse_set_item(self) -&gt; {str}: """ &lt;set item&gt; = &lt;range&gt; | &lt;char&gt; """ self._lexer.mark() set_item = self.parse_range() if set_item: self._lexer.clear() return set_item self._lexer.backtrack() next_item = self._lexer.eat_char() return {next_item.lexeme} if next_item else set() def parse_set_items(self) -&gt; {str}: """ &lt;set items&gt; = &lt;set item&gt;+ """ items = self.parse_set_item() if not items: return set() next_items = self.parse_set_item() while next_items: items.update(next_items) next_items = self.parse_set_item() return items def parse_positive_set(self) -&gt; {str}: if not self._lexer.eat_metachar('['): return set() set_items = self.parse_set_items() if not set_items: return set() if not self._lexer.eat_metachar(']'): return set() return set_items def parse_negative_set(self) -&gt; {str}: if not self._lexer.eat_metachar('['): return set() if not self._lexer.eat_metachar('^'): return set() set_items = self.parse_set_items() if not set_items: return set() if not self._lexer.eat_metachar(']'): return set() return set(string.printable).difference(set_items) def parse_set(self) -&gt; {str}: """ Parse something like [a-z9] and return the set of allowed characters """ self._lexer.mark() set_items = self.parse_positive_set() if set_items: self._lexer.clear() return set_items self._lexer.backtrack() return self.parse_negative_set() </code></pre> <p>Finally, a small set of unit tests to show usage:</p> <pre><code>import unittest from state_machine import StateMachine from regex import Regex class TestStateMachine(unittest.TestCase): def test_union(self): state_machine = StateMachine.from_string('abc') state_machine = state_machine.union(StateMachine.from_string('def')) self.assertEqual(state_machine.match('abc'), 'abc') self.assertEqual(state_machine.match('def'), 'def') self.assertIsNone(state_machine.match('de')) def test_kleene(self): state_machine = StateMachine.from_string('abc') state_machine = state_machine.kleene() self.assertEqual(state_machine.match(''), '') self.assertEqual(state_machine.match('abc'), 'abc') self.assertEqual(state_machine.match('abcabc'), 'abcabc') self.assertEqual(state_machine.match('abcDabc'), 'abc') def test_concat(self): state_machine = StateMachine.from_string('ab') state_machine = state_machine.concat(StateMachine.from_string('cd')) self.assertEqual(state_machine.match('abcd'), 'abcd') self.assertEqual(state_machine.match('abcde'), 'abcd') self.assertIsNone(state_machine.match('abc')) class TestRegex(unittest.TestCase): def test_identifier_regex(self): regex = Regex('[a-zA-Z_][a-zA-Z0-9_]*') self.assertEqual(regex.match('a'), 'a') self.assertFalse(regex.match('0')) self.assertTrue(regex.match('a0')) self.assertEqual(regex.match('a0_3bd'), 'a0_3bd') self.assertEqual(regex.match('abd-43'), 'abd') def test_parentheses(self): regex = Regex('d(ab)*') self.assertEqual(regex.match('d'), 'd') self.assertEqual(regex.match('dab'), 'dab') self.assertEqual(regex.match('daa'), 'd') self.assertEqual(regex.match('dabab'), 'dabab') def test_union(self): regex = Regex('(ab*d)|(AG)') self.assertEqual(regex.match('adG'), 'ad') self.assertEqual(regex.match('AGfe'), 'AG') if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T16:14:04.057", "Id": "398078", "Score": "0", "body": "Hello, this looks like a very interesting question and a well written piece of code! By any chance, would you have any small example that could be used to test your code ?" }, ...
[ { "body": "<p>Yay! You ran <code>flake8</code> and followed PEP-8. Nice clean code.</p>\n\n<pre><code> self.assertEqual(state_machine.match('abc'), 'abc')\n</code></pre>\n\n<p>Ummm, this is arguably backwards.\nConvention for xUnit in many languages is to <code>assertEqual(expected, computed)</code>.\nIt can...
{ "AcceptedAnswerId": "216610", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T15:16:52.450", "Id": "206333", "Score": "9", "Tags": [ "python", "python-3.x", "parsing", "regex", "reinventing-the-wheel" ], "Title": "Minimal regex engine" }
206333
<p>I have many images and want to compute the GLCM properties for every image. Below my code that runs many hours to complete the task:</p> <pre><code>import numpy as np from skimage.feature import greycomatrix, greycoprops ANGLES = [0., np.pi/4., np.pi/2., 3.*np.pi/4.] DISTANCES = [1,2] properties = ["correlation", "contrast", "homogeneity", "energy"] n_img = 1000 I = np.random.randint(0,255,size=(n_img, 100, 100)) stats = [] for k in range(n_img): glcm = greycomatrix(I[k], distances=DISTANCES, angles=ANGLES, levels=256, symmetric=True, normed=True) prop = [np.mean(greycoprops(glcm, properties[i])) for i in range(len(properties))] stats.append(prop) stats = np.array(stats) </code></pre> <p>This code is a real bottleneck. How can parallelize the task? Are there other ways to speed up the code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T15:44:01.657", "Id": "398076", "Score": "1", "body": "related: https://github.com/scikit-image/scikit-image/issues/3413 and https://stackoverflow.com/questions/35551249/implementing-glcm-texture-feature-with-scikit-image-and-python"...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T15:26:07.173", "Id": "206334", "Score": "2", "Tags": [ "python", "performance", "image", "numpy", "signal-processing" ], "Title": "Gray-level co-occurrence matrix feature computation" }
206334
<p>During an interview I was asked to design the menu for a coffee shop <strong>employee</strong> so that the employee would go and add different items to the menu. This is the design that I came up with. </p> <p>I just want to know what other things I'm expected to think of. Are there any problems/complexities that I haven't taken into account?</p> <p>One other important question is my usage of struct/class. I just want to know if there is anything that I need to be considerate of. </p> <p>My main objects are: </p> <ul> <li>The <code>Product</code> object. </li> <li>The <code>Region</code> object. It contains different stores of different types. </li> <li>The <code>MenuHandler</code> object. It just adds the products to a region or store. It also allows adding a certain snack to a certain product.</li> <li>I've also added a restriction that each product has certain acceptableRegions. So if an employee attempts to add it to a non-acceptable region then an error is to be thrown. </li> </ul> <p></p> <pre><code>import UIKit import Foundation struct Product{ let id : String let name : String let price : String let imageURL: URL var snack: Snack? let requirement: Requirement var acceptedRegions = Set&lt;Region&gt;() } class Region : Hashable { let id : String let name: String var stores : [Store] init(id: String, name: String) { self.id = id self.name = name } var hashValue: Int { return id.hashValue } static func == (lhs: Region, rhs: Region) -&gt; Bool{ return lhs.id == rhs.id } } enum StoreType { case normal case superStore } class Store { let id: String let type: StoreType var products : [Product] = [] init(id: String, type: StoreType) { self.type = type self.id = id } } struct Requirement{ let neededTime : TimeInterval let skillLevel : Employees let device : Devices let material : [ResourceAllocation] } struct Employees : OptionSet{ let rawValue: Int static let junior = Employees(rawValue: 1 &lt;&lt; 0) static let senior = Employees(rawValue: 1 &lt;&lt; 1) static let manager = Employees(rawValue: 1 &lt;&lt; 2) static let all : Employees = [.junior, .senior, .manager] } struct Devices : OptionSet{ let rawValue: Int static let expressoMaker = Devices(rawValue: 1 &lt;&lt; 0) static let coffeeMaker = Devices(rawValue: 1 &lt;&lt; 1) static let mixer = Devices(rawValue: 1 &lt;&lt; 2) } enum Resource : String{ case milk case sugar case cream case coffeeBag case teaBag } struct ResourceAllocation{ let resource : Resource let amount : Int } struct Snack{ } protocol MenuHandlerType{ typealias ProductID = String typealias RegionID = String var products : [ProductID: Product] {get set} func add(_ product: Product, to region: Region) func add(_ product: Product, to store: Store, in region: Region) func add(_ snack: Snack , to product: Product) } class MenuHandler: MenuHandlerType { var products: [ProductID : Product] = [:] var regions : [RegionID: Region] required init(regions: [RegionID : Region]) { self.regions = regions } func add(_ product: Product, to region: Region) { guard let _region = regions[region.id] else { print("You need to first add this region") return } _region.stores.forEach { (store) in store.products.append(product) } } func add(_ product: Product, to store: Store, in region: Region) { guard let _region = regions[region.id] else { print("You need to first add this region") return } if _region.stores.contains(where: { (_store) -&gt; Bool in store.id == _store.id }){ print("You need to add this store to this region") return } } func add(_ snack: Snack, to product: Product) { &lt;#code#&gt; } } class AddProductsViewController: NSObject{ let menuHandler : MenuHandler init(menuHandler: MenuHandler) { self.menuHandler = menuHandler } // this will be called by a button. @objc func add(_ product: Product ,to region: Region){ if product.acceptedRegions.contains(region){ menuHandler.add(product, to: region) }else { print("this product is not FDA approved in this region") } } // add other buttonActions for adding Snack and adding product to store. } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T03:24:41.367", "Id": "398134", "Score": "0", "body": "why do you do this? `_region = regions[region.id]`? Why not just use the region they provide you as a param" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2...
[ { "body": "<p>I'll go through this, type by type:</p>\n\n<h1>Product</h1>\n\n<h2>price</h2>\n\n<p>I'm not a fan of <code>String</code> price. It's rather see an <code>priceCents: Int</code> or <code>price: Decimal</code>, with a <code>formattedPrice: String</code> computed property, that uses a currency formatt...
{ "AcceptedAnswerId": "206346", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T17:55:28.910", "Id": "206342", "Score": "0", "Tags": [ "object-oriented", "interview-questions", "swift" ], "Title": "Design a system for creating a coffeeshop menu" }
206342
<p>I have made Connect 4 in C#. If you have never played Connect 4, it is like Tic Tac Toe, except the pieces fall to the bottom of the grid, and the grid is usually 6x7.</p> <p>This is the first big project I have made in C#, so I don't know if I wrote the program well. How can I improve my code?</p> <pre><code>using System; namespace Connect4 { class Program { static void Main(string[] args) { Engine game = new Engine(); char player = '1'; int column; bool gameLoop = true; bool inputLoop; while (gameLoop) { System.Console.Clear(); game.DisplayGrid(); do { inputLoop = true; Console.Write("\nPlayer "); Console.Write(player); Console.Write(": "); if (Int32.TryParse(Console.ReadLine(), out column)) { if (1 &lt;= column &amp;&amp; column &lt;= 7) { if (game.DropPieceInGrid(player, column)) { inputLoop = false; } else { System.Console.Clear(); game.DisplayGrid(); Console.WriteLine("\nThat column is full."); } } else { System.Console.Clear(); game.DisplayGrid(); Console.WriteLine("\nThe integer must be between 1 and 7."); } } else { System.Console.Clear(); game.DisplayGrid(); Console.WriteLine("\nPlease enter an integer."); } } while (inputLoop); if (game.FourInARow(player)) { System.Console.Clear(); game.DisplayGrid(); Console.Write("\nPlayer "); Console.Write(player); Console.Write(" has won!\n"); Console.WriteLine("\nPress enter to quit."); gameLoop = false; } else if (game.GridIsFull()) { System.Console.Clear(); game.DisplayGrid(); Console.WriteLine("\nIt is a draw."); Console.WriteLine("\nPress enter to quit."); gameLoop = false; } else { player = player == '1' ? '2' : '1'; } } Console.ReadKey(); } } class Engine { const int NUMBER_OF_ROWS = 6, NUMBER_OF_COLUMNS = 7; const char EMPTY = '0', PLAYER1 = '1', PLAYER2 = '2'; private char[,] grid; int pieceCount; public Engine() { grid = new char[NUMBER_OF_ROWS, NUMBER_OF_COLUMNS]; for (int y = 0; y &lt; NUMBER_OF_ROWS; y++) for(int x = 0; x &lt; NUMBER_OF_COLUMNS; x++) grid[y, x] = EMPTY; } public void DisplayGrid() { for (int y = 0; y &lt; NUMBER_OF_ROWS; y++) { for (int x = 0; x &lt; NUMBER_OF_COLUMNS; x++) { Console.Write(grid[y, x]); Console.Write(' '); } Console.Write('\n'); } } // Returns true if the piece can be dropped in that column. public bool DropPieceInGrid(char player, int column) { column--; if (grid[0, column] != EMPTY) return false; for (int y = 0; y &lt; NUMBER_OF_ROWS; y++) { if ((y == NUMBER_OF_ROWS - 1) || (grid[y + 1, column] != EMPTY)) { grid[y, column] = player; break; } } pieceCount++; return true; } public bool FourInARow(char player) { // Horizontal check: for (int y = 0; y &lt; NUMBER_OF_ROWS; y++) for (int x = 0; x &lt; 4; x++) if (grid[y, x] == player &amp;&amp; grid[y, x + 1] == player) if (grid[y, x + 2] == player &amp;&amp; grid[y, x + 3] == player) return true; // Vertical check: for (int y = 0; y &lt; 3; y++) for (int x = 0; x &lt; NUMBER_OF_COLUMNS; x++) if (grid[y, x] == player &amp;&amp; grid[y + 1, x] == player) if (grid[y + 2, x] == player &amp;&amp; grid[y + 3, x] == player) return true; // Diagonal check: for (int y = 0; y &lt; 3; y++) { for (int x = 0; x &lt; NUMBER_OF_COLUMNS; x++) { if (grid[y, x] == player) { // Diagonally left: try { if (grid[y + 1, x - 1] == player) { if (grid[y + 2, x - 2] == player) if (grid[y + 3, x - 3] == player) return true; } } catch (IndexOutOfRangeException) {} // Diagonally right: try { if (grid[y + 1, x + 1] == player) { if (grid[y + 2, x + 2] == player) if (grid[y + 3, x + 3] == player) return true; } } catch (IndexOutOfRangeException) {} } } } return false; } public bool GridIsFull() { return pieceCount &gt;= NUMBER_OF_ROWS * NUMBER_OF_COLUMNS; } } } </code></pre>
[]
[ { "body": "<p>I am assuming that the code works as intended and hence will not remark on any logic.</p>\n\n<h1>General remarks</h1>\n\n<p>You need to split your code into either functions or classes. The for loops and <code>Main</code> are barely readable. This is the <strong>very first thing</strong> (right af...
{ "AcceptedAnswerId": "206359", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T18:41:22.640", "Id": "206348", "Score": "2", "Tags": [ "c#", "connect-four" ], "Title": "Text-based Connect 4 Game" }
206348
<p><code>$elements</code> is an array, which <em>may</em> contain 'x' or 'y' keys, I want to check if they exist, otherwise assign a 0. I'm looking for a clean way to validate it. I'm new to PHP, so I want to make sure my code is created according to PHP best practices.</p> <p>Input array:</p> <pre><code>Array ( [0] =&gt; Array ( ) [1] =&gt; Array ( [x] =&gt; 123 ) [2] =&gt; Array ( [x] =&gt; 123 [y] =&gt; 456 ) [3] =&gt; Array ( [y] =&gt; 456 ) ) </code></pre> <p>Code:</p> <pre><code>foreach ($elements as $element) { $element_x = $element_y = 0; if (isset($element['x'])) $element_x = $element['x']; if (isset($element['y'])) $element_y = $element['y']; $results[] = sprintf('(%d,%d)', $element_x, $element_y); } </code></pre> <p>Is there a cleaner way to do it?</p>
[]
[ { "body": "<p>First: Upgrade PHP!!! PHP 5.6 is losing security support on December 31st this year. <a href=\"http://php.net/supported-versions.php\" rel=\"nofollow noreferrer\">Ref</a>. All other PHP 5 versions are completely unsupported. You should be running PHP 7 today.</p>\n\n<p>Once you've done that, you c...
{ "AcceptedAnswerId": "206363", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T03:21:20.907", "Id": "206361", "Score": "1", "Tags": [ "php", "php5" ], "Title": "Validate array elements in PHP" }
206361
<p>I have a function to check the leap year as follows</p> <pre><code>bool IsLeapYear(int year) { if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) return true; else return false; } else return true; } else return false; } </code></pre> <p>I was wondering whether it would be correct to change this function by using guard clauses like below</p> <pre><code>bool IsLeapYear(int year) { if (year % 4 != 0) { return false; } if (year % 4 == 0 &amp;&amp; year % 100 == 0 &amp;&amp; year % 400 != 0) { return false; } return true; } </code></pre> <p>Is it going to introduce any side effects by using guard clause like this or is there a better way to write this function?</p>
[]
[ { "body": "<h1>Compilers</h1>\n\n<p>Welcome to Code Review. First of all, \"better\" is a very personal opinion term, unless it has been defined. From a compiler's point of view, both functions do the same. As compilers are data flow analysis beasts, a decent one will simplify the function's flow to the followi...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T06:09:40.373", "Id": "206365", "Score": "4", "Tags": [ "c++", "datetime", "comparative-review" ], "Title": "Leap year determination using guard clause" }
206365
<p>I have the following method, which can be written in the following two ways: which one would you prefer, and why?</p> <pre><code># version with case...when def choose(value) case value when value &lt; LOWER_LIMIT 'a' when value &gt; UPPER_LIMIT 'b' else 'c' end # version with Hash#fetch def choose(value) { (value &lt; LOWER_LIMIT) =&gt; 'a', (value &gt; UPPER_LIMIT) =&gt; 'b' }.fetch(true, 'c') end </code></pre> <p>I personally find the first one more linear and readable.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T18:48:43.300", "Id": "398262", "Score": "0", "body": "What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the ...
[ { "body": "<p>I would have just gone for an if/else, this really isn't a good use case for a <code>case</code> statement and I've never seen anyone use a hash like that except for demonstration purposes:</p>\n\n<pre><code>def choose(value)\n if value &lt; LOWER_LIMIT\n 'a'\n elsif value &lt;= UPPER_LIMIT\n...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T08:23:31.030", "Id": "206370", "Score": "2", "Tags": [ "ruby", "hash-map" ], "Title": "case...when or Hash#fetch" }
206370
<p>I query a database and pass the data for processing as a <code>DataTable</code>. After all computations (grouping, filtering, formatting etc.) I need to send it to a Web-Service as json that will generate emails. This means I need to convert it to a more json and html friendly structure because I need a header, body and footer parts separated. I was using a <code>DataTable</code> and a flat structure before but it's a pain to debug it as you never really know where the header, body or footer begin or end. Passing indexes around is very error prone.</p> <p>To make this conversion process more reliable and debug-friendly I created a couple of helpers.</p> <p>At the top there is the <code>TripleTableDto</code> that should resemble a html-table with its three parts.</p> <pre><code>internal class TripleTableDto { public TripleTableDto(IEnumerable&lt;SoftString&gt; columns, bool areHeaders = true) { Head = new TableDto&lt;object&gt;(columns); if (areHeaders) { Head.NewRow(); foreach (var column in columns) { Head.LastRow[column] = column; } } Body = new TableDto&lt;object&gt;(columns); Foot = new TableDto&lt;object&gt;(columns); } public TripleTableDto(IEnumerable&lt;string&gt; columns, bool areHeaders = true) : this(columns.Select(SoftString.Create), areHeaders) { } [NotNull] public TableDto&lt;object&gt; Head { get; } [NotNull] public TableDto&lt;object&gt; Body { get; } [NotNull] public TableDto&lt;object&gt; Foot { get; } [NotNull] public IDictionary&lt;string, IEnumerable&lt;IEnumerable&lt;object&gt;&gt;&gt; Dump() { return new Dictionary&lt;string, IEnumerable&lt;IEnumerable&lt;object&gt;&gt;&gt; { [nameof(Head)] = Head.Dump(), [nameof(Body)] = Body.Dump(), [nameof(Foot)] = Foot.Dump(), }; } } </code></pre> <p>This is made of three <code>TableDto&lt;T&gt;</code>s that hold the actual data. </p> <pre><code>internal class TableDto&lt;T&gt; { private readonly IDictionary&lt;SoftString, ColumnDto&gt; _columnByName; private readonly IDictionary&lt;int, ColumnDto&gt; _columnByOrdinal; private readonly List&lt;RowDto&lt;T&gt;&gt; _rows = new List&lt;RowDto&lt;T&gt;&gt;(); public TableDto(IEnumerable&lt;SoftString&gt; names) { var columns = names.Select((name, ordinal) =&gt; new ColumnDto { Name = name, Ordinal = ordinal }).ToList(); _columnByName = columns.ToDictionary(x =&gt; x.Name); _columnByOrdinal = columns.ToDictionary(x =&gt; x.Ordinal); } public TableDto(params string[] names) : this(names.Select(SoftString.Create)) { } [NotNull] public RowDto&lt;T&gt; LastRow =&gt; _rows.LastOrDefault() ?? throw new InvalidOperationException("There are no rows."); [NotNull] public RowDto&lt;T&gt; NewRow() { var newRow = new RowDto&lt;T&gt; ( _columnByName.Values, name =&gt; _columnByName.GetItemSafely(name), ordinal =&gt; _columnByOrdinal.GetItemSafely(ordinal) ); _rows.Add(newRow); return newRow; } [NotNull, ItemNotNull] public IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Dump() =&gt; _rows.Select(row =&gt; row.Dump()); } </code></pre> <p>I wanted to make sure that I'm not introducing new column names or change their order by mistake. This is taken care of by two more dtos. The <code>ColumnDto</code> that stores information about a single column...</p> <pre><code>internal class ColumnDto { public static readonly IComparer&lt;ColumnDto&gt; Comparer = ComparerFactory&lt;ColumnDto&gt;.Create ( isLessThan: (x, y) =&gt; x.Ordinal &lt; y.Ordinal, areEqual: (x, y) =&gt; x.Ordinal == y.Ordinal, isGreaterThan: (x, y) =&gt; x.Ordinal &gt; y.Ordinal ); public SoftString Name { get; set; } public int Ordinal { get; set; } public override string ToString() =&gt; $"{Name}[{Ordinal}]"; } </code></pre> <p>...and the <code>RowDto</code> that keeps an eye on the correct column order. It can work either with names or indexes and retrieves the actual column used as a key for the <code>SortedDictionary</code> in one of two other mapping dictionaries. I'm using here one of my dictionary extensions <a href="https://github.com/he-dev/Reusable/blob/master/Reusable.Core/src/Collections/DictionaryHelper.cs#L10" rel="noreferrer"><code>GetItemSafely</code></a> that provides a wrapper exception with the name of the missing key for easier debugging.</p> <pre><code>public class RowDto&lt;T&gt; { private readonly IDictionary&lt;ColumnDto, T&gt; _data; private readonly Func&lt;SoftString, ColumnDto&gt; _getColumnByName; private readonly Func&lt;int, ColumnDto&gt; _getColumnByOrdinal; internal RowDto(IEnumerable&lt;ColumnDto&gt; columns, Func&lt;SoftString, ColumnDto&gt; getColumnByName, Func&lt;int, ColumnDto&gt; getColumnByOrdinal) { // All rows need to have the same length so initialize them with 'default' values. _data = new SortedDictionary&lt;ColumnDto, T&gt;(columns.ToDictionary(x =&gt; x, _ =&gt; default(T)), ColumnDto.Comparer); _getColumnByName = getColumnByName; _getColumnByOrdinal = getColumnByOrdinal; } [CanBeNull] public T this[SoftString name] { get =&gt; _data.GetItemSafely(_getColumnByName(name)); set =&gt; _data[_getColumnByName(name)] = value; } [CanBeNull] public T this[int ordinal] { get =&gt; _data.GetItemSafely(_getColumnByOrdinal(ordinal)); set =&gt; _data[_getColumnByOrdinal(ordinal)] = value; } [NotNull, ItemCanBeNull] public IEnumerable&lt;T&gt; Dump() =&gt; _data.Values; } </code></pre> <p>The order of the columns is supported by the <code>ComparerFactory&lt;T&gt;</code> that is a helper for creating <code>IComparer&lt;T&gt;</code>s without worrying about the <code>null</code>-checks or returning the correct number in each case.</p> <pre><code>internal static class ComparerFactory&lt;T&gt; { private class Comparer : IComparer&lt;T&gt; { private readonly Func&lt;T, T, bool&gt; _isLessThan; private readonly Func&lt;T, T, bool&gt; _areEqual; private readonly Func&lt;T, T, bool&gt; _isGreaterThan; public Comparer(Func&lt;T, T, bool&gt; isLessThan, Func&lt;T, T, bool&gt; areEqual, Func&lt;T, T, bool&gt; isGreaterThan) { _isLessThan = isLessThan; _areEqual = areEqual; _isGreaterThan = isGreaterThan; } public int Compare(T x, T y) { if (ReferenceEquals(x, y)) return 0; if (ReferenceEquals(x, null)) return -1; if (ReferenceEquals(y, null)) return 1; if (_isLessThan(x, y)) return -1; if (_areEqual(x, y)) return 0; if (_isGreaterThan(x, y)) return 1; // Makes the compiler very happy. return 0; } } public static IComparer&lt;T&gt; Create(Func&lt;T, T, bool&gt; isLessThan, Func&lt;T, T, bool&gt; areEqual, Func&lt;T, T, bool&gt; isGreaterThan) { return new Comparer(isLessThan, areEqual, isGreaterThan); } } </code></pre> <h3>Example</h3> <p>When I'm done filling this with data I call <code>.Dump()</code> on the <code>TripleTableDto</code> and pass it to the json-serializer to do the rest (it uses one more helper for <a href="https://github.com/he-dev/Reusable/blob/master/Reusable.Utilities.JsonNet/src/SoftStringConverter.cs" rel="noreferrer">converting my <code>SoftString</code></a> to json).</p> <pre><code>void Main() { var table = new TripleTableDto(new[] { "Timestamp", "Level", "Message" }); // add other data in different order table.Body.NewRow(); table.Body.LastRow["timestamp"] = DateTime.UtcNow; table.Body.LastRow["message"] = "Hallo!"; table.Body.LastRow["level"] = "Debug"; table.Body.NewRow(); table.Body.LastRow["level"] = "Warning"; table.Body.LastRow["timestamp"] = DateTime.UtcNow; table.Body.LastRow["message"] = "Hi!"; table.Foot.NewRow(); //table.Foot.LastRow["message"] = 4; //table.Foot.LastRow["timestamp"] = 2; table.Foot.LastRow["level"] = 3; //table.Foot.LastRow["levels"] = 3; // Boom! // TableDto.Dump() + LINQPad.Dump() table.Dump().Dump(); JsonConvert.SerializeObject(table.Dump(), new JsonSerializerSettings { Converters = { new SoftStringConverter() }, Formatting = Newtonsoft.Json.Formatting.Indented }).Dump(); } </code></pre> <p>I'm sequentially adding data to this dto so there are not many APIs. Just as many as required to support this simple workflow: add a row, set its values, next... dump.</p> <p>It produces the following json-ouput from</p> <p><img src="https://i.stack.imgur.com/KwMwZ.png" width="300" /></p> <pre class="lang-js prettyprint-override"><code>{ "Head": [ [ "Timestamp", "Level", "Message" ] ], "Body": [ [ "2018-10-27T08:17:33.8372643Z", "Debug", "Hallo!" ], [ "2018-10-27T08:17:33.8372643Z", "Warning", "Hi!" ] ], "Foot": [ [ null, 3, null ] ] } </code></pre> <hr> <p>The server is <em>stupid</em> and doesn't require much logic (yet) so it parses everything into something simpler:</p> <blockquote> <pre><code>internal class TableDto { public List&lt;List&lt;object&gt;&gt; Head { get; set; } = new List&lt;List&lt;object&gt;&gt;(); public List&lt;List&lt;object&gt;&gt; Body { get; set; } = new List&lt;List&lt;object&gt;&gt;(); public List&lt;List&lt;object&gt;&gt; Foot { get; set; } = new List&lt;List&lt;object&gt;&gt;(); } </code></pre> </blockquote> <hr> <p>In what way would you improve any of these classes? My main goal is to provide as much debugging help as possible when a mistake happens. I'd like to know primarily what went wrong and where without much effort. Preprocessing the data is tricky enough so I don't want to add any more logic on the user-side. This table-dto should be able to take care of itself. What do you think?</p>
[]
[ { "body": "<p>This</p>\n\n<blockquote>\n<pre><code> Head.NewRow();\n foreach (var column in columns)\n {\n Head.LastRow[column] = column;\n }\n</code></pre>\n</blockquote>\n\n<p>can be optimized a bit:</p>\n\n<pre><code> var newRow = Head.NewRow();\n foreach ...
{ "AcceptedAnswerId": "206431", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T08:37:32.713", "Id": "206371", "Score": "4", "Tags": [ "c#", "sorting", "hash-map", "json.net", "dto" ], "Title": "Preparing tabular data to be sent as json" }
206371
<p>I needed to convert some custom icons that were in .png format to .svg format and did not want to use an online converter for it. </p> <p>I could not find an out-of-the-box solution online so I created my own with what I could find.</p> <p>Out of curiosity and a willingness to learn, as well as to maybe serve the needs of others trying to accomplish the same task I am uploading it here as my first post. </p> <p>My knowledge on image formats is very minimum at best. My knowledge of shell scripting is at a beginner's stage. My knowledge of coding overall is at hobby level.</p> <p><strong>I am hoping any comments will help to</strong>:</p> <ol> <li>Improve on the overall code quality &amp; readability (also to benefit future maintenance)</li> <li>Improve on the quality of the actual conversion, make it less lossy.</li> <li>If possible remove any unneccessary dependencies, as currently potrace is used which wasn't installed by default on my arch system. </li> </ol> <p><strong>My current working setup</strong>:</p> <pre><code>function png_to_svg() { ### First use convert to convert to .pnm format ### number_of_dots_in_filepath=$(echo "$1" | grep -o "\." | wc -l) pnm_filepath="" for i in $(seq 1 $number_of_dots_in_filepath); do pnm_filepath="$pnm_filepath.$(echo "$1" | cut -f $i -d '.')" done remove_leading_space=${pnm_filepath#?} pnm_filepath="$remove_leading_space.pnm" command="convert \"$1\" \"$pnm_filepath\"" eval "$command" ### Second use potrace to convert .pnm to .svg file ### svg_filepath="$remove_leading_space.svg" command="potrace \"$pnm_filepath\" -s -o \"$svg_filepath\"" eval "$final_command" ### Third and last: remove temporary .pnm file ### eval "rm \"$pnm_filepath\"" } </code></pre> <p><strong>Edited setup after first reply</strong>:</p> <pre><code>function png_to_svg() { ### First use convert to convert to .pnm format ### pnm_filepath=${1%.*}.pnm convert "$1" "$pnm_filepath" ### Second use potrace to convert .pnm to .svg file ### svg_filepath=${1%.*}.svg potrace "$pnm_filepath" -s -o "$svg_filepath" ### Third and last: remove temporary .pnm file ### rm "$pnm_filepath" } </code></pre>
[]
[ { "body": "<p>You don’t need <code>eval</code>. For example,</p>\n\n<pre><code>eval \"rm \\\"$pnm_filepath\\\"\"\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>rm \"$pnm_filepath\"\n</code></pre>\n\n<p>but the latter is more readable.</p>\n\n<p>The same is true for the other two cases where you use <code...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T11:29:15.423", "Id": "206376", "Score": "4", "Tags": [ "beginner", "image", "linux", "shell", "svg" ], "Title": "Shell function to convert .png to .svg file" }
206376
<p>The code below takes an input and based on the input gives out a time, date or both. Please will you review me for this and tell me how I can improve this? By the way, I only started learning python.</p> <pre><code>import datetime x = datetime.datetime.now() s = '/' c = ':' print("Welcome to Date and Time!") input = int(input("Please choose one of these options below and type it in the prompt: \n 1 - To know the date (DD : MM : YY) \n 2 - To know the time (Hours : Minutes : Seconds ) \n 3 - To know both date and time.\n")) if input == 1 : print(str(x.day) + s + str(x.month) + s + str(x.year) ) elif input == 2 : print(x.strftime('%H') + c + x.strftime('%M') + c + x.strftime('%S')) elif input == 3 : print(str(x.day) + s + str(x.month) + s + str(x.year) + ' ' + x.strftime('%H') + c + x.strftime('%M') + c + x.strftime('%S')) else: print("You didn't type in 1, 2 or 3!") </code></pre>
[]
[ { "body": "<p>My first time here providing code review on stackexchange. I randomly clicked a link and arrived here. Anyway, here's how I'd improve your code:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python\n\nimport datetime\n\nDATE_FORMAT = \"%d/%m/%y\"\nDATE_FORMAT_FOR_HUMA...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T11:37:44.970", "Id": "206377", "Score": "2", "Tags": [ "python", "beginner", "datetime" ], "Title": "Display date and/or time" }
206377
<p>I'm trying to write as simple I/O library in x64 using linux syscalls</p> <pre><code>section .text strlen: xor rdx, rdx .loop: cmp [rsi + rdx], 0 je .exit inc rdx jmp .loop .exit: ret ; value in rdx puts: ; string passed through rsi mov rax, 1 call strlen syscall </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T10:54:21.497", "Id": "398215", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y...
[ { "body": "<p>Your loop uses 2 jumps (<code>je</code>/<code>jmp</code>) on every iteration! Jumping is expensive, so a solution that needs only 1 jump (<code>jne</code>) will be more effective.</p>\n\n<pre><code>strlen:\n xor rdx, rdx\n dec rdx ; This compensates for the INC that is happening first....
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T13:04:03.243", "Id": "206381", "Score": "4", "Tags": [ "strings", "io", "linux", "assembly", "x86" ], "Title": "Simple puts() function in x64 assembly" }
206381
<p>My goals for the algorithm were to use recursion, to avoid mutation, and to decouple the tree walking from the action that we take on each node. My sense is that the result uses mode code is reasonably readable but that it might be unconventional. </p> <h1>Test</h1> <h3>Test Data</h3> <pre><code>const nestedPaths: TreeNode = { path: '/', children: [ { path: '/one', children: [ { path: '/two', children: [ { path: '/three', } ] } ] }, { path: '/four', children: [ { path: '/five', }, { path: '/six' } ], } ] }; </code></pre> <h3>Test Output</h3> <p>The <code>...</code> represents the unchanged <code>path</code> and <code>children</code> properties of the original node. </p> <pre><code>const expected = [ { fullPath: '/four/six', ... }, { fullPath: '/four/five', ... }, { fullPath: '/four', ... }, { fullPath: '/one/two/three', ... }, { fullPath: '/one/two', ... }, { fullPath: '/one', ... }, ]; </code></pre> <h1>Algorithm</h1> <h3>Types</h3> <pre><code>type TreeNode = { path: string; children?: TreeNode[]; }; type FlatTreeNode = TreeNode &amp; { fullPath: string; }; type FlattenTreeNodeState = { previousNode: FlatTreeNode; flattenedTree: FlatTreeNode[]; }; </code></pre> <h3>Walk Tree Depth First</h3> <pre><code>const walkTreeDepthFirst = &lt;TState&gt;( node: TreeNode, action: (parent: TreeNode, nextChild: TreeNode, state?: TState) =&gt; TState, state?: TState): TState | undefined =&gt; { // Use $state to avoid naming collisions while maintaining a functional approach. const traverseChildren = ($state?: TState, next = 0): TState | undefined =&gt; { // base cases: // there is no node // the node has no children // the node has children, but no next child if (!node || !node.children || !node.children[next]) { return $state; } const nextChild = node.children[next]; $state = action(node, nextChild, $state); const $updatedState = walkTreeDepthFirst(nextChild, action, $state); return traverseChildren($updatedState, next + 1); }; return traverseChildren(state); }; </code></pre> <h3>Flatten Tree Node</h3> <pre><code>const flattenTreeNode = ( parentNode: TreeNode, currentNode: TreeNode, state?: FlattenTreeNodeState) : FlattenTreeNodeState =&gt; { const defaultState = { previousNode: { path: '/', fullPath: '/', }, flattenedTree: [] }; const { previousNode, flattenedTree } = state || defaultState; const fullPathToParentNode = parentNode.path === previousNode.path ? previousNode.fullPath : parentNode.path; const fullPathToCurrentNode = fullPathToParentNode === '/' ? currentNode.path : fullPathToParentNode + currentNode.path; const currentNodeWithFullPath = { ...currentNode, fullPath: fullPathToCurrentNode, }; return { previousNode: currentNodeWithFullPath, flattenedTree: [...flattenedTree, currentNodeWithFullPath], } } </code></pre> <h3>Flatten Tree</h3> <pre><code>const flattenTree = (node: TreeNode) =&gt; walkTreeDepthFirst(node, flattenTreeNode); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T14:48:25.033", "Id": "206388", "Score": "1", "Tags": [ "algorithm", "tree", "graph", "typescript" ], "Title": "Functional, recursive algorithm for flattening a tree" }
206388
<p>This wrapper library parses text into commands for the <a href="https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/overview" rel="nofollow noreferrer">Adafruit Motor Shield v2</a> using the <a href="https://github.com/nickgammon/Regexp" rel="nofollow noreferrer">Regexp</a> library. Currently, only the DC motor functions <code>setSpeed</code> and <code>setDirection</code> are implemented, but adding more functions is trivial.</p> <p>The general command syntax is <code>MSv2_&lt;shield number in hex&gt;_&lt;command name&gt;_&lt;parameters separated by _s&gt;</code></p> <p><em>For example:</em></p> <p>To set the speed to 255/255 for motor 1 on shield 96, pass <code>MSv2_60_speed_1_FF</code> to the message parameter of <code>checkMotorShieldMessage</code>.</p> <p>To set the direction to FORWARD for motor 1 on shield 96, pass <code>MSv2_60_direction_1_1</code>. </p> <p>A pointer to the toWrite String is passed so the function can dereference and alter it. In this way, toWrite can pass an error or success message back to where it was called.</p> <p><strong>motor_shield.ino</strong></p> <pre><code>/* This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2 It won't work with v1.x motor shields! Only for the v2's with built in PWM control For use with the Adafruit Motor Shield v2 ----&gt; http://www.adafruit.com/products/1438 */ #include &lt;Wire.h&gt; #include "MotorShieldv2Lib.h" String toWrite; void setup() { Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("Adafruit Motorshield v2 - DC Motor test!"); toWrite = ""; } void loop() { String usb = Serial.readString(); if(checkMotorShieldMessage(usb, &amp;toWrite)){ //https://stackoverflow.com/questions/2229498/passing-by-reference-in-c //make sure this changes Serial.print(toWrite);//passing the pointer } } </code></pre> <p><strong>MotorShieldv2Lib.h</strong></p> <pre><code>#ifndef MotorShieldv2lib #define MotorShieldv2lib #if (ARDUINO &gt;=100) #include &lt;arduino.h&gt; #else #include "WProgram.h" #endif //#include &lt;Wire.h&gt; // the serial library? // hardware vs software serial https://forum.arduino.cc/index.php?topic=407633.0 // maybe you don't need serial? #include &lt;Adafruit_MotorShield.h&gt; #include "MotorShieldv2Lib.h" using namespace std; /* * Take a message and a Stream (Serial object) * - the message was received from the stream * - The stream will send a message back if it has to (error code...) */ boolean checkMotorShieldMessage(String message, String *toWrite); #endif </code></pre> <p><strong>MotorShieldv2Lib.cpp</strong></p> <pre><code>#include &lt;Regexp.h&gt; //from here: https://github.com/nickgammon/Regexp installed in computer's Arduino library, so you'll have to do this // https://www.youtube.com/watch?v=fE3Dw0slhIc //#include &lt;Wire.h&gt; // the serial library? #include &lt;Adafruit_MotorShield.h&gt; #include "MotorShieldv2Lib.h" static const char SHIELD_PATTERN_START [] = "^MSv2_[67][0-9A-Fa-f]_";//len == 8 static const char SPEED_PATTERN [] = "^MSv2_[67][0-9A-Fa-f]_speed_[1-4]_[0-9a-fA-F]{2,2}$"; //make sure you send hex bytes! static const char DIR_PATTERN [] = "^MSv2_[67][0-9A-Fa-f]_direction_[1-4]_[0-2]$"; static Adafruit_MotorShield *shields [32] = {}; // Initialized as all null //https://stackoverflow.com/questions/2615071/c-how-do-you-set-an-array-of-pointers-to-null-in-an-initialiser-list-like-way // the above link described this initialization // shields holds pointer to the shield objects. // shields are addressed 0x60 to 0x7F for a total of 32 unique addresses. // In this array, [0] == address 0x60, [31] == address 0x7F // note, static in this context means the array's pointer //can't change, the array values can /* * Converts the message from the Serial port to its corresponding motor * */ boolean getMotorShield(String message, Adafruit_MotorShield *shield){ // * https://stackoverflow.com/questions/45632093/convert-char-to-uint8-t-array-with-a-specific-format-in-c // the above might help with the conversion //https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/stacking-shields //Note: 0x70 is the broadcast //pointers: https://stackoverflow.com/questions/28778625/whats-the-difference-between-and-in-c String shieldAddress = message.substring(5,7);//make sure this is the right length char carr [2]; shieldAddress.toCharArray(carr, 2); uint8_t addr = strtol(carr, NULL, 16); if(addr&lt;96 || addr &gt; 127){ Serial.print(addr); Serial.print(shieldAddress +"\n");//not sure if this will work return false; } if(!shields[addr - 96]){//checks for null pointer //Adafruit_MotorShield *AMS = malloc(sizeof(Adafruit_MotorShield)); //AMS-&gt;add Adafruit_MotorShield AMS = Adafruit_MotorShield(addr); shields[addr - 96] = &amp;AMS; } *shield = *shields[addr - 96]; return true; }; /* * gets the motor, then sets the speed */ boolean setMotorSpeed(String message, Adafruit_MotorShield shield){ String motorID = message.substring(15,16);//make sure this is the right length char carr [1]; motorID.toCharArray(carr, 1); uint8_t motorAddr = strtol(carr, NULL, 16); String speedIn = message.substring(16,18);//make sure this is the right length char speedCarr [2]; speedIn.toCharArray(speedCarr, 2); uint8_t intSpeed = strtol(speedCarr, NULL, 16); shield.getMotor(motorAddr)-&gt;setSpeed(intSpeed); return true; } /* * gets the motor, then sets the direction * * see here: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/library-reference#void-run-uint8-t-9-7 */ boolean setMotorDir(String message, Adafruit_MotorShield shield){ String motorID = message.substring(19,20);//make sure this is the right length char carr [1]; motorID.toCharArray(carr, 1); uint8_t motorAddr = strtol(carr, NULL, 16); String dirIn = message.substring(21,23);//make sure this is the right length char dirCarr [2]; dirIn.toCharArray(dirCarr, 2); uint8_t intDir = strtol(dirCarr, NULL, 16); shield.getMotor(motorAddr)-&gt;run(intDir); return true; } /* * motor shield signals are of the format "MSv2_shield number_then the command_parameters" * see the constants at the top for the commands * * if the message is meant for a motor shield: * - If the shield doesn't exist, create it and add it to shields * - If there's not a shield connected with the corresponding address, throw an error * - Run the function on the right shield * - return true * else: * - return false * * Remember, you NEED to de-reference toWrite with this: https://stackoverflow.com/questions/2229498/passing-by-reference-in-c */ boolean checkMotorShieldMessage(String message, String *toWrite){ MatchState ms; char buf [message.length()]; message.toCharArray(buf, message.length()); ms.Target(buf); char isForShield = ms.Match(SHIELD_PATTERN_START);//check if the message is for the shield // converting to char array: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/tochararray/ // regex from: https://github.com/nickgammon/Regexp also see the installed examples if(isForShield &gt; 0){ //parse out which shield, set it as a variable Adafruit_MotorShield as = Adafruit_MotorShield();//can't be named asm? if(!getMotorShield(message, &amp;as)){ //set toWrite to an error message saying this isn't a //valid number *toWrite = String("MotorShield: That isn't a valid shield address." + message); return true; } if(ms.Match(SPEED_PATTERN) &gt; 0){ //parse out params //set speed on the shield setMotorSpeed(message, as); return true; }else if(ms.Match(DIR_PATTERN) &gt; 0){ //set direction setMotorDir(message, as); return true; //ADD OTHER STUFF (SET SERVOS...) // note, people can put crap between the //SHIELD_PATTERN_START and the parameter patterns, but this isn't //really a problem }else{ *toWrite = String("MotorShield: No matching command found."); return false; } }else{ return false; } } </code></pre>
[]
[ { "body": "<h2>Avoid regular expressions</h2>\n\n<blockquote>\n <p>Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. -- <em>Jamie Zawinsky</em></p>\n</blockquote>\n\n<p>Your problem is simple enough that you don't need any regular expressions...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T17:23:56.827", "Id": "206393", "Score": "1", "Tags": [ "c++", "arduino" ], "Title": "Arduino Adafruit Motor Shield v2 wrapper for parsing text into commands" }
206393
<p>I currently need some advice regarding the best practices and whether this is code is valid from a review perspective.</p> <p>Needs some tips of what i should be writing like and whether there are any clear pointers on how i can improve.</p> <pre><code>var Structure = function () { var _this = this; this.Version = "1.0"; this.GetDataFromCache = function (relatedNewsRequest) { _this.listRequest = _this.SetDefaultsProperties(relatedNewsRequest); return Product.AddIn.Cache.Get(Product.Digispace.SiteContext.WebId + _this.GetCacheKey()); }; this.GetCacheInterval = function () { var validCacheInterval = typeof (_this.listRequest.CacheInterval !== "undefined") &amp;&amp; _this.listRequest.CacheInterval !== null &amp;&amp; !isNaN(_this.listRequest.CacheInterval); if (validCacheInterval) { if (_this.listRequest.CacheInterval === -1) { return Product.Digispace.ConfigurationContext.CachingStrategyInterval; } else { return parseInt(_this.listRequest.CacheInterval); } } else { return 0; } }; this.GetCacheKey = function () { return Product.Digispace.ConfigurationContext.getCacheKey(_this.listRequest.SenderId); }; this.GetPropertyValue = function (requestIn, key, defaultValue) { var propertyValue = ""; for (var prop in requestIn) { if (key.toLowerCase() === prop.toLowerCase()) { propertyValue = requestIn[prop]; break; } } return (propertyValue === undefined || propertyValue.toString().trim() === "") ? defaultValue : propertyValue; }; this.SetDefaultsProperties = function (requestIn) { var requestOut = requestIn; requestOut.SenderId = _this.GetPropertyValue(requestIn, "id", ""); requestOut.rootWeb = _this.GetPropertyValue(requestIn, "isroot", true); requestOut.selectFields = _this.GetPropertyValue(requestIn, "selectfields", "ID,Title,TOImage,TOLink"); requestOut.viewXml = _this.GetPropertyValue(requestIn, "viewxml", `&lt;View&gt; &lt;Query&gt; &lt;OrderBy&gt;&lt;FieldRef Name='Title' Ascending='True' /&gt;&lt;/OrderBy&gt; &lt;/Query&gt; &lt;/View&gt;`); return requestOut; }; this.Init = function (properties) { _this.listRequest = _this.SetDefaultsProperties(properties); _this.listRequest.EditMode = Product.AddIn.Utilities.getEditMode(); _this.listRequest.listControl = _this; window["Example.Widgets.Structure.GetLandingItems"] = _this.GetLandingItems; _this.Prerender(); var control = new Product.AddIn.GenericListControlWidget(); control.Init(_this.listRequest); _this.listControl = control; }; this.Prerender = function () { Product.Digispace.AppPart.Eventing.Subscribe('/widget/updated/', _this.RefreshWidget, _this.listRequest.SenderId); }; this.Render = function () { _this.listControl.Render(); }; this.RefreshWidget = function (newProps) { if (newProps.id === _this.listRequest.id) { newProps = _this.SetDefaultsProperties(newProps); var control = new Product.AddIn.GenericListControlWidget(); control.Init(newProps); _this.listControl = control; _this.Render(); } }; this.GetLandingItems = function (data) { var dataItem, newItem, newData = {}, itemList = [], id = _this.listRequest.id; if (id === '12312-213123-513dasd') { newData.Header = 'Corporate Teams'; } else { newData.Header = 'Structure'; } try { for (var i = 0; i &lt; data.Items.length; i++) { dataItem = data.Items[i]; newItem = { Name: dataItem.Title, Url: dataItem.TOLink ? dataItem.TOLink.get_url() : '', Image: dataItem.TOImage ? dataItem.TOImage.get_url() : '' }; itemList.push(newItem); } newData.Items = itemList; newData.HasItems = newData.Items.length &gt; 0 ? true : false; return newData; } catch (err) { console.log(err); } }; }; module.exports = Structure; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T20:25:03.727", "Id": "398175", "Score": "1", "body": "What version of Node are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T21:32:36.487", "Id": "398178", "Score": "2", "body...
[ { "body": "<p><strong>(Potential) Mistakes</strong></p>\n\n<pre><code>typeof (_this.listRequest.CacheInterval !== \"undefined\")\n</code></pre>\n\n<p>This is not syntactically wrong, but it's not going to work the way you intended. This is going to return the type of the expression <code>(_this.listRequest.Cach...
{ "AcceptedAnswerId": "206427", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T19:48:58.623", "Id": "206398", "Score": "-1", "Tags": [ "javascript" ], "Title": "JS Pattern & Writing style" }
206398
<p>I'm trying to write an equivalent of PHP's htmlspecialchars() in C. What is my implementation missing or doing wrong?</p> <pre><code>char www_specialchars_html(char *dest, char *dest_last, char *src) { while (*src != 0) { switch(*src) { //If a special character is found, replace with its HTML entity. case '&amp;': if ((dest + 5) &gt; dest_last) { return 1; } *dest = '&amp;'; dest++; *dest = 'a'; dest++; *dest = 'm'; dest++; *dest = 'p'; dest++; *dest = ';'; dest++; src++; break; case '"': if ((dest + 6) &gt; dest_last) { return 1; } *dest = '&amp;'; dest++; *dest = 'q'; dest++; *dest = 'u'; dest++; *dest = 'o'; dest++; *dest = 't'; dest++; *dest = ';'; dest++; src++; break; case '\'': if ((dest + 6) &gt; dest_last) { return 1; } *dest = '&amp;'; dest++; *dest = '#'; dest++; *dest = '0'; dest++; *dest = '3'; dest++; *dest = '9'; dest++; *dest = ';'; dest++; src++; break; case '&lt;': if ((dest + 4) &gt; dest_last) { return 1; } *dest = '&amp;'; dest++; *dest = 'l'; dest++; *dest = 't'; dest++; *dest = ';'; dest++; src++; break; case '&gt;': if ((dest + 4) &gt; dest_last) { return 1; } *dest = '&amp;'; dest++; *dest = 'g'; dest++; *dest = 't'; dest++; *dest = ';'; dest++; src++; break; case '\\': //Not required in HTML. if ((dest) &gt; dest_last) { return 1; } src++; break; default: //Default for characters that don't need to be replaced. if ((dest + 1) &gt; dest_last) { return 1; } *dest = *src; src++; dest++; break; } } *dest = 0; return 0; } </code></pre> <p>The function takes pointers to the destination, the last element of the destination and the source. It returns 1 if it can't write to the destination, and returns 0 when it has successfully copied to the destination. I'm still a relatively new C programmer.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T22:07:46.897", "Id": "398179", "Score": "0", "body": "Can you explain the `case` that handles the backslash character?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T22:13:20.037", "Id": "398180"...
[ { "body": "<ul>\n<li><p>You shouldn't pass a <code>char*</code> as buffer end but a <code>size_t size</code> corresponding to the size of the allocated buffer. So your available <code>length</code> will be <code>size - 2</code> (\"zero-indexed\" and \"trailing <code>'\\0'</code>\").</p></li>\n<li><p>You return ...
{ "AcceptedAnswerId": "206410", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T21:32:29.880", "Id": "206403", "Score": "3", "Tags": [ "beginner", "c", "strings", "html", "escaping" ], "Title": "htmlspecialchars() equivalent in C" }
206403
<p>I was looking for ways to traverse a binary tree and came across things like Morris Traversal. Except I don't like the idea of modyfying my tree, nor use stack or recursion. Not finding other solution, I wrote my own algorithm. Basically it's depth-first search, but every node has counter of type integer indicating how many times the method traversed this node. Given every node has a parent and two children, this counter takes values from 0 to 2. Therefore the method executes 3 times for every node. Here's the code:</p> <pre><code>Node root; public void Traverse() { Node node = root; while(node != null) { node = Get(node); } } Node Get(Node node) { Node child; if(node.Counter == 0) { child = node.Left; } else if(node.Counter == 1) { child = node.Right; System.Console.WriteLine(node);//display node } else { node.Counter = 0;//reset counter if(node.Parent != null) { node.Parent.Counter++; return node.Parent; } else { return null; } } if(child == null) { node.Counter++; return node; } return child; } </code></pre> <p>My question: in what terms if any, this code is better than Morris traversal or using stack?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T07:16:00.540", "Id": "398202", "Score": "1", "body": "Does this have any purpose or is it just for fun?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T10:03:10.297", "Id": "398208", "Score": ...
[ { "body": "<p><strong>Comparison</strong></p>\n\n<p>I don't think this approach offers any benefits compared to Morris traversal, a stack-based or a recursive approach:</p>\n\n<ul>\n<li>Both this and Morris are modifying the given tree, which I consider to be a negative thing. You're not rearranging nodes like ...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T22:18:46.387", "Id": "206409", "Score": "0", "Tags": [ "c#", "performance", "algorithm" ], "Title": "Binary tree inorder traversal without stack or recursion" }
206409
<p>I was looking for a light weight coding challenge and found <a href="http://www.cplusplus.com/forum/beginner/191523/" rel="nofollow noreferrer">this</a>:</p> <blockquote> <p>In the sport of diving, seven judges award a score between 0 and 10, where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score. Write a computer program that inputs a degree of difficulty and seven judges’ scores, and outputs the overall score for that dive. The program should ensure that all inputs are within the allowable data ranges.</p> </blockquote> <p>So, I tried to write some modern c++, and I am looking for suggestions to modernize it or is it so basic that this isn't a concept.</p> <pre><code>#include "pch.h" #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; constexpr auto JUDGES = 7; constexpr auto FUDGE_FACTOR = 0.6f; constexpr auto MIN_DIFFICULTY = 1.2f; constexpr auto MAX_DIFFICULTY = 3.8f; constexpr auto MIN_SCORE = 0.f; constexpr auto MAX_SCORE = 10.f; using std::cout; using std::endl; using std::cin; using std::string; using std::stringstream; float getInput(float low, float high) { string line; float ret; while (std::getline(cin, line)) { stringstream ss(line); if (ss &gt;&gt; ret &amp;&amp; ss.eof()) { if (ret&gt;=low &amp;&amp; ret&lt;=high) return ret; } cout &lt;&lt; "invalid input, try again: "; } return -1.0; } int main() { float difficulty; float total{ 0. }; float min{ MAX_SCORE }; float max{ MIN_SCORE }; cout &lt;&lt; "please enter degree of difficulty for the dive: "; difficulty = getInput(MIN_DIFFICULTY, MAX_DIFFICULTY); for (int i = 0; i &lt; JUDGES; ++i) { cout &lt;&lt; "please enter the judge #"&lt;&lt;i+1&lt;&lt;"'s score: "; auto score = getInput(MIN_SCORE, MAX_SCORE); if (score &lt; min) min = score; if (score &gt; max) max = score; total += score; } total -= (min + max); total *= difficulty * FUDGE_FACTOR; cout &lt;&lt; "The dive scored: " &lt;&lt; total &lt;&lt; endl; } </code></pre> <p>Any thoughts/suggestions will be welcome.</p>
[]
[ { "body": "<ul>\n<li><p>Variables should be initialized with proper values when declared (if not, they should be declared as close to the point of usage as practical). This way there's no need to initialize them to some invalid value, or risk leaving them uninitialized. (<code>difficulty</code> and <code>ret</c...
{ "AcceptedAnswerId": "206455", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T03:02:11.340", "Id": "206415", "Score": "4", "Tags": [ "c++", "beginner", "calculator" ], "Title": "Calculator for scoring dives in a competition" }
206415
<p>I wrote a small tool for searching git repositories for forbidden strings that I don't want to commit publicly. It's still something basic but it does the job.</p> <p>The project contains three files.</p> <p><code>config.py</code> - this is the file where I store the <em>secrects</em> like which directories to scan and which strings to look for in a long regex (here redacted). This is commited to a VSTS repository because they are private.</p> <pre><code>import re paths = [ "c:\\..", "c:\\.." ] re_forbidden = re.compile(r"(class)") </code></pre> <p><code>main.py</code> - this is the core file. It uses <code>os.walk</code> to list all files and directories. Not all directories and files are processed. Paths that don't get commited like <code>.git</code> or <code>bin</code> and files like <code>dll</code> are skipped. Paths and the <code>re_forbitten</code> regex are imported from the above <code>config.py</code>. When found something suspicious then it just outputs the path of the affected file.</p> <pre><code>import os import time import itertools import shutil import re import importlib.util config_spec = importlib.util.spec_from_file_location("config", "c:\\home\\projects\\classified\\python\\sanipyzer\\config.py") config = importlib.util.module_from_spec(config_spec) config_spec.loader.exec_module(config) from pprint import pprint ignore_dirs = [".git", "bin", "obj", ".vs"] ignore_files = ["dll", "exe", "pdb", "map"] def format_filemtime(path): filemtime = os.path.getmtime(path) return time.strftime('%Y-%m-%d', time.gmtime(filemtime)) def ignore_dir(dirpath): for dir in ignore_dirs: pattern = r"\\" + re.escape(dir) + r"(\\|$)" if re.search(pattern, dirpath): return True return False def ignore_file(file_name): for ext in ignore_files: pattern = r"\." + ext + "$" if re.search(pattern, file_name): return True return False def sanitize(path): start = time.perf_counter() for (dirpath, dirnames, filenames) in os.walk(path): if ignore_dir(dirpath): continue searchable_filenames = [filename for filename in filenames if not ignore_file(filename)] for filename in searchable_filenames: full_name = os.path.join(dirpath, filename) # without 'ignore' it throws for some files the UnicodeDecodeError 'utf-8' codec can't decode byte XXX in position XXX: invalid start byte with open(full_name, 'r', encoding="utf8", errors="ignore") as searchable: text = searchable.read() if config.re_forbidden.search(text): pprint(full_name) end = time.perf_counter() elapsed = round(end - start,2) print(f"elapsed: {elapsed} sec") # --- --- --- def main(): for path in config.paths: sanitize(path) if __name__ == '__main__': main() </code></pre> <p><code>test.py</code> - this file is a very simple unittest. It tests the two <em>ignore</em> methods.</p> <pre><code>import unittest from main import ignore_dir from main import ignore_file class MainTest(unittest.TestCase): def test_ignore_dir(self): self.assertTrue(ignore_dir("c:\\temp\\.git")) self.assertTrue(ignore_dir("c:\\temp\\.git\\abc")) def test_ignore_file(self): self.assertTrue(ignore_file("c:\\temp\\project\\program.dll")) self.assertFalse(ignore_file("c:\\temp\\project\\program.cs")) # tests the test #self.assertTrue(ignore_file("c:\\temp\\project\\program.cs")) if __name__ == "__main__": # use False to avoid the traceback "Exception has occurred: SystemExit" unittest.main(exit=False) </code></pre> <p>What do you think of it? Is this an acceptable solution or are there still many <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged &#39;beginner&#39;" rel="tag">beginner</a> mistakes? I wasn't sure about the two <code>ignore</code> lists whether they are <code>const</code> and should be UPPER_CASE or are they just simple variables?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T07:15:49.387", "Id": "398292", "Score": "1", "body": "Have you considered turning this into a [git pre-commit hook](https://githooks.com)? Then the rules would be automatically enforced (unless you commit with the `--no-verify` opti...
[ { "body": "<p>In general, it is a good code. However, I have a few remarks. Note: I am assuming that the code works perfectly as it should and will comment only on the style. Also, I assume that you are an experienced programmer and hence will not be explaining the basics, although if something is not clear ple...
{ "AcceptedAnswerId": "206439", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T07:37:44.357", "Id": "206422", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "regex", "file-system" ], "Title": "Searching repositories for files with forbidden strings" }
206422
<p>I want to create a 2D topdown game with Unity. When moving the player I also want him to rotate. </p> <p>Most tutorials provide a solution changing the localscale of the transform component on the x axis setting -1 for left movement and 1 for right movement.</p> <p>The attached SpriteRenderer component also got <code>flipX</code> and <code>flipY</code> checkboxes. I think setting these checkboxes by code might be more efficient.</p> <p>Using this example code achieves the desired rotation</p> <pre><code>bool flipX; bool flipY; void Update() { float horizontalInput = movementDirection.x; if (horizontalInput &gt; 0) { flipX = false; } else if (horizontalInput &lt; 0) { flipX = true; } float verticalInput = movementDirection.y; if (verticalInput &gt; 0) { flipY = false; } else if (verticalInput &lt; 0) { flipY = true; } spriteRenderer.flipX = flipX; spriteRenderer.flipY = flipY; } </code></pre> <p>My question is: Is there a way avoiding these four if-statements? Maybe there is a more optimized way using some math.</p>
[]
[ { "body": "<p>If you need people to review your code you have to give a complete bunch of working code. \nHere, we can only make assumptions about how what you show interoperate with what you don't show.</p>\n\n<p>Your <code>movementDirection..x</code> and <code>movementDirection..y</code> can only be <code>-1<...
{ "AcceptedAnswerId": "206430", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T09:43:36.750", "Id": "206424", "Score": "0", "Tags": [ "c#", "unity3d" ], "Title": "Flip Sprite using the SpriteRenderer component" }
206424
<p>I'm really struggling to understand application of classes and best practices in fairly advanced level GUIs, and such an example could be extremely helpful. Please note that this is my first GUI implementation and almost first Python implementation, and its working well. But the source code is ugly and long and definitely not how the code is supposed to be written.</p> <pre><code>from tkinter import * import json def guier(): #Indent four spaces gParmDict = {'var01': 1, 'var02': 'ABCD', 'var03': 'EFG', 'var04': 2.0, 'var05': 0.1, 'var06': 0.1, 'var07': 0.05, 'var08': 35, 'var09': 1.2, 'var10': 0.1, 'var11': 100.0, 'var12': 0.35, 'var13': 0.05, 'var14': 2.0, 'var15': 100.0} # Root Box #--------------------------------------------------------------------------------- gRoot = Tk() gRoot.configure(background='#696969') gRoot.title('Alpha (build 0.01)') gRoot.geometry('1140x690') gRoot.resizable(False, False) # Top Left Box #--------------------------------------------------------------------------------- lFrameLT = Frame(gRoot, width=300, height=500, bg = 'silver') lFrameLT.grid(row = 0, column = 0, padx = 5, pady = 5, ipadx = 5, ipady = 5) lFrameLT.grid_propagate(0) lFrameLT.grid_columnconfigure (0, weight = 1) Label(lFrameLT, text = "Algorithms", bg = '#313233', fg = '#FFFFFF', anchor = 'w', font='Helvetica 8 bold').grid(row = 0, column = 0, columnspan = 2, sticky = 'NSEW') var01Hold = IntVar() var01Hold.set(gParmDict['var01']) Radiobutton(lFrameLT, text='''Algorithm 1: ''', variable=var01Hold, value=1, indicatoron = 1).grid(row = 1, column = 0, padx = (20, 5), pady = (20, 0), sticky = 'W') Label(lFrameLT, text='''Description of algo 1 xxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxx xxxxxxxx xxxxxxxxxxxx xxxxxxxx xxxxxxxxxx''', justify = LEFT, bg = 'silver', fg = 'grey', wraplength = 265, font='Helvetica 8').grid(row = 2, column = 0, padx = (20, 5), pady = (0, 10), sticky = 'W') Radiobutton(lFrameLT, text='''Algorithm 2: ''', variable=var01Hold, value=2, indicatoron = 1).grid(row = 3, column = 0, padx = (20, 5), pady = (0, 0), sticky = 'W') Label(lFrameLT, text='''Description of algo 2 xxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxx xxxxxxxx xxxxxxxxxxxx xxxxxxxx xxxxxxxxxx''', justify = LEFT, bg = 'silver', fg = 'grey', wraplength = 265, font='Helvetica 8').grid(row = 4, column = 0, padx = (20, 5), pady = (0, 10), sticky = 'W') Radiobutton(lFrameLT, text='''Algorithm 3: ''', variable=var01Hold, value=3, indicatoron = 1).grid(row = 5, column = 0, padx = (20, 5), pady = (0, 0), sticky = 'W') Label(lFrameLT, text='''Description of algo 3 xxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxx xxxxxxxx xxxxxxxxxxxx xxxxxxxx xxxxxxxxxx''', justify = LEFT, bg = 'silver', fg = 'grey', wraplength = 265, font='Helvetica 8').grid(row = 6, column = 0, padx = (20, 5), pady = (0, 10), sticky = 'W') Radiobutton(lFrameLT, text='''Algorithm 4: ''', variable=var01Hold, value=4, indicatoron = 1).grid(row = 7, column = 0, padx = (20, 5), pady = (0, 0), sticky = 'W') Label(lFrameLT, text='''Description of algo 4 xxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxx xxxxxxxx xxxxxxxxxxxx xxxxxxxx xxxxxxxxxx''', justify = LEFT, bg = 'silver', fg = 'grey', wraplength = 265, font='Helvetica 8').grid(row = 8, column = 0, padx = (20, 5), pady = (0, 10), sticky = 'W') # Bottom Left Box #-------------------------------------------------------------------------------------- lFrameLB = Frame(gRoot, width=300, height=150, bg = 'silver') lFrameLB.grid(row = 1, column = 0, padx = 5, pady = 5, ipadx = 5, ipady = 5) lFrameLB.grid_propagate(0) lFrameLB.grid_columnconfigure (0, weight = 1) Label(lFrameLB, text = "Control", bg = '#313233', fg = '#FFFFFF', anchor = 'w', font='Helvetica 8 bold').grid(row = 0, column = 0, columnspan = 4, sticky = 'NSEW') Button(lFrameLB, text = "Test Algorithm", command = print("Test in progress")).grid(row = 1, column = 1, sticky = 'NSEW', padx = (5, 20), pady = (10, 10)) Button(lFrameLB, text = "Activate Algorithm", command = print("Algo live...")).grid(row = 1, column = 3, sticky = 'NSEW', padx = (5, 20), pady = (10, 10)) # Top Right Box #-------------------------------------------------------------------------------------- lFrameRT = Frame(gRoot, width=800, height=500, bg = 'silver') lFrameRT.grid(row = 0, column = 1, padx = 5, pady = 5, ipadx = 5, ipady = 5) lFrameRT.grid_propagate(0) lFrameRT.grid_columnconfigure (0, weight = 1) Label(lFrameRT, text = "Parameters", bg = '#313233', fg = '#FFFFFF', anchor = 'w', font='Helvetica 8 bold').grid(row = 0, column = 0, columnspan = 6, sticky = 'NSEW') var02Hold = StringVar() var02Hold.set(gParmDict['var02']) Label(lFrameRT, text = "Base method:", bg = 'silver').grid(row = 1, column = 0, padx = (20, 5), pady = (20, 0), sticky = 'E') Entry(lFrameRT, width = 10, textvariable = var02Hold, justify = 'center').grid(row = 1, column = 1, padx = (5, 20), pady = (20, 0), sticky = 'W') var03Hold = StringVar() var03Hold.set(gParmDict['var03']) Label(lFrameRT, text = "Target method:", bg = 'silver').grid(row = 2, column = 0, padx = (20, 5), pady = (20, 0), sticky = 'E') Entry(lFrameRT, width = 10, textvariable = var03Hold, justify = 'center').grid(row = 2, column = 1, padx = (5, 20), pady = (20, 0), sticky = 'W') var04Hold = DoubleVar() var04Hold.set(gParmDict['var04']) Label(lFrameRT, text = "Goal [%]:", bg = 'silver').grid(row = 1, column = 2, padx = (20, 5), pady = (20, 0), sticky = 'E') Entry(lFrameRT, width = 10, textvariable = var04Hold, justify = 'center').grid(row = 1, column = 3, padx = (5, 20), pady = (20, 0), sticky = 'W') var05Hold = DoubleVar() var05Hold.set(gParmDict['var05']) Label(lFrameRT, text = "Test Backup [Days]:", bg = 'silver').grid(row = 2, column = 2, padx = (20, 5), pady = (20, 0), sticky = 'E') Entry(lFrameRT, width = 10, textvariable = var05Hold, justify = 'center').grid(row = 2, column = 3, padx = (5, 20), pady = (20, 0), sticky = 'W') var06Hold = DoubleVar() var06Hold.set(gParmDict['var06']) Label(lFrameRT, text = "Cost factors [%]:", bg = 'silver').grid(row = 1, column = 4, padx = (20, 5), pady = (20, 0), sticky = 'E') Entry(lFrameRT, width = 10, textvariable = var06Hold, justify = 'center').grid(row = 1, column = 5, padx = (5, 20), pady = (20, 0), sticky = 'W') var07Hold = DoubleVar() var07Hold.set(gParmDict['var07']) Label(lFrameRT, text = "Cost factor2 [%]:", bg = 'silver').grid(row = 2, column = 4, padx = (20, 5), pady = (20, 0), sticky = 'E') Entry(lFrameRT, width = 10, textvariable = var07Hold, justify = 'center').grid(row = 2, column = 5, padx = (5, 20), pady = (20, 0), sticky = 'W') lFrameRTB = Frame(lFrameRT, width=700, height=320, bg = 'dark grey') lFrameRTB.grid(row = 3, column = 0, padx = 20, pady = (20, 10), ipadx = 5, ipady = 5, columnspan = 6, sticky = 'NSEW') lFrameRTB.grid_propagate(0) Label(lFrameRTB, text = "SITUATION 1", width = 10, bg = 'dark orange', fg = 'white', font = 'helvatica 8 bold').grid(row = 0, column = 0, columnspan = 2, sticky = 'NSEW') var08Hold = IntVar() var08Hold.set(gParmDict['var08']) Label(lFrameRTB, text = "Drive [Minutes]:", bg = 'dark grey').grid(row = 1, column = 0, padx = (20, 5), pady = (10, 0), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var08Hold, justify = 'center').grid(row = 1, column = 1, padx = (5, 20), pady = (10, 0), sticky = 'W') var09Hold = DoubleVar() var09Hold.set(gParmDict['var09']) Label(lFrameRTB, text = "Minimum drop [%]:", bg = 'dark grey').grid(row = 2, column = 0, padx = (20, 5), pady = (10, 0), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var09Hold, justify = 'center').grid(row = 2, column = 1, padx = (5, 20), pady = (10, 0), sticky = 'W') var10Hold = DoubleVar() var10Hold.set(gParmDict['var10']) Label(lFrameRTB, text = "Min rise [%]:", bg = 'dark grey').grid(row = 3, column = 0, padx = (20, 5), pady = (10, 0), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var10Hold, justify = 'center').grid(row = 3, column = 1, padx = (5, 20), pady = (10, 0), sticky = 'W') var11Hold = DoubleVar() var11Hold.set(gParmDict['var11']) Label(lFrameRTB, text = "Proportion [%]:", bg = 'dark grey').grid(row = 4, column = 0, padx = (20, 5), pady = (10, 20), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var11Hold, justify = 'center').grid(row = 4, column = 1, padx = (5, 20), pady = (10, 20), sticky = 'W') Label(lFrameRTB, text = "SITUATION 2", width = 10, bg = 'dark blue', fg = 'white', font = 'helvatica 8 bold').grid(row = 0, column = 3, columnspan = 2, sticky = 'NSEW') var12Hold = DoubleVar() var12Hold.set(gParmDict['var12']) Label(lFrameRTB, text = "Minimum [%]:", bg = 'dark grey').grid(row = 1, column = 3, padx = (20, 5), pady = (10, 0), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var12Hold, justify = 'center').grid(row = 1, column = 4, padx = (5, 20), pady = (10, 0), sticky = 'W') var13Hold = DoubleVar() var13Hold.set(gParmDict['var13']) Label(lFrameRTB, text = "Maximum [%]:", bg = 'dark grey').grid(row = 2, column = 3, padx = (20, 5), pady = (10, 0), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var13Hold, justify = 'center').grid(row = 2, column = 4, padx = (5, 20), pady = (10, 0), sticky = 'W') var14Hold = DoubleVar() var14Hold.set(gParmDict['var14']) Label(lFrameRTB, text = "Stop [%]:", bg = 'dark grey').grid(row = 3, column = 3, padx = (20, 5), pady = (10, 0), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var14Hold, justify = 'center').grid(row = 3, column = 4, padx = (5, 20), pady = (10, 0), sticky = 'W') var15Hold = DoubleVar() var15Hold.set(gParmDict['var15']) Label(lFrameRTB, text = "Move [%]:", bg = 'dark grey').grid(row = 4, column = 3, padx = (20, 5), pady = (10, 20), sticky = 'E') Entry(lFrameRTB, width = 10, textvariable = var15Hold, justify = 'center').grid(row = 4, column = 4, padx = (5, 20), pady = (10, 20), sticky = 'W') lFrameRTBM = Frame(lFrameRTB, width=275, height=320, bg = 'grey') lFrameRTBM.grid(row = 0, column = 2, rowspan = 5, padx = 5, ipadx = 5, ipady = 5, sticky = 'NSEW') lFrameRTBM.grid_propagate(0) # Botom Right Box #-------------------------------------------------------------------------------------- lFrameRB = Frame(gRoot, width=800, height=150, bg = 'silver') lFrameRB.grid(row = 1, column = 1, padx = 5, pady = 5, ipadx = 5, ipady = 5) lFrameRB.grid_propagate(0) lFrameRB.grid_columnconfigure (0, weight = 1) Label(lFrameRB, text = "Results", bg = '#313233', fg = '#FFFFFF', anchor = 'w', font='Helvetica 8 bold').grid(row = 0, column = 0, columnspan = 2, sticky = 'NSEW') Label(lFrameRB, text = "RB").grid(row = 1, column = 0, sticky = 'NW') gRoot.mainloop() guier() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T23:20:56.843", "Id": "398278", "Score": "0", "body": "Welcome to Code Review, please edit the title to reflect what the program actually does - lots of code here uses Python or Tkinter, it doesn't help to distinguish this post from ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T09:50:18.270", "Id": "206426", "Score": "2", "Tags": [ "python", "python-3.x", "inheritance", "gui", "tkinter" ], "Title": "Tkinter GUI Python implementation using classes" }
206426
<p>I have a stream of sensor data which I want to visualize in a plot with many subplots. Plotting the data is a real bottleneck in my code. Right now I get with small resolution only 16 FPS which is far too slow.</p> <p>Here is what it looks like:</p> <p><a href="https://i.stack.imgur.com/yMaNb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yMaNb.png" alt="enter image description here"></a></p> <pre><code>import time from matplotlib import pyplot as plt import numpy as np def live_plot(): loops=100 n = 7 p = 30 fig, axes = plt.subplots(ncols=n, nrows=n) fig.canvas.draw() handles=[] axes = np.array(axes) for ax in axes.reshape(-1): ax.axis("off") handles.append(ax.imshow(np.random.rand(p,p), interpolation="None", cmap="RdBu")) t0 = time.time() for i in np.arange(loops): for h in handles: h.set_data(np.random.rand(p,p)) for h, ax in zip(handles, axes.reshape(-1)): ax.draw_artist(h) plt.pause(1e-12) print("avg: " + "%.1f" % (loops/(time.time()-t0)) + " FPS") live_plot() </code></pre> <p>What can I do to get more frames per second?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T12:23:42.807", "Id": "398225", "Score": "0", "body": "You would probably get better answers if you included some sample data in your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T12:30:53....
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T10:25:07.977", "Id": "206428", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "numpy", "matplotlib" ], "Title": "Live plot with many subplots" }
206428
<p>Here is the code:</p> <pre><code>var http = require("http"); var fs = require("fs"); var path = require("path"); var ip = require("request-ip"); var hostname = "localhost"; var port = 3001; const logs = {}; http.createServer ( function(req, res) { addLog(req); console.clear(); console.log(logsToString()); if (req.method.toLowerCase() === "get"){ if (req.url === "/"){ pipeToRes(res,200, "text/html", "./public/index.html", "utf-8"); } else if (req.url.match(/.css$/)){ pipeToRes(res, 200, "text/css", path.join(__dirname, "public", req.url), "utf-8"); } else if (req.url.match(/.js$/)){ pipeToRes(res, 200, "application/javascript", path.join(__dirname, "public", req.url), "utf-8"); } else if (req.url.match(/.ttf$/)){ pipeToRes(res, 200, "application/octet-stream", path.join(__dirname, "public", req.url), ""); } else if (req.url.match(/.ico$/)){ pipeToRes(res, 200, "image/ico", path.join(__dirname, "public", req.url), ""); } else { fillRes(res, 404, "text/plain", "404: File Not Found"); } } else{ let body = []; req.on("data", function(chunk){ body.push(chunk); }); req.on("end", function(){ body = Buffer.concat(body).toString(); fillRes(res, 405, "text/plain", `Request Body: ${body}\n\n `+"405: Method Not Allowed: This server \ does not require any information from you, but only responds to GET requests by serving back to \ the client the web files (HTML, CSS, JS, Image Files, icons, Videos, e.t.c..) to view them on the \ browser."); }); } }).listen(port); console.log(`Server ${hostname} is listening on port ${port}`); function addLog(req){ var thisIP = ip.getClientIp(req) if (logs[thisIP] != undefined){ logs[thisIP].push({"method": req.method, "url": req.url}); } else { logs[thisIP] = [{"method": req.method, "url": req.url}]; } } function logsToString(){ var formatted = "----------------\nCURRENT LOGS\n----------------\n\n"; for (var clientIp in logs){ formatted += "\nFROM IP ("+clientIp+"):" var clientLogs = logs[clientIp]; for (var i = 0; i &lt; clientLogs.length; i++){ var thisLog = clientLogs[i]; formatted += "\n\t- Recieved "+thisLog["method"]+" request for "+thisLog["url"] } } return formatted; } function fillRes(res, responseCode, mimeType, data){ res.writeHead(responseCode, {"Content-Type": mimeType}); res.end(data); } function pipeToRes(res, responseCode, mimeType, pathParam, readAs){ res.writeHead(responseCode, {"Content-Type": mimeType}); fs.createReadStream(pathParam, readAs).pipe(res); } </code></pre> <p><strong>Points I am interested in:</strong></p> <ul> <li>Is using the functions <em>fillRes</em> and <em>pipeToRes</em> a good choice rather than repeating <code>res.writeHead ... res.end()</code></li> <li>What about their names? The semantics of fillRes is that basically you are manipulating the response object passed to you by <code>http.createServer</code>, as in you are "filling" the response write stream. is something like <code>writeResponse</code> or <code>writeRes</code> better?</li> <li>What do you think about the technique used to log the requests? Each time a request is received, the server checks if this specific IP has requested before and then groups all his request in a list. A dictionary called <code>logs</code> stores all these requests, where the IP is the key, and the value is a list of all the requests from that IP.</li> <li>Anything else? What should I improve? Please remember that I am a total newbie, and all help is really honestly greatly appreciated.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T10:50:30.433", "Id": "206429", "Score": "1", "Tags": [ "javascript", "node.js", "asynchronous", "http", "server" ], "Title": "Node.js HTTP server with request logging" }
206429
<p>It is said that </p> <blockquote> <p>Being consistent in percentage annual returns leads to larger amount over time.</p> </blockquote> <p>That is for any given principal, getting 20% successively for 2 years is better than 30% for first year and 10% for second year even though both percentages add to 40. First case yields 44% while the later one yields 43%. </p> <p>I have tried to simulate this for arbitrary number of years and arbitrary percentages using Python 3. The obvious added constraint is that sum of percentages is constant (otherwise, inconsistent arbitrarily high percentages will obviously beat consistent low percentages).</p> <pre><code>from operator import mul from functools import reduce import numpy as np from collections import namedtuple from typing import List, Tuple def avg_cagr(percents: List[int]) -&gt; float: '''Given (successive) % annual growth rates, returns average Compound Annual Growth Rate''' amount = reduce(mul, [1+p/100 for p in percents]) return (amount**(1/len(percents)) - 1)*100 def dirichlet(n: int = 5, amount: float = 100) -&gt; List[float]: '''Returns n random numbers which sum to "amount"''' random_returns = np.random.dirichlet(alpha=np.ones(n), size=1)[0]*amount return random_returns def simulate_returns(n: int = 5, amount: float = 100, iterations: int = 40) -&gt; List[Tuple[float, float]]: '''Generate bunch of random percentages that sum to a constant and compare average CAGR with their deviation''' net_returns = namedtuple('net_returns', 'deviation CAGR') results = [] for _ in range(iterations): random_returns = dirichlet(n, amount) avg_returns = avg_cagr(random_returns) deviation = np.std(random_returns) results.append(net_returns(deviation, avg_returns)) return sorted(results, key=lambda x: x.CAGR, reverse=True) if __name__ == '__main__': results = simulate_returns() print('\n'.join(('dev=' + str(round(result.deviation, 2)) + ', ' + 'CAGR=' + str(round(result.CAGR, 2))) for result in results)) </code></pre> <p>Key Ideas in the code:</p> <ul> <li>Dirichlet distribution is used to generate bunch of random numbers that sum to a constant</li> <li>Standard deviation is used to illustrate consistency</li> </ul> <p>Result: Simulation agrees with maxim.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T10:28:41.533", "Id": "398319", "Score": "1", "body": "The maxim (if stated precisely) is actually a theorem: [the arithmetic mean of a list of non-negative real numbers is greater than or equal to the geometric mean of the same list...
[ { "body": "<pre><code>def avg_cagr(percents: List[int]) -&gt; float:\n '''Given (successive) % annual growth rates, returns average Compound Annual Growth Rate'''\n amount = reduce(mul, [1+p/100 for p in percents])\n return (amount**(1/len(percents)) - 1)*100\n</code></pre>\n\n<p>In a production enviro...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T14:48:32.493", "Id": "206435", "Score": "2", "Tags": [ "python", "python-3.x", "statistics", "simulation", "finance" ], "Title": "The importance of consistency in percentage returns when investing" }
206435
<p>I'm a bit of a beginner when it comes to Java, and I created this small code to help me grasp a few small subjects. It allows its user to convert a radical to a degree measure and a degree measure to a radical. This is my final code:</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class MainClass { public static void dtr (BufferedReader dRead) throws IOException { ArrayList&lt;Integer&gt; divisors = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; gcd = new ArrayList&lt;Integer&gt;(); int d = Integer.parseInt(dRead.readLine()); for (int pd = 1; pd &lt;= d; pd++) { if (d % pd == 0) { divisors.add(pd); } } for (int index = 0; index &lt; divisors.size(); ++index) { if (180.0 % divisors.get(index) == 0) { gcd.add(divisors.get(index)); } } int dem = (180 / gcd.get(gcd.size() - 1)); if ((d / (gcd.get(gcd.size() - 1))) == 1) { System.out.print("Radical: pi / " + dem); } else { System.out.print("Radical: " + (d / (gcd.get(gcd.size() - 1))) + "pi / " + dem); } } public static void rtd (BufferedReader rnRead, BufferedReader rdRead) throws IOException { int rn = Integer.parseInt(rnRead.readLine()); int rd = Integer.parseInt(rdRead.readLine()); int dividend = rn * 180; System.out.print("Degrees: " + (dividend / rd)); } public static void main(String[] args) throws IOException { System.out.println("Do you want to convert from radicals to degrees, or degrees to radicals?"); System.out.print("Use \"R\" for radials to degrees, and \"D\" for degrees to radicals: "); BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)); String userChoice = userInput.readLine(); if (userChoice.contains("D") || userChoice.contains("d")) { System.out.print("Degrees: "); BufferedReader dRead = new BufferedReader(new InputStreamReader(System.in)); dtr(dRead); } else if (userChoice.contains("R") || userChoice.contains("r")) { System.out.println("Radical numerator (omit pi): "); BufferedReader rnRead = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Radical denominator: "); BufferedReader rdRead = new BufferedReader(new InputStreamReader(System.in)); rtd(rnRead, rdRead); } else { System.out.println("Invalid response. Please restart the program."); } } } </code></pre> <p>I know how bad some of this code is, but I just want to know if there is any way I could have optimized what this does, because I'd like to apply those concepts to everything that I'll make in the future.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T18:15:19.517", "Id": "398254", "Score": "0", "body": "Regarding ` BufferedReader userInput ...` while in this example it is harmless no to close IO resources, it is good practice to do so in general. Check out try with resources sta...
[ { "body": "<p>Nowadays is common to omit the generic type on the right hand side of an assignment so instead of</p>\n\n<pre><code> ArrayList&lt;Integer&gt; divisors = new ArrayList&lt;Integer&gt;(); \n</code></pre>\n\n<p>you can write </p>\n\n<pre><code> ArrayList&lt;Integer&gt; divisors = new ArrayList&lt;&gt;...
{ "AcceptedAnswerId": "206473", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T14:59:38.350", "Id": "206436", "Score": "3", "Tags": [ "java", "beginner", "rational-numbers", "unit-conversion" ], "Title": "Beginner radian/degree converter program" }
206436
<p>I have a task to write a concurrent version of <code>quicksort</code> algorithm, to speed it up. This is what I wrote:</p> <pre><code>template &lt;class T&gt; void quicksort::sort(T *data, int len) { thread_count = 0; int p = 0; int r = len - 1; _sort(data, p, r); } template &lt;class T&gt; void quicksort::_swap(T *data, int first, int second) { auto temp = data[first]; data[first] = data[second]; data[second] = temp; } template &lt;class T&gt; void quicksort::_sort(T *data, int p, int r) { thread_count++; if (p &lt; r) { auto q = _partition(data, p, r); if (thread_count &gt;= thread_limit) { _sort(data, p, q - 1); _sort(data, q + 1, r); } else { std::thread lower(&amp;quicksort::_sort&lt;T&gt;, this, data, p, q - 1); std::thread upper(&amp;quicksort::_sort&lt;T&gt;, this, data, q + 1, r); lower.join(); upper.join(); } } thread_count--; } template &lt;class T&gt; int quicksort::_partition(T *data, int p, int r) { auto first = data[p]; auto last = data[r]; T pivot = 0; // Median of three auto middle = data[(p + 2) / 2]; if (first &gt; middle) { if (middle &gt; last) { pivot = middle; } else { pivot = last; } } else { if (middle &gt; last) { pivot = std::max(first, last); } else { pivot = middle; } } auto i = p - 1; for (auto j = p; j &lt; r; ++j) { if (data[j] &lt;= pivot) { _swap(data, ++i, j); } } _swap(data, i + 1, r); return i + 1; } </code></pre> <p>Those are methods from class <code>quicksort</code>, which also has <code>std::atomic&lt;int&gt; thread_limit</code> and <code>std::atomic&lt;int&gt; thread_count</code>. </p> <p>So f.e I cap the thread limit to f.e maximum 1000 threads. </p> <p>The part I am particularly not sure of is the part in <code>_sort()</code> function. Basically, I don't know if my way of starting those threads and then joining them is the right way to do it.</p> <p>I have a benchmark method, and I benchmarked my quicksort implementation like this: I took the average of 100 benchmarks for every thread_limit from 200 to 2000, stepping by 100 (so 200, 300, 400) and for single-threaded quicksort of mine. And this was for <code>1.000.000</code>-sized arrays (every time I was creating a new one - this overhead was not measured). The result was shocking for me. It occurred, that of course, even with 2000 threads it was faster than with only 1 thread, but still, the fastest one was with <code>thread_limit = 200</code>. I thought that the optimum would be somewhere nearer the middle.</p> <p>Sometimes f.e 700 threads were faster than 600 threads, but still, the general rule was: the more threads, the slower.</p> <p>Do you guys see any flaws in my code or in my understanding of the benchmark I made?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T15:36:49.710", "Id": "398233", "Score": "0", "body": "Having more threads than are present in your hardware (likely 4 or 8 for typical laptops, possibly 12 for desktop) is not beneficial." }, { "ContentLicense": "CC BY-SA 4....
[ { "body": "<ul>\n<li><p>Thread creation is an expensive operation, and you do it way more than needed. Even though the number of threads running at any given time is capped, the threads are constantly joined and recreated over and over again (I run your code with cap of 10, over a 1000000-strong array, and coun...
{ "AcceptedAnswerId": "206463", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T15:24:11.190", "Id": "206438", "Score": "5", "Tags": [ "c++", "multithreading", "quick-sort" ], "Title": "Concurrent quicksort in C++" }
206438
<p>This is a very simple sorting logic that I have written and it's working also. But Is there anything wrong in the traversing of the array? Or the code is not optimized? The code is simply declaring an array of size N. And then sorting is performed by traversing.</p> <pre><code>import java.util.Scanner; import java.io.*; class BubbleSort { public static void main(String args[])throws IOException { int size,temp=0; System.out.println("Enter the size of the array"); Scanner sc=new Scanner(System.in); size=sc.nextInt(); int arr[]=new int[size]; System.out.println("Enter the elements in the array"); for(int i=0;i&lt;size;i++) { arr[i]=sc.nextInt(); } for(int i=0;i&lt;size;i++) //Here is the sorting logic { for(int j=i+1;j&lt;size;j++) { if(arr[i]&gt;arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } for(int i=0;i&lt;size;i++) { System.out.print(arr[i]); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T14:00:40.350", "Id": "398238", "Score": "0", "body": "You're using *Bubble Sort*, there are multiple algorithms to sort an array. You can go through them" } ]
[ { "body": "<p>While this code works as intended, there is room for improvement.</p>\n\n<h3>Use small functions that do one thing</h3>\n\n<p>The <code>main</code> method does too many things:</p>\n\n<ul>\n<li>Read input from the console</li>\n<li>Sort the array</li>\n<li>Print the array</li>\n</ul>\n\n<p>These s...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T13:57:19.380", "Id": "206441", "Score": "1", "Tags": [ "java", "sorting" ], "Title": "Sorting an unsorted array" }
206441
<p>In my <code>cowboy</code> (Erlang) application, I have a handler called <code>projects_from_json</code>. This takes a JSON POST request as input and should create a database entry from this. Then, it should respond with a success message or the correct error message to the user.</p> <p>I started with two exceptions that could occur (simplified):</p> <pre><code>projects_from_json(Req=#{method := &lt;&lt;"POST"&gt;&gt;}, State) -&gt; {ok, ReqBody, Req2} = cowboy_req:read_body(Req), try Name = parse_json(ReqBody), % Continuation of happy path db:create_project(Name) catch error:{badkey, Key} -&gt; % return error message about invalid JSON % [&lt;&lt;"Key \""&gt;&gt;, Key, &lt;&lt;"\" does not exist in passed data"&gt;&gt;] throw:duplicate -&gt; % return error message about duplicate name % [&lt;&lt;"A project with name \""&gt;&gt;, Name, &lt;&lt;"\" already exists"&gt;&gt;] end </code></pre> <p>Already in this case, this did not work, because <code>Name</code> is not safe in the second catch clause (since it comes from the try clause and could potentially be unset). I also could not move the call of <code>db:create_project(Name)</code> outside of the <code>try</code>, because then again <code>Name</code> would not be safe to be used.</p> <p>Since there were some more exceptions and errors to be handled, I ended up with a very deeply nested situation (follows below).</p> <p>My first idea would be to move stuff into own functions, but most of the code is error handling and as far as I know I can only handle the error by returning a tuple from the <code>projects_from_json</code> handler.</p> <p>So here follows my nested mess. In total, I currently want to handle three error situations:</p> <ul> <li>InvalidValue: The project name sent by the user contains invalid characters</li> <li>DuplicateValue: A project with the same name already exists</li> <li>MissingKey: User did not supply all required keys</li> </ul> <p>Code:</p> <pre><code>projects_from_json(Req=#{method := &lt;&lt;"POST"&gt;&gt;}, State) -&gt; {ok, ReqBody, Req2} = cowboy_req:read_body(Req), try Name = project_name(ReqBody), case validate_project_name(Name) of invalid -&gt; molehill_respond:respond_error(&lt;&lt;"InvalidValue"&gt;&gt;, &lt;&lt;"The project name can only consist of ASCII characters and numbers, and dash in the middle of the word."&gt;&gt;, 400, Req2, State); ok -&gt; {ok, Conn} = moledb:connect_from_config(), try moledb:create_project(Conn, Name), Data = prepare_project_json(Name), molehill_respond:respond_status(Data, 201, Req2, State) catch throw:duplicate_element -&gt; molehill_respond:respond_error(&lt;&lt;"DuplicateValue"&gt;&gt;, erlang:iolist_to_binary( [&lt;&lt;"A project with name \""&gt;&gt;, Name, &lt;&lt;"\" already exists"&gt;&gt;]), 409, Req2, State) end end catch error:{badkey, Key} -&gt; molehill_respond:respond_error( &lt;&lt;"MissingKey"&gt;&gt;, erlang:iolist_to_binary( [&lt;&lt;"Key \""&gt;&gt;, Key, &lt;&lt;"\" does not exist in passed data"&gt;&gt;]), 400, Req2, State) end. </code></pre> <p>Is it possible to restructure this to a clean form where all possible errors are on a similar indentation level at the end of the function?</p> <p><a href="https://github.com/molescrape/molehill/blob/1d7b500173d4b661b539078ac175e46154d9cc4d/src/molehill_respond.erl" rel="nofollow noreferrer"><code>molehill_respond</code></a> is a helper module I wrote to simplify the creation of my JSON return messages, <a href="https://github.com/molescrape/molehill/blob/1d7b500173d4b661b539078ac175e46154d9cc4d/src/moledb.erl" rel="nofollow noreferrer"><code>moledb</code></a> is a helper module that executes all the SQL queries.</p>
[]
[ { "body": "<p>My first attempt (without changing any of your functions nor the semantics of your handler) would be:</p>\n\n<pre><code>projects_from_json(Req=#{method := &lt;&lt;\"POST\"&gt;&gt;}, State) -&gt;\n try\n {ok, ReqBody, Req2} = cowboy_req:read_body(Req),\n Name = get_project_name(Req...
{ "AcceptedAnswerId": "206505", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T16:24:37.870", "Id": "206445", "Score": "1", "Tags": [ "erlang" ], "Title": "Managing many exceptions in Erlang cowboy without deeply nested trees" }
206445
<p>This post has been answered and <a href="https://codereview.stackexchange.com/questions/206852/template-matrix-class-suggestions">updated</a>.</p> <p>This was the first time I've ever written a template class. I've spent probably a bunch of times re-writing matrix code for different types, different functions. I'm looking to make a general library for future work of mine.</p> <p>With that in mind, I'd like to have a nice working one to begin with that can be general. (i.e. handle different sizes appropriately).</p> <p>-What is the best way to do that (I am using visual studio 2012)?</p> <p>-Is there a way I can ensure the types being used are restricted to values safe for my implementation (currently, arithmetic heavy that would not be good for string data, for example).</p> <p>-How should I properly handle errors? I string/silent failing is probably not appropriate.</p> <p>-Any other general tips?</p> <p>Thanks!</p> <p>Matrix.h</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; template &lt;typename T&gt; class Matrix; template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Matrix&lt;T&gt;&amp; rhs); template&lt;typename T&gt; class Matrix { private: std::vector&lt;T&gt; data; int rows; int cols; public: Matrix(); Matrix(std::vector&lt;T&gt;, int rows, int cols); void set(std::vector&lt;T&gt;, int rows, int cols); //Matrix(const Matrix&lt;T&gt;&amp;); void print(); Matrix&lt;T&gt; transpose(); Matrix&lt;T&gt; dot(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; add(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; sub(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; mult(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; mult(const T &amp;); bool isEqual(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; concat(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; stack(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; kronecker(const Matrix&lt;T&gt; &amp;); int getRows(); int getCols(); friend std::ostream&amp; operator&lt;&lt; &lt;&gt;(std::ostream&amp;, const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; operator+(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; operator-(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; operator*(const Matrix&lt;T&gt; &amp;); Matrix&lt;T&gt; operator*(const T &amp;); bool operator==(const Matrix&lt;T&gt; &amp;); }; /** Default Constructor creates an empty matrix */ template &lt;typename T&gt; Matrix&lt;T&gt;::Matrix() { data.clear(); rows = 0; cols = 0; } /** Constructor creates the matrix as the following: @params elements, - the elements of the matrix in Row-major form numRows, - the number of rows in the matrix numCols; - the number of coumns in the matrix */ template &lt;typename T&gt; Matrix&lt;T&gt;::Matrix(std::vector&lt;T&gt; elements, int numRows, int numCols) { rows = numRows; cols = numCols; data.clear(); for(unsigned int i = 0; i &lt; elements.size(); i++) { data.push_back(elements[i]); } } /** set resets the matrix to the input @params elements, - the elements of the matrix in Row-major form numRows, - the number of rows in the matrix numCols; - the number of coumns in the matrix @return void; nothing to return */ template &lt;typename T&gt; void Matrix&lt;T&gt;::set(std::vector&lt;T&gt; elements, int numRows, int numCols) { rows = numRows; cols = numCols; data.clear(); for(unsigned int i = 0; i &lt; elements.size(); i++) { data.push_back(elements[i]); } } /** operator+ (add) lhs + rhs; elementwise adition of rhs to lhs @params rhs; the matrix to add @return matrix; the sum */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::operator+(const Matrix&lt;T&gt; &amp; rhs) { return this-&gt;add(rhs); } /** operator- (subtract) lhs - rhs; elementwise subtraction of rhs from lhs @params rhs; the matrix to subtract @return matrix; the difference */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::operator-(const Matrix&lt;T&gt; &amp; rhs) { return this-&gt;sub(rhs); } /** operator(*) dot product lhs * rhs; https://en.wikipedia.org/wiki/Matrix_multiplication calculate dot product of a matrix @params rhs; the second matrix @return matrix; the transformed product matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::operator*(const Matrix&lt;T&gt; &amp; rhs) { return this-&gt;dot(rhs); } /** operator* (scalar multiplication) M&lt;T&gt; * T; calculate scalar product of a matrix @params rhs; the scalar; @return matrix; the transformed product matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::operator*(const T &amp; T) { return this-&gt;mult(T); } /** operator == elemetnwise comparison of two matrices of equal size @params rhs; the second matrix @return bool; true if same size and elements all equal */ template &lt;typename T&gt; bool Matrix&lt;T&gt;::operator==(const Matrix&lt;T&gt; &amp; rhs) { return this-&gt;isEqual(rhs); } /** ostream operator adds elements to output stream formatted e11, e12 e21, e22 @params os, rhs; ostream refernece and matrix to output @return os, ostream reference */ template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Matrix&lt;T&gt; &amp; rhs) { for(unsigned int i = 0; i &lt; rhs.data.size(); i++) { os &lt;&lt; rhs.data[i] &lt;&lt; " "; if((i+1)%rhs.cols == 0) os &lt;&lt; std::endl; } return os; } /** isEqual elemetnwise comparison of two matrices of equal size @params rhs; the second matrix @return bool; true if same size and elements all equal */ template &lt;typename T&gt; bool Matrix&lt;T&gt;::isEqual(const Matrix&lt;T&gt; &amp; rhs) { if(rows != rhs.rows || cols != rhs.cols) { return false; } for(unsigned int i = 0; i &lt; data.size(); i++) { if(data[i] != rhs.data[i]) return false; } return true; } /** add elementwise adition of rhs to lhs @params rhs; the matrix to add @return matrix; the sum */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::add(const Matrix&lt;T&gt; &amp; rhs) { if(rows != rhs.rows || cols != rhs.cols) { Matrix&lt;T&gt; matrix; return matrix; } std::vector&lt;T&gt; vec; for(unsigned int i = 0; i &lt; data.size(); i++) { vec.push_back(data[i] + rhs.data[i]); } return Matrix&lt;T&gt;(vec,rows,cols); } /** dot product https://en.wikipedia.org/wiki/Matrix_multiplication calculate dot product of a matrix @params rhs; the second matrix @return matrix; the transformed product matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::dot(const Matrix&lt;T&gt; &amp; rhs) { if(cols != rhs.rows) { std::cout &lt;&lt; "Error! Can not resolve dot product on these matrices!" &lt;&lt; std::endl; std::cout &lt;&lt; "Requested: [" &lt;&lt; rows &lt;&lt; "x" &lt;&lt; cols &lt;&lt; "] &lt;alt+7&gt; [" &lt;&lt; rhs.rows &lt;&lt; "x" &lt;&lt; rhs.cols &lt;&lt; "]" &lt;&lt; std::endl; Matrix&lt;T&gt; matrix; return matrix; } std::vector&lt;T&gt; vec; T sum = 0; for(int j = 0; j &lt; rows; j++) { for(int k = 0; k &lt; rhs.cols; k++) { for(int i = 0; i &lt; cols; i++) { sum += data[i+j*cols] * rhs.data[k+i*rhs.cols]; } vec.push_back(sum); sum = 0; } } return Matrix(vec,rows,rhs.cols); } /** multiplication (Hardamard Product) https://en.wikipedia.org/wiki/Hadamard_product_(matrices) calculate elemetnwise product of a matrix @params rhs; the second matrix @return matrix; the transformed product matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::mult(const Matrix&lt;T&gt; &amp; rhs) { if(rows != rhs.rows || cols != rhs.cols) { Matrix&lt;T&gt; matrix; return matrix; } std::vector&lt;T&gt; vec; for(unsigned int i = 0; i &lt; data.size(); i++) { vec.push_back(data[i] * rhs.data[i]); } return Matrix&lt;T&gt;(vec,rows,cols); } /** multiplication (scalar) calculate scalar product of a matrix @params rhs; the scalar; @return matrix; the transformed product matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::mult(const T &amp; scalar) { std::vector&lt;T&gt; vec; for(unsigned int i = 0; i &lt; data.size(); i++) { vec.push_back(data[i] * scalar); } return Matrix&lt;T&gt;(vec,rows,cols); } /** subtract elementwise subtraction of rhs from lhs @params rhs; the matrix to subtract @return matrix; the difference */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::sub(const Matrix&lt;T&gt; &amp; rhs) { if(rows != rhs.rows || cols != rhs.cols) { Matrix&lt;T&gt; matrix; return matrix; } std::vector&lt;T&gt; vec; for(unsigned int i = 0; i &lt; data.size(); i++) { vec.push_back(data[i] - rhs.data[i]); } return Matrix&lt;T&gt;(vec,rows,cols); } template &lt;typename T&gt; void Matrix&lt;T&gt;::print() { for(unsigned int i = 0; i &lt; data.size(); i++) { std::cout &lt;&lt; data[i] &lt;&lt; ", "; if((i+1) % cols == 0) std::cout &lt;&lt; std::endl; } } /** transpose Calculate transpose of matrix @return matrix; the transpose of this matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::transpose() { std::vector&lt;T&gt; vec; for(unsigned int i = 0; i &lt; data.size(); i++) { vec.push_back(data[(cols*(i%rows)+i/rows)]); } return Matrix&lt;T&gt;(vec, cols, rows); } /** Concat append two matrices of equal row count @params rhs; the matrix to concatanate @return matrix; the contanated matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::concat(const Matrix&lt;T&gt; &amp; rhs) { if(rows != rhs.rows) return Matrix&lt;T&gt;(*this); std::vector&lt;T&gt; vec; for(int i = 0; i &lt; rows; i++) { for(int j = 0; j &lt; cols; j++) { vec.push_back(data[i*cols + j]); } for(int j = 0; j &lt; rhs.cols; j++) { vec.push_back(rhs.data[i*rhs.cols + j]); } } return Matrix&lt;T&gt;(vec,rows,cols+rhs.cols); } /** stack append two matrices of equal column count @params rhs; the matrix to stack below @return matrix; the lhs stacked ontop of rhs matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::stack(const Matrix&lt;T&gt; &amp; rhs) { if(cols != rhs.cols) return Matrix&lt;T&gt;(*this); std::vector&lt;T&gt; vec; for(unsigned int i = 0; i &lt; data.size(); i++) { vec.push_back(data[i]); } for(unsigned int i = 0; i &lt; rhs.data.size(); i++) { vec.push_back(rhs.data[i]); } return Matrix&lt;T&gt;(vec,rows+rhs.rows,cols); } /** Kronecker https://en.wikipedia.org/wiki/Kronecker_product calculate kroncker product of two matrices @params rhs; the matrix operand @return matrix; the Kronecker product matrix */ template &lt;typename T&gt; Matrix&lt;T&gt; Matrix&lt;T&gt;::kronecker(const Matrix&lt;T&gt; &amp; rhs) { std::vector&lt;T&gt; vec; for(int i = 0; i &lt; (rows*cols*rhs.rows*rhs.cols); i++) { int j = (i/rhs.cols)%cols + (i/(cols*rhs.rows*rhs.cols))*cols; //iterate lhs in proper order int k = (i%rhs.cols) + ((i / (cols * rhs.cols))%rhs.rows)*rhs.cols; //iterate rhs in proper order //can use scalar multiplactions, matrix concat and stacking, but this is a single iteration through the vector. //Kronecker iterates both matrices in a pattern relative to the large product matrix. //std::cout &lt;&lt; i &lt;&lt; " : " &lt;&lt; j &lt;&lt; " : " &lt;&lt; k &lt;&lt; std::endl; //std::cout &lt;&lt; i &lt;&lt; " : " &lt;&lt; j &lt;&lt; " : " &lt;&lt; k &lt;&lt; " : " &lt;&lt; l &lt;&lt; std::endl; vec.push_back(data[j]*rhs.data[k]); } return Matrix&lt;T&gt;(vec,rows*rhs.rows,cols*rhs.cols); } template &lt;typename T&gt; int Matrix&lt;T&gt;::getRows() { return rows; } template &lt;typename T&gt; int Matrix&lt;T&gt;::getCols() { return cols; } </code></pre> <p>Source.cpp (Just testing implementation)</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "Matrix.h" #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; //void testMatrix(); //testing function. //Matrix loadData(std::string); //Not implemented yet //bool saveData(Matrix, std::string); //Not implemented yet void testMatrixClass(); int main() { //testMatrix(); testMatrixClass(); return 0; } void testMatrixClass() { std::vector&lt;Matrix&lt;float&gt;&gt; testResults; std::vector&lt;std::string&gt; testInfo; std::vector&lt;Matrix&lt;int&gt;&gt; intTestResults; std::vector&lt;std::string&gt; intTestInfo; Matrix&lt;float&gt; temp; testResults.push_back(temp); testInfo.push_back("Default Constructor"); std::vector&lt;float&gt; tempVec; for(int i = 0; i &lt; 9; i++) { tempVec.push_back((float)(i%3)); } Matrix&lt;float&gt; temp2(tempVec, 3, 3); testResults.push_back(temp2); testInfo.push_back("Vector constructor"); testResults.push_back(temp2.transpose()); testInfo.push_back("Vector transpose"); tempVec.push_back(10.0); Matrix&lt;float&gt; temp3(tempVec, 5, 2); testResults.push_back(temp3); testInfo.push_back("Vector constructor"); Matrix&lt;float&gt; temp4(temp3.transpose()); testResults.push_back(temp4); testInfo.push_back("Vector transpose"); testResults.push_back(temp2.dot(temp2)); testInfo.push_back("Dot product"); testResults.push_back(temp2.dot(temp3)); testInfo.push_back("Error Dot Product"); testResults.push_back(temp3.dot(temp4)); testInfo.push_back("Dot product"); testResults.push_back(temp2.add(temp2)); testInfo.push_back("Add product"); testResults.push_back(temp2.sub(temp2)); testInfo.push_back("Sub product"); testResults.push_back(temp2.mult(temp2)); testInfo.push_back("hadamard product"); testResults.push_back(temp2.mult(3)); testInfo.push_back("scalar product"); std::vector&lt;int&gt; tempInts; for(unsigned int i = 0; i &lt; 9; i++) { tempInts.push_back((int)(i%3+i%4)); } Matrix&lt;int&gt; intMatrix(tempInts,3,3); intTestResults.push_back(intMatrix); intTestInfo.push_back("Integer test"); Matrix&lt;int&gt; intMatrix2 = intMatrix + intMatrix; intTestResults.push_back(intMatrix2); intTestInfo.push_back("Operator tests"); Matrix&lt;int&gt; intMatrix3 = intMatrix * 2; intTestResults.push_back(intMatrix3); intTestInfo.push_back("Scalar Multiplacation"); intTestResults.push_back(intMatrix2); if(intMatrix2 == intMatrix3) { intTestInfo.push_back("Boolean Comparison Successful"); } else { intTestInfo.push_back("Boolean Comparison Failed"); } intTestResults.push_back(intMatrix.concat(intMatrix2)); intTestInfo.push_back("Concatanation Test"); Matrix&lt;int&gt; intMatrix4 = intMatrix.stack(intMatrix2); intTestResults.push_back(intMatrix4); intTestInfo.push_back("Stack Test"); intTestResults.push_back(intMatrix4.concat(intMatrix3)); intTestInfo.push_back("Concat Error Check - Result should be [6x3] - (Prevents unequal row size)"); intTestResults.push_back((intMatrix.concat(intMatrix2)).stack(intMatrix)); intTestInfo.push_back("Stack Error Check - Result should be [3x6] - (Prevents unequal row size)"); tempInts.clear(); std::vector&lt;int&gt; tempInt2; for(unsigned int i = 0; i &lt; 4; i++) { tempInts.push_back(i+1); } for(unsigned int i = 0; i &lt; 6; i++) { tempInt2.push_back(i); } Matrix&lt;int&gt; intMatrix5(tempInts,2,2); tempInts.clear(); tempInts.push_back(0); for(unsigned int i = 0; i &lt; 3; i++) { tempInts.push_back(i+5); } Matrix&lt;int&gt; intMatrix6(tempInts,2,2); intTestResults.push_back(intMatrix5); intTestInfo.push_back("Integer test"); intTestResults.push_back(intMatrix6); intTestInfo.push_back("Integer test"); intTestResults.push_back(intMatrix5.kronecker(intMatrix6)); intTestInfo.push_back("Kroncker Test"); Matrix&lt;int&gt; intMatrix7(tempInt2,2,3); intTestResults.push_back(intMatrix7); intTestInfo.push_back("Integer test"); intTestResults.push_back(intMatrix5.kronecker(intMatrix7)); intTestInfo.push_back("Kroncker Test"); for(unsigned int i = 0; i &lt; testResults.size(); i++) { std::cout &lt;&lt; "Test: " &lt;&lt; testInfo[i] &lt;&lt; ": " &lt;&lt; std::endl &lt;&lt; testResults[i] &lt;&lt; std::endl; } for(unsigned int i = 0; i &lt; intTestResults.size(); i++) { std::cout &lt;&lt; "Test: " &lt;&lt; intTestInfo[i] &lt;&lt; ": " &lt;&lt; std::endl &lt;&lt; intTestResults[i] &lt;&lt; std::endl; } } // //Matrix loadData(std::string) { // //TODO: Implement file loading and data parsing // // Matrix matrix; // return matrix; //} //bool saveData(Matrix, std::string) { // // return true; //} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-01T11:07:02.330", "Id": "398774", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y...
[ { "body": "<p><strong>Testing:</strong></p>\n\n<ul>\n<li>It's hard to notice problems in a long list of output like that.</li>\n<li>It's hard to track the state of the <code>tempVec</code> and determine the correct output for each case.</li>\n<li>Both these become harder if you have to come back to it later, ma...
{ "AcceptedAnswerId": "206495", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T16:45:11.623", "Id": "206447", "Score": "6", "Tags": [ "c++", "object-oriented", "matrix", "template" ], "Title": "First template class - Matrix functions" }
206447
<pre><code>isLineTerminator c = c == '\r' || c == '\n' leadWords [] = [] leadWords cs = let (pre, suf) = break isLineTerminator cs in (head (words pre)) : case suf of ('\r':'\n':rest) -&gt; leadWords rest ('\r':rest) -&gt; leadWords rest ('\n':rest) -&gt; leadWords rest _ -&gt; [] fixLines :: String -&gt; String fixLines input = unlines (leadWords input) interactWith function inputFile outputFile = do input &lt;- readFile inputFile writeFile outputFile (function input) main = mainWidth myFunction where mainWidth function = do args &lt;- getArgs case args of [input, output] -&gt; interactWith function input output _ -&gt; putStrLn "error: exactly two arguments needed" myFunction = fixLines </code></pre> <p>Much of this program is written by the author of the book on Haskell that I'm reading, so I assume that much of it is good. However, my part is in altering the <code>leadWords</code> function. Does it look like a:</p> <ol> <li>readable, elegant function?</li> <li>efficient and optimized function? </li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T18:20:59.653", "Id": "398255", "Score": "0", "body": "Why did you alter it? What was wrong with the original?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T01:22:54.903", "Id": "398281", "Sc...
[ { "body": "<h1>Errors</h1>\n\n<pre>\n\n\n</pre>\n\n<p>The code block above is an example where your program will fail. Any empty line will lead to an empty list in <code>words \"\"</code> and therefore to <code>head []</code>, which calls <code>error</code>.</p>\n\n<h1>Standard library</h1>\n\n<p>That being sai...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T17:10:42.920", "Id": "206450", "Score": "1", "Tags": [ "strings", "haskell" ], "Title": "Haskell program to extract the first words of each line of a text file" }
206450
<p>I'm making a particle engine that can spawn new explosions while keeping particles from previous ones active (until they despawn).</p> <p>The code works well on its own but within the game, two or more active explosions at once causes stutters, especially on laptops that are a few years old. I'm wondering if there's something inherently inefficient with my code, or if any of the coding practices used are bad.</p> <p>In in the code snippet below, you can click anywhere within the canvas element to see the particle effect. Let me know if there's something that's unclear.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var explosions = []; var mouseX; var mouseY; canvas.addEventListener('mousemove', setMouse, false); canvas.addEventListener('click', function() { explosions.push(new explosion(mouseX, mouseY)); }, false); function loop() { ctx.clearRect(0, 0, 500, 500); drawExplosion(); requestAnimationFrame(loop); } loop(); function drawExplosion() { if (explosions.length === 0) { return; } for (let i = 0; i &lt; explosions.length; i++) { const explosion = explosions[i]; const projectiles = explosion.projectiles; if (projectiles.length === 0) { explosions.splice(i, 1); return; } const projectilesRemove = projectiles.slice(); for (let ii = 0; ii &lt; projectiles.length; ii++) { const projectile = projectiles[ii]; // remove projectile if radius is below 0 if (projectile.radius &lt; 0) { projectilesRemove.splice(ii, 1); continue; } // draw ctx.beginPath(); ctx.arc(projectile.x, projectile.y, projectile.radius, Math.PI * 2, 0, false); ctx.closePath(); ctx.fillStyle = 'hsl(' + projectile.h + ',' + projectile.s + '%,' + projectile.l + '%)'; ctx.fill(); // update projectile.x -= projectile.vx * 1; projectile.y -= projectile.vy * 1; projectile.radius -= 0.02; // collisions if (projectile.x &gt; 500) { projectile.x = 500; projectile.vx *= -1; } if (projectile.x &lt; 0) { projectile.x = 0; projectile.vx *= -1; } if (projectile.y &gt; 500) { projectile.y = 500; projectile.vy *= -1; } if (projectile.y &lt; 0) { projectile.y = 0; projectile.vy *= -1; } } explosion.projectiles = projectilesRemove; } } function explosion(x, y) { this.projectiles = []; for (let i = 0; i &lt; 100; i++) { this.projectiles.push( new projectile(x, y) ); } } function projectile(x, y) { this.x = x; this.y = y; this.radius = 2 + Math.random() * 4; this.vx = -10 + Math.random() * 20; this.vy = -10 + Math.random() * 20; this.h = 200; this.s = Math.floor((Math.random() * 100) + 70); this.l = Math.floor((Math.random() * 70) + 30); } function setMouse(e) { mouseX = e.offsetX; mouseY = e.offsetY; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;canvas id="canvas" width="500" height="500" style="border:1px solid #000;"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T09:47:39.027", "Id": "398314", "Score": "1", "body": "Just a minor thing: Jon Burton, who has worked on a lot of games since the 16 bit era, has a pretty thorough video on his YouTube channel about how he developed a really efficien...
[ { "body": "<h1>Games and Animation.</h1>\n\n<p>Writing games means managing the compromise between the creative and artistic need, performance practicalities, and coding style. </p>\n\n<p>When developing you usually have a top end gaming machine, sadly this is the wrong machine to develop on. </p>\n\n<p>You nee...
{ "AcceptedAnswerId": "206478", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T17:13:52.700", "Id": "206451", "Score": "5", "Tags": [ "javascript", "performance", "animation", "canvas" ], "Title": "Rendering explosion of bouncing balls on a canvas" }
206451
<p>This is an interview question. A sorted rotated array is a sorted array which was rotated 0 or more times.</p> <p>For example: <code>[1,2,3] -&gt; [2,3,1]</code> </p> <p>Please tell me what do you think about the following (correctness, efficiency, coding conventions) and specifically if I can remove in some way the special handle for array of two elements: </p> <pre><code>static int findMax(int arr[]) { return findMax(arr, 0 , arr.length - 1); } static int findMax(int arr[], int low, int high) { int middle; if (low == high) { return arr[low]; } if ( Math.abs(high - low) == 1 ) { return Math.max(arr[low], arr[high]); } middle = (low + high) &gt;&gt; 1; if (arr[middle] &gt; arr[middle + 1]) { return arr[middle]; } if (arr[low] &gt; arr[middle]) { return findMax(arr, low, middle - 1); } return findMax(arr, middle + 1, high); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T11:22:14.257", "Id": "398323", "Score": "0", "body": "Welcome to Code Review! Have you tested this? How? Does it pass your tests? What made you write this? Please add more context. More context => better questions => better answers....
[ { "body": "<ul>\n<li><p><code>Math.abs</code> in <code>Math.abs(high - low) == 1</code> is suspicious. <code>high</code> <em>should</em> always be not less than <code>low</code>. Remove it.</p></li>\n<li><p><code>middle = (low + high) &gt;&gt; 1</code> <a href=\"https://ai.googleblog.com/2006/06/extra-extra-rea...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T19:18:19.397", "Id": "206460", "Score": "1", "Tags": [ "java", "performance", "interview-questions", "complexity", "binary-search" ], "Title": "Find maximum in sorted and rotated array" }
206460
<p>I was hoping I could get some help making my code more efficient. I'm a math major taking an Intro to Programming class, and I was asked to write a C program that generates:</p> <ol> <li><p>A text file named random_ints.txt containing 1≤n≤1000 random integers, separated by commas, in the range [2,1000000] and; </p></li> <li><p>A second file named primes.txt that contains a list of the prime numbers contained in random_ints.txt.</p></li> </ol> <p>The basic idea of my program is to:</p> <blockquote> <ol> <li><p>Create an array of n random integers and print them onto the first text file.</p></li> <li><p>Identify all prime numbers and place them at the beginning of the array.</p></li> <li><p>Sort them in non-decreasing order (increasing, with <em>(if any)</em> repetitions)</p></li> <li><p>Sort them in strictly increasing order (no repetitions).</p></li> <li><p>Print them onto the prime text file.</p></li> </ol> </blockquote> <p>This is the final revision of my code (which works fine):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;time.h&gt; int prime(int n){ /*creates function of primality test*/ int c = 0; if ( (n &lt;= 0) || (n == 1) ) { return 0; } else { for (int k = 2; k &lt;= (int)sqrt((double)n); ++k) { if( n % k == 0) { c = 1; } } if (c == 1) { return 0; } else { return 1; } } } int main(void) { int n; printf("\nPlease enter a positive amount (less than 1,000) of integers you would like to scan for primality:\n"); for (;;) { scanf("%d", &amp;n); if (n&gt;=1) { printf("\n"); break; } printf("\nError! Please enter a number between 1 and 1000:\n"); } int random[n]; /*begins declaring array*/ srand(time(0)); /*seeds the srand function*/ for (int i = 0; i &lt; n; ++i) /*fills in the array with random numbers from 2 to 1,000,000*/ { random[i] = rand() % (1000000 - 2 + 1) +2; FILE *fptr; fptr = fopen("random_ints.txt","w"); /*writes the random numbers of the array onto a text file*/ for (int i = 0; i &lt; n; ++i) { if (i == 0) { fprintf(fptr,"%d",random[i]); } else { fprintf(fptr,", %d",random[i]); } } fclose(fptr); if((n&gt;0) &amp;&amp; (n&lt;3)) /*deals with case where we have only one or two random numbers, since more than two numbers are needed to work with our for loop in line 119*/ { fptr = fopen("primes.txt","w"); /*checks whether the numbers are prime and, if so, writes them onto the prime text file*/ for (int i = 0; i &lt;= n; ++i) { if (prime(random[i]) == 1) { if (i == 0) { fprintf(fptr,"%d",random[i]); } else { fprintf(fptr,", %d",random[i]); } } } fclose(fptr); printf("Success!\n"); return 0; } else { if (n &gt;= 3) /*deals with case where we have 3 or more random numbers*/ { int p1 = 0; /*declares variable to be used to keep track of where to place a prime number once it is found on the array*/ for (int i = 0; i &lt; n; ++i) { if (prime(random[i]) == 1) /*checks every value in the array for primes; if it finds one, saves it on the p1-th place and increases this value by one*/ { random[p1] = random[i]; p1++; } } for (int i = p1; i &lt; n; ++i) /*(now, values from random[0] to random[p1 - 1] will be filled with random prime numbers) sets the rest of values to zero*/ { random[i] = 0; } for (int i = 0; i &lt; (p1-1); ++i) /*organizes the prime numbers in the array from least to greatest*/ { for (int k = (i + 1); k &lt; p1; ++k) { if (random[i] &gt; random[k]) { int temp = random[i]; random[i] = random[k]; random[k] = temp; } } } for (int i = 0; i &lt; (p1 - 1); ++i) /*shifts the array to get rid of repeated primes (except for the last one)*/ { if (random[i] == random[i + 1]) { int m = (i + 1); for (int k = (i + 1); k &lt; p1; ++k) { if(random[i] != random[k]) { random[m] = random[k]; m++; } } } } int r = 0; int z = 0; /*records where the last non-repeated prime is located*/ while(random[z] != random[z + 1]) { r++; z++; } fptr = fopen("primes.txt","w"); for (int i = 0; i &lt; r; ++i) { if (prime(random[i]) == 1) /*verifies that the numbers on the array are prime then, if so, writes them onto the prime number text file*/ { if (i == 0) { fprintf(fptr,"%d",random[i]); } else { fprintf(fptr,", %d",random[i]); } } } fclose(fptr); printf("Success!\n"); return 0; } else{ return -1; } } } </code></pre>
[]
[ { "body": "<p>You can simplify a lot your first function, you have a lot of useless statements. Also, you don't have to call sqrt each time, just save the result (I know, optimizer can do it for you but...).</p>\n\n<p>Your code fail if we give 2, it's prime, you don't catch this case. Once you know <code>n</cod...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T21:08:25.810", "Id": "206468", "Score": "0", "Tags": [ "beginner", "c", "primes" ], "Title": "Finding primes from random integers" }
206468
<p>I've recently been dipping my toes in to async code so I'm not 100% sure if there's a better way to do this, or if I'm going to run into problems down the road.</p> <p>I plan on using the following class in Unity. I'll be capturing a minimal amount of game state data every frame (between 25-100 bytes). I add the data to a queue and when it reaches around 1kb, I give it to my client object to serialize and send it to a server via tcp. I've called each data holding queue a 'chunk'. (Packet probably would have been better)</p> <p>I need to minimize blocking of Unity's main thread, I don't want there to be any opportunity for my client tasks to block the game thread so this class is supposed to act as a layer between the two. Recorder is probably a bad name for it.</p> <p>Everything works right now, I'm just unsure if theres a better way to (nearly) asynchronously pass data through queues for processing between threads.</p> <p>This class will be used like so:</p> <pre><code>Recorder recorder = new Recorder(); recorder.StartRecording(client, 30); //30 frames per chunk ... //every frame recorder.Record(frameData); ... recorder.StopRecording(); </code></pre> <p>frameData is any serializable class or struct. I have my own </p> <pre><code>public class Recorder&lt;T&gt; { private BlockingCollection&lt;Queue&lt;T&gt;&gt; dataQueue; private BlockingCollection&lt;T&gt; receivingQueue; private int chunkSize; private CancellationTokenSource cts; private Client client; public Recorder(Client _client, int _chunkSize) { dataQueue = new BlockingCollection&lt;Queue&lt;T&gt;&gt;(); receivingQueue = new BlockingCollection&lt;T&gt;(); client = _client; chunkSize = _chunkSize; cts = new CancellationTokenSource(); } public void StartRecording() { CancellationToken token = cts.Token; Task.Factory.StartNew(() =&gt; QueueFillerTask(token), token); Task.Factory.StartNew(() =&gt; DataSendingTask(token), token); } public void StopRecording() { cts.Cancel(); } public void Record(T obj) { receivingQueue.Add(obj); } private void QueueFillerTask(CancellationToken token) { while (true) { Queue&lt;T&gt; chunk = new Queue&lt;T&gt;(); try { while (chunk.Count &lt; chunkSize) { T obj = receivingQueue.Take(token); chunk.Enqueue(obj); } dataQueue.Add(chunk); Logger.Log("Chunk added"); } catch (System.OperationCanceledException e) { if (chunk.Count &gt; 0) { //Put the incomplete chunk in the dataqueue. dataQueue.Add(chunk); } Logger.Log("Recording ended"); break; } } } private void DataSendingTask(CancellationToken token) { try { while (true) { Queue&lt;T&gt; data = dataQueue.Take(token); client.PackAndShip(data); } } catch (System.OperationCanceledException e) { bool moreData; do { Queue&lt;T&gt; remainingItem; moreData = dataQueue.TryTake(out remainingItem); if (moreData) { client.PackAndShip(moreData); } } while (moreData); Logger.Log("Sending ended"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:37:52.333", "Id": "398301", "Score": "0", "body": "Could you explain how the two queues work together? I'm having a hard time figuring this out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T12:1...
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T22:05:04.287", "Id": "206472", "Score": "2", "Tags": [ "c#", "networking", "unity3d", "task-parallel-library" ], "Title": "Task based GameObject recorder for networked game" }
206472
<p>As my first simple PHP project, I've created a simple project that allows you to just enter your name and two numbers, where it displays them on the page and stores them in a database. It consists of 3 files: index.php, db.php &amp; process.php. I wonder whether I have created the code efficiently.</p> <p>I'm curious about all the talk behind procedural PHP vs OOP. I initially used some deprecated PHP5 functions and was corrected by the stack overflow community, but this has left me confused as to what specifically I should learn with PHP as a beginner. It sounds like procedural and OOP are very different, and that I should only pick one and learn that.</p> <p>So my questions are as follows:</p> <ol> <li>Is the coding in my project acceptable?</li> <li>Is it similar to how most PHP projects are built? (i.e. are most procedural or OOP)</li> <li>What should I learn as a beginner? (procedural or OOP?)</li> <li>Do you have any beginner advice?</li> </ol> <p>Any advice here would be very much appreciated as I'm new to PHP. Thanks for any help here. The files and code (excluding HTML &amp; CSS) are below:</p> <p>index.php:</p> <pre><code>&lt;?php include 'db.php'; ?&gt; &lt;?php // Fetch data from db $query = mysqli_query($con, 'SELECT * FROM data'); ?&gt; &lt;!-- create a loop (while there are results in the DB, spit them out) --&gt; &lt;?php while ($row = $query-&gt;fetch_assoc()) : ?&gt; &lt;li&gt;&lt;?php echo $row['t_name'] ?&gt; entered &lt;?php echo $row['t_firstNo'] ?&gt; and &lt;?php echo $row['t_secondNo'] ?&gt; (result = &lt;?php $first = $row['t_firstNo']; $second = $row['t_secondNo']; $result = $first * $second; echo $result; ?&gt;)&lt;/li&gt; &lt;?php endwhile ?&gt; &lt;!-- if bad input, get &amp; display error --&gt; &lt;?php if(isset($_GET['error'])) : // if error variable is there ?&gt; &lt;?php echo $_GET['error']; // get the error ?&gt; &lt;?php endif ?&gt; </code></pre> <p>db.php:</p> <pre><code>&lt;?php // Connect $con = mysqli_connect("localhost", "tnnick", "PHPprojects", "timesNumbers"); // Test Connection if (mysqli_connect_errno()) { echo 'Failed: '.mysqli_connect_error(); } ?&gt; </code></pre> <p>process.php:</p> <pre><code>&lt;?php include 'db.php' ; ?&gt; &lt;?php if(isset($_POST['submit'])) { // if form submitted $nickname = mysqli_real_escape_string($con, $_POST['nickname']); // get the inputs $firstNo = mysqli_real_escape_string($con, $_POST['firstNo']); $secondNo = mysqli_real_escape_string($con, $_POST['secondNo']); } ?&gt; &lt;?php // validate inputs if(!isset($nickname) || $nickname=='' || !isset($firstNo) || $firstNo=='' || !isset($secondNo) || $secondNo=='' ) { // if invalid input, send error to index.php $error = 'Bad input - try again.'; // create error message header("Location: index.php?error=".urlencode($error)); // attach to URL &amp; send to index.php exit(); } else { // insert into DB $putIntoDB = "INSERT INTO data (t_name, t_firstNo, t_secondNo) VALUES ('$nickname','$firstNo','$secondNo')"; // check it inserted if(!mysqli_query($con, $putIntoDB)) { die('Error'); } else { header("Location: index.php"); exit(); } } ?&gt; </code></pre>
[]
[ { "body": "<blockquote>\n<ol>\n<li>Is the coding in my project acceptable?</li>\n</ol>\n</blockquote>\n<p>More or less. There are no essential flaws but the structure is quite questionable.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Is it similar to how most PHP projects are built? (i.e. are most procedural or OO...
{ "AcceptedAnswerId": "206490", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T22:18:21.060", "Id": "206474", "Score": "0", "Tags": [ "beginner", "php", "sql", "mysqli" ], "Title": "Simple PHP project to store inputs in MySQL and output them" }
206474
<p>I have image files consisting of black and white pixels encoded as RGB8. I want to count the number of blobs i.e. contiguous areas of white pixels. I rewrote <a href="http://algebra.sci.csueastbay.edu/~grewe/CS6825/Mat/BinaryImageProcessing/BlobDetection.htm" rel="nofollow noreferrer">this algorithm</a> in haskell.<br> The algorithm works as follows: The image is traversed and whenever a white pixel is encountered the counter is incremented and all accessible pixels are set to black(so they don't get counted again).</p> <pre><code>import System.Environment import Codec.Picture import Codec.Picture.Types import Data.Vector.Storable ( (!), (//), Vector, toList ) import GHC.Word main = do args &lt;- getArgs Right im &lt;- readPng (head args) let imgRGB8 = (\(ImageRGB8 t) -&gt; t) im let imgGray = pixelMap computeLuma imgRGB8 let w = imageWidth imgGray let h = imageHeight imgGray let imVec = imageData imgGray let coords = [0..(w*h -1)] print (loop w h imVec coords 0) type I = Data.Vector.Storable.Vector GHC.Word.Word8 loop :: Int -&gt; Int -&gt; I -&gt; [Int] -&gt; Int -&gt; Int loop _ _ _ [] blobCount = blobCount loop w h image (c:cs) blobCount = if (image ! c) == 255 then loop w h (deleteBlob w h image c) cs (blobCount+1) else loop w h image cs blobCount deleteBlob :: Int -&gt; Int -&gt; I -&gt; Int -&gt; I deleteBlob w h image c | image ! c == 255 = foldl (deleteBlob w h) (image // [(c, 0)]) coords | otherwise = image where coords = environment w h c environment w h i = takeWhile (&lt; w*h) $ dropWhile (&lt;0) [i-w-1, i-w, i-w+1 {- in a vector image the row above is -} ,i -1, i +1 {- imageWidth apart. perks: easy clipping -} ,i+w-1, i+w, i+w+1] </code></pre> <p>My main concern is that my haskell version is so much slower than my python version.<br> Second concern is am I loading the images right? Should I have used a more recent library? This is the only way I could make it work.<br> Thirdly, is this how a haskeller would write a blob count?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-31T13:27:21.930", "Id": "398642", "Score": "0", "body": "This is called connected component analysis. There exist much more efficient algorithms using a UnionFind data structure. I would review your code, but I don’t know Haskell, so c...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T00:52:30.033", "Id": "206476", "Score": "4", "Tags": [ "performance", "algorithm", "haskell", "image" ], "Title": "Functional blob counting" }
206476
<p>I am writing a simple compiled programming language. Everything but the bytecode interpreter can run as slow as possible, but I would like the interpreter to fun fast, because that's why I made it compiled. </p> <p>Now that much of the language is working, I decided to profile it to see where I could improve the interpreter. And I find out that a particular method, the method that enables the interpreter to use space freed up by previously deleted variables, is the major bottleneck.</p> <p>The function, <code>find_space</code>, takes in the size of the contiguous memory block to find. A nonlocal variable called <code>used_mem</code> stores all the indices that are being used by other variables. To <code>find_space</code>, one must find an index where the next <code>size</code> items are not in <code>used_mem</code>.</p> <p>The original implementation (also the fastest):</p> <pre><code>def find_space(size: int) -&gt; int: for i in range(256): # all possible memory indices for offset in range(size): # for index past the starting index in size if i+offset in used_mem: # check that new index is not in the used memory break # oh well, its used, lets move on else: return i # it works! lets use it return None </code></pre> <p>My second implementation (slowest):</p> <pre><code>def find_space(size: int) -&gt; int: return next(i for i in range(256) if all(i+offset not in used_mem for offset in range(size))) </code></pre> <p>My third implementation (middle):</p> <pre><code>def find_space(size: int) -&gt; int: for i in range(256): if used_mem.isdisjoint(range(i, i+size)): return i return None </code></pre> <p>However, all these implementations still couldn't get the average total time used on calculating the 46th fibonacci number 10 times below 0.086 sec.</p> <p>I've tried 3 times, and 3rd time is supposed to be the charm. Therefore, I'm asking all you wonderful, talented people of codereview.stackexchange.com to help me in optimizing this code. </p> <p><strong>How can I optimize this code to run as fast as humanely possible in python?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T04:27:45.507", "Id": "398283", "Score": "1", "body": "What is `used_mem`? A list? A dict? A set?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:03:05.353", "Id": "398297", "Score": "0",...
[ { "body": "<p>I'll start with the obligatory:</p>\n\n<p>If you're looking to write a fast interpreter, and you've identified a bottleneck in your memory allocator, a smarter algorithm may save you but at the end of the day rewriting in something lower level is probably the way to go if interpreter speed is that...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T01:40:28.757", "Id": "206477", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "comparative-review", "memory-management" ], "Title": "Lowest open space in memory" }
206477
<p>I implemented an <code>Entity</code> and <code>ComponentManager&lt; T &gt;</code> for my new Entity-Component-System (ECS) architecture in my game engine. My older ECS maintained the <code>Entity</code> to <code>Components</code> mapping on the <code>Entities</code> themselves, and the <code>Component</code> to <code>Entity</code> mappings on the <code>Components</code> themselves; all using custom pointer types, since the actual <code>Entities</code> and <code>Components</code> were stored elsewhere in contiguous memory. This does, however, not result in minimally and optimally packed and aligned <code>Entities</code> and <code>Components</code>, as is the case for (or at least could be achieved with) my new ECS architecture.</p> <p>Each <code>Component</code> type is managed by a separate container, <code>ComponentManager&lt; T &gt;</code>, that encapsulates three separate containers for the following data:</p> <ul> <li>A contiguous block of memory holding the <code>Components</code>. In most cases, <code>Components</code> will be processed in front-to-back order without requiring the corresponding <code>Entities</code> per frame.</li> <li>A contiguous block of memory holding the <code>Entities</code>. The <code>Component</code> at index <code>i</code> in <code>Components</code> is associated with the <code>Entity</code> at index <code>i</code> in <code>Entities</code> (i.e. a map where the keys and values are stored separately as opposed to key-value pairs). In rare cases, <code>Component</code>-<code>Entity</code> pairs are processed in front-to-back order (at most once per <code>ComponentManager&lt; T &gt;</code>) per frame.</li> <li>An unordered mapping from <code>Entities</code> to <code>Component</code> indices in <code>Components</code>. In rare cases, the <code>Component</code> associated with a given <code>Entity</code> needs to be retrieved (at most once per <code>ComponentManager&lt; T &gt;</code>) per frame.</li> </ul> <p>Since <code>Components</code> are mostly processed without requiring the corresponding <code>Entities</code>, the <code>ComponentManager&lt; T &gt;</code>'s interface provides iterators to <code>Components</code> (e.g., support for ranged-based for loop). An additional <code>RecordIterator&lt; T &gt;</code> can be used for reordering (e.g., <code>std::sort</code>, <code>std::partition</code>, etc.) the <code>Components</code> of a <code>ComponentManager&lt; T &gt;</code>, while reordering the data of the other two containers as well. (Originally, <code>RecordIterator&lt; T &gt;</code> and its value type, <code>Record&lt; T &gt;</code>, were contained in <code>ComponentManager&lt; T &gt;</code> due to their tight connection, but then I could not partially specialize <code>iterator_traits</code>.)</p> <p>I need to put the <code>swap(mage::Record&lt; T &gt; lhs, mage::Record&lt; T &gt; rhs)</code> in the <code>mage</code> instead of <code>std</code> namespace, since both arguments are not passed as references, because <code>RecordIterator&lt; T &gt;::operator*</code> returns by value instead of reference. Currently, I do not see a possibility of returning by reference, since <code>Record&lt; T &gt;</code>'s do not pre-exist. This, unfortunately, makes the overload of <code>RecordIterator&lt; T &gt;::operator-&gt;</code> impossible (not sure, however, which STL algorithms actually use this operator anyway).</p> <p>It is not necessary to update all iterators at once in <code>RecordIterator&lt; T &gt;</code>. Only one iterator is updated via the iterator operator overloads. The other iterators are only computed upon swapping. This is much cheaper than retrieving the associated <code>std::unordered_map&lt; Entity, std::size_t &gt;::iterator</code> every iterator update (e.g., a completely sorted vector of components does not require any swaps and will thus not perform any <code>std::unordered_map::operator[]</code> invocations).</p> <p>The erase-remove idiom is currently not possible, since associative containers (e.g., <code>std::unordered_map</code>) do not support <code>std::remove/std::remove_if</code>. I already provide a template function performing both erase and remove/remove_if on a given container, which can thus be overloaded and specialized for a <code>ContainerManager&lt; T &gt;</code> to support this as well.</p> <p>My most important goals are: </p> <ul> <li>Good performance by exploiting cache coherency, both data and instruction locality, for the most common case of processing the <code>Components</code>. (This depends on the actual processing of a <code>Component</code> as well, but that is outside the scope of the <code>ComponentManager&lt; T &gt;</code>).</li> <li>STL compliance: the container and more importantly the associated iterators must be compatible with the functions provided in <code>&lt;algorithm&gt;</code> (e.g., work with <code>std::partition</code>, <code>std::sort</code>, <code>std::nth_element</code>, etc.).</li> </ul> <p>I especially like to have some feedback with regard to the latter. General guidelines, best practices? (<strong>Note</strong> that I am less concerned with naming conventions: I use PascalCase for my class and method names, but deviate if similar to or needed for the <code>std</code>.)</p> <p><a href="https://wandbox.org/permlink/sGjgQ6Xfq4GrVu7I" rel="nofollow noreferrer">Try It Online</a></p> <p><strong>Includes</strong>:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;cstdint&gt; #include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; </code></pre> <p><strong>Placeholders</strong>:</p> <pre><code>using U32 = std::uint32_t; template&lt; typename T &gt; using AlignedVector = std::vector&lt; T &gt;; // placeholder </code></pre> <p><strong>Entity</strong>:</p> <pre><code>namespace mage { class Entity { public: //--------------------------------------------------------------------- // Constructors and Destructors //--------------------------------------------------------------------- constexpr explicit Entity(U32 id = 0u) noexcept : m_id(id) {} constexpr Entity(const Entity&amp; entity) noexcept = default; constexpr Entity(Entity&amp;&amp; entity) noexcept = default; ~Entity() = default; //--------------------------------------------------------------------- // Assignment Operators //--------------------------------------------------------------------- Entity&amp; operator=(const Entity&amp; entity) noexcept = default; Entity&amp; operator=(Entity&amp;&amp; entity) noexcept = default; //--------------------------------------------------------------------- // Member Methods //--------------------------------------------------------------------- [[nodiscard]] constexpr U32 GetID() const noexcept { return m_id; } [[nodiscard]] constexpr explicit operator U32() const noexcept { return GetID(); } [[nodiscard]] constexpr bool IsValid() const noexcept { return 0u != m_id; } [[nodiscard]] constexpr explicit operator bool() const noexcept { return IsValid(); } [[nodiscard]] constexpr bool operator==(const Entity&amp; rhs) const noexcept { return m_id == rhs.m_id; } [[nodiscard]] constexpr bool operator!=(const Entity&amp; rhs) const noexcept { return m_id != rhs.m_id; } [[nodiscard]] constexpr bool operator&lt;=(const Entity&amp; rhs) const noexcept { return m_id &lt;= rhs.m_id; } [[nodiscard]] constexpr bool operator&gt;=(const Entity&amp; rhs) const noexcept { return m_id &gt;= rhs.m_id; } [[nodiscard]] constexpr bool operator&lt;(const Entity&amp; rhs) const noexcept { return m_id &lt; rhs.m_id; } [[nodiscard]] constexpr bool operator&gt;(const Entity&amp; rhs) const noexcept { return m_id &gt; rhs.m_id; } [[nodiscard]] std::size_t Hash() const noexcept { return std::hash&lt; U32 &gt;()(m_id); } private: //--------------------------------------------------------------------- // Member Variables //--------------------------------------------------------------------- U32 m_id; }; static_assert(sizeof(U32) == sizeof(Entity)); } namespace std { template&lt;&gt; struct hash&lt; mage::Entity &gt; { size_t operator()(const mage::Entity&amp; entity) const { return entity.Hash(); } }; } </code></pre> <p><strong>ComponentManager</strong>:</p> <pre><code>namespace mage { //------------------------------------------------------------------------- // ComponentManager //------------------------------------------------------------------------- template&lt; typename T &gt; class ComponentManager { public: //--------------------------------------------------------------------- // Class Member Types //--------------------------------------------------------------------- using ComponentContainer = AlignedVector&lt; T &gt;; using EntityContainer = AlignedVector&lt; Entity &gt;; using MappingContainer = std::unordered_map&lt; Entity, std::size_t &gt;; using value_type = typename ComponentContainer::value_type; using size_type = typename ComponentContainer::size_type; using difference_type = typename ComponentContainer::difference_type; using reference = typename ComponentContainer::reference; using const_reference = typename ComponentContainer::const_reference; using pointer = typename ComponentContainer::pointer; using const_pointer = typename ComponentContainer::const_pointer; using iterator = typename ComponentContainer::iterator; using const_iterator = typename ComponentContainer::const_iterator; using reverse_iterator = typename ComponentContainer::reverse_iterator; using const_reverse_iterator = typename ComponentContainer::const_reverse_iterator; //--------------------------------------------------------------------- // Friends //--------------------------------------------------------------------- template&lt; typename U &gt; friend class Record; template&lt; typename U &gt; friend class RecordIterator; //--------------------------------------------------------------------- // Constructors and Destructors //--------------------------------------------------------------------- ComponentManager() = default; ComponentManager(const ComponentManager&amp; manager) = default; ComponentManager(ComponentManager&amp;&amp; manager) noexcept = default; ~ComponentManager() = default; //--------------------------------------------------------------------- // Assignment Operators //--------------------------------------------------------------------- ComponentManager&amp; operator=(const ComponentManager&amp; manager) = default; ComponentManager&amp; operator=(ComponentManager&amp;&amp; manager) noexcept = default; //--------------------------------------------------------------------- // Member Methods: Element access //--------------------------------------------------------------------- [[nodiscard]] bool Contains(Entity entity) const noexcept { return m_mapping.find(entity) != m_mapping.cend(); } [[nodiscard]] pointer Get(Entity entity) noexcept { if (const auto it = m_mapping.find(entity); it != m_mapping.cend()) { return &amp;m_components[it-&gt;second]; } return nullptr; } [[nodiscard]] const_pointer Get(Entity entity) const noexcept { if (const auto it = m_mapping.find(entity); it != m_mapping.cend()) { return &amp;m_components[it-&gt;second]; } return nullptr; } [[nodiscard]] reference at(size_type index) { return m_components.at(index); } [[nodiscard]] const_reference at(size_type index) const { return m_components.at(index); } [[nodiscard]] reference operator[](size_type index) noexcept { return m_components[index]; } [[nodiscard]] const_reference operator[](size_type index) const noexcept { return m_components[index]; } [[nodiscard]] reference front() noexcept { return m_components.front(); } [[nodiscard]] const_reference front() const noexcept { return m_components.front(); } [[nodiscard]] reference back() noexcept { return m_components.back(); } [[nodiscard]] const_reference back() const noexcept { return m_components.back(); } [[nodiscard]] value_type* data() noexcept { return m_components.data(); } [[nodiscard]] const value_type* data() const noexcept { return m_components.data(); } //--------------------------------------------------------------------- // Member Methods: Iterators //--------------------------------------------------------------------- [[nodiscard]] iterator begin() noexcept { return m_components.begin(); } [[nodiscard]] const_iterator begin() const noexcept { return m_components.begin(); } [[nodiscard]] const_iterator cbegin() const noexcept { return m_components.cbegin(); } [[nodiscard]] iterator end() noexcept { return m_components.end(); } [[nodiscard]] const_iterator end() const noexcept { return m_components.end(); } [[nodiscard]] const_iterator cend() const noexcept { return m_components.end(); } [[nodiscard]] reverse_iterator rbegin() noexcept { return m_components.rbegin(); } [[nodiscard]] const_reverse_iterator rbegin() const noexcept { return m_components.rbegin(); } [[nodiscard]] const_reverse_iterator crbegin() const noexcept { return m_components.crbegin(); } [[nodiscard]] reverse_iterator rend() noexcept { return m_components.rend(); } [[nodiscard]] const_reverse_iterator rend() const noexcept { return m_components.rend(); } [[nodiscard]] const_reverse_iterator crend() const noexcept { return m_components.crend(); } //--------------------------------------------------------------------- // Member Methods: Capacity //--------------------------------------------------------------------- [[nodiscard]] bool empty() const noexcept { return m_components.empty(); } [[nodiscard]] size_type size() const noexcept { return m_components.size(); } [[nodiscard]] size_type max_size() const noexcept { return m_components.max_size(); } void reserve(size_type new_capacity) { m_components.reserve(new_capacity); m_entities.reserve(new_capacity); m_mapping.reserve(new_capacity); } [[nodiscard]] size_type capacity() const noexcept { return m_components.capacity(); } void shrink_to_fit() { m_components.shrink_to_fit(); m_entities.shrink_to_fit(); } //--------------------------------------------------------------------- // Member Methods: Modifiers //--------------------------------------------------------------------- void clear() noexcept { m_components.clear(); m_entities.clear(); m_mapping.clear(); } void push_back(Entity entity, const value_type&amp; value) { emplace_back(entity, value); } void push_back(Entity entity, value_type&amp;&amp; value) { emplace_back(entity, std::move(value)); } template&lt; typename... ConstructorArgsT &gt; reference emplace_back(Entity entity, ConstructorArgsT&amp;&amp;... args) { if (const auto it = m_mapping.find(entity); it != m_mapping.cend()) { return m_components[it-&gt;second]; } m_mapping.emplace(entity, size()); m_entities.push_back(entity); return m_components.emplace_back( std::forward&lt; ConstructorArgsT &gt;(args)...); } void pop_back() { m_mapping.erase(m_entities.back()); m_components.pop_back(); m_entities.pop_back(); } void swap(ComponentManager&amp; other) noexcept { std::swap(m_components, other.m_components); std::swap(m_entities, other.m_entities); std::swap(m_mapping, other.m_mapping); } // private: commented for std::cout illustration //--------------------------------------------------------------------- // Member Variables //--------------------------------------------------------------------- AlignedVector&lt; value_type &gt; m_components; AlignedVector&lt; Entity &gt; m_entities; std::unordered_map&lt; Entity, std::size_t &gt; m_mapping; }; </code></pre> <p><strong>Record</strong>:</p> <pre><code> //------------------------------------------------------------------------- // Record //------------------------------------------------------------------------- template&lt; typename T &gt; class Record { public: //--------------------------------------------------------------------- // Class Member Types //--------------------------------------------------------------------- using ComponentIterator = typename ComponentManager&lt; T &gt;::iterator; //--------------------------------------------------------------------- // Constructors and Destructors //--------------------------------------------------------------------- Record() noexcept : m_component_it{}, m_component_manager(nullptr) {} explicit Record(ComponentIterator component_it, ComponentManager&lt; T &gt;* component_manager) noexcept : m_component_it(std::move(component_it)), m_component_manager(component_manager) {} Record(const Record&amp; record) noexcept = default; Record(Record&amp;&amp; record) noexcept = default; ~Record() = default; //--------------------------------------------------------------------- // Assignment Operators //--------------------------------------------------------------------- Record&amp; operator=(const Record&amp; record) = delete; Record&amp; operator=(Record&amp;&amp; record) noexcept { swap(record); return *this; } //--------------------------------------------------------------------- // Member Methods //--------------------------------------------------------------------- [[nodiscard]] constexpr bool operator==(const T&amp; rhs) const noexcept { return *m_component_it == rhs; } [[nodiscard]] constexpr bool operator!=(const T&amp; rhs) const noexcept { return *m_component_it != rhs; } [[nodiscard]] constexpr bool operator&lt;=(const T&amp; rhs) const noexcept { return *m_component_it &lt;= rhs; } [[nodiscard]] constexpr bool operator&gt;=(const T&amp; rhs) const noexcept { return *m_component_it &gt;= rhs; } [[nodiscard]] constexpr bool operator&lt;(const T&amp; rhs) const noexcept { return *m_component_it &lt; rhs; } [[nodiscard]] constexpr bool operator&gt;(const T&amp; rhs) const noexcept { return *m_component_it &gt; rhs; } [[nodiscard]] friend constexpr bool operator==(const T&amp; lhs, const Record&amp; rhs) noexcept { return lhs == *rhs.m_component_it; } [[nodiscard]] friend constexpr bool operator!=(const T&amp; lhs, const Record&amp; rhs) noexcept { return lhs != *rhs.m_component_it; } [[nodiscard]] friend constexpr bool operator&lt;=(const T&amp; lhs, const Record&amp; rhs) noexcept { return lhs &lt;= *rhs.m_component_it; } [[nodiscard]] friend constexpr bool operator&gt;=(const T&amp; lhs, const Record&amp; rhs) noexcept { return lhs &gt;= *rhs.m_component_it; } [[nodiscard]] friend constexpr bool operator&lt;(const T&amp; lhs, const Record&amp; rhs) noexcept { return lhs &lt; *rhs.m_component_it; } [[nodiscard]] friend constexpr bool operator&gt;(const T&amp; lhs, const Record&amp; rhs) noexcept { return lhs &gt; *rhs.m_component_it; } [[nodiscard]] constexpr bool operator==(const Record&amp; rhs) const noexcept { return *m_component_it == *rhs.m_component_it; } [[nodiscard]] constexpr bool operator!=(const Record&amp; rhs) const noexcept { return *m_component_it != *rhs.m_component_it; } [[nodiscard]] constexpr bool operator&lt;=(const Record&amp; rhs) const noexcept { return *m_component_it &lt;= *rhs.m_component_it; } [[nodiscard]] constexpr bool operator&gt;=(const Record&amp; rhs) const noexcept { return *m_component_it &gt;= *rhs.m_component_it; } [[nodiscard]] constexpr bool operator&lt;(const Record&amp; rhs) const noexcept { return *m_component_it &lt; *rhs.m_component_it; } [[nodiscard]] constexpr bool operator&gt;(const Record&amp; rhs) const noexcept { return *m_component_it &gt; *rhs.m_component_it; } void swap(Record&amp; other) noexcept { assert(nullptr != m_component_manager); assert(m_component_manager == other.m_component_manager); assert(m_component_manager-&gt;end() != m_component_it); assert(m_component_manager-&gt;end() != other.m_component_it); const std::size_t index1 = m_component_it - m_component_manager-&gt;m_components.begin(); auto&amp; entity1 = m_component_manager-&gt;m_entities[index1]; auto&amp; mapping1 = m_component_manager-&gt;m_mapping[entity1]; const std::size_t index2 = other.m_component_it - m_component_manager-&gt;m_components.begin(); auto&amp; entity2 = m_component_manager-&gt;m_entities[index2]; auto&amp; mapping2 = m_component_manager-&gt;m_mapping[entity2]; std::swap(*m_component_it, *other.m_component_it); std::swap(entity1, entity2); std::swap(mapping1, mapping2); } private: //--------------------------------------------------------------------- // Member Variables //--------------------------------------------------------------------- ComponentIterator m_component_it; ComponentManager&lt; T &gt;* m_component_manager; }; </code></pre> <p><strong>RecordIterator</strong>:</p> <pre><code> //------------------------------------------------------------------------- // RecordIterator //------------------------------------------------------------------------- template&lt; typename T &gt; class RecordIterator { public: //--------------------------------------------------------------------- // Class Member Types //--------------------------------------------------------------------- using ComponentIterator = typename ComponentManager&lt; T &gt;::iterator; //--------------------------------------------------------------------- // Constructors and Destructors //--------------------------------------------------------------------- RecordIterator() noexcept : m_component_it{}, m_component_manager(nullptr) {} explicit RecordIterator(ComponentIterator component_it, ComponentManager&lt; T &gt;* component_manager) noexcept : m_component_it(std::move(component_it)), m_component_manager(component_manager) {} RecordIterator(const RecordIterator&amp; it) noexcept = default; RecordIterator(RecordIterator&amp;&amp; it) noexcept = default; ~RecordIterator() = default; //--------------------------------------------------------------------- // Assignment Operators //--------------------------------------------------------------------- RecordIterator&amp; operator=(const RecordIterator&amp; it) noexcept = default; RecordIterator&amp; operator=(RecordIterator&amp;&amp; it) noexcept = default; //--------------------------------------------------------------------- // Member Methods //--------------------------------------------------------------------- Record&lt; T &gt; operator*() noexcept { return Record&lt; T &gt;(m_component_it, m_component_manager); } Record&lt; T &gt; operator*() const noexcept { return Record&lt; T &gt;(m_component_it, m_component_manager); } [[nodiscard]] Record&lt; T &gt; operator[](std::size_t n) noexcept { return Record&lt; T &gt;(m_component_it + n, m_component_manager); } [[nodiscard]] Record&lt; T &gt; operator[](std::size_t n) const noexcept { return Record&lt; T &gt;(m_component_it + n, m_component_manager); } [[nodiscard]] std::size_t operator-(const RecordIterator&amp; it) const noexcept { return m_component_it - it.m_component_it; } [[nodiscard]] const RecordIterator operator+(std::size_t n) const noexcept { return RecordIterator(m_component_it + n, m_component_manager); } [[nodiscard]] const RecordIterator operator-(std::size_t n) const noexcept { return RecordIterator(m_component_it - n, m_component_manager); } [[nodiscard]] friend const RecordIterator operator+(std::size_t n, const RecordIterator&amp; it) noexcept { return it + n; } RecordIterator&amp; operator++() noexcept { ++m_component_it; return *this; } RecordIterator&amp; operator--() noexcept { --m_component_it; return *this; } [[nodiscard]] friend const RecordIterator operator++(const RecordIterator&amp; it) noexcept { return RecordIterator(it.m_component_it + 1u, it.m_component_manager); } [[nodiscard]] friend const RecordIterator operator--(const RecordIterator&amp; it) noexcept { return RecordIterator(it.m_component_it - 1u, it.m_component_manager); } RecordIterator&amp; operator+=(std::size_t n) noexcept { m_component_it += n; return *this; } RecordIterator&amp; operator-=(std::size_t n) noexcept { m_component_it -= n; return *this; } [[nodiscard]] constexpr bool operator==(const RecordIterator&amp; rhs) const noexcept { return m_component_it == rhs.m_component_it; } [[nodiscard]] constexpr bool operator!=(const RecordIterator&amp; rhs) const noexcept { return m_component_it != rhs.m_component_it; } [[nodiscard]] constexpr bool operator&lt;=(const RecordIterator&amp; rhs) const noexcept { return m_component_it &lt;= rhs.m_component_it; } [[nodiscard]] constexpr bool operator&gt;=(const RecordIterator&amp; rhs) const noexcept { return m_component_it &gt;= rhs.m_component_it; } [[nodiscard]] constexpr bool operator&lt;(const RecordIterator&amp; rhs) const noexcept { return m_component_it &lt; rhs.m_component_it; } [[nodiscard]] constexpr bool operator&gt;(const RecordIterator&amp; rhs) const noexcept { return m_component_it &gt; rhs.m_component_it; } private: ComponentIterator m_component_it; ComponentManager&lt; T &gt;* m_component_manager; }; </code></pre> <p><strong>Miscellaneous</strong>:</p> <pre><code> template&lt; typename T &gt; [[nodiscard]] inline RecordIterator&lt; T &gt; RecordBegin(ComponentManager&lt; T &gt;&amp; manager) noexcept { return RecordIterator&lt; T &gt;(manager.begin(), &amp;manager); } template&lt; typename T &gt; [[nodiscard]] inline RecordIterator&lt; T &gt; RecordEnd(ComponentManager&lt; T &gt;&amp; manager) noexcept { return RecordIterator&lt; T &gt;(manager.end(), &amp;manager); } template&lt; typename T &gt; void swap(mage::Record&lt; T &gt; lhs, mage::Record&lt; T &gt; rhs) noexcept { lhs.swap(rhs); } } namespace std { template&lt; typename T &gt; struct iterator_traits&lt; mage::RecordIterator&lt; T &gt; &gt; { public: using value_type = mage::Record&lt; T &gt;; using reference_type = mage::Record&lt; T &gt;&amp;; // not sure? using pointer_type = mage::Record&lt; T &gt;*; // not sure? using difference_type = ptrdiff_t; using iterator_category = random_access_iterator_tag; }; } </code></pre> <p><strong>Main</strong>:</p> <pre><code>int main() { mage::ComponentManager&lt; float &gt; manager; manager.emplace_back(mage::Entity(5u), 5.0f); manager.emplace_back(mage::Entity(4u), 4.0f); manager.emplace_back(mage::Entity(3u), 3.0f); manager.emplace_back(mage::Entity(2u), 2.0f); manager.emplace_back(mage::Entity(1u), 1.0f); for (auto&amp; c : manager.m_components) { std::cout &lt;&lt; c; } std::cout &lt;&lt; std::endl; for (auto&amp; e : manager.m_entities) { std::cout &lt;&lt; U32(e); } std::cout &lt;&lt; std::endl; for (auto&amp; [e, i] : manager.m_mapping) { std::cout &lt;&lt; '(' &lt;&lt; U32(e) &lt;&lt; "-&gt;" &lt;&lt; i &lt;&lt; ')'; } std::cout &lt;&lt; std::endl; std::sort(RecordBegin(manager), RecordEnd(manager)); for (auto&amp; c : manager.m_components) { std::cout &lt;&lt; c; } std::cout &lt;&lt; std::endl; for (auto&amp; e : manager.m_entities) { std::cout &lt;&lt; U32(e); } std::cout &lt;&lt; std::endl; for (auto&amp; [e, i] : manager.m_mapping) { std::cout &lt;&lt; '(' &lt;&lt; U32(e) &lt;&lt; "-&gt;" &lt;&lt; i &lt;&lt; ')'; } std::cout &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<ul>\n<li><p>I guess you've already checked the iterator requirements, but just in case; it's basically implementing everything on this page (and the \"named requirements\" pages linked from it): <a href=\"https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator\" rel=\"nofollow noreferrer\">...
{ "AcceptedAnswerId": "206523", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:02:57.753", "Id": "206484", "Score": "3", "Tags": [ "c++", "c++17" ], "Title": "C++ multiple container synchronization in Entity-Component-System compatible with STL" }
206484
<p>I have been implementing the <code>merge-sort</code> algorithm for sorting the data for a long time, each time I use the following source code for implementation. By secure, I mean, taking care of memory management, loopholes etc.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;assert.h&gt; void mergesort(int*,int,int); void mergeSequence(int*,int,int,int); //Merge the two arrays void displaySequence(int*); int n; int main() { int t,test; int*num=NULL; int i; printf("Enter the number of test cases\n", test); scanf("%d", &amp;test); assert(test&gt;0); for(t=0;t&lt;test;t++) { printf("Enter the size of the sequence\n", n); scanf("%d", &amp;n); assert(n&gt;0); num=calloc(sizeof(int),n); assert(num); printf("Enter the sequence\n"); for(i=0;i&lt;n;i++) scanf("%d", (num+i)); printf("Sequence before sorting\n"); displaySequence(num); mergeSort(num,0,(n-1)); printf("Sequence after sorting\n"); display(num); free(num); } return 0; } void displaySequence(int*num) { int i; for(i=0;i&lt;n;i++) printf("%d ", num[i]); printf("\n"); } void mergeSort(int*num,int start,int end) { int mid; mid=start+((end-start)/2); printf("Mid-&gt;%d\n", mid); if(start&lt;end) { mergeSort(num,start,mid); mergeSort(num,(mid+1),end); mergeSequence(num,start,mid,end); } } void mergeSequence(int*num,int start,int mid,int end) { int n1,n2; int i,j,k; n1=(mid-start)+1; n2=(end-mid); printf("N1-&gt;%d\nN2-&gt;%d\n", n1,n2); int left[n1]; int right[n2]; for(i=0;i&lt;n1;i++) left[i]=num[start+i]; for(i=0;i&lt;n1;i++) printf("%d ", left[i]); printf("\n"); for(j=0;j&lt;n2;j++) right[j]=num[(mid+1)+j]; for(j=0;j&lt;n2;j++) printf("%d ", right[j]); printf("\n"); //Now I have two arrays, and I can now merge them k=start; i=0; j=0; while((k&lt;=end)) { if(i==n1) { num[k]=right[j]; j++; } else if(j==n2) { num[k]=left[i]; i++; } else if(left[i]&lt;=right[j]) { num[k]=right[j]; j=j+1; } else { num[k]=left[i]; i=i+1; } k++; } displaySequence(num); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T22:27:35.053", "Id": "458228", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y...
[ { "body": "<h1>Always check the result of <code>scanf()</code></h1>\n\n<p>This code optimistically assumes that numeric inputs are successfully parsed. We need to check that the result of <code>scanf()</code> (the number of conversions successfully parsed and assigned) matches our expectations before using any...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:27:43.513", "Id": "206485", "Score": "3", "Tags": [ "algorithm", "c", "sorting", "mergesort" ], "Title": "How can I make my Merge Sort Code In C more secure, effective and efficient" }
206485
<h2>Intro</h2> <p>This class emulates a <code>switch</code> statement, in order to</p> <ul> <li>include non-switchable types (POJOs)</li> <li>have the same switch statement executable for different values</li> <li>be able to extend a previously defined switch</li> <li>TODO: Refactor into <code>ConsumerSwitch.Builder</code> and <code>FunctionSwitch.Builder</code> that represents <code>SwitchCase&lt;Predicate&lt;T&gt;, Consumer&lt;T&gt;&gt;</code> and <code>SwitchCase&lt;Predicate&lt;T&gt;, Function&lt;T, U&gt;&gt;</code></li> </ul> <h2>Implementation</h2> <pre><code>/* Switch.java * Copyright (C) 2018 Zymus * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. */ package net.zephyrion.util; import java.util.LinkedList; import java.util.function.Consumer; import java.util.function.Predicate; public final class Switch&lt;T&gt; { public static final class Builder&lt;T&gt; { private final LinkedList&lt;SwitchCase&lt;T&gt;&gt; cases = new LinkedList&lt;&gt;(); private Consumer&lt;T&gt; defaultCase; public Builder() { } public Builder(final Switch&lt;T&gt; existingSwitch) { this.cases.addAll(existingSwitch.cases); this.defaultCase = existingSwitch.defaultCase; } public Builder&lt;T&gt; when(final Predicate&lt;T&gt; predicate, final Consumer&lt;T&gt; consumer) { cases.add(new SwitchCase&lt;&gt;(predicate, consumer, false)); return this; } public Builder&lt;T&gt; breakWhen(final Predicate&lt;T&gt; predicate, final Consumer&lt;T&gt; consumer) { cases.add(new SwitchCase&lt;&gt;(predicate, consumer, true)); return this; } public Builder&lt;T&gt; defaultCase(final Consumer&lt;T&gt; consumer) { this.defaultCase = consumer; return this; } public Switch&lt;T&gt; build() { return new Switch&lt;&gt;(cases, defaultCase); } } private static class SwitchCase&lt;T&gt; { private final Predicate&lt;T&gt; predicate; private final Consumer&lt;T&gt; consumer; private final boolean shouldBreak; private SwitchCase(final Predicate&lt;T&gt; predicate, final Consumer&lt;T&gt; consumer, final boolean shouldBreak) { this.predicate = predicate; this.consumer = consumer; this.shouldBreak = shouldBreak; } private boolean evaluate(final T value) { if (predicate.test(value)) { consumer.accept(value); return true; } return false; } } private LinkedList&lt;SwitchCase&lt;T&gt;&gt; cases; private Consumer&lt;T&gt; defaultCase; private Switch(LinkedList&lt;SwitchCase&lt;T&gt;&gt; cases, Consumer&lt;T&gt; defaultCase) { this.cases = cases; this.defaultCase = defaultCase; } public void evaluate(final T value) { boolean caseExecuted = false; for (final SwitchCase&lt;T&gt; switchCase : cases) { caseExecuted = switchCase.evaluate(value); if (switchCase.shouldBreak) { break; } } if (!caseExecuted) { if (defaultCase != null) { defaultCase.accept(value); } } } } </code></pre> <h2>Tests</h2> <p>Tests use <code>String</code> as type, even though <code>String</code> is switchable, but this allows non-constant value tests.</p> <pre><code>/* SwitchTests.java * Copyright (C) 2018 Zymus * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. */ package net.zephyrion.util; import org.junit.Test; public class SwitchTests { @Test public void testSwitches() { final String mod = "Mod"; final String notMod = "Admin"; final Switch&lt;String&gt; nonBreakingNameSwitch = createNonBreakingTestSwitch(); final Switch&lt;String&gt; breakingSwitch = createBreakBeforeLastTestSwitch(); nonBreakingNameSwitch.evaluate(mod); System.out.println(); breakingSwitch.evaluate(mod); System.out.println(); nonBreakingNameSwitch.evaluate(notMod); System.out.println(); final Switch&lt;String&gt; extendedSwitch = createNonBreakingExtendedTestSwitch(nonBreakingNameSwitch); System.out.println("===== Extended Switch ====="); extendedSwitch.evaluate(mod); System.out.println(); extendedSwitch.evaluate(notMod); System.out.println(); final Switch&lt;String&gt; extendedSwitchWithoutDefault = createNonBreakingExtendedTestSwitchWithoutDefault(nonBreakingNameSwitch); System.out.println("===== Extended Switch Without Default ====="); extendedSwitchWithoutDefault.evaluate(mod); System.out.println(); extendedSwitchWithoutDefault.evaluate(notMod); System.out.println(); } private Switch&lt;String&gt; createNonBreakingTestSwitch() { final Switch.Builder&lt;String&gt; nameSwitchBuilder = new Switch.Builder&lt;&gt;(); return nameSwitchBuilder.defaultCase(this::printUnhandledName) .when(this::nameContainsUppercaseLetter, this::printUppercaseName) .when(this::nameIsMod, this::printNameIsMod) .when(this::nameContainsM, this::printNameContainsM) .build(); } private Switch&lt;String&gt; createBreakBeforeLastTestSwitch() { final Switch.Builder&lt;String&gt; nameSwitchBuilder = new Switch.Builder&lt;&gt;(); return nameSwitchBuilder.defaultCase(this::printUnhandledName) .when(this::nameContainsUppercaseLetter, this::printUppercaseName) .breakWhen(this::nameIsMod, this::printNameIsMod) .when(this::nameContainsM, this::printNameContainsM) .build(); } private Switch&lt;String&gt; createNonBreakingExtendedTestSwitch(final Switch&lt;String&gt; existingSwitch) { final Switch.Builder&lt;String&gt; nameSwitchBuilder = new Switch.Builder&lt;&gt;(existingSwitch); return nameSwitchBuilder.defaultCase(this::differentDefaultCase) .when(this::nameContainsO, this::printNameContainsO) .build(); } private Switch&lt;String&gt; createNonBreakingExtendedTestSwitchWithoutDefault(final Switch&lt;String&gt; existingSwitch) { final Switch.Builder&lt;String&gt; nameSwitchBuilder = new Switch.Builder&lt;&gt;(existingSwitch); return nameSwitchBuilder.when(this::nameContainsO, this::printNameContainsO) .build(); } private void printUnhandledName(final String name) { System.out.println("Unhandled name: " + name); } // region Uppercase Case private boolean nameContainsUppercaseLetter(final String name) { return name.chars().anyMatch(Character::isUpperCase); } private void printUppercaseName(final String name) { System.out.println(name + " contains uppercase letter"); } // endregion //region Mod case private boolean nameIsMod(final String name) { return name.equals("Mod"); } private void printNameIsMod(final String name) { System.out.println("name is Mod"); } // endregion //region M case private boolean nameContainsM(final String name) { return name.contains("M"); } private void printNameContainsM(final String name) { System.out.println("name contains M"); } // endregion // region o case private boolean nameContainsO(final String name) { return name.contains("o"); } private void printNameContainsO(final String name) { System.out.println("name contains o"); } private void differentDefaultCase(final String name) { System.out.println(name + " triggered the different default case"); } // endregion } </code></pre> <h2>Output</h2> <pre class="lang-none prettyprint-override"><code>Mod contains uppercase letter name is Mod name contains M Mod contains uppercase letter name is Mod Admin contains uppercase letter Unhandled name: Admin ===== Extended Switch ===== Mod contains uppercase letter name is Mod name contains M name contains o Admin contains uppercase letter Admin triggered the different default case ===== Extended Switch Without Default ===== Mod contains uppercase letter name is Mod name contains M name contains o Admin contains uppercase letter Unhandled name: Admin </code></pre>
[]
[ { "body": "<h1>Bugs</h1>\n\n<p>Unfortunately this doesn't work as expected</p>\n\n<p>Assuming that <code>breakWhen</code> works like <code>break</code> in a regular <code>switch</code>, then I expect this:</p>\n\n<pre><code> new Switch.Builder&lt;&gt;() //\n .breakWhen(x -&gt; x.equals(\"A\"), x -...
{ "AcceptedAnswerId": "206655", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:44:25.603", "Id": "206486", "Score": "2", "Tags": [ "java", "fluent-interface" ], "Title": "Switch-like functionality for non-switchable types in Java" }
206486
<p>So I started learning OOs and code refactoring and decided to do some project. It just some simple quiz game.</p> <p>Here are some mechanics</p> <ul> <li><p>There are 3 sets</p></li> <li><p>Each set have 8 Brands (types)</p></li> <li><p>Each brand have 10 questions</p></li> </ul> <p>So what I did was this</p> <p><strong>Set Class</strong></p> <pre><code>public class Set{ public string setName; public Brand[] brands; } </code></pre> <p><strong>Brand Class</strong></p> <pre><code>public class Brand{ public string brandName; public Question[] questions; } </code></pre> <p><strong>Question Class</strong></p> <pre><code>public class Question { public string question; public string[] choices = new string[3]; //choices for each question public string correctAnswer; //will hold the correct answer for a question public string questionID(){ // making a id for question string qID = ""; qID += question + "|"; foreach(string choice in choices){ qID += choice + "|"; } qID += correctAnswer + "|"; qID += fontSize; return qID; } } </code></pre> <p>So what I need is to create some kind of id for each question, what I did is this</p> <pre><code>public class QuestionManager : MonoBehaviour { public void saveToDB(){ int setID = 0; foreach(Set set in sets){ int brandID = 0; foreach(Brand brand in set.brands){ int questionID = 0; foreach(Question question in brand.questions){ string questionKey = "s" + setID + "|" + "b" + brandID + "|" + "q" + questionID; string questionAnswer = "value:"+ set.setName + "|" + brand.brandName + "|" + question.questionID() ; PlayerPrefs.SetString( key: questionKey, value: questionAnswer ); // save to the database questionID++; } brandID++; } setID++; } } } </code></pre> <p>I'm really curious if there are some good refactoring for this kind of loop. Also I should add that I'll be using this ids for getting the questions later.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:49:28.443", "Id": "398302", "Score": "1", "body": "Before anyone can write any review we must know what your code is doing. Currently we only know it's quiz. Could you explain how it works by [edit]ing your quesiton and adding th...
[ { "body": "<p>You ask for a refactoring of the current method. It could be:</p>\n\n<pre><code>public void saveToDB()\n{\n int setID = 0;\n foreach (Set set in sets)\n {\n int brandID = 0;\n foreach (Brand brand in set.brands)\n {\n int questionID = 0;\n foreach (Question question in brand....
{ "AcceptedAnswerId": "206503", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T08:46:46.930", "Id": "206487", "Score": "0", "Tags": [ "c#", "unity3d" ], "Title": "Generating a QuestionID Using a Nested Loop for a Quiz Game" }
206487
<p><strong>Brief:</strong></p> <p>I've create simple filter in my laravel project. I'll send parameters with ajax request.</p> <p><strong>Code:</strong></p> <pre><code>public function specialitiesAjaxLoadMore(Request $request) { $city = null; if(isset($request-&gt;city_id)) { $city = City::find($request-&gt;city_id); if($city !== null) { $city = $city-&gt;id; } } $sex = null; if((isset($request-&gt;sex) &amp;&amp; is_numeric($request-&gt;sex)) &amp;&amp; $request-&gt;sex == 1 || $request-&gt;sex == 2) { $sex = $request-&gt;sex; } $ageFrom = null; if((isset($request-&gt;ageFrom) &amp;&amp; is_numeric($request-&gt;ageFrom)) &amp;&amp; $request-&gt;ageFrom &gt; 7) { $ageFrom = $request-&gt;ageFrom; } $ageTo = null; if((isset($request-&gt;ageTo) &amp;&amp; is_numeric($request-&gt;ageTo)) &amp;&amp; $request-&gt;ageTo &gt; 7) { $ageTo = $request-&gt;ageTo; } if(isset($city)) { $candidates = Candidate::where('city_id', $city)-&gt;get(); } if(isset($sex)) { $candidates = Candidate::where('sex', $sex)-&gt;get(); } if(isset($ageFrom)) { $candidates = Candidate::where('birthday', '&lt;=', date('Y-m-d', strtotime("-$ageFrom years")))-&gt;get(); } if(isset($ageTo)) { $candidates = Candidate::where('birthday', '&gt;=', date('Y-m-d', strtotime("-$ageTo years")))-&gt;get(); } if(isset($city, $sex)) { $candidates = Candidate::where('city_id', $city)-&gt;where('sex', $sex)-&gt;get(); } if(isset($city, $sex, $ageFrom)) { $candidates = Candidate::where('city_id', $city) -&gt;where('sex', $sex) -&gt;where('birthday', '&lt;=', date('Y-m-d', strtotime("-$ageFrom years"))) -&gt;get(); } if(isset($city, $sex, $ageFrom, $ageTo) &amp;&amp; $ageTo &lt; $ageFrom) { $candidates = Candidate::where('city_id', $city) -&gt;where('sex', $sex) -&gt;where('birthday', '&lt;=', date('Y-m-d', strtotime("-$ageFrom years"))) -&gt;where('birthday', '&gt;=', date('Y-m-d', strtotime("-$ageTo years"))) -&gt;get(); } } </code></pre> <p>In my case there will be a <strong>lot of parameters</strong> from the request and if I continue to write everything in such a way as seisai then there will be a lot of <strong>combinations</strong>. So is it possible to <strong>improve or shorten</strong> my current code?</p>
[]
[ { "body": "<p><a href=\"https://laravel.com/docs/5.7/queries#where-clauses\" rel=\"nofollow noreferrer\">https://laravel.com/docs/5.7/queries#where-clauses</a></p>\n\n<pre><code>$where = [];\nif($city) {\n $where[] = ['city_id', '=', $city];\n}\nif($sex) {\n $where[] = ['sex', '=', $sex];\n}\nif($ageFrom)...
{ "AcceptedAnswerId": "206491", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T09:24:05.817", "Id": "206489", "Score": "0", "Tags": [ "performance", "php", "laravel" ], "Title": "How I can short my code when request have many parameters" }
206489
<p>I want to clean this code to be more production ready. What can be improved, added or removed?</p> <pre><code> enum Suits {Spades, Hearts, Diamonds, Clubs} class Card { public string Value { set; get;} public Suits Suit {get; set;} } class Player { public string Name { get; set; } public List&lt;Card&gt; Cards { get; set; } public int CalculatePoints() { int points = 0; int aces = 0; foreach (Card c in Cards) { if (c.Value == "A") { aces++; // points++; } else if (c.Value == "J" || c.Value == "Q" || c.Value == "K") points += 10; else points += int.Parse(c.Value); } if ((points - 21) &lt;= 10) { for (int j = 0; j &lt; aces; j++) { if (j == 0) points += 11; // Adding at least one 11 else points += 1; // the rest can only be 1s } } else { points += aces; //if we do not have a space for an 11 then lets just add 1s } return points; } } class Program { static void Main(string[] args) { Player Dealer = new Player { Name = "Dealer", Cards = new List&lt;Card&gt; { new Card{Value= "J", Suit = Suits.Spades}, new Card{Value= "9", Suit = Suits.Hearts} } }; Player Billy = new Player { Name = "Billy", Cards = new List&lt;Card&gt;{ new Card{Value="2", Suit = Suits.Spades}, new Card{Value="2", Suit = Suits.Diamonds}, new Card{Value="2", Suit = Suits.Hearts}, new Card{Value="4", Suit = Suits.Diamonds}, new Card{Value="5", Suit = Suits.Clubs} } }; Player Lemmy = new Player { Name = "Lemmy", Cards = new List&lt;Card&gt;{ new Card{Value="A", Suit = Suits.Spades}, new Card{Value="7", Suit = Suits.Hearts}, new Card{Value="A", Suit = Suits.Diamonds} } }; Player Andrew = new Player { Name = "Andrew", Cards = new List&lt;Card&gt;{ new Card{Value="K", Suit = Suits.Diamonds}, new Card{Value="4", Suit = Suits.Spades}, new Card{Value="4", Suit = Suits.Clubs} } }; Player Carla = new Player { Name = "Carla", Cards = new List&lt;Card&gt;{ new Card{Value="Q", Suit = Suits.Clubs}, new Card{Value="6", Suit = Suits.Spades}, new Card{Value="9", Suit = Suits.Diamonds} } }; Console.WriteLine("Dealer's Points = {0}", Dealer.CalculatePoints()); Console.WriteLine("=========================="); //Output the winner Console.WriteLine(String.Format("Billy's Points = {0} | {1}", Billy.CalculatePoints(), getWinner(Dealer, Billy))); Console.WriteLine(String.Format("Lemmy's Points = {0} | {1}", Lemmy.CalculatePoints(), getWinner(Dealer, Lemmy))); Console.WriteLine(String.Format("Andrew's Points = {0} | {1}", Andrew.CalculatePoints(), getWinner(Dealer, Andrew))); Console.WriteLine(String.Format("Carla's Points = {0} | {1}", Carla.CalculatePoints(), getWinner(Dealer, Carla))); Console.ReadLine(); } //Calculate the winner private static string getWinner(Player dealer, Player player) { if (player.CalculatePoints() &gt; 21) { return "Looses"; } else if (dealer.CalculatePoints() &gt; 21) { return "Wins"; } else if (player.Cards.Count == 5) { return "Wins : Has 5 cards"; } return dealer.CalculatePoints() &gt; player.CalculatePoints() ? "Looses" : "Wins"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T11:58:16.367", "Id": "398331", "Score": "0", "body": "Thanks,Can anyone assist me?" } ]
[ { "body": "<p>I'm not familiar with the rules of Black Jack so I won't comment the calculations.</p>\n\n<p>You should have an enum for faces as you have for suits:</p>\n\n<pre><code>enum Suits { Spades, Hearts, Diamonds, Clubs }\nenum Faces { Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T10:56:21.890", "Id": "206497", "Score": "2", "Tags": [ "c#", "beginner", "console", "playing-cards" ], "Title": "Self playing console Blackjack game with four players" }
206497
<p>I am trying to fight my way trough self learning Django (as this is a beast on its own) and Python (just for coding &lt;3) in combination with nginx, PostgreSQL and gunicorn - I have some limited experience with PHP.</p> <p>After a short struggle I managed to get everything up and running (enough tutorials for that around).</p> <p>Basically what I am doing right now is trying to customize the Django authentication system, specifically starting with the login part and adding a "remember me" option for the user, I got everything to work the way I like, but I am wondering if I am doing everything the 'correct' (or convenient) way? (I started with customizing the user model, so you might encounter some bits and pieces related to that.) So I could use some pointers of what I can do better or improve.</p> <p>In my project directory:</p> <p><strong>settings.py</strong></p> <pre><code>SESSION_EXPIRE_AT_BROWSER_CLOSE = True </code></pre> <p>I added the above line so that any sessions that are created are expired on browser close by default (yes, this might not always work in Chrome).</p> <p>In my APP directory for the user authentication:</p> <p><strong>forms.py</strong></p> <pre><code>from django import forms from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Username','required': True,'autofocus' : True})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password','required': True})) remember_me = forms.BooleanField(required=False) </code></pre> <p>As you can see I am using bootstrap classes to style the input fields.</p> <p><strong>view.py</strong></p> <pre><code>from django.shortcuts import render # Create your views here. from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth import login from .forms import CustomAuthenticationForm class Login(LoginView): authentication_form = CustomAuthenticationForm form_class = CustomAuthenticationForm template_name = 'login.html' def form_valid(self, form): remember_me = form.cleaned_data['remember_me'] login(self.request, form.get_user()) if remember_me: self.request.session.set_expiry(1209600) return super(LoginView, self).form_valid(form) </code></pre> <p>To make the "remember me" option work I am trying to read out the "remember_me" checkbox for the template that has been posted in the form. Based on if it's set or not, it sets the session expiry to two weeks.</p> <p>This is how my urls.py looks like in my 'users' APP:</p> <p><strong>urls.py</strong></p> <pre><code>from django.urls import path from . import views from .forms import CustomAuthenticationForm urlpatterns = [ path('login/', views.Login.as_view(), name='login') ] </code></pre> <p>The most ugliest and least django/python-fied must be my templates (e.&nbsp;g. the labels, as I tried to avoid using the full form 'generation'). I am absolutely sure this and the forms.py can be improved a lot.</p> <p>The two templates:</p> <p><strong>base.html</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"&gt; {% block head %} {% load static %} &lt;link rel="stylesheet" href="{% static '/main/css/style.css' %}" type="text/css"&gt; &lt;title&gt;My Python Website&lt;/title&gt; {% endblock %} &lt;/head&gt; &lt;body&gt; {% block body %} {% endblock %} &lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Here I load the bootstrap CSS/JS files and a custom CSS file:</p> <p><strong>login.html</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends 'base.html' %} {% block head %} {% load static %} &lt;link rel="stylesheet" href="{% static '/users/css/style.css' %}" type="text/css"&gt; &lt;title&gt;My Python Login&lt;/title&gt; {% endblock %} {% block body %} &lt;div class="container text-center"&gt; &lt;form class="form-signin" method="post" action="{% url 'login' %}"&gt; {% csrf_token %} &lt;img class="mb-4" src="{% static 'main/images/placeholder_logo.png' %}" width="114" height="100" alt=""&gt; &lt;h1 class="h3 mb-3 font-weight-normal"&gt;Please Sign in&lt;/h1&gt; &lt;label for="id_username" class="sr-only"&gt;Username&lt;/label&gt; {{ form.username }} &lt;label for="id_password" class="sr-only"&gt;Password&lt;/label&gt; {{ form.password }} &lt;div class="checkbox mb-3"&gt; &lt;label for="id_remember_me"&gt; {{ form.remember_me }} Remember me &lt;/label&gt; &lt;/div&gt; {% if form.errors %} &lt;p class="alert alert-danger" role="alert"&gt; Your username and password didn't match. Please try again. &lt;/p&gt; {% endif %} &lt;button class="btn btn-lg btn-primary btn-block" type="submit"&gt;Sign in&lt;/button&gt; &lt;p class="mt-5 mb-3 text-muted"&gt;&amp;copy; My First Python Website 2017-2018&lt;/p&gt; &lt;/form&gt; &lt;/div&gt; {% endblock %}</code></pre> </div> </div> </p> <p>So now, how does this look like? Things that confuse me at the moment if for example the CSS styling approach of the templates and the forms. As half of the class/id assigning is happening in the <strong>templates</strong> and the other half in the <strong>forms.py</strong>. How can I improve upon this and what is the general way of working or the recommended way of doing this?</p>
[]
[ { "body": "<p>In your <code>forms.py</code>, widget attr common class <code>form-control</code> added for <code>username</code>, and <code>password</code>. </p>\n\n<p>If you are confirm that all of your form class have same name like all of my field have <code>form-control</code> class then you can use it on yo...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T10:59:33.527", "Id": "206498", "Score": "3", "Tags": [ "python", "html", "django" ], "Title": "Custom login class based view" }
206498
<p>This is a simple program converting user input decimal numbers into octal ones. </p> <pre><code>#include &lt;iostream&gt; using namespace std; main() { int de,oc,y,i=1,octal; float decimal,deci,x; cout&lt;&lt;"Enter decimal no :: "; cin&gt;&gt;decimal; de=decimal; deci=decimal-de; cout&lt;&lt;"("&lt;&lt;decimal&lt;&lt;")10 = ("; while(de&gt;0) { oc=de%8; de=de/8; octal=octal+(oc*i); i=i*10; }cout&lt;&lt;octal&lt;&lt;"."; while(deci&gt;0) { x=deci*8; y=x; deci=x-y; cout&lt;&lt;y; } cout&lt;&lt;")8"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-04T16:27:23.403", "Id": "399195", "Score": "0", "body": "thanks a lot it is a correct program i needed this program its very helpful to me" } ]
[ { "body": "<p>Just, i don't understand why?</p>\n\n<p>What's wrong with (for integer):</p>\n\n<pre><code>#include &lt;iostream&gt;\nint main() {\n int input;\n std::cout &lt;&lt; \"Enter decimal number: \";\n std::cin &gt;&gt; std::dec &gt;&gt; input;\n std::cout &lt;&lt; '\\n' &lt;&lt; std::oct &lt...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T11:00:42.723", "Id": "206499", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "number-systems" ], "Title": "Converting decimal to octal" }
206499
<p>I'm making a WeatherApp. It uses the browser's location to get the GPS coordinates, then sends those to an API to get details about the location (e.g. city, country, etc.). The city is then sent to a weather API to get weather information, which is then displayed on the page - see the image below for a sample.</p> <p>But I thinks there're a lot of ways to make it less clumsy. If you have some advice, you are welcome)</p> <p>What's a better way to make "universal" widget?</p> <p>While the code functions in the snippet, there is a security restriction. It does, however, work in <a href="https://s.codepen.io/purplecandle/debug/aRXzvX/vWMRwaVGvvZr" rel="nofollow noreferrer">this codepen</a>. It should output data to widget: <a href="https://i.stack.imgur.com/YPkaz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YPkaz.jpg" alt="Widget on Codepen"></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// (1) There I get geolocation with two functions in case of success or error navigator.geolocation.getCurrentPosition(success, error); function success(position) { const locationToken = '6efc940a8a8a31'; let lat = position.coords.latitude; let lon = position.coords.longitude; let locRequest = new XMLHttpRequest(); // (2) I use LocationIq to get the City name by geolocatioan coordinates locRequest.open( 'GET', `https://eu1.locationiq.com/v1/reverse.php?key=${locationToken}&amp;lat=${lat}&amp;lon=${lon}&amp;format=json`, true ); locRequest.send(); locRequest.onreadystatechange = function() { if (this.readyState != 4) return; if (this.status != 200) { alert('Error: ' + (this.status ? this.statusText : 'request aborted')); return; } // (3) Okay, I got the city name and pass it to another function to get the weather in that city let data = JSON.parse(this.responseText); getWeather(data.address.city); } }; function error() { console.log = "Unable to retrieve your location"; }; function getWeather(location) { const weatherToken = 'bce14d2969489e270e45aaf51514f3a8'; let weatherLocation = location; let weatherRequest = new XMLHttpRequest(); // (4) I send a request to OpenWeather using the City name weatherRequest.open( 'GET', `https://api.openweathermap.org/data/2.5/weather?q=${weatherLocation}&amp;units=metric&amp;appid=${weatherToken}`, true ); weatherRequest.send(); weatherRequest.onreadystatechange = function() { if (this.readyState != 4) return; if (this.status != 200) { alert('Error: ' + (this.status ? this.statusText : 'request aborted')); return; } let weather = JSON.parse(this.responseText); // (5) and, finally, I pass all weather data to my widget weatherWidget(weather); } } function weatherWidget(data) { let allData = data; let currentLocation = document.querySelector('.js-currentLocation'); let temp = document.querySelector('.js-temp'); let weatherType = document.querySelector('.js-weatherType'); let weatherPreview = document.querySelector('.js-widgetPrev'); // (6) Here I pass necessary data to my Widget currentLocation.innerHTML = allData.name; temp.innerHTML = `${allData.main.temp}&amp;deg;C`; weatherType.innerHTML = allData.weather[0].main; let weatherPrevClass = allData.weather[0].main.toLowerCase(); weatherPreview.classList.add(weatherPrevClass); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>:root { --widget-size: 400px; --widget-padding: 50px; --widget-border-rad: 40px; } html, body { height: 100%; } body { // background-color: #f9f8f8; background-image: linear-gradient(to right bottom, #89f6df, #8ef9cb, #9dfab4, #b4f999, #d0f67f); display: flex; align-items: center; justify-content: center; font-family: 'Open Sans', sans-serif; } .widget { position: relative; width: var(--widget-size); height: var(--widget-size); color: #fff; border-radius: var(--widget-border-rad); background-color: rgba(255, 255, 255, .7); box-shadow: 0 19px 38px rgba(0, 0, 0, 0.20), 0 15px 12px rgba(0, 0, 0, 0.15); background-image: linear-gradient(to left top, #ffc94d, #ffb93a, #ffa729, #ff9518, #ff8208); &amp;__info { position: absolute; bottom: var(--widget-padding); left: var(--widget-padding); } &amp;__temp { font-size: 6em; line-height: 1em; } &amp;__desc { position: absolute; top: var(--widget-padding); left: var(--widget-padding); font-size: 2.5em; font-weight: 700; } &amp;__currentLocation { // text-align: center; font-size: 2em; } &amp;__prev { position: absolute; top: var(--widget-padding); right: var(--widget-padding); } } // ---&gt; Sunny .sun { width: 100px; height: 100px; background-color: #fdde35; border-radius: 50%; position: relative; } .sun::after { content: ''; display: block; position: absolute; width: inherit; height: inherit; border-radius: inherit; background-color: inherit; animation: sunshines 2s infinite; } @keyframes sunshines { 0% { transform: scale(1); opacity: 0.6; } 100% { transform: scale(1.5); opacity: 0; } } // ---&gt; Cloudy .clouds { margin-top: 40px; position: relative; height: 60px; width: 140px; background-color: #fff; border-radius: 30px; animation: clouds 2.5s infinite ease-in-out; &amp;::after { content: ''; display: block; position: absolute; width: 60px; height: 60px; background-color: inherit; border-radius: 50%; left: 25px; top: -35px; } &amp;::before { content: ''; display: block; position: absolute; width: 50px; height: 50px; background-color: inherit; border-radius: 50%; left: 70px; top: -25px; } } @keyframes clouds { 50% { transform: translateY(7px); } 100% { transform: translateY(0px); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="widget"&gt; &lt;div class="widget__desc js-weatherType"&gt;&lt;/div&gt; &lt;div class="widget__info"&gt; &lt;div class="widget__temp js-temp"&gt;&lt;/div&gt; &lt;div class="widget__currentLocation js-currentLocation"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="widget__prev"&gt; &lt;div class="js-widgetPrev"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T16:27:37.937", "Id": "398374", "Score": "0", "body": "You could add a description of the output, perhaps with a sample screenshot. I tried running the codepen but see the Error message, since the query to `https://api.openweathermap...
[ { "body": "<p>There appears to be a flaw with the function <code>error</code>:</p>\n\n<blockquote>\n<pre><code>function error() {\n console.log = \"Unable to retrieve your location\";\n};\n</code></pre>\n</blockquote>\n\n<p>That will <strong>re-assign</strong> that string literal to <code>console.log</code>....
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T11:40:16.867", "Id": "206506", "Score": "1", "Tags": [ "javascript", "beginner", "api", "ajax" ], "Title": "WeatherApp, working with APIs" }
206506
<p>Starting from React 16.3 there are some new lifecycle methods introduced. One of them is the <code>static getDerivedStateFromProps(props,state)</code> method. This method essentially synchronizes properties and state. </p> <p>The <code>props</code> and <code>state</code> of a react component aren't always a one-on-one match. But for simple components often a couple of props do match exactly on the state.</p> <p>It's not strictly necessary to have this <code>getDerivedStateFromProps(...)</code> method actually. If your component doesn't really have an internal state, then there is no need to worry about it.</p> <p>Anyway, in a case where there is an exact match of <code>props</code> and <code>state</code> I am trying to find the most elegant way to write this code.</p> <p>The following is rather verbose:</p> <pre><code>static getDerivedStateFromProps(props, state) { // these 3 properties can change over time. const activeBaseNode = props.activeBaseNode; const filterOID = props.filterOID; const quickFilterRequest = props.quickFilterRequest; // compare them to the state if ((state.filterOID !== filterOID) || (state.activeBaseNode !== activeBaseNode) || (state.quickFilterRequest !== quickFilterRequest)) { // updates the state return ({ activeBaseNode, filterOID, quickFilterRequest }); } // no changes --&gt; no updates return null; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T15:42:33.313", "Id": "398367", "Score": "1", "body": "Why do you need to clone them into state? You would be able to use `this.props` directly inside your component?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate"...
[ { "body": "<p>Here is one possibility:</p>\n\n<pre><code>static getDerivedStateFromProps(props, state) {\n const { activeBaseNode, filterOID, quickFilterRequest } = props;\n\n let updateState = false;\n ['activeBaseNode', 'filterOID', 'quickFilterRequest'].forEach(item =&gt; {\n if(state[item] !== props[i...
{ "AcceptedAnswerId": "206548", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T12:49:03.367", "Id": "206508", "Score": "2", "Tags": [ "javascript", "react.js", "state" ], "Title": "getDerivedStateFromProps" }
206508
<p>this code is counting the average protein length (number of amino acids) across the proteome of some microbes.</p> <p>As it stands the code takes a very very long time to run, I think I'm being very inefficient somewhere but not 100% sure where.</p> <p>The way I run the code is using a bash-loop (using find for each example of particular file type, like *.faa) like this:</p> <pre><code>for FAA in $(find . -name "*.faa") do python proteinlengthgen.py $FAA done </code></pre> <p><strong>My code:</strong></p> <pre><code>from Bio import SeqIO import sys from collections import Counter def species_name_function(infile): for record in SeqIO.parse(infile, "fasta"): speciesname = record.description.split('[', 1)[1].split(']', 1)[0] return speciesname if __name__ == '__main__': frequency = [] infile = sys.argv[1] avgproteinlength = 0 totalproteinlength = 0 fastacounter = 0 for fasta in SeqIO.parse(open(infile), "fasta"): dna = str(fasta.seq) freq = Counter(dna) fastacounter = fastacounter + 1 frequency.append(freq) species_name = species_name_function(infile) genomesize = freq['G'] + freq['A'] + freq['L'] + freq['M'] + freq['F'] + freq['W'] + freq['K'] + freq['Q'] + freq['E'] + freq['S'] + freq['P'] + freq['V'] + freq['I'] + freq['C'] + freq['Y'] + freq['H'] + freq['R'] + freq['N'] + freq['D'] + freq['T'] listofbases = ['G', 'A', 'L', 'M', 'F', 'W', 'K', 'Q', 'E', 'S', 'P', 'V', 'I', 'C', 'Y', 'H', 'R', 'N', 'D', 'T'] totalproteinlength = genomesize + totalproteinlength avgproteinlength = totalproteinlength / fastacounter towrite = str(avgproteinlength) + '\t' + species_name + '\t' + '\n' with open("proteinlength.csv", "a") as myfile: myfile.write(towrite) </code></pre> <p><strong>Example of a subset of input file</strong> (I cannot use a whole one as they are very big):</p> <pre><code>&gt;WP_013179448.1 DNA-directed RNA polymerase [Methanococcus voltae] MYKILTIEDTIRIPPKMFGNPLKDNVQKVLMEKYEGILDKDLGFILAIEDIDQISEGDIIYGDGAAYHDTTFNILTYEPE VHEMIEGEIVDIVEFGAFIRLGPLDGLIHISQVMDDYVAFDPQREAIIGKETGKVLEKGDKVRARIVAVSLKEDRKRGSK IALTMRQPALGKLEWLEDEKLETMENAEF &gt;WP_013179449.1 DNA-directed RNA polymerase subunit E'' [Methanococcus voltae] MARKGLKACTKCNYITHDDFCPICQHETSENIRGLLIILDPVNSEVAKIAQKDIKGKYALSVK &gt;WP_013179451.1 30S ribosomal protein S24e [Methanococcus voltae] MDIKVVSEKNNPLLGRKEVKFALKYEGATPAVKDVKMKLVAILNANKELLVIDELAQEFGKMEANGYAKIYESEEAMNSI EKKSIIEKNKIVEEAEEAQE &gt;WP_013179452.1 30S ribosomal protein S27ae [Methanococcus voltae] MAQKTKKSDYYKIDGDKVERLKKSCPKCGEGVFMAEHLNRFACGKCGYMEYKKNEKAEKEE &gt;WP_013179453.1 hypothetical protein [Methanococcus voltae] MNELNELKNPDKIDGKNNNTKNNNNNNNKDSNTENSITEIIKADNETQDNLSDLCVLEDIKTLKSKYKVYKTSKYLTKKD INNIIEKDYDEIIMPQSIYKLLNEKNKSSMEKLRLCGIIVKTTDNVGRPKKITKYDKDKIKELLVDGKSVRKTAEIMDMK KTTVWENIKDCMNEIKIEKFRKMIYEYKELLIMQERYGSYVESLFLELDIYINNEDMENALEILNKIIIYVKSEDKKD &gt;WP_013179454.1 integrase [Methanococcus voltae] MKNKRINNNQKSKWETMRTDVINTQRNQNINSKNKQYRVKKHYCKEWLTKEELKVFIETIEYSEHKLFFKMLYGMALRVS ELLKIKVQDLQLKEGVCKLWDTKTDYFQVCLIPDWLINDIKEYIALKSLDSSQELFKFNNRKYVWELAKKYSKMAELDKD ISTHTFRRSRALHLLNDGVPLEKVSKYLRHKSIGTTMSYIRITVVDLKQELDKIDDWYEL &gt;WP_013179455.1 hypothetical protein [Methanococcus voltae] MNTQNAIKKTLKTSKVNKNISNVIIGYSAILLDTYSNNKNLLLVKYDKLFKGFLNSSSITEKQYNKLYDTVLNSLF &gt;WP_013179456.1 hypothetical protein [Methanococcus voltae] MVVKLVKISNGGYVSSLELKRINDIILSQLTNEFTIKDIVNMYSNKYDDCNNNAIAQKTRRLLNNHIESGVFTVRNALKN KKIYKFKDVFVPASAGDTNTSLLFYSTSMKNSNHIEKQKKNNNKYNTNVNKPTITPDQIRVMAGIVNNPQIKSLKKERFK SILHLNCKHMLNEEDRTELLENFKEYIIKASSQNLVLERTRYHKNKPKYITFPYLTRFTNSKQLKRQLAQYNCIFEQKAI KYNRGVHLTLTTDPKLFRNIYEANKHFSKAFNRFMSFLSKRNKDVNGKSRRPVYLAAYEYTKSGLCHAHILIFGKKYLLD QRVITQEWSRCGQGQIAHIYSIRRDGINWIYGRARPEEIQTGEYKNANEYLKKYLVKSLYSELDGSMYWAMNKRFFTFSK SLKPAMMKRPKPEKYYKFVGIWTDEEFTDEINQAFKTGIPYDEIKKIHWKNLNNGLSCG &gt;WP_013179457.1 hypothetical protein [Methanococcus voltae] MVRGRYPVFSGFKKFNKINLGKEKRNEGVYKYYNQDKTLLYVGVSNEVKLRLLSAYYGRSDYAVLENKKKLRQNIAYYKV KYCGLDQARKIEHRIKKQCKYNLN </code></pre> <p><strong>Output of code:</strong></p> <pre><code>302.7408088235294 Methanococcus voltae </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T16:59:12.660", "Id": "398378", "Score": "0", "body": "So, how long is a \"very very long time\"? Multiple days per file? Minutes? Seconds, but you have a million files?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDa...
[ { "body": "<p>In Python there is no need to initialize variables before using them. So e.g. <code>avgproteinlength = 0</code> is not needed.</p>\n\n<p>Python also has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommend using <code>...
{ "AcceptedAnswerId": "206556", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T15:58:54.740", "Id": "206516", "Score": "2", "Tags": [ "python", "python-3.x", "time-limit-exceeded", "bioinformatics" ], "Title": "Counting average protein length from a proteome fasta file" }
206516
<p>I really think there's a better way to do this, but I can't seem to find it. Can you please point me in the right direction?</p> <pre><code>import colorama import os from enum import Enum def clearscreen(): # Clear the screen os.system('cls' if os.name=='nt' else 'clear') class Color(Enum): """ An Enum for representing escape sequences, that color the terminal, even in Windows, with colorama. """ NATIVE = "\033[m" BLACK = "\033[0;30m" BLUE = "\033[0;34m" GREEN = "\033[0;32m" CYAN = "\033[0;36m" RED = "\033[0;31m" PURPLE = "\033[0;35m" BROWN = "\033[0;33m" GRAY = "\033[0;37m" DARK_GRAY = "\033[1;30m" LIGHT_BLUE = "\033[1;34m" LIGHT_GREEN = "\033[1;32m" LIGHT_CYAN = "\033[1;36m" LIGHT_RED = "\033[1;31m" LIGHT_PURPLE = "\033[1;35m" YELLOW = "\033[1;33m" WHITE = "\033[1;37m" class Dialoge(): """ Basic Dialoge class, with various methods. """ def __init__(self): colorama.init() def important(self, wrap) # Print an "I---I"-like line based on the length of the text print("I", end="") for dash in range(wrap): print("-", end="") print("I", end="") print() def tprint(self, message, color, char, rank): """ Print Dialoge to the terminal, with a lot more options """ total = "" if rank == 0: if char == "NO_CHAR": if color != "DEFAULT": print(f"{color}{message}{Color.NATIVE.value}") else: print(f"{message}") else: if color != "DEFAULT": print(f"{color}[{char}]:{Color.NATIVE.value} {message}") else: print(f"[{char}]: {message}") else: if char == "NO_CHAR": if color != "DEFAULT": if rank == 1: print(f"{color}! - {message} - !{Color.NATIVE.value}") elif rank == 2: total = f"!! -- {message} -- !!" print(color, end="") self.important(len(f"!! -- {message} -- !!") - 2) # When evaluating the length of a string, rest -2 for the "/r/n". print(total) self.important(len(f"!! -- {message} -- !!") - 2) print(Color.NATIVE.value, end="") elif rank == 3: clearscreen() print(color, end="") total = f"!!! --- {message} --- !!!" self.important(len(f"!!! --- {message} --- !!!") - 2) print(total) self.important(len(f"!!! --- {message} --- !!!") - 2) print(Color.NATIVE.value, end="") else: if rank == 1: print(f"! - {message} - !") elif rank == 2: total = f"!! -- {message} -- !!" self.important(len(total) - 2) print(total) self.important(len(total) - 2) elif rank == 3: clearscreen() total = f"!!! --- {message} --- !!!" self.important(len(total) - 2) print(total) self.important(len(total) - 2) else: if color != "DEFAULT": if rank == 1: print(f"! - {color}[{char}]:{Color.NATIVE.value} {message} - !") elif rank == 2: total = f"!! -- {color}[{char}]:{Color.NATIVE.value} {message} -- !!" self.important(len(f"!! -- [{char}]: {message} -- !!") - 2) print(total) self.important(len(f"!! -- [{char}]: {message} -- !!") - 2) elif rank == 3: clearscreen() total = f"!!! --- {color}[{char}]:{Color.NATIVE.value} {message} --- !!!" self.important(len(f"!!! --- [{char}]: {message} --- !!!") - 2) print(total) self.important(len(f"!!! --- [{char}]: {message} --- !!!") - 2) else: if rank == 1: print(f"! - [{char}]: {message} - !") elif rank == 2: total = f"!! -- [{char}]: {message} -- !!" self.important(len(total) - 2) print(total) self.important(len(total) - 2) elif rank == 3: clearscreen() total = f"!!! --- [{char}]: {message} --- !!!" self.important(len(total) - 2) print(total) self.important(len(total) - 2) </code></pre>
[]
[ { "body": "<p>Your color code is not portable. Instead, try using something like the <a href=\"https://pypi.org/project/termcolor/\" rel=\"nofollow noreferrer\"><code>termcolor</code> package</a> which handles the complexity of colors for you. It seems like you've imported an initialized <code>colorama</code>, ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T16:42:27.950", "Id": "206517", "Score": "2", "Tags": [ "python", "beginner", "console" ], "Title": "Text printing for a text adventure game, with color and other stuff (Python)" }
206517
<p>I like python's <a href="https://docs.python.org/2/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a> and I was missing it in C#. It's a very convenient API so I thought I create my own utility that does something similar. </p> <p>The original API uses tuples as return values and slightly different names. I adjusted them to match C# conventions. Instead of returning a tuple which would be difficult to override/mock in a test I used an interface. Also the method signature would be very long and incovenient.</p> <p>It works with a single loop that for each directory creates a <code>DirectoryTreeNode</code>s that in turn can enumerate directories and files for that directory. It can also be turned into a tuple which an extension makes possible. I used a <code>Queue</code> and not a <code>Stack</code> because the latter would change the order to descending per directory. There is a very simple exception handling that passes any exception to the caller and let's it decide how to handle it. Alternatively the <code>WalkSilently</code> extension ignores them.</p> <p>I'm going to use it primarily for searching for directories and/or files and replace an older API.</p> <p>For now, it doesn't have to behave exactly like the python's API does; just the basic stuff. I don't know what to think of symbolic links yet.</p> <pre><code>public interface IDirectoryTree { [NotNull, ItemNotNull] IEnumerable&lt;IDirectoryTreeNode&gt; Walk([NotNull] string path, [NotNull] Action&lt;Exception&gt; onException); } public class DirectoryTree : IDirectoryTree { public IEnumerable&lt;IDirectoryTreeNode&gt; Walk(string path, Action&lt;Exception&gt; onException) { if (path == null) throw new ArgumentNullException(nameof(path)); if (onException == null) throw new ArgumentNullException(nameof(onException)); var nodes = new Queue&lt;DirectoryTreeNode&gt; { new DirectoryTreeNode(path) }; while (nodes.Any()) { var current = nodes.Dequeue(); yield return current; try { foreach (var directory in current.DirectoryNames) { nodes.Enqueue(new DirectoryTreeNode(Path.Combine(current.DirectoryName, directory))); } } catch (Exception inner) { onException(inner); } } } } [PublicAPI] public interface IDirectoryTreeNode { [NotNull] string DirectoryName { get; } [NotNull, ItemNotNull] IEnumerable&lt;string&gt; DirectoryNames { get; } [NotNull, ItemNotNull] IEnumerable&lt;string&gt; FileNames { get; } } internal class DirectoryTreeNode : IDirectoryTreeNode { internal DirectoryTreeNode(string path) { DirectoryName = path; } public string DirectoryName { get; } public IEnumerable&lt;string&gt; DirectoryNames =&gt; Directory.EnumerateDirectories(DirectoryName).Select(Path.GetFileName); public IEnumerable&lt;string&gt; FileNames =&gt; Directory.EnumerateFiles(DirectoryName).Select(Path.GetFileName); } </code></pre> <p>Additional functionality like turning a node into a tuple or checking for the existance of it is provided by extensions:</p> <pre><code>public static class DirectoryTreeNodeExtensions { public static void Deconstruct( [CanBeNull] this IDirectoryTreeNode directoryTreeNode, [CanBeNull] out string directoryName, [CanBeNull] out IEnumerable&lt;string&gt; directoryNames, [CanBeNull] out IEnumerable&lt;string&gt; fileNames) { directoryName = directoryTreeNode?.DirectoryName; directoryNames = directoryTreeNode?.DirectoryNames; fileNames = directoryTreeNode?.FileNames; } public static bool Exists( [CanBeNull] this IDirectoryTreeNode directoryTreeNode) { // Empty string does not exist and it'll return false. return Directory.Exists(directoryTreeNode?.DirectoryName ?? string.Empty); } } </code></pre> <p>In case you are wondering how the <code>Queue</code> initialzer works, I have a helper extension for it:</p> <pre><code>public static class QueueExtensions { public static void Add&lt;T&gt;(this Queue&lt;T&gt; queue, T item) { queue.Enqueue(item); } } </code></pre> <hr> <h3>Example 1 - Basic usage</h3> <p>The usage is very easy. Create or inject the <code>DirectoryTree</code> and call <code>Walk</code> or <code>WalkSilently</code>:</p> <p>Used directly:</p> <pre><code>var directoryTree = new DirectoryTree(); directoryTree .WalkSilently(@"c:\temp") .Where(n =&gt; !n.DirectoryName.Contains(".git")) .Take(100) .Select(node =&gt; node.DirectoryName) .Dump(); </code></pre> <p>or with a loop:</p> <pre><code>foreach (var (dirpath, dirnames, filenames) in directoryTree.WalkSilently(@"c:\temp").Where(n =&gt; !n.DirectoryName.Contains(".git")).Take(10)) { filenames.Dump(); } </code></pre> <hr> <h3>Filtering</h3> <p>I've added a couple of extensions for filtering the results. They work by creating a <code>DirectoryTreeNodeFilter</code> that contains the linq expression selecting or skipping files:</p> <pre><code>internal class DirectoryTreeNodeFilter : IDirectoryTreeNode { internal DirectoryTreeNodeFilter(string path, IEnumerable&lt;string&gt; directoryNames, IEnumerable&lt;string&gt; fileNames) { DirectoryName = path; DirectoryNames = directoryNames; FileNames = fileNames; } public string DirectoryName { get; } public IEnumerable&lt;string&gt; DirectoryNames { get; } public IEnumerable&lt;string&gt; FileNames { get; } } </code></pre> <p>and here are the extensions (there's also the <code>WalkSilently</code> method):</p> <pre><code>public static class DirectoryTreeExtensions { [NotNull, ItemNotNull] public static IEnumerable&lt;IDirectoryTreeNode&gt; WalkSilently([NotNull] this IDirectoryTree directoryTree, [NotNull] string path) { if (directoryTree == null) throw new ArgumentNullException(nameof(directoryTree)); if (path == null) throw new ArgumentNullException(nameof(path)); return directoryTree.Walk(path, _ =&gt; { }); } [NotNull, ItemNotNull] public static IEnumerable&lt;IDirectoryTreeNode&gt; SkipDirectories([NotNull] this IEnumerable&lt;IDirectoryTreeNode&gt; nodes, [NotNull][RegexPattern] string directoryNamePattern) { if (nodes == null) throw new ArgumentNullException(nameof(nodes)); if (directoryNamePattern == null) throw new ArgumentNullException(nameof(directoryNamePattern)); return from node in nodes where !node.DirectoryName.Matches(directoryNamePattern) select new DirectoryTreeNodeFilter ( node.DirectoryName, from dirname in node.DirectoryNames where !dirname.Matches(directoryNamePattern) select dirname, node.FileNames ); } [NotNull, ItemNotNull] public static IEnumerable&lt;IDirectoryTreeNode&gt; SkipFiles([NotNull] this IEnumerable&lt;IDirectoryTreeNode&gt; nodes, [NotNull][RegexPattern] string fileNamePattern) { if (nodes == null) throw new ArgumentNullException(nameof(nodes)); if (fileNamePattern == null) throw new ArgumentNullException(nameof(fileNamePattern)); return from node in nodes select new DirectoryTreeNodeFilter ( node.DirectoryName, node.DirectoryNames, from fileName in node.FileNames where !fileName.Matches(fileNamePattern) select fileName ); } [NotNull, ItemNotNull] public static IEnumerable&lt;IDirectoryTreeNode&gt; WhereDirectories([NotNull] this IEnumerable&lt;IDirectoryTreeNode&gt; nodes, [NotNull][RegexPattern] string directoryNamePattern) { if (nodes == null) throw new ArgumentNullException(nameof(nodes)); if (directoryNamePattern == null) throw new ArgumentNullException(nameof(directoryNamePattern)); return from node in nodes where node.DirectoryName.Matches(directoryNamePattern) select new DirectoryTreeNodeFilter ( node.DirectoryName, from dirname in node.DirectoryNames where dirname.Matches(directoryNamePattern) select dirname, node.FileNames ); } [NotNull, ItemNotNull] public static IEnumerable&lt;IDirectoryTreeNode&gt; WhereFiles([NotNull] this IEnumerable&lt;IDirectoryTreeNode&gt; nodes, [NotNull][RegexPattern] string fileNamePattern) { if (nodes == null) throw new ArgumentNullException(nameof(nodes)); if (fileNamePattern == null) throw new ArgumentNullException(nameof(fileNamePattern)); return from node in nodes select new DirectoryTreeNodeFilter ( node.DirectoryName, node.DirectoryNames, from fileName in node.FileNames where fileName.Matches(fileNamePattern) select fileName ); } private static bool Matches(this string name, [RegexPattern] string pattern) { return Regex.IsMatch(name, pattern, RegexOptions.IgnoreCase); } } </code></pre> <h3>Example 2 - Extensions</h3> <p>The extensions can be chained very easily to find what we need:</p> <pre><code>var directoryTree = new DirectoryTree(); directoryTree .WalkSilently(@"c:\temp") .SkipDirectories("\\.git") //.SkipFiles("\\.(cs|dll)$") .WhereDirectories("Project") .WhereFiles("\\.cs$") .Dump(); </code></pre> <hr> <p>There is very little magic here but maybe still room for improvements?</p>
[]
[ { "body": "<p>Your code is clean, straightforward, and easy to follow. There is very little to comment on here.</p>\n\n<p>1) You should consider using braces always. You don't have to, but they will save you a bug at some point (or you'll have to fix someone else's bug introduced into your code).</p>\n\n<p>2) I...
{ "AcceptedAnswerId": "207496", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T17:07:23.373", "Id": "206519", "Score": "6", "Tags": [ "c#", "file-system", "iterator" ], "Title": "Walking directory tree like python does" }
206519
<p>I need to run this script to update the value of 3 columns based on certain conditions. Right now, this is what I have:</p> <pre><code>UPDATE dbo.Roles SET DisplayName = Name WHERE DisplayName LIKE ''; UPDATE dbo.Roles SET Name = CONCAT(Tenant, '_', DisplayName) WHERE Name NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%'); UPDATE dbo.Roles SET NormalizedName = CONCAT(Tenant, '_', UPPER(DisplayName)) WHERE NormalizedName NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%'); </code></pre> <p>I'm doing this with 3 separate update statements. I can't help but think there's probably a better way, but maybe I'm overthinking. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T10:08:04.140", "Id": "398460", "Score": "1", "body": "I think there is nothing wrong with this code and you should keep it as it is. See my comment at Sam's answer below." } ]
[ { "body": "<p>I haven't tested this but you should be able to use <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\"><code>CASE</code></a> statements to conditionally update column values, with fallback values of the existi...
{ "AcceptedAnswerId": "206534", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T20:20:33.927", "Id": "206529", "Score": "0", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Updating 3 columns conditionally on a database table" }
206529
<p>I have a class with some properties. In the class I have a method that is "collecting" all the properties in a specific instance of the class to a dictionary, with the properties name being the dictionary key and the properties value being the dictionary value. Later in the class I have a method where I read text from a file into a string. This textfile includes the properties name with a template value. And in my method I want to replace the template value with the actual value that the properties of the instance contains. For this I have a struct that contains a method that is using LINQ to find a specific property and store that value into another dictionary. This dictionary will then contain the values that the template values in the file will be replaced with. </p> <p>The thing is that the method in my struct is using a lot of LINQ queries just stacked one after another. I found it to be badly written code to just reuse hardcoded lines like this and I would like to find a way to "automate" the method a little bit more.</p> <p>To show you more precisely what I mean here is my code:</p> <p>First the class:</p> <pre><code>public class Files { //All the properties in the class: public string Type { get; set; } public string FileName { get; set; } public string InternalName { get; set; } public string DdsName { get; set; } public string ColorName{ get; set; } public string FlashName{ get; set; } public string HexName{ get; set; } public string Number{ get; set; } public string TxtName { get; set; } public string Price { get; set; } public string Unlock { get; set; } public string Stock { get; set; } public string Base { get; set; } public string BaseLocked { get; set; } public string R_base { get; set; } public string B_base { get; set; } public string G_base { get; set; } public string brush { get; set; } public string Mask { get; set; } public string R_brush_color { get; set; } public string G_brush_color { get; set; } public string B_brush_color { get; set; } public string G_brush_locked { get; set; } public string B_brush_locked { get; set; } public string DdsDestpath { get; set; } public string DdsSourcepath { get; set; } //Method in the class that is collecting all the properties Note that //this method //and the CreateDefaultPart() method is in a class while the //DictionaryReplacements() is in a struct. //Collects all properties in the class and adds them to a dictionary public dynamic DictionaryOfProperties() { var dictionary = new Dictionary&lt;string, string&gt;(); var properties = typeof(Files).GetProperties(); for (int i = 0; i &lt; properties.Length; i++) dictionary.Add(properties[i] .Name.ToString(), properties[i] .GetValue(this, null)?.ToString()); return dictionary; } //Here is the method that is using the DictionaryReplacements method. public virtual void CreateDefaultPart() { var propInfo = DictionaryOfProperties(); //This method is getting all the current objects properties and returns a dictionary with the properties names and values var replacements = new Replacements(propInfo); //The struct that has the DictionaryReplacements() method string destPath = Path.Combine(@"C:\PathToDest", FileName); string sourcePath = Path.Combine(@"C:\PathToTemplateFile", "files", "cars", "main_part.txt"); string text = File.ReadAllText(sourcePath); Regex regex = new Regex(string.Join("|", replacements.DictionaryReplacements().Keys.Select(x =&gt; Regex.Escape(x)))); string replaced = regex.Replace(text, m =&gt; replacements.DictionaryReplacements()[m.Value]); File.WriteAllText(destPath, replaced); } } </code></pre> <p>And here is the struct:</p> <pre><code> struct Replacements { #region Fields //Private field Dictionary&lt;string, string&gt; properties; #endregion #region Constructor/Destructor //Constructor /// &lt;summary&gt; /// Creates a instance of the struct /// &lt;/summary&gt; public Replacements(Dictionary&lt;string, string&gt; properties) { this.properties = properties; } #endregion /// &lt;summary&gt; /// Returns a dictionary with keys from a template file that will be replaced with the properties in the baseFile class /// &lt;/summary&gt; /// &lt;param name="properties"&gt;Dictionary with all properties from base class&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public Dictionary&lt;string, string&gt; DictionaryReplacements() { string internalName = properties.Where(name =&gt; name.Key == "InternalName").Select(name =&gt; name.Value).FirstOrDefault(); string stock = properties.Where(name =&gt; name.Key == "Stock").Select(name =&gt; name.Value).FirstOrDefault(); string brush = properties.Where(name =&gt; name.Key == "Brush").Select(name =&gt; name.Value).FirstOrDefault(); string mask = properties.Where(name =&gt; name.Key == "Mask").Select(name =&gt; name.Value).FirstOrDefault(); string r_brush_color = properties.Where(name =&gt; name.Key == "R_brush_color").Select(name =&gt; name.Value).FirstOrDefault(); string g_brush_color = properties.Where(name =&gt; name.Key == "G_brush_color").Select(name =&gt; name.Value).FirstOrDefault(); string b_brush_color = properties.Where(name =&gt; name.Key == "B_brush_color").Select(name =&gt; name.Value).FirstOrDefault(); string base_b = properties.Where(name =&gt; name.Key == "Base").Select(name =&gt; name.Value).FirstOrDefault(); string r_brush_locked = properties.Where(name =&gt; name.Key == "R_brush_locked").Select(name =&gt; name.Value).FirstOrDefault(); string g_brush_locked = properties.Where(name =&gt; name.Key == "G_brush_locked").Select(name =&gt; name.Value).FirstOrDefault(); string b_brush_locked = properties.Where(name =&gt; name.Key == "B_brush_locked").Select(name =&gt; name.Value).FirstOrDefault(); string baseLocked = properties.Where(name =&gt; name.Key == "BaseLocked").Select(name =&gt; name.Value).FirstOrDefault(); var DictionaryMaskReplacements = new Dictionary&lt;string, string&gt;() { {"[internalName]", internalName }, {"[stock]", stock }, {"[brush]", brush }, {"[mask_temp]", mask }, {"[red_brush_color]", r_brush_color }, {"[green_brush_color]", g_brush_color }, {"[blue_brush_color]", b_brush_color }, {"[base]", base_b }, {"[red_brush_locked]", r_brush_locked }, {"[green_brush_locked]", g_brush_locked }, {"[blue_brush_locked]", b_brush_locked }, {"[base_locked]", baseLocked } }; return DictionaryMaskReplacements; } } </code></pre> <p>I have an awful lot of hardcoded LINQ queries stacked one after another in the <code>DictionaryReplacements()</code> method that you can see in the struct and I would really want to reduce my queries because it does not feel very productive and it feels like it is badly written code when you repeat the same code over and over like in this example. I would really like it if anyone could point me to a solution where I do not need so many queries. There must be some way I can "automate" the code, perhaps with loops?.</p> <p>properties that you see in the DictionaryReplacements() method is the dictionary that holds the return results from the listOfProperties() method</p> <p>Example of the text file:</p> <pre><code>{ _internalname: [internalName] _stock: [stock] _mask_temp: [mask_temp] _red_brush_color : [red_brush_color] etc... } </code></pre> <p>The name in the brackets is the "template value" that will be replaced with the actual values</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T20:29:08.773", "Id": "398404", "Score": "1", "body": "This isn't any better than your last question :-\\" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T10:20:31.730", "Id": "398464", "Score":...
[ { "body": "<p>So your actual goal is to substitute placeholders in a file, based on property values. The code you have shown is a lot more complicated than it needs to be.</p>\n\n<p>First, to address your immediate question:</p>\n\n<ul>\n<li>In <code>DictionaryReplacements</code>, <code>properties</code> is a d...
{ "AcceptedAnswerId": "206567", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T20:26:39.943", "Id": "206530", "Score": "-2", "Tags": [ "c#", "linq", "hash-map", "properties" ], "Title": "Method to populate a dictionary from properties" }
206530
<p>I've been reading Bjarne's Principles in Programming and was given some code to demonstrate the usage of vectors and how we can return specific values for certain functionality such as mean and median. However, in the chapter I noticed that the code he provided was purposely made so that it doesn't always calculate the median correctly which was correct, he had purposely made it so we had to go back and alter the code as follows:</p> <blockquote> <pre><code>#include "../../std_lib_facilities.h" int main() { vector&lt;double&gt; temps; for (double temp; cin &gt;&gt; temp;) temps.push_back(temp); sort(temps); cout &lt;&lt; "Median temperature: " &lt;&lt; temps[temps.size() / 2] &lt;&lt; '\n'; } </code></pre> </blockquote> <p>However, when asked in a question format it states: </p> <blockquote> <p>If we define the median of a sequence as “a number so that exactly as many elements come before it in the sequence as come after it,” fix the program in 4.6.3 so that it always prints out a median. Hint: A median need not be an element of a sequence.</p> </blockquote> <p>I assumed he meant that we want equal values on both sides of our median as the previous algorithm only divides the vector size by 2 and returns, if odd the middle index + 1, therefore I'm assuming that he wanted the exact median value of the range rather than a specific element within the array? Regardless, the code I had created follows:</p> <pre><code>//Program to compute the median of a temperature vector #include "../../std_lib_facilities.h" int main() { //Define variables and Read in values double median_value; vector&lt;double&gt; temps; for (double temp; cin &gt;&gt; temp;) temps.push_back(temp); //Compute Median Temperatures sort(temps); if (temps.size() % 2 == 0) median_value = (temps[temps.size() / 2] + temps[temps.size() / 2 - 1]) / 2; else median_value = temps[temps.size() / 2]; cout &lt;&lt; "Median Temperature of input values: " &lt;&lt; median_value &lt;&lt; '\n'; for (int i = 0; i &lt; temps.size(); ++i) cout &lt;&lt; temps[i] &lt;&lt; ", "; } </code></pre> <p>I'm assuming this is what he meant by “a number so that exactly as many elements come before it in the sequence as come after it". I've probably missed the point of this exercise hence the post for some verification that I completed the exercise correctly.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T00:13:20.160", "Id": "398420", "Score": "0", "body": "you need to take of the case where `temps.size() == 0`, because it fits the `temps.size() % 2 == 0` but then `temps[temps.size() / 2 - 1]` will backfire" }, { "ContentLic...
[ { "body": "<pre><code>#include \"../../std_lib_facilities.h\"\n</code></pre>\n\n<p>While PPP is structured around using this header, you will eventually be including only what you really need to make your code self-sufficiently compilable. So instead of <a href=\"https://github.com/BjarneStroustrup/Programming...
{ "AcceptedAnswerId": "206551", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T22:01:13.247", "Id": "206536", "Score": "1", "Tags": [ "c++", "beginner", "statistics", "vectors" ], "Title": "Median of a Vector assignment" }
206536
<p>This code is a Extension to just be able to read a line quickly and efficiently with support for <code>SslStream</code>.</p> <p>What i'm looking to achieve:</p> <ul> <li>Lower CPU usage by improving how it stores bytes for being converted to string later</li> <li>Lower CPU usage by possibly not reading per-byte some how. In my debug tests its using up the most CPU by far. 33%/55% of samples are the ReadByte</li> </ul> <p>So your probably asking why im using a Queue as a buffer? Basically the Queue allows me to more efficiently store bytes in an array format. <code>byte[]</code> is un-acceptable due to the fact its size can't be changed dynamically (you would have to make a new byte, move over the old data, add the new, replace the old <code>byte[]</code>, in-efficient)</p> <p>queue however (or Stack if you .<code>Reverse()</code> it with linq) lets you add bytes whenever you want and then <code>.ToArray</code> when you need it as a <code>byte[]</code> Same thing can be done with <code>List&lt;byte&gt;</code> but I dont feel like it's the best tool for the job in this case.</p> <p>Another thing I could do here is just convert with <code>Encoding.GetString</code> on every byte and <code>StringBuilder</code> it but that seems to use more CPU and a lot more memory.</p> <p>Any suggestions?</p> <pre><code>public static string ReadLine(this Stream stream, ref int bodySize, Encoding encoding) { bool bodySizeWasSpecified = bodySize &gt; 0; byte b = 0; Queue&lt;byte&gt; Buffer = new Queue&lt;byte&gt;(); while (true) { #region Try Get 1 Byte from Stream try { int i = stream.ReadByte(); if (i == -1) { break;//stream ended/closed } b = (byte)i; } catch { return null;//timeout //not authenticated context } #endregion #region If there's a body size specified, decrement back 1 if (bodySizeWasSpecified) { bodySize--; } #endregion #region If Byte is \n or \r if (b == 10 || b == 13) { #region If ByteArray is Empty and the byte is \n reloop so we dont start with a leading \n if (Buffer.Count == 0 &amp;&amp; b == 10) { continue; } #endregion #region We hit a newline, lets finish the reads here. break; #endregion } #endregion #region Add the read byte to the Byte Array Buffer.Enqueue(b); #endregion #region Break if bodysize was greater than 0 but now its 0 if (bodySizeWasSpecified &amp;&amp; bodySize == 0) { break; } #endregion } return encoding.GetString(Buffer.ToArray()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T18:32:35.123", "Id": "398532", "Score": "1", "body": "I need to ask you to roll back your last edits. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers): _**Do ...
[ { "body": "<blockquote>\n <p>So your probably asking why im using a Queue as a buffer? Basically the Queue allows me to more efficiently store bytes in an array format. byte[] is un-acceptable due to the fact its size can't be changed dynamically (you would have to make a new byte, move over the old data, add ...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T01:48:57.663", "Id": "206543", "Score": "5", "Tags": [ "c#", "performance", "io", "stream", "ssl" ], "Title": "SslStream-compatible ReadLine extension" }
206543
<p>I have an XLSX file that contains a hierarchical list of categories. Each category has a basic query associated with it. I need to flatten these categories which involves combining the categories. I believe it easiest to show a picture of what I'm referring to. </p> <p>Here is an XLSX file that I receive: <a href="https://i.stack.imgur.com/u7fkc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u7fkc.png" alt="enter image description here"></a></p> <p>These categories need to be flattened, so the first one would have the following label:</p> <p><strong>Satisfaction - Committed - Helpfulness</strong></p> <p>The second label would be:</p> <p><strong>Satisfaction - Committed - Cleanliness</strong></p> <p>The third label would be:</p> <p><strong>Satisfaction - Technology</strong></p> <p>The fourth label would be:</p> <p><strong>Happiness</strong></p> <p>The queries also need to be combined and the commas should be switched to "or." </p> <p>Here is what the query should look like for each </p> <ol> <li>Satisfaction - Committed - Helpfulness <ul> <li><code>(( satisfied or satisfaction )) and (( committed or comitted or commited or committing ) and ( very ) and not ( committee )) and (( helpful or helpful ))</code></li> </ul></li> <li>Satisfaction - Committed - Cleanliness <ul> <li><code>(( satisfied or satisfaction )) and (( committed or comitted or commited or committing ) and ( very ) and not ( committee )) and (( cleanliness ))</code></li> </ul></li> <li>Satisfaction - Technology <ul> <li><code>(( satisfied or satisfaction )) and (( tech or technology ) and not ( techno ))</code></li> </ul></li> <li>Happiness <ul> <li><code>( happy ) and not ( upset )</code></li> </ul></li> </ol> <p>My code uses recursion to loop through each category and build the query. The base case is reaching a "leaf node." When it reaches a leaf node, the query is added to an array. </p> <pre><code>const XLSX = require('xlsx'); exports.parseFile = function(worksheet) { // Convert the XLSX file into JSON let xlsxJson = XLSX.utils.sheet_to_json(worksheet); let operations = []; // Creating an object with a counter to keep track of the number of categories processed. // We create it as an object so that the counter will be pass by reference. let indexObj = { counter: 0 }; let n = Object.keys(xlsxJson).length; while (indexObj.counter &lt; n) { parseCategoryRecursive(xlsxJson, Object.keys(xlsxJson), "", "", indexObj, operations); indexObj.counter = indexObj.counter + 1; } console.log(operations); }; /** * Parses each category recursively. */ var parseCategoryRecursive = function(xlsxJson, keys, query, label, indexObj, operations) { let category = xlsxJson[keys[indexObj.counter]]; // Build label let additionalLabel = category[Object.keys(category)[0]]; label += (label.length &gt; 0) ? " - " : ""; label += additionalLabel; // Determine if this category has a child let hasMoreChildren = isNextCategoryChild(xlsxJson, keys, indexObj.counter, category); // Build query let additionalQuery = buildQuery(category); if (additionalQuery.length &gt; 0) { // If there is not a parent query, and the current cateogry has no children, // just add the query. if (query.length == 0 &amp;&amp; !hasMoreChildren) { query += additionalQuery; } else { // If there is already a parent query, add an "and" query += (query.length &gt; 0) ? " and " : ""; query += "(" + additionalQuery + ")"; } } /* * The Base Case */ if (!hasMoreChildren) { operations.push(query); } /* * If "hasMoreChildren" is true, then the current category is a parent category, * continue recursing through the children. */ while (hasMoreChildren) { indexObj.counter = indexObj.counter + 1; parseCategoryRecursive(xlsxJson, keys, query, label, indexObj, operations); hasMoreChildren = isNextCategoryChild(xlsxJson, keys, indexObj.counter, category); } }; var isNextCategoryChild = function(xlsxJson, keys, index, category) { if (index + 1 &gt;= keys.length) { return false; } let currentCategory = Object.keys(category)[0]; let nextCategory = Object.keys(xlsxJson[keys[index + 1]])[0]; return (currentCategory &lt; nextCategory); }; var buildQuery = function(category) { let query = ""; if (category.hasOwnProperty("Keywords")) { query = category["Keywords"].replace(/,/g, ' or'); query = "( " + query + " )"; } if (category.hasOwnProperty("And Words")) { query += " and ( " + category["And Words"].replace(/,/g, ' or') + " )"; } if (category.hasOwnProperty("Not Words")) { if (query.length &gt; 0) { query += " and"; } query += " not ( " + category["Not Words"].replace(/,/g, ' or') + " )"; } return query; }; </code></pre> <p>I'm looking mostly to get feedback on the algorithm/recursion I have. I had to create a "pass-by-reference" counter which seemed like a bit of a code smell to me, but I found it to be much easier.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T05:02:31.637", "Id": "206549", "Score": "2", "Tags": [ "javascript", "algorithm", "recursion", "node.js" ], "Title": "Flatten Hierarchical Categories" }
206549
<p>The data I'm using is summoning rates from a gacha game, One Piece Treasure Cruise. The game provides the probability of getting a certain character in percents rounded to the nearest thousandth. However, the data does not sum to 100%, so I want to find the original fractions used to calculate those decimals. </p> <p>I've programmed a brute force approach to find these ratios. It iterates through potential numerators for each sub-category of data. If the results match all given in-game output, it gets displayed. The problem is that it takes a long time to run, so I need help optimizing it. I'm certain that there are better ways to do what I'm attempting. </p> <p>In the game, characters in this particular dataset are divided into three rarity categories: 5 Star, 4 Star, and 3 Star. Each character also has one of six types (STR, DEX, QCK, PSY, or INT). Within the 5 Star and 4 Star categories, there are 4 subgroups, each with different probabilities. I added some comments to clarify parts of the code. </p> <pre><code>double round5places(double input); int main() { double given5rate = 0.07089; // The in-game rate for summoning a 5 star char double given4rate = 0.72911; double given3rate = 0.2; double givenSTR = 0.19934; // The in-game rate for summoning a STR char double givenDEX = 0.13355; double givenQCK = 0.25456; double givenPSY = 0.2124; double givenINT = 0.20014; double denom = 1; // The denominator of the fractions (iterates to 1,000,000) double given5_1 = 0.00182; // The in-game rate for a sub-group of the 5 star characters double cat5_1 = 0; // The category's numerator that will be iterated double num5_1 = 1; // The number of characters in this subset double given5_2 = 0.00016; double cat5_2 = 0; double num5_2 = 12; double given5_3 = 0.00222; double cat5_3 = 0; double num5_3 = 5; double given5_4 = 0.00043; double cat5_4 = 0; double num5_4 = 129; double given4_1 = 0.01818; double cat4_1 = 0; double num4_1 = 1; double given4_2 = 0.00156; double cat4_2 = 0; double num4_2 = 11; double given4_3 = 0.02218; double cat4_3 = 0; double num4_3 = 5; double given4_4 = 0.00435; double cat4_4 = 0; double num4_4 = 134; double given3_1 = 0.02222; double cat3_1 = 0; double num3_1 = 9; double sum5 = 0; double sum4 = 0; double sum3 = 0; double sumSTR = 0; double sumDEX = 0; double sumQCK = 0; double sumPSY = 0; double sumINT = 0; for (denom = 1; denom &lt;= 1000000; ++denom) { for (cat5_1 = 1; cat5_1 &lt; denom; ++cat5_1) { if (given5_1 == round5places(cat5_1 / denom)) { // If the fraction for the first sub-category of 5 stars matches the posted in-game rate, start working on the next sub-category for (cat5_2 = 1; cat5_2 &lt; denom - cat5_1; ++cat5_2) { if (given5_2 == round5places(cat5_2 / denom)) { for (cat5_3 = 1; cat5_3 &lt; denom - cat5_1 - cat5_2; ++cat5_3) { if (given5_3 == round5places(cat5_3 / denom)) { for (cat5_4 = 1; cat5_4 &lt; denom - cat5_1 - cat5_2 - cat5_3; ++cat5_4) { if (given5_4 == round5places(cat5_4 / denom)) { sum5 = num5_1 * (cat5_1 / denom) + num5_2 * (cat5_2 / denom) + num5_3 * (cat5_3 / denom) + num5_4 * (cat5_4 / denom); if (given5rate == round5places(sum5)) { for (cat4_1 = 1; cat4_1 &lt; denom - cat5_1 - cat5_2 - cat5_3 - cat5_4; ++cat4_1) { if (given4_1 == round5places(cat4_1 / denom)) { for (cat4_2 = 1; cat4_2 &lt; denom - cat5_1 - cat5_2 - cat5_3 - cat5_4 - cat4_1; ++cat4_2) { if (given4_2 == round5places(cat4_2 / denom)) { for (cat4_3 = 1; cat4_3 &lt; denom - cat5_1 - cat5_2 - cat5_3 - cat5_4 - cat4_1 - cat4_2; ++cat4_3) { if (given4_3 == round5places(cat4_3 / denom)) { for (cat4_4 = 1; cat4_4 &lt; denom - cat5_1 - cat5_2 - cat5_3 - cat5_4 - cat4_1 - cat4_2 - cat4_3; ++cat4_4) { if (given4_4 == round5places(cat4_4 / denom)) { sum4 = num4_1 * (cat4_1 / denom) + num4_2 * (cat4_2 / denom) + num4_3 * (cat4_3 / denom) + num4_4 * (cat4_4 / denom); if (given4rate == round5places(sum4)) { for (cat3_1 = 1; cat3_1 &lt; denom - cat5_1 - cat5_2 - cat5_3 - cat5_4 - cat4_1 - cat4_2 - cat4_3 - cat4_4; ++cat3_1) { if (given3_1 == round5places(cat3_1 / denom)) { sum3 = num3_1 * (cat3_1 / denom); if (given3rate == round5places(sum3)) { if ((sum5 + sum4 + sum3) == 1.0) { sumSTR = 1.0 * (cat3_1 / denom) + 3.0 * (cat4_2 / denom) + 37.0 * (cat4_4 / denom) + 4.0 * (cat5_2 / denom) + 35.0 * (cat5_4 / denom); if (givenSTR == round5places(sumSTR)) { sumDEX = 1.0 * (cat3_1 / denom) + 1.0 * (cat4_2 / denom) + 23.0 * (cat4_4 / denom) + 1.0 * (cat5_2 / denom) + 23.0 * (cat5_4 / denom); if (givenDEX == round5places(sumDEX)) { sumQCK = 2.0 * (cat3_1 / denom) + 2.0 * (cat4_2 / denom) + 29.0 * (cat4_4 / denom) + 2.0 * (cat4_3 / denom) + 1.0 * (cat4_1 / denom) + 2.0 * (cat5_2 / denom) + 26.0 * (cat5_4 / denom) + 2.0 * (cat5_3 / denom) + 1.0 * (cat5_1 / denom); if (givenQCK == round5places(sumQCK)) { sumPSY = 3.0 * (cat3_1 / denom) + 1.0 * (cat4_2 / denom) + 24.0 * (cat4_4 / denom) + 1.0 * (cat4_3 / denom) + 1.0 * (cat5_2 / denom) + 25.0 * (cat5_4 / denom) + 1.0 * (cat5_3 / denom); if (givenPSY == round5places(sumPSY)) { sumINT = 2.0 * (cat3_1 / denom) + 4.0 * (cat4_2 / denom) + 21.0 * (cat4_4 / denom) + 2.0 * (cat4_3 / denom) + 4.0 * (cat5_2 / denom) + 20.0 * (cat5_4 / denom) + 2.0 * (cat5_3 / denom); if (givenINT == round5places(sumINT)) { std::cout &lt;&lt; "Denominator: " &lt;&lt; denom &lt;&lt; "\n5-1: " &lt;&lt; cat5_1 &lt;&lt; "\n5-2: " &lt;&lt; cat5_2 &lt;&lt; "\n5-3: " &lt;&lt; cat5_3 &lt;&lt; "\n5-4: " &lt;&lt; cat5_4 &lt;&lt; "\n4-1: " &lt;&lt; cat4_1 &lt;&lt; "\n4-2: " &lt;&lt; cat4_2 &lt;&lt; "\n4-3: " &lt;&lt; cat4_3 &lt;&lt; "\n4-4: " &lt;&lt; cat4_4 &lt;&lt; "\n3-1: " &lt;&lt; cat3_1; } } } } } } } } } } } } } } } } } } } } } } } } } } } } return 0; } double round5places(double input) { return (round(input * 100000.0) / 100000.0); } </code></pre> <p>If something is unclear, please let me know. Thanks in advance for your help!</p>
[]
[ { "body": "<p>If I'm not mistaken, the question stated in the title isn't the question you ask in your post's body. Finding the nearest rational approximation of a double-precision number is one thing, mirroring the character selection of a game another.</p>\n\n<p>As to the first one, a fairly good answer is ba...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T07:30:34.510", "Id": "206553", "Score": "2", "Tags": [ "c++", "performance", "iterator", "iteration" ], "Title": "Finding the Original Fractions from Rounded Decimals" }
206553
<p>I want to create a matrix like this in Python: <span class="math-container">$$ \begin{pmatrix} 0 &amp; 0 &amp; 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 2 &amp; 2 &amp; 2 &amp; 2 &amp; 3 &amp; 3 &amp; 3 &amp; 3\\ 0 &amp; 1 &amp; 2 &amp; 3 &amp; 0 &amp; 1 &amp; 2 &amp; 3 &amp; 0 &amp; 1 &amp; 2 &amp; 3 &amp; 0 &amp; 1 &amp; 2 &amp; 3\\ 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 1 \end{pmatrix} $$</span></p> <p>I have written a code that works, but takes a long time to execute:</p> <pre><code>row = 3000 col = 4000 row_1 = np.asarray((col)*[0]) for i in range(1,row): row_1 = np.append(row_1, np.asarray((col)*[i])) row_2 = np.asarray(row*[x for x in range(0,col)]) row_3 = np.asarray(col*(row)*[1]) output = np.vstack([row_1,row_2,row_3]) </code></pre> <p>It takes between 55 to 65 seconds to run this code. Is it possible to create the same matrix in a way that is more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T03:26:50.510", "Id": "399655", "Score": "0", "body": "As mentioned many times on SO, use of `np.append` iteratively is slow. If you must iterate, collect values in a list, and use `concatenate` once at the end." } ]
[ { "body": "<p>The <a href=\"https://docs.scipy.org/doc/numpy/reference/index.html\" rel=\"noreferrer\">NumPy Reference</a> should be the first place you look when you have a problem like this. The operations you need are nearly always in there somewhere. And functions that you find while browsing the reference ...
{ "AcceptedAnswerId": "206557", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T08:02:35.240", "Id": "206554", "Score": "12", "Tags": [ "python", "time-limit-exceeded", "matrix", "numpy" ], "Title": "Looking for a way to create a particular matrix in python in a less amount of time" }
206554
<p>I started practicing on HackerRank to see how my learning is going on with Java. I wrote this code for problem which involved input having:</p> <blockquote> <ol> <li>String with maximum length of 10, followed by</li> <li>A 3 digit or lesser integer</li> </ol> </blockquote> <p>Examples: <code>"java 100"</code>, <code>"Amazing 98"</code></p> <p>Expected output:</p> <blockquote> <ol> <li>String should be left-justified with trailing white spaces till 15th character</li> <li>Leading digit of integer starts at 16th place with leading zeroes if it is less than 3 digits(padding) to make up for 18 characters</li> </ol> </blockquote> <p>Examples: <code>"java 100"</code>, <code>"Amazing 098"</code></p> <pre><code>package HackerRank; import java.util.ArrayList; import java.util.Scanner; public class IOFormatting { public ArrayList&lt;String&gt; getAllLines(){ ArrayList&lt;String&gt; allInputs = new ArrayList&lt;String&gt;(); Scanner getIp = new Scanner(System.in); while(getIp.hasNext()) { allInputs.add(getIp.nextLine()); } getIp.close(); return allInputs; } public ArrayList&lt;Character&gt; getTheInputAsArrayList(String input) { ArrayList&lt;Character&gt; inputLine = new ArrayList&lt;Character&gt;(); for(int itr1=0;itr1&lt;input.length();itr1++) { inputLine.add(input.charAt(itr1)); } return inputLine; } public ArrayList&lt;Character&gt; formatTheArrayList(ArrayList&lt;Character&gt; inputLine){ int itr2 = getBreakPoint(inputLine); for(int itr3=itr2+1;itr3&lt;15;itr3++) { inputLine.add(itr3,' '); } return inputLine; } public int getBreakPoint(ArrayList&lt;Character&gt; inputLine){ for(int itr2=0;itr2&lt;=10;itr2++) { if(inputLine.get(itr2) == ' ') { return itr2; } } return 0; } public ArrayList&lt;Character&gt; doIntegerPadding(ArrayList&lt;Character&gt; inputLine){ int padSize = 18 - inputLine.size(); if(padSize&gt;0) { for(int itr4=15;itr4&lt;=14+padSize;itr4++) { inputLine.add(itr4,'0'); } } return inputLine; } public String convertToFinalString(ArrayList&lt;Character&gt; inputLine) { String outputString = ""; StringBuffer sb = new StringBuffer(); for (Character s : inputLine) { sb.append(s); } outputString = sb.toString(); return outputString; } public static void main(String args[]) { IOFormatting io = new IOFormatting(); ArrayList&lt;String&gt; allInputs = io.getAllLines(); System.out.println("================================"); for(int mainItr=0;mainItr&lt;allInputs.size();mainItr++) { String input = allInputs.get(mainItr); ArrayList&lt;Character&gt; inputLine = io.getTheInputAsArrayList(input); inputLine = io.formatTheArrayList(inputLine); inputLine = io.doIntegerPadding(inputLine); String outputString = io.convertToFinalString(inputLine); System.out.println(outputString); } System.out.println("================================"); } } </code></pre>
[]
[ { "body": "<p>You are vastly overcomplicating the solution. The <code>Scanner</code> is perfectly capable of reading a string and an integer separately. Then, it is a simple matter of calling <a href=\"https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#printf%27java.lang.String,java.lang.Obje...
{ "AcceptedAnswerId": "206590", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T09:03:35.450", "Id": "206559", "Score": "2", "Tags": [ "java", "beginner", "formatting" ], "Title": "Justifying a string followed by a number" }
206559
<p>I have a pretty simple question but I can't seem to find a solution for it. I have the following SCSS code (can be found below) which works fine, but I think it could be simplified to get rid of the double code. </p> <p>I'm trying to create 3 simple dots with CSS. I figured I could use one <code>div</code> and the <code>:before and :after</code> selectors. I'm looking for a pure (S)CSS solution and don't want to use icons/images. I have a working example but I feel like it could be a lot better structured.</p> <p>Mainly I'm looking to change the selectors so I can get a format like:</p> <pre><code>div { // Styling for the div in it's normal state. [selector for div itself] &amp;:after, &amp;:before { // Styling for the div in it's normal state AND for it's :before and :after state } &amp;:after, &amp;:before { // Styling for JUST the :before and :after state } &amp;:after { // Styling for JUST the :after state } &amp;:before { // Styling for JUST the :before state } } </code></pre> <p>&nbsp;</p> <p>Current code</p> <p>SCSS:</p> <pre><code>.row-options-icon{ padding: 2rem; &amp;:hover{ div, div:after, div:before{ background-color: black; } } div { position: relative; border-radius:100px; background-color:gray; width:.5rem; height:.5rem; &amp;:after, &amp;:before { content: ''; position: absolute; border-radius:100px; background-color:gray; width:.5rem; height:.5rem; display: inline-block; } &amp;:after { top: -1rem; } &amp;:before { top: 1rem; } } } </code></pre> <p>HTML:</p> <pre><code>&lt;div class="row-options-icon"&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="https://codepen.io/anon/pen/MPdmEB" rel="nofollow noreferrer">Working Codepen example</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T10:16:06.447", "Id": "398461", "Score": "1", "body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what y...
[ { "body": "<p>What you're looking for is just <code>&amp;</code>:</p>\n\n<pre><code> div {\n position: relative;\n &amp;, &amp;:after, &amp;:before {\n border-radius:100px;\n background-color:gray;\n width:.5rem;\n height:.5rem;\n }\n &amp;:after, &amp;:before {\n content: ...
{ "AcceptedAnswerId": "206571", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T09:45:38.463", "Id": "206563", "Score": "2", "Tags": [ "css", "sass" ], "Title": "Rendering three vertical dots using SCSS" }
206563
<p>I've been researching if this is possible, but I've drawn a blank, I'm wondering if it's possible to optimize these for and if statements together?</p> <pre><code>&lt;?php // calculate total number of pages $total_pages = ceil($total_rows / $records_per_page); // range of links to show $range = 2; // display links to 'range of pages' around 'current page' $initial_num = $page - $range; $condition_limit_num = ($page + $range) + 1; ?&gt; &lt;ul class="pagination margin-zero"&gt; &lt;?php if ($page&gt;1) : ?&gt; &lt;li&gt; &lt;a href='&lt;?php echo $page_url; ?&gt;' title='Go to the first page.'&gt; First Page &lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php for ($x = $initial_num; $x&lt;$condition_limit_num; $x++) : if (($x &gt; 0) &amp;&amp; ($x &lt;= $total_pages)) : if ($x == $page) : ?&gt; &lt;li class='active'&gt; &lt;a href="#"&gt;&lt;?php echo $x; ?&gt; &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php else : ?&gt; &lt;li&gt; &lt;a href='&lt;?php echo $page_url; ?&gt;page=&lt;?php echo $x; ?&gt;'&gt;&lt;?php echo $x; ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; endif; endfor; ?&gt; &lt;?php if ($page&lt;$total_pages) : ?&gt; &lt;li&gt; &lt;a href='&lt;?php echo $page_url; ?&gt;page=&lt;?php echo $total_pages; ?&gt;' title='Last page is &lt;?php echo $total_pages; ?&gt;'&gt; Last Page &lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;/ul&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T11:32:45.757", "Id": "398478", "Score": "1", "body": "Please provide the *full actual code* that runs on your page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T11:39:20.040", "Id": "398479", ...
[ { "body": "<p>The main loop code lacks the prior validation. So in the business logic part</p>\n\n<ul>\n<li>verify that $x is positive. if not, make it the least number possible (1 I suppose)</li>\n<li>verify that $x is &lt;= $total_pages. Make them equal otherwise</li>\n<li>prepare the page numbers in the form...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T11:27:50.510", "Id": "206570", "Score": "1", "Tags": [ "php", "pagination" ], "Title": "Displaying pagination links, maybe with links to first and last page" }
206570
<p>I have a C++ method that uses the Intel performance primitives library to convert an image from YUV422 format into RGB 24. I am PInvoking this method from C# (WPF) where the YUV images are coming from a high frame rate camera. The method takes a pointer to the image data, and the width and height and returns a pointer to the modified data.</p> <p>This single method is taking up 23% of my entire application CPU and must be running at all times (the video is always visible).</p> <p>I am not a C++ maestro and I am sure that this code could be improved significantly in terms of performance, but I am not sure where to start.</p> <p>Any suggestions for improvements would be most appreciated</p> <pre><code>extern "C" __declspec(dllexport)unsigned char* YUV422ToRGB24(unsigned char* input, int width, int height) { const int ALIGNMENT_64BIT_MASK = 64u; int stepRGB, stepYUV; Ipp8u *rgbImg, *imgYUV422_IPP; bool success = false; IppiSize size; UINT32 width3 = width * 3; UINT32 width2 = width * 2; unsigned char *ptr = NULL; unsigned char* pBGR = new unsigned char[(width * height) * 3]; // ippi functions require 32Bit alignment, if not a if ((((uintptr_t)pBGR % ALIGNMENT_64BIT_MASK) == 0) &amp;&amp; (width3 % ALIGNMENT_64BIT_MASK == 0)) { rgbImg = pBGR; stepRGB = width3; } else { rgbImg = ippiMalloc_8u_C3(width, height, &amp;stepRGB); if (rgbImg == NULL) return false; } if ((((uintptr_t)input % ALIGNMENT_64BIT_MASK) == 0) &amp;&amp; (width2 % ALIGNMENT_64BIT_MASK == 0)) { imgYUV422_IPP = input; stepYUV = width2; } else { imgYUV422_IPP = ippiMalloc_8u_C2(width, height, &amp;stepYUV); if (imgYUV422_IPP == NULL) { ippiFree(imgYUV422_IPP); return false; } // copy source to yuv ptr = imgYUV422_IPP; // simple case where step is compatable, can copy entire row if (stepYUV == width2) { memcpy(ptr, input, height * stepYUV); } else { for (int col = 0; col &lt; height; ++col) { memcpy(ptr, input, width2); input += width2; ptr += stepYUV; } } } // convert yu422 to rgb size.width = width; size.height = height; if (ippiYCbCr422ToBGR_8u_C2C3R(imgYUV422_IPP, stepYUV, rgbImg, stepRGB, size) == 0) { // ouptut destination not same location as result, so copy over memory if (pBGR != rgbImg) { // copy memory to destination ptr = rgbImg; // simple case where step is compatable, can copy entire row if (stepRGB == width3) { memcpy(pBGR, ptr, height * stepRGB); } else { for (int col = 0; col &lt; height; ++col) { memcpy(pBGR, ptr, width3); pBGR += width3; ptr += stepRGB; } } } success = true; } // only free memory if not same as pointers provided if (pBGR != rgbImg) ippiFree(rgbImg); if (input != imgYUV422_IPP) ippiFree(imgYUV422_IPP); return pBGR; } </code></pre>
[]
[ { "body": "<p>If your function is called with non-aligned memory, it will allocate two buffers, copy, do the simple fast thing, copy again, and free. That’s a whole lotta work for something simple and fast. And if the step sizes don’t match, the copy will be even slower.</p>\n\n<p>If this the normal execution c...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T12:48:42.313", "Id": "206575", "Score": "3", "Tags": [ "c++", "image" ], "Title": "YUV422 to RGB24 using Intel Performance Primitives" }
206575
<p>This is my first class. I've been working a while on it, some functions are future ideas and are right now just bare bones and intended to be worked on later. I'm really looking for a good review of what I have so far, I've never done this before so hopefully I'm off to a decent start. I tried to log my errors as well and handle them by skipping but annotating which values are trouble. Also first time using *args in my functions.</p> <pre><code>class Matrix(): def __init__(self, height, width): self.rows = [[0]*width for i in range(height)] self.height = height self.width = width def __str__(self): s = "\n" + "\n".join([str(i) for i in [rows for rows in self.rows] ]) + "\n" return s def __repr__(self): return (f'{self.__class__.__name__} ({self.height!r} , {self.width!r})') def len(self): return self.height * self.width def __add__(self, matrix2): return def __mul__(self, matrix2): return def remove(self, item): return def fill_matrix(self, fill_list): index = 0 for i in range(len(self.rows)): try: for j in range(len(self.rows[i])): self.rows[i][j] = fill_list[index] index += 1 except IndexError: print (f"Matrix not filled \nMatrix fill stopped at: row {i}, Column {j}") break return fill_list[index:] def add_value(self, *args): log = [] for arg in args: try: arg_size = len(arg) except TypeError: log.append(f'Parameter must be sequence, skipped: {arg}') continue try: if arg_size == 3: self.rows[arg[0]] [arg[1]] = arg[2] else: log.append(f'Parameter has too little or too much data, skipped: {arg}') except IndexError: log.append(f'Location parameters are out of range, skipped: {arg}') except TypeError: log.append(f'Location indicies must contain integral types, skipped: {arg}') return log myMat = Matrix(5,5) overflow = myMat.fill_matrix([i for i in range(26)]) print(myMat) Errors = myMat.add_value((-1,3,500), (0,0,3),(51,5, 7), (1, 2, 667), [3,4,676], (1), (1,"a", 1), (1,1, "£")) print(myMat) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T18:09:39.817", "Id": "398528", "Score": "0", "body": "I know no one has really said anything about it, but I'm generalizing my fill function to fill partitions or whole thing" }, { "ContentLicense": "CC BY-SA 4.0", "Crea...
[ { "body": "<ol>\n<li>There is no need for brackets in <code>class Matrix(): ...</code>. It can be just <code>class Matrix: ...</code>. See <a href=\"https://docs.python.org/3/tutorial/classes.html#class-definition-syntax\" rel=\"nofollow noreferrer\">docs</a> for class definition syntax.</li>\n<li>In <code>self...
{ "AcceptedAnswerId": "206799", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T13:25:19.740", "Id": "206577", "Score": "1", "Tags": [ "python", "beginner", "matrix" ], "Title": "Basic beginner's matrix class in Python" }
206577
<h2>Task:</h2> <p>Link to original problem :<a href="https://www.spoj.com/problems/FACTCG2/" rel="nofollow noreferrer">https://www.spoj.com/problems/FACTCG2/</a></p> <blockquote> <p>The task in this problem is to write a number in a multiplication of prime numbers separated by “<code>x</code>”. You need to put the number 1 in this multiplication.</p> <h3>Input:</h3> <p>The input consists of several lines.</p> <p>Each line consists of one integer N (1 &lt;= N &lt;= 10^7) .</p> <h3>Example Input:</h3> <pre><code> 1 2 4 8 </code></pre> <h3>Example Ouput:</h3> <pre><code> 1 1 x 2 1 x 2 x 2 1 x 2 x 2 x 2 </code></pre> </blockquote> <h2>My approach:</h2> <p>I pre-compute an array <code>Primes</code> which contains the smallest prime factor of every number from 1 to 1e7 using the sieve. Then to find the answer , I divide the number given in each query by its least prime factor until it becomes '1' or a prime number. Then I display it.</p> <p>The code works for small inputs but SPOJ gives me time limit exceeded. I think maybe the vector in <code>factorise</code> function has something to do with it. I tried printing the answer without storing it in vector but 'x' makes it difficult .</p> <h2>My code:</h2> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; vector&lt;long long&gt;Primes(1e7); bool prime(long long x) { for(int i=2;i&lt;=sqrt(x);i++) { if(x%i==0) return false; } return true; } void least_prime_factor() //To store least prime factor of a // given number { Primes[1]=1; for(int i=2;i&lt;=1e7;i++) { if(Primes[i]==0) { Primes[i]=i; for(int j=2;i*j&lt;=1e7;j++) { if(Primes[i*j]==0) Primes[i*j]=i; } } } } vector&lt;long long&gt;factorise(int x) //This is to store the factors //of a number { vector&lt;long long&gt;ret; while(x!=1||prime(x)!=true) { ret.push_back(Primes[x]); x=x/Primes[x]; } return ret; } int main() { least_prime_factor(); int n; while(scanf("%d", &amp;n) == 1) if(n==1) { cout&lt;&lt;"1"&lt;&lt;endl; } else{ vector&lt;long long&gt;ans=factorise(n); cout &lt;&lt; "1 x" ; for(int i=0;i&lt;ans.size();i++) { if(i==ans.size()-1) printf(" %d ", ans[i]); else printf(" %d x", ans[i]); } cout&lt;&lt;endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T15:37:36.147", "Id": "398512", "Score": "3", "body": "Could you please indent your code in a more readable/consistent way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-31T07:40:45.097", "Id": "398...
[ { "body": "<p>Don't include <code>&lt;bits/stdc++.h&gt;</code> - it's not standard, and on platforms that provide it, it drags in far too much.</p>\n\n<p>Don't <code>using namespace std</code> - this namespace is not designed for wholesale inclusion, and can produce subtle bugs when its names overload your own....
{ "AcceptedAnswerId": "206589", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T13:47:07.247", "Id": "206580", "Score": "1", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded", "primes" ], "Title": "Display a number as a product of its prime factors" }
206580
<p>The master launch sequence consists of several independent sequences for different systems. Your goal is to verify that all the individual system sequences are in strictly increasing order. In other words, for any two elements <code>i</code> and <code>j</code> (<code>i &lt; j</code>) of the master launch sequence that belong to the same system (having <code>systemNames[i] = systemNames[j]</code>), their values should be in strictly increasing order (i.e. <code>stepNumbers[i] &lt; stepNumbers[j]</code>).</p> <p>The input <code>systemNames[i]</code> contains the name of the system to which the ith element of the master launch sequence belongs. Guaranteed constraints:</p> <ul> <li>1 ≤ systemNames.length ≤ 5 · 10<sup>4</sup>,</li> <li>1 ≤ systemNames[i].length ≤ 10.</li> </ul> <p>The input <code>stepNumbers[i]</code> is an array of positive integers that contains the value of the ith element of the master launch sequence. Guaranteed constraints:</p> <ul> <li>stepNumbers.length = systemNames.length,</li> <li>1 ≤ stepNumbers[i] ≤ 10<sup>9</sup>.</li> </ul> <p>Return true if all the individual system sequences are in strictly increasing order, otherwise return false.</p> <h3>Example</h3> <p>For <code>systemNames = ["stage_1", "stage_2", "dragon", "stage_1", "stage_2", "dragon"]</code> and <code>stepNumbers = [1, 10, 11, 2, 12, 111]</code>, the output should be <code>launchSequenceChecker(systemNames, stepNumbers) = true</code>.</p> <p>There are three independent sequences for systems <code>stage_1</code>, <code>stage_2</code>, and <code>dragon</code>. These sequences are <code>[1, 2]</code>, <code>[10, 12]</code>, and <code>[11, 111]</code>, respectively. The elements are in strictly increasing order for all three.</p> <p>Here is my code.</p> <pre><code>(defun launchSequenceChecker (systemNames stepNumbers) (setf mmm (remove-duplicates (copy-seq systemNames) :test #'equal)) (setf lname (map 'list #'identity mmm)) (setf lnum (make-list (length mmm):initial-element '0)) (setf lnum1 (make-list (length mmm):initial-element '1000000001)) (loop named haha for x from 0 to (1- (length systemNames)) for name = (aref systemNames x) for name1 = (aref systemNames (- (1-(length systemNames)) x)) for num = (aref stepNumbers x) for num1 = (aref stepNumbers (- (1-(length systemNames)) x)) for pos = (position name lname :test #'equal) for pos1 = (position name1 lname :test #'equal) if(&gt;= (nth pos lnum) num) do(return-from haha nil) else if(&lt;= (nth pos1 lnum1) num1) do(return-from haha nil) else do (setf (nth pos lnum) num ) (setf (nth pos1 lnum1)num1) finally (return-from haha t))) </code></pre> <p>The problem I am having is that this code passes the tests but exceeds the 6-second time limit.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-14T17:05:51.607", "Id": "400870", "Score": "0", "body": "One of the basic mistakes: you haven't defined your variables: MMM, LNAME, LNUM, LNUM1. `setf` doesn't define variables, it just sets them. Use `LET` or `LET*` to define local va...
[ { "body": "<p>You are using a list to store the association between names and the previous maximum value. This makes your algorithm O(N^2) because for each element, you might have to go through a list of all previous elements.</p>\n\n<p>You can use a hash table (which has O(1) lookup) to make your algorithm O(N...
{ "AcceptedAnswerId": "206593", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T14:44:27.413", "Id": "206583", "Score": "1", "Tags": [ "algorithm", "sorting", "time-limit-exceeded", "common-lisp" ], "Title": "Verify that each named sequence is strictly increasing" }
206583
<p>I have a function <code>addSupplier()</code> that adds a supplier. Each supplier has multiple addresses and each address has multiple contacts.</p> <pre><code>public function addSupplier ($request) { // ADDING THE SUPPLIER BASIC INFO $supplier_fillable_values = array_merge( $request -&gt; except('address_contact_inputs'), ['created_by' =&gt; $this-&gt;getAuthUserId()] ); $new_supplier = Supplier::create($supplier_fillable_values); // ADDING THE SUPPLIER ADDRESSES AND THE ADDRESS CONTACTS foreach ($request -&gt; address_contact_inputs as $address) { // ADD ADDRESS $new_supplier_address = $new_supplier -&gt; addresses() -&gt; create([ 'address' =&gt; $address['address'], 'created_by' =&gt; $this -&gt; getAuthUserId() ]); // ADD ADDRESS CONTACTS foreach ($address['contacts'] as $contact) $new_supplier_address -&gt; contacts() -&gt; create([ 'name' =&gt; $contact['name'], 'phone_number' =&gt; $contact['phone_number'], 'created_by' =&gt; $this -&gt; getAuthUserId() ]); } return $request -&gt; address_contact_inputs; } </code></pre> <p>Everything works fine but question is: Is this the best practice or I should use events and create an event for:</p> <ol> <li>Storing the supplier basic info</li> <li>Storing the supplier addresses</li> <li>Storing contact for each supplier's address</li> </ol>
[]
[ { "body": "<p>You could use events for triggering these kinds of things, but there is a danger that your code starts to become harder to follow. Martin Fowler gives a good top-level talk on it <a href=\"https://www.youtube.com/watch?v=STKCRSUsyP0\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>There are two i...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T15:54:15.180", "Id": "206588", "Score": "1", "Tags": [ "php", "mvc", "laravel", "repository" ], "Title": "Laravel function to add a supplier, and associated addresses and contacts" }
206588
<p>I am looking for help in code proofreading. The program is trying to solve this question: Fit non-congruent rectangles into an array_size x array_size square grid. What is the smallest difference possible between the areas of the largest and the smallest rectangles? </p> <p>I have a class of Rectangles, which I try to fit in a class called Boards. The function AutoInsert is basically the algorithm, where I have a linked list consisting of both Boards &amp; Rectangles that adds and removes potential Rectangles from the Boards. This program works for small numbers of global variable array_size. </p> <p>I appreciate any help at all: even if you don't understand the question or my programming, if you recognize any bad practices in my programming, please do tell.</p> <pre><code>#include&lt;iostream&gt; #include&lt;math.h&gt; #include&lt;vector&gt; #include&lt;time.h&gt; #include&lt;stdlib.h&gt; #include &lt;cstdio&gt; #include &lt;ctime&gt; using namespace std; const int array_size = 15; //array_size x array_size square const int upperbound = ceil(3+array_size/log(array_size)); //given in reddit link const int SQ = pow(array_size,2); char getRandom(){ int n=rand()%78; char c=(char)(n+49); return c; } class Rect{ private: int l,w,use; //int use: 0=haven't used, 1=using, 2=congruent use, 3=never use again ... should I add a possible use number w. respect to wnBounds? int coords[4]; //top left x,tly,brx,bry char random; public: Rect(){ l=0; w=0; use=0; for(int i=0;i&lt;4;i++){ coords[i]=-1; } } void setL(int l){this-&gt;l=l;} void setW(int w){this-&gt;w=w;} void setUse(int use){this-&gt;use=use;} void setCoords(int coords[]){ for(int i=0;i&lt;4;i++){ this-&gt;coords[i]=coords[i]; } } int getL(){return l;} int getW(){return w;} int getArea(){return l*w;} int getUse(){return use;} int *getCoords(){return coords;} int tlx(){return coords[0];} int tly(){return coords[1];} int brx(){return coords[2];} int bry(){return coords[3];} char setPiece(char c){random=c;} char getPiece(){return random;} }; class Rboard{ private: bool inRange(int c[4]); //defensive functions bool rectAtLoc(int c[4]); //defense bool canUse(Rect n); //defense Rect p[SQ]; //all possible rectangles, p[pow(array_size,2)-1] is the square so be careful Rect first; //initial Rect int difference; public: Rboard(); Rboard(Rect n); //initialize Rboard with first Rectangle, it will be up to Rsort to input good rectangles bool coords[array_size][array_size]; //main coords, all begin as false, true is if occupied void setFirst(Rect n){first=n;} void editPoss(int c[4],int n); Rect returnP(int n){return p[n];} int getIndex(int l, int w); int getDiff(); int spaceLeft(); vector&lt;int&gt; wnBound(); //returns rectangles within upperbound of initial rectangle vector&lt;int&gt; pp(); //returns the Index of possible rectangles which can be placed vector&lt;int&gt; pc(int i); //even index = top left x, odd index=y, can figure out rest of coords of rectangle from this information. void display(); }; Rboard::Rboard(){ difference=upperbound; int i=0; for(int i=0;i&lt;array_size;i++){ for(int j=0;j&lt;array_size;j++){ coords[i][j]=false; } } for(int j=0;j&lt;array_size;j++){ for(int k=0;k&lt;array_size;k++){ p[i].setL(j+1); p[i].setW(k+1); i++; } } } Rboard::Rboard(Rect n){ Rboard(); first=n; } int Rboard::getIndex(int l, int w){ for(int i=0;i&lt;SQ;i++){ if((p[i].getL()==l)&amp;&amp;(p[i].getW()==w)){ return i; } } } void Rboard::editPoss(int c[4],int n){ Rect g=p[n]; g.setCoords(c); g.setL(p[n].getL()); g.setW(p[n].getW()); if(canUse(g)){ p[n].setPiece(getRandom()); p[n].setCoords(c); p[n].setUse(1); if(g.getL()!=g.getW()){ p[getIndex(g.getW(),g.getL())].setUse(2); } for(int i=p[n].tly();i&lt;=p[n].bry();i++){ for(int j=p[n].tlx();j&lt;=p[n].brx();j++){ coords[j][i]=true; } } } } bool Rboard::inRange(int c[4]){ for(int i=0;i&lt;4;i++){ if((c[i]&gt;=array_size)||(c[i]&lt;0)){ return false; } } return true; } bool Rboard::rectAtLoc(int c[4]){ for(int i=c[0];i&lt;=c[2];i++){ for(int j=c[1];j&lt;=c[3];j++){ if(coords[i][j]){ return true; } } } return false; } bool Rboard::canUse(Rect n){ if((n.getUse()==0)&amp;&amp;(inRange(n.getCoords()))&amp;&amp;(rectAtLoc(n.getCoords())==false)){ return true; } return false; } int Rboard::getDiff(){ int oriDiff=difference, counter=0, minN=SQ+1, maxN=-1; //biggest number, smallest number for(int i=0;i&lt;SQ;i++){ if(p[i].getUse()==1){ if(p[i].getArea()&gt;maxN){ maxN=p[i].getArea(); } if(p[i].getArea()&lt;minN){ minN=p[i].getArea(); } counter++; } } if((counter&lt;=1)&amp;&amp;(spaceLeft()==0)){ return oriDiff; }else{ return maxN-minN; } } int Rboard::spaceLeft(){ int sum=0; for(int i=0;i&lt;array_size;i++){ for(int j=0;j&lt;array_size;j++){ if(coords[i][j]){ sum+=1; } } } return (SQ-sum); } vector&lt;int&gt; Rboard::wnBound(){ vector&lt;int&gt; output; for(int i=0;i&lt;SQ;i++){ if(abs(p[i].getArea()-first.getArea())&lt;=upperbound){ output.push_back(i); } } return output; } vector&lt;int&gt; Rboard::pc(int i){ vector&lt;int&gt; output; int l=p[i].getL(),w=p[i].getW(),area=p[i].getArea(),counter=0; for(int a=0;a&lt;(array_size-l+1);a++){ for(int b=0;b&lt;(array_size-w+1);b++){ for(int c=0;c&lt;w;c++){ for(int d=0;d&lt;l;d++){ if(!coords[b+c][a+d]){ counter++; } } } if(counter==area){ output.push_back(b); output.push_back(a); } counter=0; } } return output; } vector&lt;int&gt; Rboard::pp(){ vector&lt;int&gt; indexes; for(int i=0;i&lt;wnBound().size();i++){ int j=wnBound()[i]; if(p[j].getUse()==0){ if(spaceLeft()&gt;=p[j].getArea()){ if(pc(j).size()!=0){ indexes.push_back(j); } } } } return indexes; } void Rboard::display(){ for(int i=0;i&lt;array_size;i++){ for(int j=0;j&lt;array_size;j++){ if(coords[j][i]){ for(int a=0;a&lt;SQ;a++){ if((p[a].tlx()&lt;=j)&amp;&amp;(p[a].brx()&gt;=j)&amp;&amp;(p[a].tly()&lt;=i)&amp;&amp;(p[a].bry()&gt;=i)){ cout&lt;&lt;p[a].getPiece()&lt;&lt;" "; } } }else{ cout&lt;&lt;0&lt;&lt;" "; } } cout&lt;&lt;endl; } } class Rnode{ private: Rect piece; Rboard state; Rnode *next; public: Rnode(Rect p, Rboard s, Rnode *n){piece=p; state=s; next=n;} Rect getPiece(){return piece;} Rboard getState(){return state;} Rnode* getNext(){return next;} void setPiece(Rect p){piece=p;} void setState(Rboard s){state=s;} void setNext(Rnode *next1){next=next1;} }; class Rsort{ private: Rnode *root; vector&lt;Rect&gt; best; int diff; public: Rsort(){ root=NULL; diff=upperbound+1; }; void setFirst(int i); bool isLoser(Rboard b); bool isDonut(Rboard b); //to do: keep track of duplicates. e.j., 1x1+1x2+3x1 has been calculated... make sure don't branch to other 6!-1 combinations. void autoInsert(Rnode *c,double duration,int maxDepth); void autoFirst(); void display(); }; void Rsort::setFirst(int i){ Rboard board; Rect f=board.returnP(i); int coords[4]={0,0,f.getW()-1,f.getL()-1}; f.setCoords(coords); board.editPoss(coords,i); board.setFirst(f); if(root!=NULL){ root=NULL; } root=new Rnode(f,board,NULL); } bool Rsort::isLoser(Rboard b){ //optimizes by 2 seconds vector&lt;int&gt; pp=b.pp(),dup; int sum=0,dupS=0; for(int i=0;i&lt;pp.size();i++){ if((b.returnP(pp[i]).getL())!=(b.returnP(pp[i]).getW())){ dup.push_back(b.returnP(pp[i]).getArea()); } sum+=b.returnP(pp[i]).getArea(); } for(int i=0;i&lt;dup.size();i++){ dupS+=dup[i]; } return ((sum-dupS/2)&lt;b.spaceLeft()); //if sum of areas of possible rectangles &lt; spaceLeft, this board will be a loser } bool Rsort::isDonut(Rboard b){ //check if there is an non-patchable "hole" bool invBoard[array_size+2][array_size+2]; vector&lt;int&gt; p=b.wnBound(); for(int x=0;x&lt;(array_size+2);x++){ invBoard[x][0]=true; invBoard[x][array_size+1]=true; } for(int y=1;y&lt;(array_size+1);y++){ invBoard[0][y]=true; for(int x=1;x&lt;(array_size+1);x++){ invBoard[x][y]=!b.coords[x-1][y-1]; //made coords public for this reason } invBoard[array_size+1][y]=true; } for(int i=0;i&lt;p.size();i++){ int l=b.returnP(i).getL(),w=b.returnP(i).getW(),area=b.returnP(i).getArea(),counter=0; for(int a=0;a&lt;(array_size-l+3);a++){ for(int b=0;b&lt;(array_size-w+3);b++){ for(int c=0;c&lt;w;c++){ for(int d=0;d&lt;l;d++){ if(invBoard[b+c][a+d]){ counter++; } } } if(counter==area){ return 0; } counter=0; } } } return 1; } void Rsort::autoInsert(Rnode *c,double duration,int maxDepth){ //add terminating counter for recursion? if(isDonut(c-&gt;getState())||(maxDepth&gt;=7)){ //max number of rectangles you want: change #. Need to define a function //to calculate this based on array_size and upperbound. This variable //alone has stopped my program from crashing at high values of array_size. //I suspect this due to the stack overflow error. return; } if(duration&gt;=15.0){ //timer x.0 seconds =&gt; gives better solutions the longer the timer root=NULL; return; } clock_t start; double d; start = clock(); vector&lt;int&gt; pp=c-&gt;getState().pp(), pc; c-&gt;setNext(NULL); if(pp.size()==0){ if(c-&gt;getState().spaceLeft()==0){ if(c-&gt;getState().getDiff()&lt;diff){ diff=c-&gt;getState().getDiff(); best.clear(); for(int a=0;a&lt;SQ;a++){ if(c-&gt;getState().returnP(a).getUse()==1){ best.push_back(c-&gt;getState().returnP(a)); } } display(); c-&gt;getState().display(); } } }else if((root!=NULL)&amp;&amp;(!isLoser(c-&gt;getState()))){ for(int i=0;i&lt;pp.size();i++){ //better restrictions here please pc=c-&gt;getState().pc(pp[i]); for(int j=0;j&lt;pc.size();j+=2){ if(j==2){ //to cut down runtime break; } Rect n; Rboard n1=c-&gt;getState(); int coords[4]={pc[j],pc[j+1],pc[j]+c-&gt;getState().returnP(pp[i]).getW()-1,pc[j+1]+c-&gt;getState().returnP(pp[i]).getL()-1}; n.setL(c-&gt;getState().returnP(pp[i]).getL()); n.setW(c-&gt;getState().returnP(pp[i]).getW()); n.setCoords(coords); n1.editPoss(coords,pp[i]); Rnode *newnode=new Rnode(n,n1,NULL); c-&gt;setNext(newnode); d=(clock()-start)/(double)CLOCKS_PER_SEC; autoInsert(c-&gt;getNext(),(duration+d),(maxDepth+1)); //remove +d if you have all the time in the world to wait for output } } } } void Rsort::autoFirst(){ //to do: only iterate through non congruent rectangles, and interquartile range of that. for(int i=SQ/4;i&lt;3*SQ/4;i++){ //interquartile range cout&lt;&lt;i&lt;&lt;endl; setFirst(i); autoInsert(root,0,0); } } void Rsort::display(){ cout&lt;&lt;diff&lt;&lt;endl; for(int i=0;i&lt;best.size();i++){ cout&lt;&lt;best[i].getL()&lt;&lt;" x "&lt;&lt;best[i].getW()&lt;&lt;endl; } } int main(){ srand(time(NULL)); Rsort r; Rboard t; r.isDonut(t); r.autoFirst(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T18:17:41.440", "Id": "398530", "Score": "0", "body": "\"The program is trying to solve this question\" Yes, and it isn't entirely clear whether it succeeded to your satisfaction or not. Could you clarify this? And take a look at the...
[ { "body": "<h2>Look at your compiler's warnings</h2>\n\n<p>When I try to compile your code, the compiler gives two warnings: <code>Rect::setPiece()</code> doesn't have a return statement, and <code>Rboard::getIndex()</code> is missing a return statement after the loop.</p>\n\n<p>The first warning can be fixed b...
{ "AcceptedAnswerId": "206606", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T17:30:29.740", "Id": "206595", "Score": "3", "Tags": [ "c++" ], "Title": "Attempt to solve Mondrian Puzzle with C++" }
206595
<p>I'm writing a bash script for deleting old files on a Linux server. Here are some relevant facts about this script:</p> <ul> <li>As currently written, it <em>does</em> work as expected. <strong>However</strong>, it's entirely possible there's some edge case I haven't considered (which is part of my reason for posting here).</li> <li>It will be run as root once a day, scheduled via <code>cron</code>.</li> <li>Only one instance should run at a time. If another instance is started, it should just exit.</li> <li>It will delete any file whose <code>mtime</code> is over 30 days old, from the time of <code>find</code>'s invocation.</li> <li>Each run of the script will take a few hours.</li> <li>The script will be running on a single CentOS 7 node, but it operates on a distributed file system exposed to hundreds of others.</li> </ul> <p>Here is the actual script:</p> <pre><code>#!/usr/bin/env bash NUM_PROCS=4 LIMIT_TIME=30 # days PIDFILE="/tmp/cleanup.pid" PID_NOW="$$" function save-pid() { echo "$1" &gt; "$PIDFILE" if [[ "$?" -ne 0 ]]; then # If we couldn't save the PID to the lockfile... echo "Failed to create PID file for PID $1 in $PIDFILE; exiting" exit 1 fi } function clean-up() { rm "$PIDFILE" } cd /scratch if [[ -f "$PIDFILE" ]]; then # If the lock file exists... (the script is either running another # instance or improperly exited earlier) read PID_SAVED &lt; "$PIDFILE" # Get the PID of the running cleanup script if ps --pid "$PID_SAVED" &amp;&gt; /dev/null; then # If a PID with this process exists... echo "Cleanup script is already running with PID $PID_SAVED; exiting" exit 1 else save-pid "$PID_NOW" fi else save-pid "$PID_NOW" fi trap clean-up HUP INT QUIT ILL ABRT BUS SEGV PIPE TERM ERR # If any further command raises a problematic signal or exits in error, # clean up $PIDFILE on the way out ls | xargs -P "$NUM_PROCS" -I{} \ find {} -type f -mtime "+$LIMIT_TIME" -delete clean-up </code></pre> <p>I'll consider any advice you have to offer, but I'm specifically curious about how I can improve my file locking and error handling.</p>
[]
[ { "body": "<p>General impressions - nice neat code, well commented. It's good that you use <code>trap</code> to clean up on exit.</p>\n\n<p>Shellcheck picks up a couple of oversights:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>206596.sh:11:11: note: Check exit code directly with e.g. 'if mycmd;...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T17:40:09.187", "Id": "206596", "Score": "5", "Tags": [ "bash", "error-handling", "file-system", "linux", "locking" ], "Title": "Script to clean up old files that should only run one instance" }
206596
<blockquote> <p><strong>The Problem</strong></p> <p>In the January 1984 issue of Scientific American, an interesting sequence of numbers known as a hailstone series was described. The series is formed by generating the next number based on the number just prior to it. If the previous number was even, the next number in the series is half of it. If the previous number was odd, the next number is three times it plus one. Although the series goes up and down, it eventually settles into a steady state of 4, 2, 1, 4, 2, 1, … For example, starting at 21, the hailstone series is: 21, 64, 32, 16, 8, 4, 2, 1, 4, 2, 1, … For 21, it required five steps before the steady state was reached.</p> <p>Write a program that computes how many steps will be necessary before the steady state is reached in the hailstone series beginning at a given number.</p> <p><strong>Sample Input</strong></p> <p>Your program must take its input from the ASCII text file <code>hail.in</code>. The file contains a sequence of one or more integer values, one per line. Sample contents of the file could appear as:</p> <pre class="lang-none prettyprint-override"><code>21 10 </code></pre> <p><strong>Sample Output</strong></p> <p>Your program must direct its output to the screen and must tell the number of steps required to reach the hailstone steady state for each integer recorded in the input file. Your program must format its output exactly as that shown below which is the output corresponding to the sample input above.</p> <pre class="lang-none prettyprint-override"><code>5 steps were necessary for 21. 4 steps were necessary for 10. </code></pre> </blockquote> <p><strong>hail.py</strong></p> <pre><code>with open('hail.in') as f: l = f.readline() while l: n, a, b, i = int(l[:-1]), [], { 4, 2, 1 }, 0 while set(a) &amp; b != b: if i == 0: a.append(n) else: a.append(a[i-1]/2 if a[i-1] % 2 == 0 else a[i-1]*3+1) i += 1 print(i - len(b), 'steps were necessary for', str(n) + '.') l = f.readline() </code></pre> <p>Any advice on performance enhancement and solution simplification or that is topical is appreciated!</p>
[]
[ { "body": "<p>Your outer loop…</p>\n\n<blockquote>\n<pre><code>with open('hail.in') as f:\n l = f.readline()\n while l:\n …\n l = f.readline()\n</code></pre>\n</blockquote>\n\n<p>… should be more idiomatically written as:</p>\n\n<pre><code>with open('hail.in') as f:\n for l in f:\n ...
{ "AcceptedAnswerId": "206601", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T18:54:21.020", "Id": "206599", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "collatz-sequence" ], "Title": "Contest Solution: Hailstones" }
206599
<p>Given array <code>a</code>, we want to find an index <code>k</code> in range <code>[0, a.length-1]</code> such that: </p> <pre><code>Math.abs( (a[0]+a[1]+...a[k-1]) - (a[k] + a[k+1] + ... + a[a.length-1]) ) </code></pre> <p>is maximal (in case <code>k == 0</code>, the result above is the sum of <code>a</code> elements). </p> <p>Below is the code I wrote.<br> Please tell me your opinion about it - run time, correctness and coding conventions. </p> <pre><code>public static int sumArray(int[] a) { int sum = 0; int len = a.length; for (int i = 0; i &lt; len; i++) { sum += a[i]; } return sum; } public static int findMaxDif(int[] a) { int left = 0; int right = sumArray(a); int max = Math.abs(right); int maxIndex = 0; int difI; int len = a.length - 1; for (int i = 0; i &lt; len; i++) { left += a[i]; right -= a[i]; difI = Math.abs(left - right); if (difI &gt; max) { max = difI; maxIndex = i + 1; } } return maxIndex; } </code></pre> <p>Simple tests that I wrote and work fine: </p> <pre><code>public static void main (String[] args) { int[] a1 = {1,2}; if (findMaxDif(a1) == 0) { System.out.println("test1 pass"); } int[] a2 = {-1,2}; if (findMaxDif(a2) == 1) { System.out.println("test2 pass"); } int[] a3 = {2,-1}; if (findMaxDif(a3) == 1) { System.out.println("test3 pass"); } int[] a4 = {-5,-4,4,3}; if (findMaxDif(a4) == 2) { System.out.println("test4 pass"); } } </code></pre>
[]
[ { "body": "<p>Some ideas:</p>\n\n<ul>\n<li>You can replace <code>sumArray</code> with <a href=\"https://stackoverflow.com/a/17846344/96588\"><code>IntStream.of(a).sum();</code></a>.</li>\n<li>Tests should be written using <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">JUnit</a> or another tes...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T19:48:07.560", "Id": "206604", "Score": "1", "Tags": [ "java", "performance", "array" ], "Title": "Best way to split array to two sub-arrays, with maximum absolute difference between them" }
206604
<p>I wrote a solution to <a href="https://www.codewars.com/kata/recover-a-secret-string-from-random-triplets" rel="nofollow noreferrer">this CodeWars challenge</a>:</p> <blockquote> <p>There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.</p> <p>A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup".</p> <p>As a simplification, you may assume that no letter occurs more than once in the secret string.</p> <p>You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.</p> </blockquote> <p>So, for example, given triplets <code>[['t','u','p'], ['w','h','i'], ['t','s','u'], ['a','t','s'], ['h','a','p'], ['t','i','s'], ['w','h','s']]</code>, my code would reconstruct the secret string <code>whatisup</code>. My code builds a dictionary, with each character from string as a key, and possible characters that precede the key as the value. Then, it loops through the dictionary, building the secret string a character at a time.</p> <pre><code>def recoverSecret(triplets): secret = '' secret_dict = {} # any better way to build a dictionary based on relationship of triplets? for x in triplets: for y in x: secret_dict.setdefault(y, set()).update(x[x.index(y) - 1]) if x.index(y) != 0 else secret_dict.setdefault(y, set()) def removeChar(c) -&gt; dict: '''find first char in secret''' #any better way to remove element from set that is value of dictionary when value in set? {v.remove(c) for k, v in secret_dict.items() if c in v} def findChar() -&gt; str: '''find first char in secret when there is no char in front of it''' #any better way to find character when value is dictionary is empty? return next(k for k, v in secret_dict.items() if not v) while secret_dict: first_char = findChar() #any better way to rebuild dictionary when key == k? secret_dict = {k: v for k, v in secret_dict.items() if k != first_char} removeChar(first_char) secret = secret + first_char return secret </code></pre>
[]
[ { "body": "<p>It looks like you have implemented <a href=\"https://en.wikipedia.org/wiki/Topological_sorting#Kahn&#39;s_algorithm\" rel=\"nofollow noreferrer\">Kahn's algorithm for topological sorting</a>.</p>\n\n<p>By PEP 8, the official Python style guide, <a href=\"https://www.python.org/dev/peps/pep-0008/#f...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T20:19:11.467", "Id": "206607", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge" ], "Title": "Reconstruct a string, given a list of subsequence triplets" }
206607