instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I've been working on this game for a couple weeks now as a purely personal project to help myself learn Java. I'd like to know if I'm on the right track with my project. Items I'd like specific feedback on: GridBagLayout - I think I'm working this out okay? Classes - Do I need to break parts of this up into other pi...
stackexchange/codereview
I need to run filtering on nested Lists and return a List of items from back I will put a sample code here with my model import lombok.Data; import java.util.List; import java.util.stream.Collectors; class Scratch { public static void main(String[] args) { ParentModel parent = new ParentModel(); ...
stackexchange/codereview
I need your review and suggestions how to make this code better. I'm just learning recursion and sure that this solution is not ideal. Question: Write a function that given an input array of integers with a varying length input integers array, and the desired target_sum, returns the number of combinations, of any lengt...
stackexchange/codereview
I've have methods for a stack and bag using a dynamic array in C. As far as I can tell everything is implemented correctly, but I'm wondering what I can do to improve this code. dynArray.h /* dynArr.h : Dynamic Array implementation. */ #ifndef DYNAMIC_ARRAY_INCLUDED #define DYNAMIC_ARRAY_INCLUDED 1 # ifndef TYPE # d...
stackexchange/codereview
I've written a simple log writing class. My code is also hosted on my Github. Specifically, I am looking for criticism on these items: Resource management. What is a more correct/safe way to obtaining a hold to stream-like objects? Clarity. Is my code as clear as it could be? Error handling. I've only had a few classe...
stackexchange/codereview
I wrote a program to display data in memory as binary and it worked. (It gave me immense sense of satisfaction and joy to see this work. I guess this happens to newbies who are just testing the waters). I know this isn't some terribly smart code, and I'm sure there must be surely lots of better ways to do this. Any adv...
stackexchange/codereview
I need to make the following C program: Given A (N, N) matrix (2D array). The program needs to find the min element in each column. Then it needs to multiply the row in which the element is, with the difference of its indexes (a[i] * i - j). Then transfer the new row on another matrix. Print the new matrix. Here is my ...
stackexchange/codereview
I've developed a program in Python that calculates the lowest possible costing path between two points in a matrix, including the values contained in the start and finish cells. The code is below. Once the matrix gets larger than 4×4, it becomes very slow. Are there any obvious problems with my code (recursive method)....
stackexchange/codereview
I've been developing a simple console application in C++ using the TinyXML2 library, and I honestly can't help but feel what I'm doing is not very robust. Maybe that's just the nature of parsing XML (this is my first foray into the topic, so I've no idea.) The following code works to the best of my knowledge, but it fe...
stackexchange/codereview
I have the following code working here on JSFIDDLE: <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> </head> <body> <label for="opt1"><input class="radio-button-selector" type="radio" name="a...
stackexchange/codereview
I have to edit a config automatically before starting a service in a docker container (a storm supervisor), and I want to append something like this in /opt/storm/conf/storm.yaml: storm.local.hostname: 1.1.1.1 (extracted from /etc/hosts) What I currently do is that: echo -n "storm.local.hostname: " >> /opt/storm/conf/...
stackexchange/codereview
I just started to learn C++ and I decided to make a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further. In particular I couldn't find an efficient way to implement a play again feature. Thanks in advance. #include <cstdlib> #include <ctime> #include <iostream> #include <strin...
stackexchange/codereview
Given the JSON response below: const result = { 'potential': { A: 514, B: 3127, C: 2970, D: 282, E: 41, F: 1, undefined: 48, }, 'current': { A: 2, B: 961, C: 2897, D: 2568, E: 455, F: 47, G: 5, undefined: 48, }, }; I need to transform it to: const tem...
stackexchange/codereview
I’ve been getting used to Java and I’ve written a simple hangman game using event-driven programming in Java 8. Please let me know of any improvements regarding the readability and design of the program, along with any pointers on how to neaten up the code. Also, any feedback regarding the use of JavaDoc style comments...
stackexchange/codereview
I have an abstract class that represents data request. The request is in XML format. There are a few classes that derive from abstract class and they do similar things. Some basic XML operations such as create XML document, write the elements and attributes of XML document and so on are implemented as methods of abstra...
stackexchange/codereview
I have a database with a number of stored procedures. These stored procedures provide the basic CRUD operations against the data. I'm trying to create a DAO layer with separate DAOs for each domain class (Album, Artist, Genre, Review, etc) which uses a common Base DAO. Using the Album DAO as an example, this is what I ...
stackexchange/codereview
I'm just a bit confused and can not write or simplify a jQuery code, that adds or removes classes based on the viewport size. I'm pretty sure there's a simpler and more efficient way to write that trivial code. Unfortunately I can not get it. Here is the current status: // initial state if ($(window).width() <...
stackexchange/codereview
#include <iostream> #include <cstdlib> #include <ctime> #include <string> using namespace std; void wrapUp() { cout << "-------------------------------------------------" << endl; system("CLS"); } int main() { srand(time(0)); string name; int player; int livesTracker = 5; int x = 1 + (r...
stackexchange/codereview
The following code reads a file, splits its data, replaces some characters in the data, and then joins the data again (I added more details in the comments): // read plain text file and make content available in data fs.readFile(filename, 'utf8', function(err, data) { if (err) throw err // turn the data into an ar...
stackexchange/codereview
To recover from yesterday's disaster, I re-read the SOLID principles and refactored my code. Hopefully I did a better job than yesterday. I wanted to keep my Student class immutable, but that meant I would have to change the class every time a new Student type was introduced, that violated the S in SOLID. Here is what ...
stackexchange/codereview
I haven't really programmed in C++ for about a year, and realised that I should get back into it, and tried my abilities out by remaking the STD vector class. However, my C++ is a bit rusty at the moment, and was wondering if I have made many mistakes in my implementation. # ifndef VECTOR_H # define VECTOR_H # include ...
stackexchange/codereview
Problem Statement Input The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space. Output For every test case print all prime numbers p such that m <= p <= n, one number per line, te...
stackexchange/codereview
Here is the script that I would like reviewed for the following: Best practices and design pattern usage Correctness in unanticipated cases Possible error checking Any streamline updates/ideas are welcome! import os import tarfile import time # Create backup filename timestr = time.strftime("%Y-%m-%d:%H%M%S") output...
stackexchange/codereview
I have the following two approaches for writing a custom string reverse algorithm and I was hoping someone could tell me which is the most efficient / preferable option and explain why. I am fairly new to Java and this would be educational for me. FYI I know this can be done using Stringbuilder but I wanted to write my...
stackexchange/codereview
I have a working code that groups items by their type values. The types can be one or multiple, however they are always returned as an array. To illustrate: if an item has types with values type1 and type2, it should be included in both type1 and type2 properties of the resulting grouped object. Although the code work...
stackexchange/codereview
I'm implementing a Producer/Consumer but the generic interface doesn't require any knowledge of blocking collections or tasks. public interface IReader { IEnumerable<Data> Read(); } Is it okay if my implementation of the IReader launches a task asynchronously and returns the consuming enumerable? public IEnumera...
stackexchange/codereview
I am implementing a program that takes commands from a user and based on those commands, drives a Robot on a grid. To implement this program I have used the Command pattern. I have used this pattern because, most importantly, I want to be able to add to the list of possible commands in the future. The program takes a s...
stackexchange/codereview
I've written this ActionResult to model an Order that goes through. I couldn't think of another way to write this without using context Db<Sets>. It runs kinda slow, taking around 4 seconds to complete. Is there way to optimize the code or is this kinda has to happen since I'm doing so many inserts? public ActionResult...
stackexchange/codereview
I've been experimenting with Perl and MySql and wrote this code for connecting and writing to a database: # MySQL DDL to create database used by code # # CREATE DATABASE sampledb; # # USE sampledb; # # CREATE TABLE `dbtable` ( # `id` int(11) NOT NULL AUTO_INCREMENT, # `demo` longtext, # PRIMARY...
stackexchange/codereview
I am trying to write simple graph lib in C++, BFS, DFS etc.. I want to create class GraphI which will represent any graph and will include necessary methods so my library could work. Could I add/remove/improve something from my code? #pragma once #include <algorithm> #include "colors.h" struct Vertex; template < typ...
stackexchange/codereview
I have a programming assignment where I need to build a webserver which can handle GET and HEAD requests. My webserver is working as it should but since I'm still a newbie at Java I'm not sure about my structure or quality of my code so if you have some criticism/tips I would appreciate it. Main: package pytteweb; imp...
stackexchange/codereview
Supports backspacing, but not wrapped backspacing. %macro newline 0.nolist mov ax, 0E0Dh int 10h mov al, 0Ah int 10h %endmacro %macro getc 0.nolist %%get: mov ah, 11h int 16h ; get keystroke status jnz %%pressed hlt jmp %%get %%pressed: mo...
stackexchange/codereview
As a player of the online game Pokéfarm Q, I'm making a fan-made extension to help players search through forum threads and CSS codes/userscripts. So that I can easily fetch data from a Pastebin I created, I added a function that ignores the CORS headers when the user is visiting https://pokefarm.com and the browser ex...
stackexchange/codereview
I want to group the elements in an arbitrary long list into pairs and implemented the following so far: (defun group-pairwise (numbers) "Returns a list with the elements of NUMBERS grouped in pairs." (cond ((null numbers) nil) ((null (rest numbers)) nil) (t (append (list (list (first numbers) (secon...
stackexchange/codereview
I have a script which is having too many modules. The script is working perfectly, but the only issue is it is taking too much time and I need to reduce the complexity of the script. I have a source file (it can have multiple rows of data, each column separated by a '|'). The script should check all the rows for all t...
stackexchange/codereview
This question is a revision of Parallel sieve of Eratosthenes. The goal is to implement a sieve of Eratosthenes with parallel strikes out from the boolean array. I tried to fix the data races and all the threading-related errors as well as to add some of the ideas from the previous answers. Now, the implementation work...
stackexchange/codereview
I made a small(ish) image editor for a client that is supposed to be able to do the following: initially scale image to preset size to avoid tiny/huge images initially center image in canvas resize uploaded image (while always maintaining original aspect ratio) prevent image from going outside the canvas bounds preven...
stackexchange/codereview
I wrote this piece of code to append index to any duplicate entry in List<T> like in the sample below. Input ["dupe", "not dupe", "dupe", "also not dupe"] Output ["dupe1", "not dupe", "dupe2", "also not dupe"] But the problem is it's O(n^2) in the second loop and I'm working on a large list (30+ items). I'm very new ...
stackexchange/codereview
I started to teach myself Haskell recently. Here is some code I wrote to convert a roman numeral into an arabic numeral: import Control.Arrow ((>>>)) import Data.Maybe (fromJust) fromRoman :: String -> Int fromRoman = translateFromRoman >>> applyNegationRule >>> sum translateFromRoman :: String -> [Int] translateFrom...
stackexchange/codereview
The fizzbuzz challenge presents a lot of interesting questions for 'intermediate' programmers like myself. I have found that I don't actually know where to draw the line with, complex (hard to read but concise/efficient) code and simple (easy to read but not concise) code. Additionally, I actually do not know if my 'mo...
stackexchange/codereview
I need to encrypt/decrypt 2D arrays (double pointers) using AES-128/CTR using Intel TinyCrypt (written in C). The following are two helper methods to simplify the library usage. Any comments would be highly appreciated. Thanks in advance. #include <tinycrypt/constants.h> #include <tinycrypt/ctr_mode.h> #include <tinycr...
stackexchange/codereview
I've created a program for my own purposes in three different languages, Perl, Python, and Ruby. Each program will be posted in with their own tag but I will add links to them through on each post. The program itself is very simple, all it does is ask the user about three different languages which are saved into an arr...
stackexchange/codereview
I created an MVC router based on knowledge of an MVC design pattern. It will simply take a URL as a string (class/method/params...), then it will instantiate a requested class controller and call its method. In my class, I call a controller method and then include the view at the same time to display data. My questions...
stackexchange/codereview
I'm developing a small C# Unity application to display stereoscopic images as part of a wider research study. Since the experiment consists of unique stages (Start, during a trial, between trials, and End), I decided to use the State Design Pattern to make a State Machine for code readability. The program design is bas...
stackexchange/codereview
CKLinkedList is the implementation of a doubly linked list. I'd like to see comments on the memory management (I'm using ARC in the code below) and formatting + overall style. CKList protocol file: // // CKList.h // CollectionsKit // // Created by Igor Rastvorov on 11/30/14. // Copyright (c) 2014 Igor Rastvorov. Al...
stackexchange/codereview
I'm consuming some messages from a rabbit queue. Within the consumer/processor I need to invalidate a varnish cache and requeue the message if the purge failed. I'm using a local purge proxy. The consumer is a Dropwizard microservice but I'm using a BasicHttpClient because JerseyClient doesn't allow me (AFAIK) to set ...
stackexchange/codereview
I created a JS script for a friend's website to allow the visitors to choose the date and time of their delivery. I'm new in web-development and I will appreciate a feedback from professionals like you. The script doesn't have an UI at the moment ,so for settings just need to change the shippingDateTime. The script aut...
stackexchange/codereview
This is my sample code to convert a integer into string. Is it very costly to do the multiple loops of [NSMutableString stringWithFormat:..]? I.e should I just use appendString and get the NSString in reverse order and then do one for loop to reverse this "reverse string". Is there any other faster/more elegant way? NS...
stackexchange/codereview
I need to apply some css styles to an IMarkupElement. The generated HTML is only for emails so all styles are inline styles and the selectors are very simple, just element names, ids or class names can be used. I'm not sure whether a Visitor is the right tool to apply styles to elements but it seemed to fit for the tas...
stackexchange/codereview
Please let me know if the MVVM pattern I followed in this is correct or not. Here is the code for ViewModel public class LoginViewModel { public string Email { get; set; } = ""; public string Password { get; set; } = ""; public ProgressBar ProgressBar { get; set; } public Label StatusLabel { get; set...
stackexchange/codereview
I'm pushing myself to learn pure JavaScript, so this morning I wrote an equal heights script in jQuery and then converted it to JavaScript. It works, but I'm using two for loops. Is there a better or more efficient way to write this code, maybe by finding a way to remove the second for loop? I've created a jsfiddle to ...
stackexchange/codereview
I'm working on porting the bullet3 physics engine to Go to learn more about physics simulations. I'm working through some of the convex hull computing code, and I've reached a component-wise, double precision multiplication class in the original C++ code. I'm not familiar with this type of low-level math, so I'm not su...
stackexchange/codereview
Can this query be improved? I iterate over a couple of thousand times, and if I can improve it, it should decrease the run time. Otherwise I might look into using a batch instead of doing one at a time. I'm using MS SQL 11. job **** id name job_stats ************* id job_id median_runtime select js.median_runtime f...
stackexchange/codereview
Just wanted to see what you all thought about my program, I basically have two different classes that I designed to allow for automated wrapping of text in a circular pattern. This is my first bit of useful and reusable code. Let me know what can be improved or added. Here are some screenshots I took of the program in ...
stackexchange/codereview
I have a complicated select procedure that I solved with a 5 query select, so I am posting it here to get suggestions on how I can shorten it up a bit. I am hoping that someone can help me make it a single query select. I'm using nhibernate query over here. I have 7 tables which are t_user t_category t_event t_announ...
stackexchange/codereview
I have a Java/Swing/Guice application that uses multiple frames. When the application runs normally, I just want some of these frames to hide (and the "master" frame can unhide them). When testing the view, I have various other main methods that can open just one frame, and perhaps populate them with sample data. Howev...
stackexchange/codereview
So I came across an interesting problem awhile back, and I finally got around to solving it. Basically, it needs to allow the user to provide two words, and have them progressively splice together, like so: Word 1: 123 Word 2: abc Result: 123abc 12a3bc 1a2b3c a1b2c3 ab1c23 abc1...
stackexchange/codereview
I have a search box for searching for people in a list of names. Here is the code that runs every time the query changes. I could not find anything open-sourced for this, so I wanted to make sure this looks good and efficient. How does it look? private final List<String> mTotalNames = ............ // some ArrayList<St...
stackexchange/codereview
I have this small subclass of JavaFX's javafx.scene.control.Dialog that requires the enum specifying the data type of the input data: package com.github.coderodde.jfx.ui; import java.util.Objects; import java.util.Optional; import javafx.event.EventHandler; import javafx.scene.control.ButtonBar.ButtonData; import ja...
stackexchange/codereview
I have two interfaces. Entity for updates. Drawable for rendering. They both have two interface methods. One that is called every frame, one every second. Entity.java public interface Entity { public void updatePerFrame (); public void updatePerSecond (); } Drawable.java public interface Drawable { public ...
stackexchange/codereview
I've got this little module that returns basic user data required for a web app that's extracted from a large number of columns per row. I was asked to replace the small, column specific select statement I'd prepared with a stored procedure that returns the entire row. This moves column pruning into the server. I've m...
stackexchange/codereview
How can I write this more pretty? private void _detailSpread_OnCellFocusChange(object sender, CellFocusChangeEventArgs e) { if (e.SourceCol == _detailSpread.GetColNumber("article")) UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]); else if (e.SourceCol == _detail...
stackexchange/codereview
I have written this code for the question: Finding k largest (or smallest) elements in an array My approach uses a temporary array. Please suggest any improvements for readability or better performance. public static void kLargest(int[] array, int k){ if(k < 0 || k > array.length){ return; } ...
stackexchange/codereview
I created this based on this website which calculates IP address information such as hosts, netmasks etc. I'm quite new to C and I'm still grasping the idea of the whole array and pointers and bit manipulations. Code works the way I want it to work but I'd like to improve this. I would like to know how I did as well as...
stackexchange/codereview
I have two very similar SQL statements INSERT INTO user_profile (user_id, setting_id, value) SELECT id, 18, true FROM users WHERE NOT EXISTS ( SELECT user_id, setting_id FROM user_profile WHERE id=user_id AND setting_id=18); INSERT INTO user_profile (user_id, setting_id, value) ...
stackexchange/codereview
This produces recursive directory listings(it's intended to do other things, so there will be something else instead of echo, but it isn't important), yet it isn't very intuitive. How can I improve it? #! /bin/bash deploy () { for file in $(ls $1); do if [ ! -d "$2$file" ]; then echo ${2}${file}...
stackexchange/codereview
I've put together a simple CRUD application to keep track of my library of books in an effort to learn the model-view-controller pattern, as well as better myself at PHP. Everything I have works so far, but I'm definitely looking to streamline/condense/refactor the more verbose parts of it, as well as address any possi...
stackexchange/codereview
I have a pandas data frame and I want to calculate some features based on some short_window, long_window and bins values. More specifically, for each different row, I want to calculate some features. In order to do so, I move one row forward the df_long = df.loc[row:long_window+row] such as in the first iteration the p...
stackexchange/codereview
I came across a piece of code that generates SELECT queries from a template. The template: SELECT TOP 1 * FROM MRH_0000004 WITH (nolock) WHERE MachineRegisterId = ${id} ORDER BY UtcTime When the code has to retrieve multiple records, it generates one large query that gets the union of all individual queries base...
stackexchange/codereview
I'm learning how to use Python with the Raspberry Pi. I successfully followed the tutorial for how to have a Python script run on the Pi to check for new email and turn on an LED if any new messages are in an inbox. I wanted to give myself a challenge by adding a feature to blink a secondary LED to indicate the number ...
stackexchange/codereview
I am trying to find a good way of parsing SQL arguments, the way I am accomplishing it now seems like it can use a lot of improvement. I am trying to convert arguments that are split apart by ', & <= =>' from a string into SQL arguments like name = 'ABC' OR name ='John Doe'. So parseSQLOperators('dan,john&steven', 'us...
stackexchange/codereview
I am developing a userscript that redirects insecure pages (HTTP) to the https: version. // ==UserScript== // @name Secure Redirect // @namespace http://tampermonkey.net/ // @version 0.1 // @description A simple userscript that redirects pages to https:. // @author You // @match * // @gr...
stackexchange/codereview
I've recently been learning (and struggling with) integrating AutoFac, NHibernate & ASP.NET Web API. I have found several tutorials with code that did not work as anticipated but managed to finally find a working solution. Essentially what I'm doing is registering a singleton of my SessionFactory to the WebApiApplicati...
stackexchange/codereview
I've been writing code for nearly 40 years now and am still not too old to learn and understand new things. Right now, my focus is a bit of OO with functional programming combined and C# with Linq is an excellent way to fool around with this. I'm also practicing deferred execution and aggregating to make it really inte...
stackexchange/codereview
My question is very simple. I wrote this program for pure entertainment. It takes a numerical input and finds the length of every Collatz Sequence up to and including that number. I want to make it faster algorithmically or mathematically (i.e. I know I could make it faster by running multiple versions parallel or by w...
stackexchange/codereview
In an earlier question, I showed my code for calculating the mine probability for each and every field in a Minesweeper board. But it doesn't stop there. In that very same Minesweeper Analyze project, there is also an algorithm for calculating the probability of each and every number for each and every field. Motivatio...
stackexchange/codereview
I have a jQuery solution as below. I am confident the solution can be made better in terms of OO way using constructor pattern var $search = $('.search'); if ($search.length > 0) { $search.removeClass('dropdown radix-dropdown-processed'); $('.search__button').on('click', function (e) { e.preventDefau...
stackexchange/codereview
For the below given exercise: Define a function cycle which takes in three functions as arguments: f1, f2, f3. cycle will then return another function. The returned fuction should take in an integer argument n and do the following: return a function that takes in an argument x and does the following: if n is 0, just r...
stackexchange/codereview
Like my previous question about my Mental Maths game , I have written a script for a ten questions Maths game and again it seems like there is a more simple method, can anyone take me out of the dark on this one? def tenquestions(): mode=input("(E)asy, (M)edium, (H)ard") questions=0 rightqs=0 while ques...
stackexchange/codereview
I recently faced an interview question where you have to find minimum needed items from an array that can added together to generate X value. For example giving: [1, 9, 2, 5, 3, 10] and the goal is: 13, => it should be [10, 3] You can't use any number out side of array. I have tried to sort items and take from the he...
stackexchange/codereview
I have some simple HTML for a +/- Button, Phone Number Textbox, and a Phone Number Type Dropdown. I'm new to Bootstrap, so with the help of the tool Bootstrap Studio I generated this code that I currently have: <div class="row"> <div class="col-lg-1 col-md-1 col-sm-1 col-xs-3"> <form> <div class...
stackexchange/codereview
Before I start implementing several REST API service endpoints, I'd like to make sure that I'm not doing it totally wrong. /** * GET /api/test * Test API example. */ export let getTest = (req: Request, res: Response, next: NextFunction) => { // const token = req.user.tokens.find((token: any) => token.kind === "f...
stackexchange/codereview
I'm trying to play around with Godot to learn C# and I was trying to creating pure functions to do the velocity, but I found I was repeating myself. public override void _PhysicsProcess(float delta) { base._PhysicsProcess(delta); Vector2 moveVelocity = velocity; moveVelocity = Run(moveV...
stackexchange/codereview
It's been nearly a year I've been using C++, and I have just implemented this queue. I've tested it in many different scenarios, and it seems to work completely fine. Would you mind telling me what can be improved? What techniques might and might not be used in a professional scenario? In general, could you please giv...
stackexchange/codereview
I am writing a function to decode Argon2 hashed string to extract parameters. I need to handle many decode errors, and handle those errors lead to write many repeating if err == nil check code. Is there a better way to do this kind of check? The encodedHash string follows the format, separated by $ "$argon2id$v=%d$m=%d...
stackexchange/codereview
This code is supposed to be the "user" system for my app. This will ask you what you want to do... If you want to add a user, remove a user or check the list of saved users. With this I learned how to open and edit text files. And my goal doing projects is keep on learning and maybe someday I will be able to work or pr...
stackexchange/codereview
This contains some complex logic and it's very difficult to provide all the things here. My intention is to simplify the loops, variable naming, and other stuff. I am thinking about splitting this big method to two or three subsidiary methods for better understanding/reading. Any ideas about that? public static void Ch...
stackexchange/codereview
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. The program can be downloaded here. You can only start it via command line, not by double-click. If I can improve my code to make it more readable, please tell me how. Ma...
stackexchange/codereview
Below is my implementation of a generic linked list in swift. Unfortunately, Swift playgrounds won't run until the compiler is totally happy - often, that involves clang making me explicitly unwrap some optionals. I just want a general idea of how to restructure my code to avoid unwrapping optionals and to make more us...
stackexchange/codereview
I have programmed Tic Tac Toe in C. How can I improve the code? I have been told that system("cls") is not secure, but I don't know any other way of clearing the screen. main.c: #include <stdio.h> #include <stdlib.h> #define BOOL short int #define TRUE 1 #define FALSE 0 #define NUMBER_OF_ROWS 3 #define NUMBER_OF_COLU...
stackexchange/codereview
I am working on this assignment to draw the flag of Liberia for my essentials of computer programming class. I finished it but had extra time to kill and noticed that a couple similar blocks of code are not very concise and could be shortened with a loop, but right now I can't seem to form the code just right! Below I...
stackexchange/codereview
I recently wrote this up and am wondering if there is a better way to achieve the results I want. Essentially, we're taking a given year and adding 'th, nd, rd, st' depending on the digit. Any suggestions on how to shorten this code and make it better? Keep in mind that this is taking centuries that change every 01st y...
stackexchange/codereview
This is a follow up to: Lvl 1 upgradeable attributes From before: I've built the groundwork for an attributes (as in Strength, Intelligence, not as in DebuggerHidden, TestMethod) framework for my game. Each attribute can be upgraded and downgraded individually as well as part of a bulk change (such as for upgr...
stackexchange/codereview
I'm a freshman in Python world, I used to program in C. I wrote a function/method that returns the power of a number: def pow(x, y): powered = x if y == 0: return 1 while y > 1: powered *= x y -= 1 return powered Mine is a logic question (correctly): if I set y = 0 then it ...
stackexchange/codereview
My code sample for finding the mean for the case of pairs is: import numpy as np Data =[] with open('testdata.txt') as my_file: for line in my_file: Data.append(line) psize = Data.size*Data.size p_avg =zeros(psize,float) for i in range(0,Data.size): for j in range(0,Data.size): if i != j: ...
stackexchange/codereview
This is the crux of a problem found on one of those code challenge sites. I'm fairly new to programming and this was a difficult challenge. I've attempted to solve this with stacks and calculating totals on the fly. I think this is pretty close to O(n). With the exception of values repeated without a larger value betwe...
stackexchange/codereview
I am designing a planetary system simulator. The coordinates used are standard for JPanel (0,0 in the upper left corner). My model is based on a class Body: public class Body { private double x, y; // position private double w, h; // dimensions for drawing private double vx = 0, vy = 0; // velocities along ...
stackexchange/codereview
I am a Python beginner and wrote a script which should run on a Raspberry PI as a UDP server. It reads and writes to a serial device and has to process and forward JSON strings. Because there is relatively much functionality included and I don't like cross compiling, I was too lazy to write a C program but instead chos...
stackexchange/codereview
I have an application developed in ASP.NET Core C#, where according to a configuration it must replace certain urls of a text when an http request is made and the text must be returned as soon as possible in response, the text can change on each request. At this moment the code I have is working well, but I would like...
stackexchange/codereview
I am trying to write a script to read a CSV file containing 1 million domain names, look up these domain names and store the results in another CSV file. I am trying the following code, but the number of records I am able to parse with time is quite less. I want to optimize the performance of this to be able to parse m...
stackexchange/codereview